diff mbox series

[v4,05/13] attr: fix BUG() when parsing attrs outside of repo

Message ID f098ce9690f03bd42411b47c4cea23ecc8d96dee.1715057362.git.ps@pks.im (mailing list archive)
State New
Headers show
Series Stop relying on SHA1 fallback for `the_hash_algo` | expand

Commit Message

Patrick Steinhardt May 7, 2024, 4:53 a.m. UTC
If either the `--attr-source` option or the `GIT_ATTR_SOURCE` envvar are
set, then `compute_default_attr_source()` will try to look up the value
as a treeish. It is possible to hit that function while outside of a Git
repository though, for example when using `git grep --no-index`. In that
case, Git will hit a bug because we try to look up the main ref store
outside of a repository.

Handle the case gracefully and detect when we try to look up an attr
source without a repository.

Signed-off-by: Patrick Steinhardt <ps@pks.im>
---
 attr.c                |  6 ++++++
 t/t0003-attributes.sh | 15 +++++++++++++++
 2 files changed, 21 insertions(+)
diff mbox series

Patch

diff --git a/attr.c b/attr.c
index a5b717e4ce..c89ab3478e 100644
--- a/attr.c
+++ b/attr.c
@@ -1226,8 +1226,14 @@  static int compute_default_attr_source(struct object_id *attr_source)
 
 	if (!default_attr_source_tree_object_name)
 		return 0;
 
+	if (!startup_info->have_repository) {
+		if (!ignore_bad_attr_tree)
+			die(_("cannot use --attr-source or GIT_ATTR_SOURCE without repo"));
+		return 0;
+	}
+
 	if (repo_get_oid_treeish(the_repository,
 				 default_attr_source_tree_object_name,
 				 attr_source)) {
 		if (!ignore_bad_attr_tree)
diff --git a/t/t0003-attributes.sh b/t/t0003-attributes.sh
index d755cc3c29..72fadca1e8 100755
--- a/t/t0003-attributes.sh
+++ b/t/t0003-attributes.sh
@@ -433,8 +433,23 @@  test_expect_success 'precedence of --attr-source, GIT_ATTR_SOURCE, then attr.tre
 		test_cmp expect actual
 	)
 '
 
+test_expect_success 'diff without repository with attr source' '
+	mkdir -p "$TRASH_DIRECTORY/outside/nongit" &&
+	(
+		cd "$TRASH_DIRECTORY/outside/nongit" &&
+		GIT_CEILING_DIRECTORIES="$TRASH_DIRECTORY/outside" &&
+		export GIT_CEILING_DIRECTORIES &&
+		touch file &&
+		cat >expect <<-EOF &&
+		fatal: cannot use --attr-source or GIT_ATTR_SOURCE without repo
+		EOF
+		test_must_fail env GIT_ATTR_SOURCE=HEAD git grep --no-index foo file 2>err &&
+		test_cmp expect err
+	)
+'
+
 test_expect_success 'bare repository: with --source' '
 	(
 		cd bare.git &&
 		attr_check_source foo/bar/f f tag-1 &&