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