summaryrefslogtreecommitdiff
path: root/dev-build/meson-format-array/files/meson-format-array.py
diff options
context:
space:
mode:
authorMike Gilbert <floppym@gentoo.org>2024-07-18 11:57:51 -0400
committerMike Gilbert <floppym@gentoo.org>2024-07-18 11:57:51 -0400
commit8d06d85786d65f354a2d8a73c33958a4b7175200 (patch)
treee80783bcaff34fa3335d121c2179a7569fa13fd3 /dev-build/meson-format-array/files/meson-format-array.py
parentc7853417493e40ea6c96346726d8c797098dc267 (diff)
downloadgentoo-8d06d85786d65f354a2d8a73c33958a4b7175200.tar.gz
gentoo-8d06d85786d65f354a2d8a73c33958a4b7175200.tar.bz2
gentoo-8d06d85786d65f354a2d8a73c33958a4b7175200.zip
dev-build/meson-format-array: add some doctests
Signed-off-by: Mike Gilbert <floppym@gentoo.org>
Diffstat (limited to 'dev-build/meson-format-array/files/meson-format-array.py')
-rw-r--r--dev-build/meson-format-array/files/meson-format-array.py43
1 files changed, 43 insertions, 0 deletions
diff --git a/dev-build/meson-format-array/files/meson-format-array.py b/dev-build/meson-format-array/files/meson-format-array.py
new file mode 100644
index 000000000000..84a490cf29eb
--- /dev/null
+++ b/dev-build/meson-format-array/files/meson-format-array.py
@@ -0,0 +1,43 @@
+#!/usr/bin/env python3
+# Copyright 2020 Gentoo Authors
+# Distributed under the terms of the GNU General Public License v2
+
+import itertools
+import shlex
+import sys
+
+
+def quote(s):
+ """ Surround a value with quotes, escape embedded quotes.
+ >>> quote("foo'bar")
+ "'foo\\\\'bar'"
+ """
+
+ return "'" + s.replace("\\", "\\\\").replace("'", "\\'") + "'"
+
+
+def format_array(args):
+ """ Format shell-compatible expressions as a meson array.
+ >>> format_array(['-O2 -pipe -DFOO="bar baz"'])
+ "['-O2', '-pipe', '-DFOO=bar baz']"
+ """
+
+ # Split each argument according to shell rules
+ args = (shlex.split(x) for x in args)
+
+ # Flatten the resulting list of lists
+ args = itertools.chain.from_iterable(args)
+
+ # Add quotes and escape embedded quotes
+ args = (quote(x) for x in args)
+
+ # Format the result
+ return "[" + ", ".join(args) + "]"
+
+
+def main(args):
+ print(format_array(args))
+
+
+if __name__ == "__main__":
+ main(sys.argv[1:])