run method

  1. @override
Future<void> run()
override

Runs this command.

The return value is wrapped in a Future if necessary and returned by CommandRunner.runCommand.

Implementation

@override
Future<void> run() async {
  final parsed = argResults!;
  final smart = parsed[smartFlag] as bool;
  final pathRaw = parsed[pathOption] as String;
  final nameRaw = parsed[nameOption] as String;

  if (smart) {
    // smartModeConfig just fills `targetDirectory` and `basename` fields.
    await smartModeConfig(path: pathRaw, name: nameRaw);
  } else {
    targetDirectory = Directory(pathRaw);
    basename = nameRaw;
  }

  if (!targetDirectory.existsSync() && !smart) {
    throw NonExistentFolderException(targetDirectory.path);
  }

  if (!TemplateGeneratorCommand.moduleNameRegexp.hasMatch(basename)) {
    throw CommandLineUsageException(
      message: '$basename is not valid module name. '
          'Module name must be in snake_case.',
    );
  }

  // getting templates contents
  await fillTemplates();

  files = simpleTemplateToFileMap(targetDirectory, basename);

  await checkTargetFilesExistance(files.values);

  final className = snakeToCamelCase(basename);

  // modification of template content
  String contentCreator(String template) => template
      .replaceAll('ClassName', className)
      .replaceAll('filename', basename);

  // Creating and writing all files
  await Future.wait(
    templateNames.map((templateName) => writeFile(
          file: files[templateName]!,
          content: contentCreator(templates[templateName]!),
        )),
  ).then((files) => files.forEach(ConsoleWriter.write)).catchError(
    // If some FileSystemException occurred - delete all files
    // ignore: avoid_types_on_closure_parameters
    (Object error, StackTrace stackTrace) async {
      await Future.wait(files.values.map((f) => f.delete()));
      // Then throw exception to return right exit code
      throw GenerationException();
    },
    test: (error) => error is FileSystemException,
  );
}