Commit 73fc5e01c2ad4af7912201fc938b234a2dc854ac

Carlos Martín Nieto 2013-09-06T21:12:26

config: fix variable overriding When two or more variables of the same name exist and the user asks for a scalar, we must return the latest value assign to it.

diff --git a/src/config_file.c b/src/config_file.c
index c835765..48a91eb 100644
--- a/src/config_file.c
+++ b/src/config_file.c
@@ -395,6 +395,7 @@ static int config_get(const git_config_backend *cfg, const char *name, const git
 	char *key;
 	khiter_t pos;
 	int error;
+	cvar_t *var;
 
 	if ((error = git_config__normalize_name(name, &key)) < 0)
 		return error;
@@ -406,7 +407,11 @@ static int config_get(const git_config_backend *cfg, const char *name, const git
 	if (!git_strmap_valid_index(b->values, pos))
 		return GIT_ENOTFOUND;
 
-	*out = ((cvar_t *)git_strmap_value_at(b->values, pos))->entry;
+	var = git_strmap_value_at(b->values, pos);
+	while (var->next)
+		var = var->next;
+
+	*out = var->entry;
 
 	return 0;
 }
diff --git a/tests-clar/config/include.c b/tests-clar/config/include.c
index 94669a5..f1019a9 100644
--- a/tests-clar/config/include.c
+++ b/tests-clar/config/include.c
@@ -71,3 +71,25 @@ void test_config_include__refresh(void)
 	git_config_free(cfg);
 	cl_fixture_cleanup("config");
 }
+
+/* We need to pretend that the variables were defined where the file was included */
+void test_config_include__ordering(void)
+{
+	git_config *cfg;
+	const char *str;
+
+	cl_git_mkfile("included", "[foo \"bar\"]\nbaz = hurrah\nfrotz = hiya");
+	cl_git_mkfile("including",
+		      "[foo \"bar\"]\nfrotz = hello\n"
+		      "[include]\npath = included\n"
+		      "[foo \"bar\"]\nbaz = huzzah\n");
+
+	cl_git_pass(git_config_open_ondisk(&cfg, "including"));
+
+	cl_git_pass(git_config_get_string(&str, cfg, "foo.bar.frotz"));
+	cl_assert_equal_s(str, "hiya");
+	cl_git_pass(git_config_get_string(&str, cfg, "foo.bar.baz"));
+	cl_assert_equal_s(str, "huzzah");
+
+	git_config_free(cfg);
+}
diff --git a/tests-clar/config/read.c b/tests-clar/config/read.c
index 395f1cf..722a15a 100644
--- a/tests-clar/config/read.c
+++ b/tests-clar/config/read.c
@@ -523,3 +523,18 @@ void test_config_read__corrupt_header(void)
 
 	git_config_free(cfg);
 }
+
+void test_config_read__override_variable(void)
+{
+	git_config *cfg;
+	const char *str;
+
+	cl_set_cleanup(&clean_test_config, NULL);
+	cl_git_mkfile("./testconfig", "[some] var = one\nvar = two");
+	cl_git_pass(git_config_open_ondisk(&cfg, "./testconfig"));
+
+	cl_git_pass(git_config_get_string(&str, cfg, "some.var"));
+	cl_assert_equal_s(str, "two");
+
+	git_config_free(cfg);
+}