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 <delphij@google.com>
Tested-by: Mike Frysinger <vapier@google.com>
This commit is contained in:
Mike Frysinger 2021-07-26 23:20:29 -04:00
parent cfa00d6e3d
commit 968d646f04

48
main.py
View File

@ -130,32 +130,21 @@ class _Repo(object):
def _ParseArgs(self, argv): def _ParseArgs(self, argv):
"""Parse the main `repo` command line options.""" """Parse the main `repo` command line options."""
name = None for i, arg in enumerate(argv):
glob = [] if not arg.startswith('-'):
name = arg
for i in range(len(argv)): glob = argv[:i]
if not argv[i].startswith('-'):
name = argv[i]
if i > 0:
glob = argv[:i]
argv = argv[i + 1:] argv = argv[i + 1:]
break break
if not name: else:
name = None
glob = argv glob = argv
name = 'help'
argv = [] argv = []
gopts, _gargs = global_options.parse_args(glob) gopts, _gargs = global_options.parse_args(glob)
name, alias_args = self._ExpandAlias(name) if name:
argv = alias_args + argv 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 <command>` for command-specific details.')
global_options.exit()
return (name, gopts, argv) return (name, gopts, argv)
@ -186,12 +175,23 @@ class _Repo(object):
if gopts.trace: if gopts.trace:
SetTrace() SetTrace()
if gopts.show_version:
if name == 'help': # Handle options that terminate quickly first.
name = 'version' if gopts.help:
else: 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 <command>` for command-specific details.')
return 0
elif gopts.show_version:
if name and name != 'help':
print('fatal: invalid usage of --version', file=sys.stderr) print('fatal: invalid usage of --version', file=sys.stderr)
return 1 return 1
name = 'version'
elif not name:
# No subcommand specified, so show the help/subcommand.
name = 'help'
SetDefaultColoring(gopts.color) SetDefaultColoring(gopts.color)