Merge branch 'bw/ls-files-recurse-submodules'
[git] / git.c
1 #include "builtin.h"
2 #include "exec_cmd.h"
3 #include "help.h"
4 #include "run-command.h"
5
6 const char git_usage_string[] =
7         "git [--version] [--help] [-C <path>] [-c name=value]\n"
8         "           [--exec-path[=<path>]] [--html-path] [--man-path] [--info-path]\n"
9         "           [-p | --paginate | --no-pager] [--no-replace-objects] [--bare]\n"
10         "           [--git-dir=<path>] [--work-tree=<path>] [--namespace=<name>]\n"
11         "           <command> [<args>]";
12
13 const char git_more_info_string[] =
14         N_("'git help -a' and 'git help -g' list available subcommands and some\n"
15            "concept guides. See 'git help <command>' or 'git help <concept>'\n"
16            "to read about a specific subcommand or concept.");
17
18 static int use_pager = -1;
19 static char *orig_cwd;
20 static const char *env_names[] = {
21         GIT_DIR_ENVIRONMENT,
22         GIT_WORK_TREE_ENVIRONMENT,
23         GIT_IMPLICIT_WORK_TREE_ENVIRONMENT,
24         GIT_PREFIX_ENVIRONMENT
25 };
26 static char *orig_env[4];
27 static int save_restore_env_balance;
28
29 static void save_env_before_alias(void)
30 {
31         int i;
32
33         assert(save_restore_env_balance == 0);
34         save_restore_env_balance = 1;
35         orig_cwd = xgetcwd();
36         for (i = 0; i < ARRAY_SIZE(env_names); i++) {
37                 orig_env[i] = getenv(env_names[i]);
38                 if (orig_env[i])
39                         orig_env[i] = xstrdup(orig_env[i]);
40         }
41 }
42
43 static void restore_env(int external_alias)
44 {
45         int i;
46
47         assert(save_restore_env_balance == 1);
48         save_restore_env_balance = 0;
49         if (!external_alias && orig_cwd && chdir(orig_cwd))
50                 die_errno("could not move to %s", orig_cwd);
51         free(orig_cwd);
52         for (i = 0; i < ARRAY_SIZE(env_names); i++) {
53                 if (external_alias &&
54                     !strcmp(env_names[i], GIT_PREFIX_ENVIRONMENT))
55                         continue;
56                 if (orig_env[i]) {
57                         setenv(env_names[i], orig_env[i], 1);
58                         free(orig_env[i]);
59                 } else {
60                         unsetenv(env_names[i]);
61                 }
62         }
63 }
64
65 static void commit_pager_choice(void) {
66         switch (use_pager) {
67         case 0:
68                 setenv("GIT_PAGER", "cat", 1);
69                 break;
70         case 1:
71                 setup_pager();
72                 break;
73         default:
74                 break;
75         }
76 }
77
78 static int handle_options(const char ***argv, int *argc, int *envchanged)
79 {
80         const char **orig_argv = *argv;
81
82         while (*argc > 0) {
83                 const char *cmd = (*argv)[0];
84                 if (cmd[0] != '-')
85                         break;
86
87                 /*
88                  * For legacy reasons, the "version" and "help"
89                  * commands can be written with "--" prepended
90                  * to make them look like flags.
91                  */
92                 if (!strcmp(cmd, "--help") || !strcmp(cmd, "--version"))
93                         break;
94
95                 /*
96                  * Check remaining flags.
97                  */
98                 if (skip_prefix(cmd, "--exec-path", &cmd)) {
99                         if (*cmd == '=')
100                                 git_set_argv_exec_path(cmd + 1);
101                         else {
102                                 puts(git_exec_path());
103                                 exit(0);
104                         }
105                 } else if (!strcmp(cmd, "--html-path")) {
106                         puts(system_path(GIT_HTML_PATH));
107                         exit(0);
108                 } else if (!strcmp(cmd, "--man-path")) {
109                         puts(system_path(GIT_MAN_PATH));
110                         exit(0);
111                 } else if (!strcmp(cmd, "--info-path")) {
112                         puts(system_path(GIT_INFO_PATH));
113                         exit(0);
114                 } else if (!strcmp(cmd, "-p") || !strcmp(cmd, "--paginate")) {
115                         use_pager = 1;
116                 } else if (!strcmp(cmd, "--no-pager")) {
117                         use_pager = 0;
118                         if (envchanged)
119                                 *envchanged = 1;
120                 } else if (!strcmp(cmd, "--no-replace-objects")) {
121                         check_replace_refs = 0;
122                         setenv(NO_REPLACE_OBJECTS_ENVIRONMENT, "1", 1);
123                         if (envchanged)
124                                 *envchanged = 1;
125                 } else if (!strcmp(cmd, "--git-dir")) {
126                         if (*argc < 2) {
127                                 fprintf(stderr, "No directory given for --git-dir.\n" );
128                                 usage(git_usage_string);
129                         }
130                         setenv(GIT_DIR_ENVIRONMENT, (*argv)[1], 1);
131                         if (envchanged)
132                                 *envchanged = 1;
133                         (*argv)++;
134                         (*argc)--;
135                 } else if (skip_prefix(cmd, "--git-dir=", &cmd)) {
136                         setenv(GIT_DIR_ENVIRONMENT, cmd, 1);
137                         if (envchanged)
138                                 *envchanged = 1;
139                 } else if (!strcmp(cmd, "--namespace")) {
140                         if (*argc < 2) {
141                                 fprintf(stderr, "No namespace given for --namespace.\n" );
142                                 usage(git_usage_string);
143                         }
144                         setenv(GIT_NAMESPACE_ENVIRONMENT, (*argv)[1], 1);
145                         if (envchanged)
146                                 *envchanged = 1;
147                         (*argv)++;
148                         (*argc)--;
149                 } else if (skip_prefix(cmd, "--namespace=", &cmd)) {
150                         setenv(GIT_NAMESPACE_ENVIRONMENT, cmd, 1);
151                         if (envchanged)
152                                 *envchanged = 1;
153                 } else if (!strcmp(cmd, "--work-tree")) {
154                         if (*argc < 2) {
155                                 fprintf(stderr, "No directory given for --work-tree.\n" );
156                                 usage(git_usage_string);
157                         }
158                         setenv(GIT_WORK_TREE_ENVIRONMENT, (*argv)[1], 1);
159                         if (envchanged)
160                                 *envchanged = 1;
161                         (*argv)++;
162                         (*argc)--;
163                 } else if (skip_prefix(cmd, "--work-tree=", &cmd)) {
164                         setenv(GIT_WORK_TREE_ENVIRONMENT, cmd, 1);
165                         if (envchanged)
166                                 *envchanged = 1;
167                 } else if (!strcmp(cmd, "--super-prefix")) {
168                         if (*argc < 2) {
169                                 fprintf(stderr, "No prefix given for --super-prefix.\n" );
170                                 usage(git_usage_string);
171                         }
172                         setenv(GIT_SUPER_PREFIX_ENVIRONMENT, (*argv)[1], 1);
173                         if (envchanged)
174                                 *envchanged = 1;
175                         (*argv)++;
176                         (*argc)--;
177                 } else if (skip_prefix(cmd, "--super-prefix=", &cmd)) {
178                         setenv(GIT_SUPER_PREFIX_ENVIRONMENT, cmd, 1);
179                         if (envchanged)
180                                 *envchanged = 1;
181                 } else if (!strcmp(cmd, "--bare")) {
182                         char *cwd = xgetcwd();
183                         is_bare_repository_cfg = 1;
184                         setenv(GIT_DIR_ENVIRONMENT, cwd, 0);
185                         free(cwd);
186                         setenv(GIT_IMPLICIT_WORK_TREE_ENVIRONMENT, "0", 1);
187                         if (envchanged)
188                                 *envchanged = 1;
189                 } else if (!strcmp(cmd, "-c")) {
190                         if (*argc < 2) {
191                                 fprintf(stderr, "-c expects a configuration string\n" );
192                                 usage(git_usage_string);
193                         }
194                         git_config_push_parameter((*argv)[1]);
195                         (*argv)++;
196                         (*argc)--;
197                 } else if (!strcmp(cmd, "--literal-pathspecs")) {
198                         setenv(GIT_LITERAL_PATHSPECS_ENVIRONMENT, "1", 1);
199                         if (envchanged)
200                                 *envchanged = 1;
201                 } else if (!strcmp(cmd, "--no-literal-pathspecs")) {
202                         setenv(GIT_LITERAL_PATHSPECS_ENVIRONMENT, "0", 1);
203                         if (envchanged)
204                                 *envchanged = 1;
205                 } else if (!strcmp(cmd, "--glob-pathspecs")) {
206                         setenv(GIT_GLOB_PATHSPECS_ENVIRONMENT, "1", 1);
207                         if (envchanged)
208                                 *envchanged = 1;
209                 } else if (!strcmp(cmd, "--noglob-pathspecs")) {
210                         setenv(GIT_NOGLOB_PATHSPECS_ENVIRONMENT, "1", 1);
211                         if (envchanged)
212                                 *envchanged = 1;
213                 } else if (!strcmp(cmd, "--icase-pathspecs")) {
214                         setenv(GIT_ICASE_PATHSPECS_ENVIRONMENT, "1", 1);
215                         if (envchanged)
216                                 *envchanged = 1;
217                 } else if (!strcmp(cmd, "--shallow-file")) {
218                         (*argv)++;
219                         (*argc)--;
220                         set_alternate_shallow_file((*argv)[0], 1);
221                         if (envchanged)
222                                 *envchanged = 1;
223                 } else if (!strcmp(cmd, "-C")) {
224                         if (*argc < 2) {
225                                 fprintf(stderr, "No directory given for -C.\n" );
226                                 usage(git_usage_string);
227                         }
228                         if ((*argv)[1][0]) {
229                                 if (chdir((*argv)[1]))
230                                         die_errno("Cannot change to '%s'", (*argv)[1]);
231                                 if (envchanged)
232                                         *envchanged = 1;
233                         }
234                         (*argv)++;
235                         (*argc)--;
236                 } else {
237                         fprintf(stderr, "Unknown option: %s\n", cmd);
238                         usage(git_usage_string);
239                 }
240
241                 (*argv)++;
242                 (*argc)--;
243         }
244         return (*argv) - orig_argv;
245 }
246
247 static int handle_alias(int *argcp, const char ***argv)
248 {
249         int envchanged = 0, ret = 0, saved_errno = errno;
250         int count, option_count;
251         const char **new_argv;
252         const char *alias_command;
253         char *alias_string;
254         int unused_nongit;
255
256         save_env_before_alias();
257         setup_git_directory_gently(&unused_nongit);
258
259         alias_command = (*argv)[0];
260         alias_string = alias_lookup(alias_command);
261         if (alias_string) {
262                 if (alias_string[0] == '!') {
263                         struct child_process child = CHILD_PROCESS_INIT;
264
265                         commit_pager_choice();
266                         restore_env(1);
267
268                         child.use_shell = 1;
269                         argv_array_push(&child.args, alias_string + 1);
270                         argv_array_pushv(&child.args, (*argv) + 1);
271
272                         ret = run_command(&child);
273                         if (ret >= 0)   /* normal exit */
274                                 exit(ret);
275
276                         die_errno("While expanding alias '%s': '%s'",
277                             alias_command, alias_string + 1);
278                 }
279                 count = split_cmdline(alias_string, &new_argv);
280                 if (count < 0)
281                         die("Bad alias.%s string: %s", alias_command,
282                             split_cmdline_strerror(count));
283                 option_count = handle_options(&new_argv, &count, &envchanged);
284                 if (envchanged)
285                         die("alias '%s' changes environment variables\n"
286                                  "You can use '!git' in the alias to do this.",
287                                  alias_command);
288                 memmove(new_argv - option_count, new_argv,
289                                 count * sizeof(char *));
290                 new_argv -= option_count;
291
292                 if (count < 1)
293                         die("empty alias for %s", alias_command);
294
295                 if (!strcmp(alias_command, new_argv[0]))
296                         die("recursive alias: %s", alias_command);
297
298                 trace_argv_printf(new_argv,
299                                   "trace: alias expansion: %s =>",
300                                   alias_command);
301
302                 REALLOC_ARRAY(new_argv, count + *argcp);
303                 /* insert after command name */
304                 memcpy(new_argv + count, *argv + 1, sizeof(char *) * *argcp);
305
306                 *argv = new_argv;
307                 *argcp += count - 1;
308
309                 ret = 1;
310         }
311
312         restore_env(0);
313
314         errno = saved_errno;
315
316         return ret;
317 }
318
319 #define RUN_SETUP               (1<<0)
320 #define RUN_SETUP_GENTLY        (1<<1)
321 #define USE_PAGER               (1<<2)
322 /*
323  * require working tree to be present -- anything uses this needs
324  * RUN_SETUP for reading from the configuration file.
325  */
326 #define NEED_WORK_TREE          (1<<3)
327 #define SUPPORT_SUPER_PREFIX    (1<<4)
328
329 struct cmd_struct {
330         const char *cmd;
331         int (*fn)(int, const char **, const char *);
332         int option;
333 };
334
335 static int run_builtin(struct cmd_struct *p, int argc, const char **argv)
336 {
337         int status, help;
338         struct stat st;
339         const char *prefix;
340
341         prefix = NULL;
342         help = argc == 2 && !strcmp(argv[1], "-h");
343         if (!help) {
344                 if (p->option & RUN_SETUP)
345                         prefix = setup_git_directory();
346                 else if (p->option & RUN_SETUP_GENTLY) {
347                         int nongit_ok;
348                         prefix = setup_git_directory_gently(&nongit_ok);
349                 }
350
351                 if (use_pager == -1 && p->option & (RUN_SETUP | RUN_SETUP_GENTLY))
352                         use_pager = check_pager_config(p->cmd);
353                 if (use_pager == -1 && p->option & USE_PAGER)
354                         use_pager = 1;
355
356                 if ((p->option & (RUN_SETUP | RUN_SETUP_GENTLY)) &&
357                     startup_info->have_repository) /* get_git_dir() may set up repo, avoid that */
358                         trace_repo_setup(prefix);
359         }
360         commit_pager_choice();
361
362         if (!help && get_super_prefix()) {
363                 if (!(p->option & SUPPORT_SUPER_PREFIX))
364                         die("%s doesn't support --super-prefix", p->cmd);
365                 if (prefix)
366                         die("can't use --super-prefix from a subdirectory");
367         }
368
369         if (!help && p->option & NEED_WORK_TREE)
370                 setup_work_tree();
371
372         trace_argv_printf(argv, "trace: built-in: git");
373
374         status = p->fn(argc, argv, prefix);
375         if (status)
376                 return status;
377
378         /* Somebody closed stdout? */
379         if (fstat(fileno(stdout), &st))
380                 return 0;
381         /* Ignore write errors for pipes and sockets.. */
382         if (S_ISFIFO(st.st_mode) || S_ISSOCK(st.st_mode))
383                 return 0;
384
385         /* Check for ENOSPC and EIO errors.. */
386         if (fflush(stdout))
387                 die_errno("write failure on standard output");
388         if (ferror(stdout))
389                 die("unknown write failure on standard output");
390         if (fclose(stdout))
391                 die_errno("close failed on standard output");
392         return 0;
393 }
394
395 static struct cmd_struct commands[] = {
396         { "add", cmd_add, RUN_SETUP | NEED_WORK_TREE },
397         { "am", cmd_am, RUN_SETUP | NEED_WORK_TREE },
398         { "annotate", cmd_annotate, RUN_SETUP },
399         { "apply", cmd_apply, RUN_SETUP_GENTLY },
400         { "archive", cmd_archive },
401         { "bisect--helper", cmd_bisect__helper, RUN_SETUP },
402         { "blame", cmd_blame, RUN_SETUP },
403         { "branch", cmd_branch, RUN_SETUP },
404         { "bundle", cmd_bundle, RUN_SETUP_GENTLY },
405         { "cat-file", cmd_cat_file, RUN_SETUP },
406         { "check-attr", cmd_check_attr, RUN_SETUP },
407         { "check-ignore", cmd_check_ignore, RUN_SETUP | NEED_WORK_TREE },
408         { "check-mailmap", cmd_check_mailmap, RUN_SETUP },
409         { "check-ref-format", cmd_check_ref_format },
410         { "checkout", cmd_checkout, RUN_SETUP | NEED_WORK_TREE },
411         { "checkout-index", cmd_checkout_index,
412                 RUN_SETUP | NEED_WORK_TREE},
413         { "cherry", cmd_cherry, RUN_SETUP },
414         { "cherry-pick", cmd_cherry_pick, RUN_SETUP | NEED_WORK_TREE },
415         { "clean", cmd_clean, RUN_SETUP | NEED_WORK_TREE },
416         { "clone", cmd_clone },
417         { "column", cmd_column, RUN_SETUP_GENTLY },
418         { "commit", cmd_commit, RUN_SETUP | NEED_WORK_TREE },
419         { "commit-tree", cmd_commit_tree, RUN_SETUP },
420         { "config", cmd_config, RUN_SETUP_GENTLY },
421         { "count-objects", cmd_count_objects, RUN_SETUP },
422         { "credential", cmd_credential, RUN_SETUP_GENTLY },
423         { "describe", cmd_describe, RUN_SETUP },
424         { "diff", cmd_diff },
425         { "diff-files", cmd_diff_files, RUN_SETUP | NEED_WORK_TREE },
426         { "diff-index", cmd_diff_index, RUN_SETUP },
427         { "diff-tree", cmd_diff_tree, RUN_SETUP },
428         { "fast-export", cmd_fast_export, RUN_SETUP },
429         { "fetch", cmd_fetch, RUN_SETUP },
430         { "fetch-pack", cmd_fetch_pack, RUN_SETUP },
431         { "fmt-merge-msg", cmd_fmt_merge_msg, RUN_SETUP },
432         { "for-each-ref", cmd_for_each_ref, RUN_SETUP },
433         { "format-patch", cmd_format_patch, RUN_SETUP },
434         { "fsck", cmd_fsck, RUN_SETUP },
435         { "fsck-objects", cmd_fsck, RUN_SETUP },
436         { "gc", cmd_gc, RUN_SETUP },
437         { "get-tar-commit-id", cmd_get_tar_commit_id },
438         { "grep", cmd_grep, RUN_SETUP_GENTLY },
439         { "hash-object", cmd_hash_object },
440         { "help", cmd_help },
441         { "index-pack", cmd_index_pack, RUN_SETUP_GENTLY },
442         { "init", cmd_init_db },
443         { "init-db", cmd_init_db },
444         { "interpret-trailers", cmd_interpret_trailers, RUN_SETUP_GENTLY },
445         { "log", cmd_log, RUN_SETUP },
446         { "ls-files", cmd_ls_files, RUN_SETUP | SUPPORT_SUPER_PREFIX },
447         { "ls-remote", cmd_ls_remote, RUN_SETUP_GENTLY },
448         { "ls-tree", cmd_ls_tree, RUN_SETUP },
449         { "mailinfo", cmd_mailinfo },
450         { "mailsplit", cmd_mailsplit },
451         { "merge", cmd_merge, RUN_SETUP | NEED_WORK_TREE },
452         { "merge-base", cmd_merge_base, RUN_SETUP },
453         { "merge-file", cmd_merge_file, RUN_SETUP_GENTLY },
454         { "merge-index", cmd_merge_index, RUN_SETUP },
455         { "merge-ours", cmd_merge_ours, RUN_SETUP },
456         { "merge-recursive", cmd_merge_recursive, RUN_SETUP | NEED_WORK_TREE },
457         { "merge-recursive-ours", cmd_merge_recursive, RUN_SETUP | NEED_WORK_TREE },
458         { "merge-recursive-theirs", cmd_merge_recursive, RUN_SETUP | NEED_WORK_TREE },
459         { "merge-subtree", cmd_merge_recursive, RUN_SETUP | NEED_WORK_TREE },
460         { "merge-tree", cmd_merge_tree, RUN_SETUP },
461         { "mktag", cmd_mktag, RUN_SETUP },
462         { "mktree", cmd_mktree, RUN_SETUP },
463         { "mv", cmd_mv, RUN_SETUP | NEED_WORK_TREE },
464         { "name-rev", cmd_name_rev, RUN_SETUP },
465         { "notes", cmd_notes, RUN_SETUP },
466         { "pack-objects", cmd_pack_objects, RUN_SETUP },
467         { "pack-redundant", cmd_pack_redundant, RUN_SETUP },
468         { "pack-refs", cmd_pack_refs, RUN_SETUP },
469         { "patch-id", cmd_patch_id, RUN_SETUP_GENTLY },
470         { "pickaxe", cmd_blame, RUN_SETUP },
471         { "prune", cmd_prune, RUN_SETUP },
472         { "prune-packed", cmd_prune_packed, RUN_SETUP },
473         { "pull", cmd_pull, RUN_SETUP | NEED_WORK_TREE },
474         { "push", cmd_push, RUN_SETUP },
475         { "read-tree", cmd_read_tree, RUN_SETUP },
476         { "receive-pack", cmd_receive_pack },
477         { "reflog", cmd_reflog, RUN_SETUP },
478         { "remote", cmd_remote, RUN_SETUP },
479         { "remote-ext", cmd_remote_ext },
480         { "remote-fd", cmd_remote_fd },
481         { "repack", cmd_repack, RUN_SETUP },
482         { "replace", cmd_replace, RUN_SETUP },
483         { "rerere", cmd_rerere, RUN_SETUP },
484         { "reset", cmd_reset, RUN_SETUP },
485         { "rev-list", cmd_rev_list, RUN_SETUP },
486         { "rev-parse", cmd_rev_parse },
487         { "revert", cmd_revert, RUN_SETUP | NEED_WORK_TREE },
488         { "rm", cmd_rm, RUN_SETUP },
489         { "send-pack", cmd_send_pack, RUN_SETUP },
490         { "shortlog", cmd_shortlog, RUN_SETUP_GENTLY | USE_PAGER },
491         { "show", cmd_show, RUN_SETUP },
492         { "show-branch", cmd_show_branch, RUN_SETUP },
493         { "show-ref", cmd_show_ref, RUN_SETUP },
494         { "stage", cmd_add, RUN_SETUP | NEED_WORK_TREE },
495         { "status", cmd_status, RUN_SETUP | NEED_WORK_TREE },
496         { "stripspace", cmd_stripspace },
497         { "submodule--helper", cmd_submodule__helper, RUN_SETUP },
498         { "symbolic-ref", cmd_symbolic_ref, RUN_SETUP },
499         { "tag", cmd_tag, RUN_SETUP },
500         { "unpack-file", cmd_unpack_file, RUN_SETUP },
501         { "unpack-objects", cmd_unpack_objects, RUN_SETUP },
502         { "update-index", cmd_update_index, RUN_SETUP },
503         { "update-ref", cmd_update_ref, RUN_SETUP },
504         { "update-server-info", cmd_update_server_info, RUN_SETUP },
505         { "upload-archive", cmd_upload_archive },
506         { "upload-archive--writer", cmd_upload_archive_writer },
507         { "var", cmd_var, RUN_SETUP_GENTLY },
508         { "verify-commit", cmd_verify_commit, RUN_SETUP },
509         { "verify-pack", cmd_verify_pack },
510         { "verify-tag", cmd_verify_tag, RUN_SETUP },
511         { "version", cmd_version },
512         { "whatchanged", cmd_whatchanged, RUN_SETUP },
513         { "worktree", cmd_worktree, RUN_SETUP },
514         { "write-tree", cmd_write_tree, RUN_SETUP },
515 };
516
517 static struct cmd_struct *get_builtin(const char *s)
518 {
519         int i;
520         for (i = 0; i < ARRAY_SIZE(commands); i++) {
521                 struct cmd_struct *p = commands + i;
522                 if (!strcmp(s, p->cmd))
523                         return p;
524         }
525         return NULL;
526 }
527
528 int is_builtin(const char *s)
529 {
530         return !!get_builtin(s);
531 }
532
533 #ifdef STRIP_EXTENSION
534 static void strip_extension(const char **argv)
535 {
536         size_t len;
537
538         if (strip_suffix(argv[0], STRIP_EXTENSION, &len))
539                 argv[0] = xmemdupz(argv[0], len);
540 }
541 #else
542 #define strip_extension(cmd)
543 #endif
544
545 static void handle_builtin(int argc, const char **argv)
546 {
547         struct argv_array args = ARGV_ARRAY_INIT;
548         const char *cmd;
549         struct cmd_struct *builtin;
550
551         strip_extension(argv);
552         cmd = argv[0];
553
554         /* Turn "git cmd --help" into "git help --exclude-guides cmd" */
555         if (argc > 1 && !strcmp(argv[1], "--help")) {
556                 int i;
557
558                 argv[1] = argv[0];
559                 argv[0] = cmd = "help";
560
561                 for (i = 0; i < argc; i++) {
562                         argv_array_push(&args, argv[i]);
563                         if (!i)
564                                 argv_array_push(&args, "--exclude-guides");
565                 }
566
567                 argc++;
568                 argv = args.argv;
569         }
570
571         builtin = get_builtin(cmd);
572         if (builtin)
573                 exit(run_builtin(builtin, argc, argv));
574         argv_array_clear(&args);
575 }
576
577 static void execv_dashed_external(const char **argv)
578 {
579         struct strbuf cmd = STRBUF_INIT;
580         const char *tmp;
581         int status;
582
583         if (get_super_prefix())
584                 die("%s doesn't support --super-prefix", argv[0]);
585
586         if (use_pager == -1)
587                 use_pager = check_pager_config(argv[0]);
588         commit_pager_choice();
589
590         strbuf_addf(&cmd, "git-%s", argv[0]);
591
592         /*
593          * argv[0] must be the git command, but the argv array
594          * belongs to the caller, and may be reused in
595          * subsequent loop iterations. Save argv[0] and
596          * restore it on error.
597          */
598         tmp = argv[0];
599         argv[0] = cmd.buf;
600
601         trace_argv_printf(argv, "trace: exec:");
602
603         /*
604          * if we fail because the command is not found, it is
605          * OK to return. Otherwise, we just pass along the status code.
606          */
607         status = run_command_v_opt(argv, RUN_SILENT_EXEC_FAILURE | RUN_CLEAN_ON_EXIT);
608         if (status >= 0 || errno != ENOENT)
609                 exit(status);
610
611         argv[0] = tmp;
612
613         strbuf_release(&cmd);
614 }
615
616 static int run_argv(int *argcp, const char ***argv)
617 {
618         int done_alias = 0;
619
620         while (1) {
621                 /*
622                  * If we tried alias and futzed with our environment,
623                  * it no longer is safe to invoke builtins directly in
624                  * general.  We have to spawn them as dashed externals.
625                  *
626                  * NEEDSWORK: if we can figure out cases
627                  * where it is safe to do, we can avoid spawning a new
628                  * process.
629                  */
630                 if (!done_alias)
631                         handle_builtin(*argcp, *argv);
632
633                 /* .. then try the external ones */
634                 execv_dashed_external(*argv);
635
636                 /* It could be an alias -- this works around the insanity
637                  * of overriding "git log" with "git show" by having
638                  * alias.log = show
639                  */
640                 if (done_alias)
641                         break;
642                 if (!handle_alias(argcp, argv))
643                         break;
644                 done_alias = 1;
645         }
646
647         return done_alias;
648 }
649
650 int cmd_main(int argc, const char **argv)
651 {
652         const char *cmd;
653         int done_help = 0;
654
655         cmd = argv[0];
656         if (!cmd)
657                 cmd = "git-help";
658
659         trace_command_performance(argv);
660
661         /*
662          * "git-xxxx" is the same as "git xxxx", but we obviously:
663          *
664          *  - cannot take flags in between the "git" and the "xxxx".
665          *  - cannot execute it externally (since it would just do
666          *    the same thing over again)
667          *
668          * So we just directly call the builtin handler, and die if
669          * that one cannot handle it.
670          */
671         if (skip_prefix(cmd, "git-", &cmd)) {
672                 argv[0] = cmd;
673                 handle_builtin(argc, argv);
674                 die("cannot handle %s as a builtin", cmd);
675         }
676
677         /* Look for flags.. */
678         argv++;
679         argc--;
680         handle_options(&argv, &argc, NULL);
681         if (argc > 0) {
682                 /* translate --help and --version into commands */
683                 skip_prefix(argv[0], "--", &argv[0]);
684         } else {
685                 /* The user didn't specify a command; give them help */
686                 commit_pager_choice();
687                 printf("usage: %s\n\n", git_usage_string);
688                 list_common_cmds_help();
689                 printf("\n%s\n", _(git_more_info_string));
690                 exit(1);
691         }
692         cmd = argv[0];
693
694         /*
695          * We use PATH to find git commands, but we prepend some higher
696          * precedence paths: the "--exec-path" option, the GIT_EXEC_PATH
697          * environment, and the $(gitexecdir) from the Makefile at build
698          * time.
699          */
700         setup_path();
701
702         while (1) {
703                 int was_alias = run_argv(&argc, &argv);
704                 if (errno != ENOENT)
705                         break;
706                 if (was_alias) {
707                         fprintf(stderr, "Expansion of alias '%s' failed; "
708                                 "'%s' is not a git command\n",
709                                 cmd, argv[0]);
710                         exit(1);
711                 }
712                 if (!done_help) {
713                         cmd = argv[0] = help_unknown_cmd(cmd);
714                         done_help = 1;
715                 } else
716                         break;
717         }
718
719         fprintf(stderr, "Failed to run command '%s': %s\n",
720                 cmd, strerror(errno));
721
722         return 1;
723 }