|
| 1 | +import 'config.dart'; |
| 2 | +import 'utils.dart'; |
| 3 | + |
| 4 | +/// Runs a script with the given name, and any extra arguments. |
| 5 | +/// Returns the exit code. |
| 6 | +Future<int> runScript(String entryName, List<String> args) async { |
| 7 | + final config = await ScriptRunnerConfig.get(); |
| 8 | + |
| 9 | + if (config.scripts.isEmpty) { |
| 10 | + throw ScriptStateError('No scripts found'); |
| 11 | + } |
| 12 | + |
| 13 | + if (['-h', '--help'].contains(entryName)) { |
| 14 | + config.printUsage(); |
| 15 | + return 0; |
| 16 | + } |
| 17 | + |
| 18 | + if (['-ls', '--list'].contains(entryName)) { |
| 19 | + final search = args.isNotEmpty ? args.first : ''; |
| 20 | + config.printScripts(search); |
| 21 | + return 0; |
| 22 | + } |
| 23 | + |
| 24 | + final entry = config.scriptsMap[entryName]; |
| 25 | + |
| 26 | + if (entry == null) { |
| 27 | + final suggestions = config.scriptsMap.keys |
| 28 | + .where((key) => key.toLowerCase().startsWith(entryName.toLowerCase())) |
| 29 | + .toList(); |
| 30 | + |
| 31 | + if (suggestions.isNotEmpty) { |
| 32 | + if (suggestions.length == 1) { |
| 33 | + throw ScriptStateError( |
| 34 | + 'No script named "$entryName" found. Did you mean "${suggestions.single}"?', |
| 35 | + ); |
| 36 | + } else { |
| 37 | + throw ScriptStateError( |
| 38 | + 'No script named "$entryName" found.\n' |
| 39 | + 'Did you mean one of: "${suggestions.join('", "')}"?', |
| 40 | + ); |
| 41 | + } |
| 42 | + } else { |
| 43 | + throw ScriptStateError( |
| 44 | + 'No script named "$entryName" found.\n' |
| 45 | + 'Available scripts: ${config.scriptsMap.keys.join('", "')}', |
| 46 | + ); |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + return entry.run(args); |
| 51 | +} |
| 52 | + |
0 commit comments