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 results = argResults!;
  final force = results.flag('force');
  final rest = results.rest;

  if (rest.length > 1) {
    stderr.writeln('init takes at most one positional argument.');
    stderr.writeln(usage);
    return 64; // EX_USAGE
  }

  final targetDir = rest.isEmpty ? Directory.current : Directory(rest.first);
  if (!targetDir.existsSync()) {
    stderr.writeln('Target directory does not exist: ${targetDir.path}');
    return 66; // EX_NOINPUT
  }

  final dialectDir = Directory(p.join(targetDir.path, 'dialect'));
  final scaffoldExists = dialectDir.existsSync();

  if (scaffoldExists && !force) {
    // Idempotent re-run: refresh the plan + AGENTS.md, leave scaffold alone.
    stdout.writeln(
      '✓ dialect/ scaffold already exists in ${targetDir.path} — '
      'refreshing init plan only (use --force to rewrite scaffold).',
    );
  } else {
    _writeScaffold(dialectDir);
    _printScaffoldSummary();
  }

  final projectType = _detectProjectType(targetDir);
  final projectName = _projectName(targetDir);

  final initPlanPath = _writeInitPlan(
    targetDir: targetDir,
    projectName: projectName,
    projectType: projectType,
  );
  stdout.writeln('  .dialect/init-plan.md');

  final agentsOutcome = _writeAgentsSection(targetDir);
  stdout.writeln('  ${agentsOutcome.relPath} (${agentsOutcome.verb})');

  final gitignoreUpdated = _ensureGitignore(targetDir);
  if (gitignoreUpdated) {
    stdout.writeln('  .gitignore (added .dialect/)');
  }

  if (projectType == 'Flutter') {
    final added = _ensureFlutterGenerateFlag(targetDir);
    if (added) {
      stdout.writeln('  pubspec.yaml (added `flutter: generate: true`)');
    }
  }

  stdout.writeln('');
  stdout.writeln('Detected project type: $projectType');
  stdout.writeln('Init plan written to: $initPlanPath');
  stdout.writeln('');
  stdout.writeln(
    'Next: paste this in your AI agent (Claude Code, Cursor, …):',
  );
  stdout.writeln('');
  stdout.writeln('  run dialect init and follow the instructions');
  stdout.writeln('');
  stdout.writeln(
    'Your agent will execute .dialect/init-plan.md and walk you through '
    'localizing the app.',
  );

  return 0;
}