Skip to content

Commit fe1fda4

Browse files
committed
Single-character flag improvements:
Gives exact matches priority for shortcut flags (-a) and supports equal signs with single-character args (-a=10 should be OK) PiperOrigin-RevId: 216056777 Change-Id: I2fdf96842b59b2b90c15b384a13997b800c538c4 Reviewed-on: https://team-review.git.corp.google.com/c/332035 Reviewed-by: David Bieber <dbieber@google.com>
1 parent 53a3498 commit fe1fda4

2 files changed

Lines changed: 88 additions & 50 deletions

File tree

‎fire/core.py‎

Lines changed: 69 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -129,12 +129,11 @@ def Fire(component=None, command=None, name=None):
129129
component_trace = _Fire(component, args, context, name)
130130

131131
if component_trace.HasError():
132-
for help_flag in ['-h', '--help']:
132+
for help_flag in ('-h', '--help'):
133133
if help_flag in component_trace.elements[-1].args:
134134
command = '{cmd} -- --help'.format(cmd=component_trace.GetCommand())
135-
print(('WARNING: The proper way to show help is {cmd}.\n'
136-
'Showing help anyway.\n').format(cmd=pipes.quote(command)),
137-
file=sys.stderr)
135+
print('INFO: Showing help with the command {cmd}.\n'.format(
136+
cmd=pipes.quote(command)), file=sys.stderr)
138137
_PrintError(component_trace)
139138
raise FireExit(2, component_trace)
140139
elif component_trace.show_trace and component_trace.show_help:
@@ -209,9 +208,7 @@ def _IsHelpShortcut(component_trace, remaining_args):
209208
show_help = False
210209
if remaining_args:
211210
target = remaining_args[0]
212-
if target == '-h':
213-
show_help = True
214-
elif target == '--help':
211+
if target in ('-h', '--help'):
215212
# Check if --help would be consumed as a keyword argument, or is a member.
216213
component = component_trace.GetResult()
217214
if inspect.isclass(component) or inspect.isroutine(component):
@@ -487,7 +484,7 @@ def _Fire(component, args, context, name=None):
487484
component_trace.AddError(error, initial_args)
488485
return component_trace
489486

490-
# If we can't access the member, we try to treat component as a callable
487+
# If we can't access the member, try to treat component as a callable.
491488
try:
492489
component, remaining_args = _CallAndUpdateTrace(component,
493490
remaining_args,
@@ -589,9 +586,9 @@ def _CallAndUpdateTrace(component, args, component_trace, treatment='class',
589586
args: Args for calling the component
590587
component_trace: FireTrace object that contains action trace
591588
treatment: Type of treatment used. Indicating whether we treat the component
592-
as a class, a routine, or a callable.
589+
as a class, a routine, or a callable.
593590
target: Target in FireTrace element, default is None. If the value is None,
594-
the component itself will be used as target.
591+
the component itself will be used as target.
595592
Returns:
596593
component: The object that is the result of the callable call.
597594
remaining_args: The remaining args that haven't been consumed yet.
@@ -791,33 +788,53 @@ def _ParseKeywordArgs(args, fn_spec):
791788
skip_argument = False
792789
continue
793790

794-
arg_consumed = False
795791
if _IsFlag(argument):
796-
# This is a named argument; get its value from this arg or the next.
797-
got_argument = False
798-
799-
keyword = ''
800-
if _IsSingleCharFlag(argument):
801-
keychar = argument.lstrip('-')
802-
potential_args = [arg for arg in fn_args if arg[0] == keychar]
803-
if len(potential_args) == 1:
804-
keyword = potential_args[0]
805-
elif len(potential_args) > 1:
806-
raise FireError("The argument '{}' is ambiguous as it could "
807-
"refer to any of the following arguments: {}".format(
808-
argument, potential_args))
792+
# This is a named argument. We get its value from this arg or the next.
793+
794+
# Terminology:
795+
# argument: A full token from the command line, e.g. '--alpha=10'
796+
# stripped_argument: An argument without leading hyphens.
797+
# key: The contents of the stripped argument up to the first equal sign.
798+
# "shortcut flag": refers to an argument where the key is just the first
799+
# letter of a longer keyword.
800+
# keyword: The Python function argument being set by this argument.
801+
# value: The unparsed value for that Python function argument.
802+
contains_equals = '=' in argument
803+
stripped_argument = argument.lstrip('-')
804+
if contains_equals:
805+
key, value = stripped_argument.split('=', 1)
809806
else:
810-
keyword = argument.lstrip('-')
807+
key = stripped_argument
811808

812-
contains_equals = '=' in keyword
809+
key = key.replace('-', '_')
813810
is_bool_syntax = (not contains_equals and
814811
(index + 1 == len(args) or _IsFlag(args[index + 1])))
815-
if contains_equals:
816-
keyword, value = keyword.split('=', 1)
812+
813+
# Determine the keyword.
814+
keyword = '' # Indicates no valid keyword has been found yet.
815+
if (key in fn_args
816+
or (is_bool_syntax and key.startswith('no') and key[2:] in fn_args)
817+
or fn_keywords):
818+
keyword = key
819+
elif len(key) == 1:
820+
# This may be a shortcut flag.
821+
matching_fn_args = [arg for arg in fn_args if arg[0] == key]
822+
if len(matching_fn_args) == 1:
823+
keyword = matching_fn_args[0]
824+
elif len(matching_fn_args) > 1:
825+
raise FireError("The argument '{}' is ambiguous as it could "
826+
"refer to any of the following arguments: {}".format(
827+
argument, matching_fn_args))
828+
829+
# Determine the value.
830+
if not keyword:
831+
got_argument = False
832+
elif contains_equals:
833+
# Already got the value above.
817834
got_argument = True
818835
elif is_bool_syntax:
819-
# Since there's no next arg or the next arg is a Flag, we consider
820-
# this flag to be a boolean.
836+
# There's no next arg or the next arg is a Flag, so we consider this
837+
# flag to be a boolean.
821838
got_argument = True
822839
if keyword in fn_args:
823840
value = 'True'
@@ -827,40 +844,44 @@ def _ParseKeywordArgs(args, fn_spec):
827844
else:
828845
value = 'True'
829846
else:
830-
if index + 1 < len(args):
831-
value = args[index + 1]
832-
got_argument = True
833-
834-
keyword = keyword.replace('-', '_')
847+
# The assert should pass. Otherwise either contains_equals or
848+
# is_bool_syntax would have been True.
849+
assert index + 1 < len(args)
850+
value = args[index + 1]
851+
got_argument = True
835852

836853
# In order for us to consume the argument as a keyword arg, we either:
837854
# Need to be explicitly expecting the keyword, or we need to be
838855
# accepting **kwargs.
856+
skip_argument = not contains_equals and not is_bool_syntax
839857
if got_argument:
840-
skip_argument = not contains_equals and not is_bool_syntax
841-
arg_consumed = True
842-
if keyword in fn_args or fn_keywords:
843-
kwargs[keyword] = value
844-
else:
845-
remaining_kwargs.append(argument)
846-
if skip_argument:
847-
remaining_kwargs.append(args[index + 1])
848-
849-
if not arg_consumed:
850-
# The argument was not consumed, so it is still a remaining argument.
858+
kwargs[keyword] = value
859+
else:
860+
remaining_kwargs.append(argument)
861+
if skip_argument:
862+
remaining_kwargs.append(args[index + 1])
863+
else: # not _IsFlag(argument)
851864
remaining_args.append(argument)
852865

853866
return kwargs, remaining_kwargs, remaining_args
854867

855868

856869
def _IsFlag(argument):
857-
"""Determines if the argument is a flag argument."""
870+
"""Determines if the argument is a flag argument.
871+
872+
If it starts with a hyphen and isn't a negative number, it's a flag.
873+
874+
Args:
875+
argument: A command line argument that may or may not be a flag.
876+
Returns:
877+
A boolean indicating whether the argument is a flag.
878+
"""
858879
return _IsSingleCharFlag(argument) or _IsMultiCharFlag(argument)
859880

860881

861882
def _IsSingleCharFlag(argument):
862883
"""Determines if the argument is a single char flag (e.g. '-a')."""
863-
return re.match('^-[a-zA-Z]$', argument)
884+
return re.match('^-[a-zA-Z]$', argument) or re.match('^-[a-zA-Z]=', argument)
864885

865886

866887
def _IsMultiCharFlag(argument):

‎fire/fire_test.py‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -441,10 +441,27 @@ def testSingleCharFlagParsing(self):
441441
command=['identity', '--alpha', 'True', '-b', '10']),
442442
(True, 10))
443443
with self.assertRaisesFireExit(2):
444-
# This test attempts to use a boolean shortcut on a function with
445-
# a naming conflict for the shortcut, triggering a FireError
444+
# This test attempts to use an ambiguous shortcut flag on a function with
445+
# a naming conflict for the shortcut, triggering a FireError.
446446
fire.Fire(tc.SimilarArgNames, command=['identity', '-b'])
447447

448+
def testSingleCharFlagParsingEqualSign(self):
449+
self.assertEqual(
450+
fire.Fire(tc.MixedDefaults,
451+
command=['identity', '-a=True']), (True, '0'))
452+
self.assertEqual(
453+
fire.Fire(tc.MixedDefaults,
454+
command=['identity', '-a=3', '--beta=10']), (3, 10))
455+
self.assertEqual(
456+
fire.Fire(tc.MixedDefaults,
457+
command=['identity', '-a=False', '-b=15']), (False, 15))
458+
self.assertEqual(
459+
fire.Fire(tc.MixedDefaults,
460+
command=['identity', '-a', '42', '-b=12']), (42, 12))
461+
self.assertEqual(
462+
fire.Fire(tc.MixedDefaults,
463+
command=['identity', '-a=42', '-b', '10']), (42, 10))
464+
448465
def testSingleCharFlagParsingCapitalLetter(self):
449466
self.assertEqual(
450467
fire.Fire(tc.CapitalizedArgNames,

0 commit comments

Comments
 (0)