makeCommand static method

Future<void> 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 Future<void> 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 commands.json file exists
  String customCommandsFilePath = "$folderPath/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 {
      final linkText = name.snakeCase;
      final link = MetroConsole.hyperlink(linkText, filePath);
      MetroConsole.writeInGreen('[Command] $link created 🎉');
    },
  );

  // Add to 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;
  }
}