[elbe-devel] [PATCH v2 3/5] elbepack: add helper for declarative commandline parsing

Thomas Weißschuh thomas.weissschuh at linutronix.de
Mon Jul 15 17:31:28 CEST 2024


These will be useful when migrating the Action-class-based subcommand
dispatcher to argparse.
And also when migrating the toplevel elbe subcommand dispatcher.

Signed-off-by: Thomas Weißschuh <thomas.weissschuh at linutronix.de>
---
 debian/python3-elbe-common.install |  1 +
 elbepack/cli.py                    | 32 ++++++++++++++++++++++++++++++++
 2 files changed, 33 insertions(+)

diff --git a/debian/python3-elbe-common.install b/debian/python3-elbe-common.install
index 2954d435e3e1..4b7706c5eb08 100644
--- a/debian/python3-elbe-common.install
+++ b/debian/python3-elbe-common.install
@@ -11,6 +11,7 @@ usr/lib/python3.*/*-packages/elbepack/aptpkgutils.py
 usr/lib/python3.*/*-packages/elbepack/aptprogress.py
 usr/lib/python3.*/*-packages/elbepack/archivedir.py
 usr/lib/python3.*/*-packages/elbepack/changelogxml.py
+usr/lib/python3.*/*-packages/elbepack/cli.py
 usr/lib/python3.*/*-packages/elbepack/config.py
 usr/lib/python3.*/*-packages/elbepack/debinstaller.py
 usr/lib/python3.*/*-packages/elbepack/default-preseed.xml
diff --git a/elbepack/cli.py b/elbepack/cli.py
new file mode 100644
index 000000000000..04889f0cea9b
--- /dev/null
+++ b/elbepack/cli.py
@@ -0,0 +1,32 @@
+# ELBE - Debian Based Embedded Rootfilesystem Builder
+# SPDX-License-Identifier: GPL-3.0-or-later
+# SPDX-FileCopyrightText: 2024 Linutronix GmbH
+
+_decorator_argparse_attr = '__' + __name__ + '.decorator_argparse'
+
+
+def add_argument(*args, **kwargs):
+    """
+    Record calls to :py:meth:`argparse.ArgumentParser.add_argument` to later be
+    applied by :py:func:`add_arguments_from_decorated_function`.
+    """
+    def decorator(f):
+        if not hasattr(f, _decorator_argparse_attr):
+            setattr(f, _decorator_argparse_attr, [])
+
+        attr = getattr(f, _decorator_argparse_attr)
+        # Decorators are evaluated inner-first, which means the bottom decorator is first.
+        # Invert the list to provide top-first behavior.
+        attr.insert(0, (args, kwargs))
+        return f
+
+    return decorator
+
+
+def add_arguments_from_decorated_function(parser, f):
+    """
+    Apply calls to :py:meth:`argparse.ArgumentParser.add_argument` recorded by
+    :py:func:`add_argument`.
+    """
+    for args, kwargs in getattr(f, _decorator_argparse_attr, []):
+        parser.add_argument(*args, **kwargs)

-- 
2.45.2



More information about the elbe-devel mailing list