From b13ab85b26b4fe4f022bdc0f9383ff019a654819 Mon Sep 17 00:00:00 2001
From: Nicolas Pope <nwpope@utu.fi>
Date: Sun, 14 Apr 2019 09:19:10 +0300
Subject: [PATCH] Merge patch config files

---
 common/cpp/src/configuration.cpp | 47 ++++++++++++++++++++++++--------
 1 file changed, 35 insertions(+), 12 deletions(-)

diff --git a/common/cpp/src/configuration.cpp b/common/cpp/src/configuration.cpp
index 4055e48a5..76e1eb99c 100644
--- a/common/cpp/src/configuration.cpp
+++ b/common/cpp/src/configuration.cpp
@@ -94,26 +94,49 @@ optional<string> locateFile(const string &name, const vector<string> &paths) {
 	return {};
 }
 
+/**
+ * Combine one json config with another patch json config.
+ */
+static bool mergeConfig(const string &path) {
+	ifstream i;
+	i.open(path);
+	if (i.is_open()) {
+		json t;
+		i >> t;
+		config.merge_patch(t);
+		return true;
+	} else {
+		return false;
+	}
+}
+
 /**
  * Find and load a JSON configuration file
  */
 static bool findConfiguration(const string &file, const vector<string> &paths,
 		const std::string &app) {
-	ifstream i;
+	bool found = false;
 	
-	if (file != "") i.open(file);
-
-	if (!i.is_open()) {
-		auto f = locateFile("config.json", paths);
-		if (!f) return false;
-		i.open(*f);
-	}
+	found |= mergeConfig(FTL_GLOBAL_CONFIG_ROOT "/config.json");
+	found |= mergeConfig(FTL_LOCAL_CONFIG_ROOT "/config.json");
+	found |= mergeConfig("./config.json");
 	
-	if (!i.is_open()) return false;
+	for (auto p : paths) {
+		if (is_directory(p)) {
+			found |= mergeConfig(p+"/config.json");
+		}
+	}
 	
-	i >> config;
-	config = config[app];
-	return true;
+	if (file != "") {
+		found |= mergeConfig(file);
+	}
+
+	if (found) {
+		config = config[app];
+		return true;
+	} else {
+		return false;
+	}
 }
 
 /**
-- 
GitLab