run method

Future<int> run(
  1. String scriptName, {
  2. bool showCommand = true,
})

Run a script by name

Implementation

Future<int> run(String scriptName, {bool showCommand = true}) async {
  final pubspec = findPubspec();
  if (pubspec == null) {
    error('No pubspec.yaml found in current directory or parents');
    return 1;
  }

  final scripts = getScripts(pubspec.path);
  if (scripts.isEmpty) {
    error('No scripts defined in pubspec.yaml');
    return 1;
  }

  final matchedName = findScript(scriptName, scripts);
  if (matchedName == null) {
    final matches = findMatchingScripts(scriptName, scripts);
    if (matches.isEmpty) {
      error('Script "$scriptName" not found');
      info('Available scripts: ${scripts.keys.join(', ')}');
    } else {
      error('Ambiguous script name "$scriptName"');
      info('Did you mean: ${matches.join(', ')}');
    }
    return 1;
  }

  final command = scripts[matchedName]!;
  final workingDir = pubspec.parent.path;

  if (showCommand) {
    info('Running: $matchedName');
    verbose('Command: $command');
    verbose('Working directory: $workingDir');
    print('');
  }

  // Run the command
  final result = await Process.run(
    Platform.isWindows ? 'cmd' : 'sh',
    Platform.isWindows ? ['/c', command] : ['-c', command],
    workingDirectory: workingDir,
    runInShell: true,
  );

  // Stream output
  if (result.stdout.toString().isNotEmpty) {
    stdout.write(result.stdout);
  }
  if (result.stderr.toString().isNotEmpty) {
    stderr.write(result.stderr);
  }

  if (result.exitCode == 0) {
    success('Script "$matchedName" completed successfully');
  } else {
    error('Script "$matchedName" failed with exit code ${result.exitCode}');
  }

  return result.exitCode;
}