makeCommand static method

dynamic makeCommand(
  1. String commandName,
  2. String value, {
  3. String folderPath = commandsFolder,
  4. bool forceCreate = false,
  5. String? creationPath,
  6. String? category,
})

Creates a new command file.

Implementation

static makeCommand(String commandName, String value,
    {String folderPath = commandsFolder,
    bool forceCreate = false,
    String? creationPath,
    String? category}) async {
  String name = commandName.replaceAll(RegExp(r'(_?command)'), "");
  ReCase nameReCase = ReCase(name);

  // create missing directories in the project
  await _makeDirectory(folderPath);
  await createDirectoriesFromCreationPath(creationPath, folderPath);

  // Check custom_commands.json file exists
  String customCommandsFilePath = "$folderPath/custom_commands.json";
  if (!await hasFile(customCommandsFilePath)) {
    await _createNewFile(customCommandsFilePath, "[]");
  }

  // create file path
  String filePath = createPathForDartFile(
      folderPath: folderPath, className: name, creationPath: creationPath);
  await _checkIfFileExists(filePath, shouldForceCreate: forceCreate);
  await _createNewFile(filePath, value, onSuccess: () async {
    MetroConsole.writeInGreen('[Command] ${name.snakeCase} created 🎉');
  });

  // Add to custom_commands.json
  String commandJson = jsonEncode({
    "name": nameReCase.snakeCase,
    "category": category ?? "app",
    "script": "${nameReCase.snakeCase}.dart"
  });

  try {
    File file = File(customCommandsFilePath);

    String customCommandsFile = await loadAsset(customCommandsFilePath);

    List<dynamic> commands = jsonDecode(customCommandsFile);
    if (!commands.any((command) => command["name"] == nameReCase.snakeCase)) {
      commands.add(jsonDecode(commandJson));
    }
    String updatedCommands = jsonEncode(commands);

    // format json file
    String formattedJson = const JsonEncoder.withIndent('  ')
        .convert(jsonDecode(updatedCommands));

    await file.writeAsString(formattedJson);
  } catch (e) {
    MetroConsole.writeInRed(
        '[Command] ${name.snakeCase} failed to create command: $e');
    return;
  }
}