run method

  1. @override
int run()
override

Runs this command.

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

Implementation

@override
int run() {
  final configSource = _results['config'] as String;
  final resultsOutput = _results['output'] as String;

  try {
    if (!File(configSource).existsSync()) {
      throw FileSystemException('Cannot read file', configSource);
    }

    final yaml = yamlDoc(File(configSource));
    final config = GatorConfig.fromYaml(yaml);
    final colors = createTintsAndShades(config.colors);
    final output = config.outputPath ?? resultsOutput;
    final fields = _buildFieldsForColor(colors);
    final constructors = [Constructor((b) => b.name = '_')];
    final directive = Directive(
      (b) => b
        ..type = DirectiveType.import
        ..url = 'package:flutter/material.dart'
        ..show = ['Color', 'MaterialColor'],
    );

    final generatedClass = Class(
      (b) => b
        ..docs = ListBuilder<String>([
          '/// **${config.className.pascalCase}**',
          ..._header,
        ])
        ..constructors = ListBuilder<Constructor>(constructors)
        ..name = config.className.pascalCase
        ..fields = ListBuilder<Field>(fields),
    );

    final library = Library(
      (b) => b
        ..body = ListBuilder(<Spec>[generatedClass])
        ..directives = ListBuilder(<Directive>[directive]),
    ).accept(_emitter);

    final generatedCode = _formatter.format('$library');

    File(output)
      ..writeAsStringSync(generatedCode)
      ..createSync(recursive: true);

    _logger.success('🖍 Created file: $output!');

    return 0;
  } on InvalidGatorConfigException catch (e) {
    _logger.err(e.message);
  } on FileSystemException catch (e) {
    _logger.err('${e.message} ${e.path}');
  } catch (e, s) {
    _logger
      ..warn(e.toString())
      ..warn(s.toString());
  }
  return 1;
}