linux-doc.vger.kernel.org archive mirror
 help / color / mirror / Atom feed
From: Mauro Carvalho Chehab <mchehab+huawei@kernel.org>
To: Jonathan Corbet <corbet@lwn.net>,
	Linux Doc Mailing List <linux-doc@vger.kernel.org>
Cc: Mauro Carvalho Chehab <mchehab+huawei@kernel.org>,
	"Mauro Carvalho Chehab" <mchehab+huawei@kernel.org>,
	linux-kernel@vger.kernel.org
Subject: [PATCH v2 03/24] docs: parse-headers.py: improve --help logic
Date: Fri, 22 Aug 2025 16:19:15 +0200	[thread overview]
Message-ID: <2c1e61d1fb1b2a2838b443beee89c1528831997f.1755872208.git.mchehab+huawei@kernel.org> (raw)
In-Reply-To: <cover.1755872208.git.mchehab+huawei@kernel.org>

When printing --help, we'd like the name of the files
from __doc__ to match the displayed positional arguments at
both usage and argument description lines.

Use a custom formatter class to convert ``foo`` into ANSI SGR
code to bold the argument, if is TTY, and adjust the help
text to match the argument names.

Here on Plasma, that makes it display it colored, wich is
really cool. Yet, I opted for SGR, as the best is to follow
the terminal color schema for bold.

Signed-off-by: Mauro Carvalho Chehab <mchehab+huawei@kernel.org>
---
 Documentation/sphinx/parse-headers.py | 67 +++++++++++++++++++++++----
 1 file changed, 58 insertions(+), 9 deletions(-)

diff --git a/Documentation/sphinx/parse-headers.py b/Documentation/sphinx/parse-headers.py
index b39284d21090..650f9c9a68d1 100755
--- a/Documentation/sphinx/parse-headers.py
+++ b/Documentation/sphinx/parse-headers.py
@@ -4,20 +4,20 @@
 # pylint: disable=C0103,R0902,R0912,R0914,R0915
 
 """
-Convert a C header or source file (C_FILE), into a ReStructured Text
+Convert a C header or source file ``FILE_IN``, into a ReStructured Text
 included via ..parsed-literal block with cross-references for the
 documentation files that describe the API. It accepts an optional
-EXCEPTIONS_FILE with describes what elements will be either ignored or
-be pointed to a non-default reference.
+``FILE_RULES`` file to describes what elements will be either ignored or
+be pointed to a non-default reference type/name.
 
-The output is written at the (OUT_FILE).
+The output is written at ``FILE_OUT``.
 
 It is capable of identifying defines, functions, structs, typedefs,
 enums and enum symbols and create cross-references for all of them.
 It is also capable of distinguish #define used for specifying a Linux
 ioctl.
 
-The EXCEPTIONS_FILE contains a set of rules like:
+The optional ``FILE_RULES`` contains a set of rules like:
 
     ignore ioctl VIDIOC_ENUM_FMT
     replace ioctl VIDIOC_DQBUF vidioc_qbuf
@@ -400,17 +400,66 @@ class ParseHeader:
             f.write("\n\n.. parsed-literal::\n\n")
             f.write(text)
 
+class EnrichFormatter(argparse.HelpFormatter):
+    """
+    Better format the output, making easier to identify the positional args
+    and how they're used at the __doc__ description.
+    """
+    def __init__(self, *args, **kwargs):
+        """Initialize class and check if is TTY"""
+        super().__init__(*args, **kwargs)
+        self._tty = sys.stdout.isatty()
+
+    def enrich_text(self, text):
+        """Handle ReST markups (currently, only ``foo``)"""
+        if self._tty and text:
+            # Replace ``text`` with ANSI bold
+            return re.sub(r'\`\`(.+?)\`\`',
+                          lambda m: f'\033[1m{m.group(1)}\033[0m', text)
+        return text
+
+    def _fill_text(self, text, width, indent):
+        """Enrich descriptions with markups on it"""
+        enriched = self.enrich_text(text)
+        return "\n".join(indent + line for line in enriched.splitlines())
+
+    def _format_usage(self, usage, actions, groups, prefix):
+        """Enrich positional arguments at usage: line"""
+
+        prog = self._prog
+        parts = []
+
+        for action in actions:
+            if action.option_strings:
+                opt = action.option_strings[0]
+                if action.nargs != 0:
+                    opt += f" {action.dest.upper()}"
+                parts.append(f"[{opt}]")
+            else:
+                # Positional argument
+                parts.append(self.enrich_text(f"``{action.dest.upper()}``"))
+
+        usage_text = f"{prefix or 'usage: '} {prog} {' '.join(parts)}\n"
+        return usage_text
+
+    def _format_action_invocation(self, action):
+        """Enrich argument names"""
+        if not action.option_strings:
+            return self.enrich_text(f"``{action.dest.upper()}``")
+        else:
+            return ", ".join(action.option_strings)
+
 
 def main():
     """Main function"""
     parser = argparse.ArgumentParser(description=__doc__,
-                                     formatter_class=argparse.RawDescriptionHelpFormatter)
+                                     formatter_class=EnrichFormatter)
 
     parser.add_argument("-d", "--debug", action="count", default=0,
                         help="Increase debug level. Can be used multiple times")
     parser.add_argument("file_in", help="Input C file")
     parser.add_argument("file_out", help="Output RST file")
-    parser.add_argument("file_exceptions", nargs="?",
+    parser.add_argument("file_rules", nargs="?",
                         help="Exceptions file (optional)")
 
     args = parser.parse_args()
@@ -418,8 +467,8 @@ def main():
     parser = ParseHeader(debug=args.debug)
     parser.parse_file(args.file_in)
 
-    if args.file_exceptions:
-        parser.process_exceptions(args.file_exceptions)
+    if args.file_rules:
+        parser.process_exceptions(args.file_rules)
 
     parser.debug_print()
     parser.write_output(args.file_in, args.file_out)
-- 
2.50.1


  parent reply	other threads:[~2025-08-22 14:19 UTC|newest]

Thread overview: 27+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2025-08-22 14:19 [PATCH v2 00/24] better handle media headers Mauro Carvalho Chehab
2025-08-22 14:19 ` [PATCH v2 01/24] docs: parse-headers.pl: improve its debug output format Mauro Carvalho Chehab
2025-08-22 14:19 ` [PATCH v2 02/24] docs: parse-headers.py: convert parse-headers.pl Mauro Carvalho Chehab
2025-08-22 14:19 ` Mauro Carvalho Chehab [this message]
2025-08-22 14:19 ` [PATCH v2 04/24] docs: parse-headers.py: better handle @var arguments Mauro Carvalho Chehab
2025-08-22 14:19 ` [PATCH v2 05/24] docs: parse-headers.py: simplify the rules for hashes Mauro Carvalho Chehab
2025-08-22 14:19 ` [PATCH v2 06/24] tools: docs: parse-headers.py: move it from sphinx dir Mauro Carvalho Chehab
2025-08-22 14:19 ` [PATCH v2 07/24] tools: docs: parse_data_structs.py: add methods to return output Mauro Carvalho Chehab
2025-08-22 14:19 ` [PATCH v2 08/24] MAINTAINERS: add files from tools/docs to documentation entry Mauro Carvalho Chehab
2025-08-22 14:19 ` [PATCH v2 09/24] docs: uapi: media: Makefile: use parse-headers.py Mauro Carvalho Chehab
2025-08-22 14:19 ` [PATCH v2 10/24] docs: kernel_include.py: Update its coding style Mauro Carvalho Chehab
2025-08-22 14:19 ` [PATCH v2 11/24] docs: kernel_include.py: allow cross-reference generation Mauro Carvalho Chehab
2025-08-22 14:19 ` [PATCH v2 12/24] docs: kernel_include.py: generate warnings for broken refs Mauro Carvalho Chehab
2025-08-22 14:19 ` [PATCH v2 13/24] docs: kernel_include.py: move rawtext logic to separate functions Mauro Carvalho Chehab
2025-08-22 14:19 ` [PATCH v2 14/24] docs: kernel_include.py: move range logic to a separate function Mauro Carvalho Chehab
2025-08-22 14:19 ` [PATCH v2 15/24] docs: kernel_include.py: remove range restriction for gen docs Mauro Carvalho Chehab
2025-08-22 14:19 ` [PATCH v2 16/24] docs: kernel_include.py: move code and literal functions Mauro Carvalho Chehab
2025-08-22 14:19 ` [PATCH v2 17/24] docs: kernel_include.py: add support to generate a TOC table Mauro Carvalho Chehab
2025-08-22 14:19 ` [PATCH v2 18/24] docs: kernel_include.py: append line numbers to better report errors Mauro Carvalho Chehab
2025-08-22 14:19 ` [PATCH v2 19/24] docs: kernel_include.py: move apply_range() and add a docstring Mauro Carvalho Chehab
2025-08-22 14:19 ` [PATCH v2 20/24] docs: kernel_include.py: remove line numbers from parsed-literal Mauro Carvalho Chehab
2025-08-22 14:19 ` [PATCH v2 21/24] docs: kernel_include.py: remove Include class inheritance Mauro Carvalho Chehab
2025-08-22 14:19 ` [PATCH v2 22/24] docs: kernel_include.py: document all supported parameters Mauro Carvalho Chehab
2025-08-22 14:19 ` [PATCH v2 23/24] scripts: sphinx-build-wrapper: get rid of uapi/media Makefile Mauro Carvalho Chehab
2025-08-22 14:32   ` Mauro Carvalho Chehab
2025-08-22 14:19 ` [PATCH v2 24/24] docs: sphinx: drop parse-headers.pl Mauro Carvalho Chehab
2025-08-29 22:03 ` [PATCH v2 00/24] better handle media headers Jonathan Corbet

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=2c1e61d1fb1b2a2838b443beee89c1528831997f.1755872208.git.mchehab+huawei@kernel.org \
    --to=mchehab+huawei@kernel.org \
    --cc=corbet@lwn.net \
    --cc=linux-doc@vger.kernel.org \
    --cc=linux-kernel@vger.kernel.org \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).