var: avoid a segmentation fault when `HOME` is unset

The code introduced in 576a37fccbf (var: add attributes files locations, 2023-06-27) paid careful attention to use `xstrdup()` for pointers known never to be `NULL`, and `xstrdup_or_null()` otherwise. One spot was missed, though: `git_attr_global_file()` can return `NULL`, when the `HOME` variable is not set (and neither `XDG_CONFIG_HOME`), a scenario not too uncommon in certain server scenarios. Fix this, and add a test case to avoid future regressions. Signed-off-by: Johannes Schindelin <johannes.schindelin@gmx.de> Acked-by: brian m. carlson <bk2204@github.com> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Johannes Schindelin committed Sep 4, 2023 at 06:21 UTC 256a94ef6c8c0c94f9629a1ffe893577ccef8efd
2 files changed +10 -1
builtin/var.c
+1 -1
@@ -64,7 +64,7 @@ static char *git_attr_val_system(int ident_flag UNUSED)
64
65 static char *git_attr_val_global(int ident_flag UNUSED)
66 {
67 - char *file = xstrdup(git_attr_global_file());
67 + char *file = xstrdup_or_null(git_attr_global_file());
68 if (file) {
69 normalize_path_copy(file, file);
70 return file;
t/t0007-git-var.sh
+9
@@ -268,4 +268,13 @@ test_expect_success 'listing and asking for variables are exclusive' '
268 test_must_fail git var -l GIT_COMMITTER_IDENT
269 '
270
271 +test_expect_success '`git var -l` works even without HOME' '
272 + (
273 + XDG_CONFIG_HOME= &&
274 + export XDG_CONFIG_HOME &&
275 + unset HOME &&
276 + git var -l
277 + )
278 +'
279 +
280 test_done