From 07da8dd413987ed8e604eba3fd21149453483fa0 Mon Sep 17 00:00:00 2001 From: Ethan Dalool Date: Tue, 6 Aug 2019 23:42:04 -0700 Subject: [PATCH] Add betterhelp.py --- voussoirkit/betterhelp.py | 65 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 voussoirkit/betterhelp.py diff --git a/voussoirkit/betterhelp.py b/voussoirkit/betterhelp.py new file mode 100644 index 0000000..b6da2cd --- /dev/null +++ b/voussoirkit/betterhelp.py @@ -0,0 +1,65 @@ +import functools + +def docstring_preview(text, indent=None): + text = text.split('\n\n')[0] + if indent: + text = _indent(text, spaces=indent) + return text + +def indent(text, spaces=4): + spaces = ' ' * spaces + return '\n'.join(spaces + line if line.strip() != '' else line for line in text.split('\n')) +_indent = indent + +def listget(li, index, fallback=None): + try: + return li[index] + except IndexError: + return fallback + +def add_previews(docstring, sub_docstrings): + previews = { + key: docstring_preview(value) + for (key, value) in sub_docstrings.items() + } + docstring = docstring.format(**previews) + return docstring + +def betterhelp(docstring): + def wrapper(main): + def wrapped(argv): + helpstrings = {'', 'help', '-h', '--help'} + + argument = listget(argv, 0, '').lower() + + if argument in helpstrings: + print(docstring) + return 1 + + return main(argv) + return wrapped + return wrapper + +def subparser_betterhelp(main_docstring, sub_docstrings): + def wrapper(main): + def wrapped(argv): + helpstrings = {'', 'help', '-h', '--help'} + + command = listget(argv, 0, '').lower() + + if command not in sub_docstrings: + print(main_docstring) + if command == '': + print('You are seeing the default help text because you did not choose a command.') + elif command not in helpstrings: + print(f'You are seeing the default help text because "{command}" was not recognized') + return 1 + + argument = listget(argv, 1, '').lower() + if argument in helpstrings: + print(sub_docstrings[command]) + return 1 + + return main(argv) + return wrapped + return wrapper