Fix adding variable to config file with no trailing newline This can occur after a manual modification of a config file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
diff --git a/src/config_file.c b/src/config_file.c
index 4ba83d1..12ae4a2 100644
--- a/src/config_file.c
+++ b/src/config_file.c
@@ -1182,6 +1182,10 @@ static int config_write(diskfile_backend *cfg, const char *key, const regex_t *p
goto rewrite_fail;
}
+ /* If we are here, there is at least a section line */
+ if (*(cfg->reader.buffer.ptr + cfg->reader.buffer.size - 1) != '\n')
+ git_filebuf_write(&file, "\n", 1);
+
git_filebuf_printf(&file, "\t%s = %s\n", name, value);
}
}
diff --git a/tests-clar/config/write.c b/tests-clar/config/write.c
index 13b669c..eeda4d6 100644
--- a/tests-clar/config/write.c
+++ b/tests-clar/config/write.c
@@ -3,11 +3,13 @@
void test_config_write__initialize(void)
{
cl_fixture_sandbox("config/config9");
+ cl_fixture_sandbox("config/config17");
}
void test_config_write__cleanup(void)
{
cl_fixture_cleanup("config9");
+ cl_fixture_cleanup("config17");
}
void test_config_write__replace_value(void)
@@ -136,3 +138,19 @@ void test_config_write__escape_value(void)
cl_assert_equal_s(str, "this \"has\" quotes and \t");
git_config_free(cfg);
}
+
+void test_config_write__add_value_in_file_with_no_clrf_at_the_end(void)
+{
+ git_config *cfg;
+ int i;
+
+ cl_git_pass(git_config_open_ondisk(&cfg, "config17"));
+ cl_git_pass(git_config_set_int32(cfg, "core.newline", 7));
+ git_config_free(cfg);
+
+ cl_git_pass(git_config_open_ondisk(&cfg, "config17"));
+ cl_git_pass(git_config_get_int32(&i, cfg, "core.newline"));
+ cl_assert_equal_i(7, i);
+
+ git_config_free(cfg);
+}
diff --git a/tests-clar/resources/config/config17 b/tests-clar/resources/config/config17
new file mode 100644
index 0000000..ca25a86
--- /dev/null
+++ b/tests-clar/resources/config/config17
@@ -0,0 +1,3 @@
+[core]
+ dummy2 = 7
+ global = 17
\ No newline at end of file