|
| 1 | +import 'package:args/command_runner.dart'; |
| 2 | +import 'package:example/src/commands/commands.dart'; |
| 3 | +import 'package:mason_logger/mason_logger.dart'; |
| 4 | + |
| 5 | +const executableName = 'example_cli'; |
| 6 | +const packageName = 'example'; |
| 7 | +const description = 'Example for cli_completion'; |
| 8 | + |
| 9 | +/// {@template example_command_runner} |
| 10 | +/// A [CommandRunner] for the CLI. |
| 11 | +/// |
| 12 | +/// ``` |
| 13 | +/// $ example_cli --version |
| 14 | +/// ``` |
| 15 | +/// {@endtemplate} |
| 16 | +class ExampleCommandRunner extends CommandRunner<int> { |
| 17 | + /// {@macro example_command_runner} |
| 18 | + ExampleCommandRunner({ |
| 19 | + Logger? logger, |
| 20 | + }) : _logger = logger ?? Logger(), |
| 21 | + super(executableName, description) { |
| 22 | + // Add root options and flags |
| 23 | + argParser.addFlag( |
| 24 | + 'rootFlag', |
| 25 | + help: 'A flag in the root command', |
| 26 | + ); |
| 27 | + |
| 28 | + // Add sub commands |
| 29 | + addCommand(SomeCommand(_logger)); |
| 30 | + addCommand(SomeOtherCommand(_logger)); |
| 31 | + } |
| 32 | + |
| 33 | + @override |
| 34 | + void printUsage() => _logger.info(usage); |
| 35 | + |
| 36 | + final Logger _logger; |
| 37 | + |
| 38 | + @override |
| 39 | + Future<int> run(Iterable<String> args) async { |
| 40 | + try { |
| 41 | + final topLevelResults = parse(args); |
| 42 | + |
| 43 | + if (topLevelResults['rootFlag'] == true) { |
| 44 | + _logger.info('You used the root flag, it does nothing :)'); |
| 45 | + return ExitCode.success.code; |
| 46 | + } |
| 47 | + |
| 48 | + return await runCommand(topLevelResults) ?? ExitCode.success.code; |
| 49 | + } on FormatException catch (e, stackTrace) { |
| 50 | + // On format errors, show the commands error message, root usage and |
| 51 | + // exit with an error code |
| 52 | + _logger |
| 53 | + ..err(e.message) |
| 54 | + ..err('$stackTrace') |
| 55 | + ..info('') |
| 56 | + ..info(usage); |
| 57 | + return ExitCode.usage.code; |
| 58 | + } on UsageException catch (e) { |
| 59 | + // On usage errors, show the commands usage message and |
| 60 | + // exit with an error code |
| 61 | + _logger |
| 62 | + ..err(e.message) |
| 63 | + ..info('') |
| 64 | + ..info(e.usage); |
| 65 | + return ExitCode.usage.code; |
| 66 | + } |
| 67 | + } |
| 68 | +} |
0 commit comments