Path: blob/master/tools/lib/python/kdoc/enrich_formatter.py
38186 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"""Initialize class and check if is TTY"""29super().__init__(*args, **kwargs)30self._tty = sys.stdout.isatty()3132def enrich_text(self, text):33"""Handle ReST markups (currently, only ``foo``)"""34if self._tty and text:35# Replace ``text`` with ANSI SGR (bold)36return re.sub(r'\`\`(.+?)\`\`',37lambda m: f'\033[1m{m.group(1)}\033[0m', text)38return text3940def _fill_text(self, text, width, indent):41"""Enrich descriptions with markups on it"""42enriched = self.enrich_text(text)43return "\n".join(indent + line for line in enriched.splitlines())4445def _format_usage(self, usage, actions, groups, prefix):46"""Enrich positional arguments at usage: line"""4748prog = self._prog49parts = []5051for action in actions:52if action.option_strings:53opt = action.option_strings[0]54if action.nargs != 0:55opt += f" {action.dest.upper()}"56parts.append(f"[{opt}]")57else:58# Positional argument59parts.append(self.enrich_text(f"``{action.dest.upper()}``"))6061usage_text = f"{prefix or 'usage: '} {prog} {' '.join(parts)}\n"62return usage_text6364def _format_action_invocation(self, action):65"""Enrich argument names"""66if not action.option_strings:67return self.enrich_text(f"``{action.dest.upper()}``")6869return ", ".join(action.option_strings)707172