run method

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

Runs this command.

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

Implementation

@override
Future<int> run() async {
  final cwd = Directory.current.path;

  // 1. Verify this is a Flutter project.
  if (!isFlutterProject(cwd)) {
    stderr.writeln(
      '\x1B[31mError:\x1B[0m The current directory is not a Flutter project.',
    );
    stderr.writeln(
      'Make sure you are in a directory with a pubspec.yaml '
      'that declares a Flutter dependency.',
    );
    return 1;
  }

  final configManager = FlaiConfigManager(projectRoot: cwd);

  // 2. Warn if already initialised.
  if (configManager.exists) {
    stderr.writeln(
      '\x1B[33mWarning:\x1B[0m flai.yaml already exists. '
      'Re-initialising will overwrite the config.',
    );
  }

  final outputDir = argResults!['output-dir'] as String;
  final theme = argResults!['theme'] as String;

  // 3. Create the config file.
  final config = FlaiConfig(
    outputDir: 'lib/$outputDir',
    theme: theme,
    installed: ['flai_init'],
  );
  configManager.write(config);
  stdout.writeln('\x1B[32m\u2713\x1B[0m Created $kConfigFileName');

  // 4. Generate core files using the flai_init Mason brick.
  final brickPath = _resolveBrickPath('flai_init');
  if (brickPath == null) {
    stderr.writeln(
      '\x1B[31mError:\x1B[0m Could not locate the flai_init brick.',
    );
    stderr.writeln(
      'Ensure you have the FlAI bricks available. '
      'If installed via pub, bricks should be bundled with the CLI.',
    );
    return 1;
  }

  stdout.writeln('\x1B[36m>\x1B[0m Generating core files...');

  try {
    final generator = await MasonGenerator.fromBrick(Brick.path(brickPath));
    final target = DirectoryGeneratorTarget(Directory(cwd));
    final files = await generator.generate(
      target,
      vars: {'output_dir': outputDir},
      fileConflictResolution: FileConflictResolution.overwrite,
    );

    for (final file in files) {
      stdout.writeln('  \x1B[32m\u2713\x1B[0m ${file.path}');
    }
  } on Exception catch (e) {
    stderr.writeln('\x1B[31mError:\x1B[0m Failed to generate files: $e');
    return 1;
  }

  stdout.writeln('');
  stdout.writeln('\x1B[32m\u2713 FlAI initialised successfully!\x1B[0m');
  stdout.writeln('');
  stdout.writeln('Next steps:');
  stdout.writeln(
    '  \x1B[36mflai add chat_screen\x1B[0m   '
    '— install the full chat screen',
  );
  stdout.writeln(
    '  \x1B[36mflai list\x1B[0m              '
    '— see all available components',
  );
  stdout.writeln(
    '  \x1B[36mflai doctor\x1B[0m            '
    '— check project health',
  );
  stdout.writeln('');

  return 0;
}