[elbe-devel] [PATCH 1/2] elbepack: add helper for declarative commandline parsing
Thomas Weißschuh
thomas.weissschuh at linutronix.de
Wed Jul 10 12:32:48 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 | 34 ++++++++++++++++++++++++++++++++++
2 files changed, 35 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..0bf0b1ec8d26
--- /dev/null
+++ b/elbepack/cli.py
@@ -0,0 +1,34 @@
+# 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)
+ attr.append((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`.
+ """
+ attr = getattr(f, _decorator_argparse_attr, None)
+ if attr is None:
+ return
+
+ for args, kwargs in attr:
+ parser.add_argument(*args, **kwargs)
--
2.45.2
More information about the elbe-devel
mailing list