From 968d646f046355313008bfddfbd3fde1e0e14339 Mon Sep 17 00:00:00 2001 From: Mike Frysinger Date: Mon, 26 Jul 2021 23:20:29 -0400 Subject: [PATCH] repo: refactor internal --help/--version parsing The _ParseArgs method parses the arguments and processes some of the options, with the rest left to the _Run method. Simplify the _ParseArgs method to only parse arguments and have _Run handle all actual processing. This will make it easier to add more terminal options (ones that exit immediately without a subcommand), and makes it easier to understand the overall code flow. Change-Id: I47f7274c3f2b59378fd479e403e70fb24b681536 Reviewed-on: https://gerrit-review.googlesource.com/c/git-repo/+/312906 Reviewed-by: Xin Li Tested-by: Mike Frysinger --- main.py | 48 ++++++++++++++++++++++++------------------------ 1 file changed, 24 insertions(+), 24 deletions(-) diff --git a/main.py b/main.py index f6631f5f..5c8ea85c 100755 --- a/main.py +++ b/main.py @@ -130,32 +130,21 @@ class _Repo(object): def _ParseArgs(self, argv): """Parse the main `repo` command line options.""" - name = None - glob = [] - - for i in range(len(argv)): - if not argv[i].startswith('-'): - name = argv[i] - if i > 0: - glob = argv[:i] + for i, arg in enumerate(argv): + if not arg.startswith('-'): + name = arg + glob = argv[:i] argv = argv[i + 1:] break - if not name: + else: + name = None glob = argv - name = 'help' argv = [] gopts, _gargs = global_options.parse_args(glob) - name, alias_args = self._ExpandAlias(name) - argv = alias_args + argv - - if gopts.help: - global_options.print_help() - commands = ' '.join(sorted(self.commands)) - wrapped_commands = textwrap.wrap(commands, width=77) - print('\nAvailable commands:\n %s' % ('\n '.join(wrapped_commands),)) - print('\nRun `repo help ` for command-specific details.') - global_options.exit() + if name: + name, alias_args = self._ExpandAlias(name) + argv = alias_args + argv return (name, gopts, argv) @@ -186,12 +175,23 @@ class _Repo(object): if gopts.trace: SetTrace() - if gopts.show_version: - if name == 'help': - name = 'version' - else: + + # Handle options that terminate quickly first. + if gopts.help: + global_options.print_help() + commands = ' '.join(sorted(self.commands)) + wrapped_commands = textwrap.wrap(commands, width=77) + print('\nAvailable commands:\n %s' % ('\n '.join(wrapped_commands),)) + print('\nRun `repo help ` for command-specific details.') + return 0 + elif gopts.show_version: + if name and name != 'help': print('fatal: invalid usage of --version', file=sys.stderr) return 1 + name = 'version' + elif not name: + # No subcommand specified, so show the help/subcommand. + name = 'help' SetDefaultColoring(gopts.color)