describe: do not use cmd_*() as a subroutine

The cmd_foo() function is a moral equivalent of 'main' for a Git subcommand 'git foo', and as such, it is allowed to do many things that make it unsuitable to be called as a subroutine, including - call exit(3) to terminate the process; - allocate resource held and used throughout its lifetime, without releasing it upon return/exit; - rely on global variables being initialized at program startup, and update them as needed, making another clean invocation of the function impossible. The call to cmd_diff_index() "git describe" makes has been working by accident that the function did not call exit(3); it sets a bad precedent for people to cut and paste. We could invoke it via the run_command() interface, but the diff family of commands have helper functions in diff-lib.c that are meant to be usable as subroutines, and using the latter does not make the resulting code all that longer. Use it. Note that there is also an invocation of cmd_name_rev() at the end; "git describe --contains" massages its command line arguments to be suitable for "git name-rev" invocation and jumps to it, never to regain control. This call is left as-is as an exception to the rule. When we start to allow calling name-rev repeatedly as a helper function, we would be able to remove this call as well. Signed-off-by: Junio C Hamano <gitster@pobox.com>

Junio C Hamano committed Oct 10, 2017 at 12:42 UTC be26d2b29b6a58fc53ed9d38c3f36b195f8a7cc9
1 file changed +11 -4
builtin/describe.c
+11 -4
@@ -7,12 +7,12 @@
7 #include "builtin.h"
8 #include "exec_cmd.h"
9 #include "parse-options.h"
10 +#include "revision.h"
11 #include "diff.h"
12 #include "hashmap.h"
13 #include "argv-array.h"
14 #include "run-command.h"
15
15 -#define SEEN (1u << 0)
16 #define MAX_TAGS (FLAG_BITS - 1)
17
18 static const char * const describe_usage[] = {
@@ -532,7 +532,9 @@ int cmd_describe(int argc, const char **argv, const char *prefix)
532 }
533 } else if (dirty) {
534 static struct lock_file index_lock;
535 - int fd;
535 + struct rev_info revs;
536 + struct argv_array args = ARGV_ARRAY_INIT;
537 + int fd, result;
538
539 read_cache_preload(NULL);
540 refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED,
@@ -541,8 +543,13 @@ int cmd_describe(int argc, const char **argv, const char *prefix)
543 if (0 <= fd)
544 update_index_if_able(&the_index, &index_lock);
545
544 - if (!cmd_diff_index(ARRAY_SIZE(diff_index_args) - 1,
545 - diff_index_args, prefix))
546 + init_revisions(&revs, prefix);
547 + argv_array_pushv(&args, diff_index_args);
548 + if (setup_revisions(args.argc, args.argv, &revs, NULL) != 1)
549 + BUG("malformed internal diff-index command line");
550 + result = run_diff_index(&revs, 0);
551 +
552 + if (!diff_result_code(&revs.diffopt, result))
553 suffix = NULL;
554 else
555 suffix = dirty;