Previously we used a combination of grep, sed, awk magic, helper
scripts and a Makefile to extract the usage information of the
kas-container script to add it to the documentation. This has proven
problematic, as error detection is tricky and also we don't have precise
control over the generated layout.
To improve this, we move the processing to a sphinx extension. By that,
sphinx also knows about the dependency to the script and properly
handles re-builds on changes of the kas-container.
docs/Makefile | 16 +-
docs/_ext/sphinx_kas_container_usage.py | 190 ++++++++++++++++++++++++
docs/_man/kas-container.rst | 19 ++-
docs/conf.py | 3 +-
docs/userguide/kas-container.rst | 17 ++-
scripts/kas-container-usage-to-rst.sh | 41 -----
6 files changed, 221 insertions(+), 65 deletions(-)
create mode 100644 docs/_ext/sphinx_kas_container_usage.py
delete mode 100755 scripts/kas-container-usage-to-rst.sh
diff --git a/docs/Makefile b/docs/Makefile
index d41c38cd7..5de69c718 100644
--- a/docs/Makefile
+++ b/docs/Makefile
@@ -49,19 +49,19 @@ clean:
rm -rf $(BUILDDIR)/*
.PHONY: html
-html: kas-container-usage
+html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
.PHONY: dirhtml
-dirhtml: kas-container-usage
+dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
.PHONY: singlehtml
-singlehtml: kas-container-usage
+singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
@@ -154,16 +154,8 @@ text:
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
-kas-container-usage:
- @echo Generate kas-container usage documentation
- @mkdir -p $(BUILDDIR)
- @../kas-container --help | ../scripts/kas-container-usage-to-rst.sh | awk '/KAS-COMMANDS/ {exit} {print}' \
- > $(BUILDDIR)/kas-container-usage-synopsis.inc
- @../kas-container --help | ../scripts/kas-container-usage-to-rst.sh | awk '/KAS-COMMANDS/ {found=1} found' \
- > $(BUILDDIR)/kas-container-usage-options.inc
-
.PHONY: man
-man: kas-container-usage
+man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) -t man $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
diff --git a/docs/_ext/sphinx_kas_container_usage.py b/docs/_ext/sphinx_kas_container_usage.py
new file mode 100644
index 000000000..dfef54e26
--- /dev/null
+++ b/docs/_ext/sphinx_kas_container_usage.py
@@ -0,0 +1,190 @@
+# kas - setup tool for bitbake based projects
+#
+# Copyright (c) Siemens AG, 2017-2026
+#
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the 'Software'), to deal
+# in the Software without restriction, including without limitation the rights
+# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+# copies of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be
+# included in all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+# SOFTWARE.
+
+'''
+ This module provides the ``kas-container-usage`` directive that extracts
+ usage information from the ``kas-container`` script and renders it as RST.
+
+ Usage::
+
+ .. kas-container-usage:: synopsis
+ .. kas-container-usage:: options
+'''
+__license__ = 'MIT'
+__copyright__ = 'Copyright (c) Siemens AG, 2017-2026'
+
+import os
+import re
+import subprocess
+
+from docutils import nodes
+from docutils.parsers.rst import Directive
+from sphinx.application import Sphinx
+from typing import Dict, Union
+
+
+KAS_CONTAINER_SCRIPT = os.path.join(
+ os.path.dirname(__file__), '..', '..', 'kas-container')
+
+
+def _get_help_output():
+ """Run kas-container --help and return the raw output."""
+ result = subprocess.run(
+ [KAS_CONTAINER_SCRIPT, '--help'],
+ capture_output=True, text=True, check=True)
+ return result.stdout
+
+
+def _parse_help(text):
+ """
+ Parse the kas-container --help output into structured sections.
+
+ Returns a dict with:
+ - 'usage_lines': list of usage line strings
+ - 'commands': list of (name, description) tuples
+ - 'options': list of (flags, description) tuples
+ """
+ sections = re.split(
+ r'^(Usage:|Positional arguments:|Optional arguments:)\n?',
+ text, flags=re.MULTILINE)
+
+ # Build a mapping of section header to content
+ parts = {}
+ for i in range(1, len(sections), 2):
+ parts[sections[i]] = sections[i + 1]
+
+ return {
+ 'usage_lines': _parse_usage(parts.get('Usage:', '')),
+ 'commands': _parse_tabbed_entries(parts.get(
+ 'Positional arguments:', '')),
+ 'options': _parse_tabbed_entries(parts.get(
+ 'Optional arguments:', '')),
+ }
+
+
+def _parse_usage(text):
+ """Extract usage lines, strip leading 'kas-container' prefix context."""
+ return [line.strip() for line in text.splitlines() if line.strip()]
+
+
+def _parse_tabbed_entries(text):
+ """Parse lines of 'key<tab>description' into (key, description) tuples."""
+ # Unwrap continuation lines (whitespace-indented lines continuing previous)
+ text = re.sub(r'\n\s+\t\t\t', ' ', text)
+ entries = []
+ for line in text.splitlines():
+ match = re.match(r'^([^\t]+?)\t+(.*)$', line)
+ if match:
+ entries.append((match.group(1), match.group(2)))
+ return entries
+
+
+def _build_synopsis(parsed):
+ """Build docutils nodes for the synopsis section."""
+ code = nodes.literal_block(text='\n'.join(parsed['usage_lines']))
+ code['language'] = 'none'
+ return [code]
+
+
+def _build_options(parsed):
+ """Build docutils nodes for the commands and options sections."""
+ result = []
+
+ # Definition list for commands
+ dlist = nodes.definition_list()
+ for name, desc in parsed['commands']:
+ item = nodes.definition_list_item()
+ term = nodes.term()
+ term += nodes.strong(text=name)
+ item += term
+ defn = nodes.definition()
+ defn += nodes.paragraph('', nodes.Text(desc))
+ item += defn
+ dlist += item
+ result.append(dlist)
+
+ return result
+
+
+def _build_option_list(parsed):
+ """Build docutils nodes for the options section."""
+ # Option list for options
+ olist = nodes.option_list()
+ for flags, desc in parsed['options']:
+ item = nodes.option_list_item()
+ group = nodes.option_group()
+ for flag in flags.split(', '):
+ opt = nodes.option()
+ opt += nodes.option_string(text=flag)
+ group += opt
+ item += group
+ description = nodes.description()
+ description += nodes.paragraph('', nodes.Text(desc))
+ item += description
+ olist += item
+ return [olist]
+
+
+class KasContainerUsageDirective(Directive):
+ """
+ Directive to include kas-container usage information.
+
+ .. kas-container-usage:: synopsis
+ .. kas-container-usage:: options
+ """
+
+ required_arguments = 1
+ optional_arguments = 0
+ has_content = False
+ option_spec = {}
+
+ def run(self):
+ section = self.arguments[0]
+ if section not in ('synopsis', 'commands', 'options'):
+ self.state_machine.reporter.error(
+ f'Invalid kas-container-usage section: {section}. '
+ 'Must be "synopsis", "commands", or "options".',
+ line=self.lineno)
+ return []
+
+ env = self.state.document.settings.env
+ env.note_dependency(KAS_CONTAINER_SCRIPT)
+
+ help_output = _get_help_output()
+ parsed = _parse_help(help_output)
+
+ if section == 'synopsis':
+ return _build_synopsis(parsed)
+ elif section == 'commands':
+ return _build_options(parsed)
+ else:
+ return _build_option_list(parsed)
+
+
+def setup(app: Sphinx) -> Dict[str, Union[bool, str]]:
+ app.add_directive('kas-container-usage', KasContainerUsageDirective)
+
+ return {
+ 'parallel_read_safe': True,
+ 'parallel_write_safe': True,
+ 'version': '1.0',
+ }
diff --git a/docs/_man/kas-container.rst b/docs/_man/kas-container.rst
index 7c2c75cab..3d1cf7e2a 100644
--- a/docs/_man/kas-container.rst
+++ b/docs/_man/kas-container.rst
@@ -3,14 +3,25 @@
kas-container manpage
=====================
-.. include:: ../_build/kas-container-usage-synopsis.inc
+SYNOPSIS
+--------
+
+.. kas-container-usage:: synopsis
DESCRIPTION
-----------
.. include:: ../userguide/kas-container-description.inc
-.. include:: ../_build/kas-container-usage-options.inc
+KAS-CONTAINER COMMANDS
+----------------------
+
+.. kas-container-usage:: commands
+
+OPTIONS
+-------
+
+.. kas-container-usage:: options
SEE ALSO
--------
@@ -18,7 +29,3 @@ SEE ALSO
:manpage:`kas(1)`,
.. include:: _kas-man-footer.inc
-
-.. |SYNOPSIS| replace:: SYNOPSIS
-.. |OPTIONS| replace:: OPTIONS
-.. |KAS-COMMANDS| replace:: KAS-CONTAINER COMMANDS
diff --git a/docs/conf.py b/docs/conf.py
index 22722033a..96b5553f6 100644
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -43,7 +43,8 @@ extensions = [
'sphinx.ext.viewcode',
'sphinxarg.ext',
'sphinx_rtd_theme',
- 'sphinx_kas_schema'
+ 'sphinx_kas_schema',
+ 'sphinx_kas_container_usage'
]
# Add any paths that contain templates here, relative to this directory.
diff --git a/docs/userguide/kas-container.rst b/docs/userguide/kas-container.rst
index 0ace45a72..5e79234ca 100644
--- a/docs/userguide/kas-container.rst
+++ b/docs/userguide/kas-container.rst
@@ -3,10 +3,17 @@ Building in a Container
.. include:: kas-container-description.inc
-.. include:: ../_build/kas-container-usage-synopsis.inc
+Synopsis
+--------
-.. include:: ../_build/kas-container-usage-options.inc
+.. kas-container-usage:: synopsis
-.. |SYNOPSIS| replace:: Synopsis
-.. |OPTIONS| replace:: Options
-.. |KAS-COMMANDS| replace:: kas-container Commands
+kas-container Commands
+----------------------
+
+.. kas-container-usage:: commands
+
+Options
+-------
+
+.. kas-container-usage:: options
diff --git a/scripts/kas-container-usage-to-rst.sh b/scripts/kas-container-usage-to-rst.sh
deleted file mode 100755
index 5f112a852..000000000
--- a/scripts/kas-container-usage-to-rst.sh
+++ /dev/null
@@ -1,41 +0,0 @@
-#!/bin/sh
-#
-# kas - setup tool for bitbake based projects
-#
-# Copyright (c) Siemens AG, 2024
-#
-# Authors:
-# Felix Moessbauer <
felix.mo...@siemens.com>
-#
-# Permission is hereby granted, free of charge, to any person obtaining a copy
-# of this software and associated documentation files (the "Software"), to deal
-# in the Software without restriction, including without limitation the rights
-# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-# copies of the Software, and to permit persons to whom the Software is
-# furnished to do so, subject to the following conditions:
-#
-# The above copyright notice and this permission notice shall be
-# included in all copies or substantial portions of the Software.
-#
-# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-# SOFTWARE.
-
-# Extract the usage information of kas-container and convert it to rst
-# to be included in the documentation.
-
-cat - | \
- sed 's/^Usage:/|SYNOPSIS|\n----------\n/g' | \
- sed -e 's/^\s*kas-container /| kas-container /g' | \
- # unwrap long lines
- perl -0pe 's/\n\s\s+/ /g' | \
- sed 's/^Positional arguments:/|KAS-COMMANDS|\n--------------/g' | \
- # each commands starts with a new line
- sed -r 's/^(build|checkout|diff|dump|lock|shell|for-all-repos|clean|cleansstate|cleanall|purge|menu)\t\t*(.*)$/:\1: \2/g' | \
- sed 's/^Optional arguments:/|OPTIONS|\n---------/g' | \
- sed '/^You can force/d' | \
- cat
--
2.53.0