git: pass in repo to builtin based on setup_git_directory_gently

The current code in run_builtin() passes in a repository to the builtin based on whether cmd_struct's option flag has RUN_SETUP. This is incorrect, however, since some builtins that only have RUN_SETUP_GENTLY can potentially take a repository. setup_git_directory_gently() tells us whether or not a command is being run inside of a repository. Use the output of setup_git_directory_gently() to help determine whether or not there is a repository to pass to the builtin. If not, then we just pass NULL. As part of this patch, we need to modify add to check for a NULL repo before calling repo_git_config(), since add -h can be run outside of a repository. Signed-off-by: John Cai <johncai86@gmail.com> Signed-off-by: Junio C Hamano <gitster@pobox.com>

John Cai committed Oct 10, 2024 at 21:13 UTC 5db948d4136b2aa84b33815c939447ff0eabd76a
2 files changed +6 -4
builtin/add.c
+2 -1
@@ -385,7 +385,8 @@ int cmd_add(int argc,
385 char *ps_matched = NULL;
386 struct lock_file lock_file = LOCK_INIT;
387
388 - repo_config(repo, add_config, NULL);
388 + if (repo)
389 + repo_config(repo, add_config, NULL);
390
391 argc = parse_options(argc, argv, prefix, builtin_add_options,
392 builtin_add_usage, PARSE_OPT_KEEP_ARGV0);
git.c
+4 -3
@@ -444,6 +444,7 @@ static int handle_alias(int *argcp, const char ***argv)
444 static int run_builtin(struct cmd_struct *p, int argc, const char **argv, struct repository *repo)
445 {
446 int status, help;
447 + int no_repo = 1;
448 struct stat st;
449 const char *prefix;
450 int run_setup = (p->option & (RUN_SETUP | RUN_SETUP_GENTLY));
@@ -455,9 +456,9 @@ static int run_builtin(struct cmd_struct *p, int argc, const char **argv, struct
456
457 if (run_setup & RUN_SETUP) {
458 prefix = setup_git_directory();
459 + no_repo = 0;
460 } else if (run_setup & RUN_SETUP_GENTLY) {
459 - int nongit_ok;
460 - prefix = setup_git_directory_gently(&nongit_ok);
461 + prefix = setup_git_directory_gently(&no_repo);
462 } else {
463 prefix = NULL;
464 }
@@ -480,7 +481,7 @@ static int run_builtin(struct cmd_struct *p, int argc, const char **argv, struct
481 trace2_cmd_name(p->cmd);
482
483 validate_cache_entries(repo->index);
483 - status = p->fn(argc, argv, prefix, (p->option & RUN_SETUP)? repo : NULL);
484 + status = p->fn(argc, argv, prefix, no_repo ? NULL : repo);
485 validate_cache_entries(repo->index);
486
487 if (status)