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 pathRaw = parsed[pathOption] as String;
  final fileNameBase = parsed[nameOption] as String;
  final isSubdirNeeded = parsed[isSubdirNeededFlag] as bool;

  final baseDir = Directory(pathRaw);
  if (!baseDir.existsSync()) {
    throw NonExistentFolderException(pathRaw);
  }

  if (!TemplateGeneratorCommand.moduleNameRegexp.hasMatch(fileNameBase)) {
    throw CommandLineUsageException(
      argumentName: nameOption,
      argumentValue: fileNameBase,
    );
  }

  // getting templates contents
  await fillTemplates();

  // with `simpleTemplateToFileMap` all files will
  // be generated in one directory
  final targetDirectory = isSubdirNeeded
      ? await Directory(p.join(pathRaw, fileNameBase)).create()
      : baseDir;

  files = simpleTemplateToFileMap(targetDirectory, fileNameBase);

  await checkTargetFilesExistance(files.values);

  final className = snakeToCamelCase(fileNameBase);

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

  // 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,
  );
}