From 07b06d76be716fa82f18c7949c00f92208962d6a Mon Sep 17 00:00:00 2001
From: Max Kellermann <max@musicpd.org>
Date: Wed, 19 Jul 2017 20:47:17 +0200
Subject: [PATCH] {android,win32}/build.py: concatenate variables from the
 command line

---
 android/build.py        |  4 ++++
 python/build/cmdline.py | 29 +++++++++++++++++++++++++++++
 win32/build.py          |  4 ++++
 3 files changed, 37 insertions(+)
 create mode 100644 python/build/cmdline.py

diff --git a/android/build.py b/android/build.py
index a37432e13..3ec3d9ba3 100755
--- a/android/build.py
+++ b/android/build.py
@@ -154,5 +154,9 @@ configure = [
 
 ] + configure_args
 
+from build.cmdline import concatenate_cmdline_variables
+configure = concatenate_cmdline_variables(configure,
+    set(('CFLAGS', 'CXXFLAGS', 'CPPFLAGS', 'LDFLAGS', 'LIBS')))
+
 subprocess.check_call(configure, env=toolchain.env)
 subprocess.check_call(['/usr/bin/make', '--quiet', '-j12'], env=toolchain.env)
diff --git a/python/build/cmdline.py b/python/build/cmdline.py
new file mode 100644
index 000000000..50245f597
--- /dev/null
+++ b/python/build/cmdline.py
@@ -0,0 +1,29 @@
+def concatenate_cmdline_variables(src, names):
+    """Find duplicate variable declarations on the given source list, and
+    concatenate the values of those in the 'names' list."""
+
+    # the result list being constructed
+    dest = []
+
+    # a map of variable name to destination list index
+    positions = {}
+
+    for item in src:
+        i = item.find('=')
+        if i > 0:
+            # it's a variable
+            name = item[:i]
+            if name in names:
+                # it's a known variable
+                if name in positions:
+                    # already specified: concatenate instead of
+                    # appending it
+                    dest[positions[name]] += ' ' + item[i + 1:]
+                    continue
+                else:
+                    # not yet seen: append it and remember the list
+                    # index
+                    positions[name] = len(dest)
+        dest.append(item)
+
+    return dest
diff --git a/win32/build.py b/win32/build.py
index 1a08ba97f..037d8088e 100755
--- a/win32/build.py
+++ b/win32/build.py
@@ -112,5 +112,9 @@ configure = [
 
 ] + configure_args
 
+from build.cmdline import concatenate_cmdline_variables
+configure = concatenate_cmdline_variables(configure,
+    set(('CFLAGS', 'CXXFLAGS', 'CPPFLAGS', 'LDFLAGS', 'LIBS')))
+
 subprocess.check_call(configure, env=toolchain.env)
 subprocess.check_call(['/usr/bin/make', '--quiet', '-j12'], env=toolchain.env)