Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
torvalds
GitHub Repository: torvalds/linux
Path: blob/master/tools/docs/lib/enrich_formatter.py
29520 views
1
#!/usr/bin/env python3
2
# SPDX-License-Identifier: GPL-2.0
3
# Copyright (c) 2025 by Mauro Carvalho Chehab <[email protected]>.
4
5
"""
6
Ancillary argparse HelpFormatter class that works on a similar way as
7
argparse.RawDescriptionHelpFormatter, e.g. description maintains line
8
breaks, but it also implement transformations to the help text. The
9
actual transformations ar given by enrich_text(), if the output is tty.
10
11
Currently, the follow transformations are done:
12
13
- Positional arguments are shown in upper cases;
14
- if output is TTY, ``var`` and positional arguments are shown prepended
15
by an ANSI SGR code. This is usually translated to bold. On some
16
terminals, like, konsole, this is translated into a colored bold text.
17
"""
18
19
import argparse
20
import re
21
import sys
22
23
class EnrichFormatter(argparse.HelpFormatter):
24
"""
25
Better format the output, making easier to identify the positional args
26
and how they're used at the __doc__ description.
27
"""
28
def __init__(self, *args, **kwargs):
29
"""Initialize class and check if is TTY"""
30
super().__init__(*args, **kwargs)
31
self._tty = sys.stdout.isatty()
32
33
def enrich_text(self, text):
34
"""Handle ReST markups (currently, only ``foo``)"""
35
if self._tty and text:
36
# Replace ``text`` with ANSI SGR (bold)
37
return re.sub(r'\`\`(.+?)\`\`',
38
lambda m: f'\033[1m{m.group(1)}\033[0m', text)
39
return text
40
41
def _fill_text(self, text, width, indent):
42
"""Enrich descriptions with markups on it"""
43
enriched = self.enrich_text(text)
44
return "\n".join(indent + line for line in enriched.splitlines())
45
46
def _format_usage(self, usage, actions, groups, prefix):
47
"""Enrich positional arguments at usage: line"""
48
49
prog = self._prog
50
parts = []
51
52
for action in actions:
53
if action.option_strings:
54
opt = action.option_strings[0]
55
if action.nargs != 0:
56
opt += f" {action.dest.upper()}"
57
parts.append(f"[{opt}]")
58
else:
59
# Positional argument
60
parts.append(self.enrich_text(f"``{action.dest.upper()}``"))
61
62
usage_text = f"{prefix or 'usage: '} {prog} {' '.join(parts)}\n"
63
return usage_text
64
65
def _format_action_invocation(self, action):
66
"""Enrich argument names"""
67
if not action.option_strings:
68
return self.enrich_text(f"``{action.dest.upper()}``")
69
70
return ", ".join(action.option_strings)
71
72