Skip to content

Commit 0ea760c

Browse files
picnixzhugovkAA-Turner
committed
Parse str-flag options in blurb
Co-authored-by: Hugo van Kemenade <1324225+hugovk@users.noreply.github.com> Co-authored-by: Adam Turner <9087854+aa-turner@users.noreply.github.com>
1 parent 1fbf587 commit 0ea760c

File tree

1 file changed

+28
-3
lines changed

1 file changed

+28
-3
lines changed

src/blurb/blurb.py

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -766,7 +766,14 @@ def help(subcommand=None):
766766
for name, p in inspect.signature(fn).parameters.items():
767767
if p.kind == inspect.Parameter.KEYWORD_ONLY:
768768
short_option = name[0]
769-
options.append(f" [-{short_option}|--{name}]")
769+
if isinstance(p.default, bool):
770+
options.append(f" [-{short_option}|--{name}]")
771+
else:
772+
if p.default is None:
773+
metavar = f'{name.upper()}'
774+
else:
775+
metavar = f'{name.upper()}[={p.default}]'
776+
options.append(f" [-{short_option}|--{name} {metavar}]")
770777
elif p.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD:
771778
positionals.append(" ")
772779
has_default = (p.default != inspect._empty)
@@ -1169,22 +1176,37 @@ def main():
11691176
kwargs = {}
11701177
for name, p in inspect.signature(fn).parameters.items():
11711178
if p.kind == inspect.Parameter.KEYWORD_ONLY:
1172-
assert isinstance(p.default, bool), "blurb command-line processing only handles boolean options"
1179+
if (p.default is not None
1180+
and not isinstance(p.default, (bool, str))):
1181+
sys.exit("blurb command-line processing cannot handle "
1182+
f"options of type {type(p.default).__qualname__}")
1183+
11731184
kwargs[name] = p.default
11741185
short_options[name[0]] = name
11751186
long_options[name] = name
11761187

11771188
filtered_args = []
11781189
done_with_options = False
1190+
consume_after = None
11791191

11801192
def handle_option(s, dict):
1193+
nonlocal consume_after
11811194
name = dict.get(s, None)
11821195
if not name:
11831196
sys.exit(f'blurb: Unknown option for {subcommand}: "{s}"')
1184-
kwargs[name] = not kwargs[name]
1197+
1198+
value = kwargs[name]
1199+
if isinstance(value, bool):
1200+
kwargs[name] = not value
1201+
else:
1202+
consume_after = name
11851203

11861204
# print(f"short_options {short_options} long_options {long_options}")
11871205
for a in args:
1206+
if consume_after:
1207+
kwargs[consume_after] = a
1208+
consume_after = None
1209+
continue
11881210
if done_with_options:
11891211
filtered_args.append(a)
11901212
continue
@@ -1199,6 +1221,9 @@ def handle_option(s, dict):
11991221
continue
12001222
filtered_args.append(a)
12011223

1224+
if consume_after:
1225+
sys.exit(f"Error: blurb: {subcommand} {consume_after} "
1226+
f"must be followed by an option argument")
12021227

12031228
sys.exit(fn(*filtered_args, **kwargs))
12041229
except TypeError as e:

0 commit comments

Comments
 (0)