Compare commits

...

4 Commits

Author SHA1 Message Date
Jakub Roztocil
ebb767ce77 render_description() and layout exploration 2022-05-05 16:53:54 +02:00
Batuhan Taskaya
3afe01bb8e x 2022-05-04 00:51:44 +03:00
Batuhan Taskaya
28e61e472f Prioritize pie styles. 2022-04-29 13:53:38 +03:00
Batuhan Taskaya
977f97d070 Display all choices on --help 2022-04-29 13:01:23 +03:00
4 changed files with 65 additions and 47 deletions

View File

@ -112,8 +112,7 @@ positional_arguments.add_argument(
search==httpie
'=' Data fields to be serialized into a JSON object (with --json, -j)
or form data (with --form, -f):
'=' Data fields to be serialized into a JSON object (with --json, -j) or form data (with --form, -f):
name=HTTPie language=Python description='CLI HTTP client'
@ -246,7 +245,7 @@ def format_style_help(available_styles, *, isolation_mode: bool = False):
text = """
Output coloring style (default is "{default}"). It can be one of:
{available_styles}
{available_styles}
"""
if isolation_mode:
text += '\n\n'
@ -472,8 +471,8 @@ output_options.add_argument(
requests/responses (such as redirects). For the second level and higher,
print these as well as the response metadata.
Level one is a shortcut for: --all --print={''.join(sorted(BASE_OUTPUT_OPTIONS))}
Level two is a shortcut for: --all --print={''.join(sorted(OUTPUT_OPTIONS))}
-v (level one) is a shortcut for: --all --print={''.join(sorted(BASE_OUTPUT_OPTIONS))}
-vv (level two) is a shortcut for: --all --print={''.join(sorted(OUTPUT_OPTIONS))}
""",
)
output_options.add_argument(
@ -629,7 +628,7 @@ def format_auth_help(auth_plugins_mapping, *, isolation_mode: bool = False):
text = """
The authentication mechanism to be used. Defaults to "{default}".
{auth_types}
{auth_types}
"""
auth_plugins = list(auth_plugins_mapping.values())
@ -643,8 +642,8 @@ def format_auth_help(auth_plugins_mapping, *, isolation_mode: bool = False):
text += 'For finding out all available authentication types in your system, try:\n\n'
text += ' $ http --auth-type'
auth_types = '\n\n '.join(
'"{type}": {name}{package}{description}'.format(
auth_types = '\n'.join(
' "{type}": {name}{package}{description}'.format(
type=plugin.auth_type,
name=plugin.name,
package=(
@ -688,6 +687,7 @@ authentication.add_argument(
'-A',
action='lazy_choices',
default=None,
metavar='AUTH_TYPE',
getter=plugin_manager.get_auth_plugin_mapping,
sort=True,
cache=False,

View File

@ -137,6 +137,9 @@ class Argument(typing.NamedTuple):
configuration['choices'] = list(choices.load())
configuration['help'] = choices.help
if 'help' in configuration:
configuration['help'] = textwrap.dedent(configuration['help'])
result = {}
if self.aliases:
result['options'] = self.aliases.copy()

View File

@ -32,7 +32,10 @@ BUNDLED_STYLES = {
def get_available_styles():
return sorted(BUNDLED_STYLES | set(pygments.styles.get_all_styles()))
return [
*PIE_STYLE_NAMES,
*sorted(BUNDLED_STYLES | set(pygments.styles.get_all_styles()))
]
class ColorFormatter(FormatterPlugin):

View File

@ -1,5 +1,4 @@
import re
import textwrap
from typing import AbstractSet, Iterable, Optional, Tuple
from rich.console import RenderableType
@ -31,6 +30,7 @@ LEFT_INDENT_2 = (1, 0, 0, 2)
LEFT_INDENT_3 = (1, 0, 0, 3)
LEFT_INDENT_BOTTOM_3 = (0, 0, 1, 3)
SINGLE_NEWLINE_RE = re.compile(r"(?<!\n)\n(?!\n)")
class OptionsHighlighter(RegexHighlighter):
highlights = [
@ -42,6 +42,32 @@ class OptionsHighlighter(RegexHighlighter):
options_highlighter = OptionsHighlighter()
def render_description(raw: str) -> str:
final = []
line_break = '\n'
space = ' '
para = line_break + line_break
empty_line = False
for line in raw.splitlines():
if not line:
empty_line = True
continue
is_indented = line.startswith(space)
is_prev_indented = final and final[-1].startswith(space)
if not empty_line and not is_indented and final:
final.append(space)
elif empty_line:
final.append(para)
if is_prev_indented and is_indented:
final.append(line_break)
final.append(line)
empty_line = False
return ''.join(final)
def unpack_argument(
argument: Argument,
) -> Tuple[Text, Text]:
@ -138,67 +164,53 @@ def to_help_message(
if argument.is_hidden:
continue
raw_form = argument.serialize()
opt1, opt2 = unpack_argument(argument)
if opt2:
opt1.append('/')
opt1.append(opt2)
# Column for a metavar, if we have one
metavar = Text(style=STYLE_METAVAR)
metavar.append(argument.configuration.get('metavar', ''))
description = Text('')
if opt1 == metavar:
metavar = Text('')
raw_form = argument.serialize()
desc = raw_form.get('short_description', '')
if raw_form.get('choices'):
desc += ' (choices: '
desc += textwrap.shorten(
', '.join(raw_form.get('choices')),
MAX_CHOICE_CHARS,
metavar_text = argument.configuration.get('metavar', '')
if metavar_text and metavar_text != str(opt1):
description.append(
Text(metavar_text, style=STYLE_METAVAR)
)
desc += ')'
description.append('\n')
elif raw_form.get('choices'):
description.append(Text(f'{{{", ".join(raw_form["choices"])}}}', style=STYLE_METAVAR))
description.append('\n')
description_text = raw_form.get('description', '').strip()
description_text = render_description(description_text)
# description_text = SINGLE_NEWLINE_RE.sub(' ', description_text)
description.append(description_text)
description.append('\n')
rows = [
Padding(
options_highlighter(opt1),
LEFT_PADDING_2,
),
metavar,
options_highlighter(desc),
options_highlighter(description),
]
options_rows.append(rows)
if argument.configuration.get('nested_options'):
options_rows.extend(
[
(
Padding(
Text(
key,
style=STYLE_USAGE_OPTIONAL,
),
LEFT_PADDING_4,
),
value,
dec,
)
for key, value, dec in argument.nested_options
]
)
group_rows[group.name] = options_rows
options_table = Table(highlight=False, box=None, show_header=False)
# We use a table of two rows
# Row 1 is the option name (`-o/--option`)
# Row 2 is the metavar/ description
options_table = Table.grid(expand=True)
for group_name, options_rows in group_rows.items():
options_table.add_row(Text(), Text(), Text())
options_table.add_row(Text(), Text())
options_table.add_row(
Text(group_name, style=STYLE_SWITCH),
Text(),
Text(),
)
options_table.add_row(Text(), Text(), Text())
options_table.add_row(Text(), Text())
for row in options_rows:
options_table.add_row(*row)