Path: blob/master/tools/lib/python/kdoc/enrich_formatter.py
122941 views
#!/usr/bin/env python31# SPDX-License-Identifier: GPL-2.02# Copyright (c) 2025 by Mauro Carvalho Chehab <[email protected]>.34"""5Ancillary argparse HelpFormatter class that works on a similar way as6argparse.RawDescriptionHelpFormatter, e.g. description maintains line7breaks, but it also implement transformations to the help text. The8actual transformations ar given by enrich_text(), if the output is tty.910Currently, the follow transformations are done:1112- Positional arguments are shown in upper cases;13- if output is TTY, ``var`` and positional arguments are shown prepended14by an ANSI SGR code. This is usually translated to bold. On some15terminals, like, konsole, this is translated into a colored bold text.16"""1718import argparse19import re20import sys2122class EnrichFormatter(argparse.HelpFormatter):23"""24Better format the output, making easier to identify the positional args25and how they're used at the __doc__ description.26"""27def __init__(self, *args, **kwargs):28"""29Initialize class and check if is TTY.30"""31super().__init__(*args, **kwargs)32self._tty = sys.stdout.isatty()3334def enrich_text(self, text):35r"""36Handle ReST markups (currently, only \`\`text\`\` markups).37"""38if self._tty and text:39# Replace ``text`` with ANSI SGR (bold)40return re.sub(r'\`\`(.+?)\`\`',41lambda m: f'\033[1m{m.group(1)}\033[0m', text)42return text4344def _fill_text(self, text, width, indent):45"""46Enrich descriptions with markups on it.47"""48enriched = self.enrich_text(text)49return "\n".join(indent + line for line in enriched.splitlines())5051def _format_usage(self, usage, actions, groups, prefix):52"""53Enrich positional arguments at usage: line.54"""5556prog = self._prog57parts = []5859for action in actions:60if action.option_strings:61opt = action.option_strings[0]62if action.nargs != 0:63opt += f" {action.dest.upper()}"64parts.append(f"[{opt}]")65else:66# Positional argument67parts.append(self.enrich_text(f"``{action.dest.upper()}``"))6869usage_text = f"{prefix or 'usage: '} {prog} {' '.join(parts)}\n"70return usage_text7172def _format_action_invocation(self, action):73"""74Enrich argument names.75"""76if not action.option_strings:77return self.enrich_text(f"``{action.dest.upper()}``")7879return ", ".join(action.option_strings)808182