t0001: exercise initialization with ref formats more thoroughly
[git/gitster.git] / git.c
blobe35af9b0e5e976d43abbc490234d033b42542530
1 #define USE_THE_REPOSITORY_VARIABLE
3 #include "builtin.h"
4 #include "config.h"
5 #include "environment.h"
6 #include "exec-cmd.h"
7 #include "gettext.h"
8 #include "help.h"
9 #include "object-file.h"
10 #include "pager.h"
11 #include "read-cache-ll.h"
12 #include "run-command.h"
13 #include "alias.h"
14 #include "replace-object.h"
15 #include "setup.h"
16 #include "attr.h"
17 #include "shallow.h"
18 #include "trace.h"
19 #include "trace2.h"
21 #define RUN_SETUP (1<<0)
22 #define RUN_SETUP_GENTLY (1<<1)
23 #define USE_PAGER (1<<2)
25 * require working tree to be present -- anything uses this needs
26 * RUN_SETUP for reading from the configuration file.
28 #define NEED_WORK_TREE (1<<3)
29 #define DELAY_PAGER_CONFIG (1<<4)
30 #define NO_PARSEOPT (1<<5) /* parse-options is not used */
32 struct cmd_struct {
33 const char *cmd;
34 int (*fn)(int, const char **, const char *);
35 unsigned int option;
38 const char git_usage_string[] =
39 N_("git [-v | --version] [-h | --help] [-C <path>] [-c <name>=<value>]\n"
40 " [--exec-path[=<path>]] [--html-path] [--man-path] [--info-path]\n"
41 " [-p | --paginate | -P | --no-pager] [--no-replace-objects] [--no-lazy-fetch]\n"
42 " [--no-optional-locks] [--no-advice] [--bare] [--git-dir=<path>]\n"
43 " [--work-tree=<path>] [--namespace=<name>] [--config-env=<name>=<envvar>]\n"
44 " <command> [<args>]");
46 const char git_more_info_string[] =
47 N_("'git help -a' and 'git help -g' list available subcommands and some\n"
48 "concept guides. See 'git help <command>' or 'git help <concept>'\n"
49 "to read about a specific subcommand or concept.\n"
50 "See 'git help git' for an overview of the system.");
52 static int use_pager = -1;
54 static void list_builtins(struct string_list *list, unsigned int exclude_option);
56 static void exclude_helpers_from_list(struct string_list *list)
58 int i = 0;
60 while (i < list->nr) {
61 if (strstr(list->items[i].string, "--"))
62 unsorted_string_list_delete_item(list, i, 0);
63 else
64 i++;
68 static int match_token(const char *spec, int len, const char *token)
70 int token_len = strlen(token);
72 return len == token_len && !strncmp(spec, token, token_len);
75 static int list_cmds(const char *spec)
77 struct string_list list = STRING_LIST_INIT_DUP;
78 int i;
79 int nongit;
82 * Set up the repository so we can pick up any repo-level config (like
83 * completion.commands).
85 setup_git_directory_gently(&nongit);
87 while (*spec) {
88 const char *sep = strchrnul(spec, ',');
89 int len = sep - spec;
91 if (match_token(spec, len, "builtins"))
92 list_builtins(&list, 0);
93 else if (match_token(spec, len, "main"))
94 list_all_main_cmds(&list);
95 else if (match_token(spec, len, "others"))
96 list_all_other_cmds(&list);
97 else if (match_token(spec, len, "nohelpers"))
98 exclude_helpers_from_list(&list);
99 else if (match_token(spec, len, "alias"))
100 list_aliases(&list);
101 else if (match_token(spec, len, "config"))
102 list_cmds_by_config(&list);
103 else if (len > 5 && !strncmp(spec, "list-", 5)) {
104 struct strbuf sb = STRBUF_INIT;
106 strbuf_add(&sb, spec + 5, len - 5);
107 list_cmds_by_category(&list, sb.buf);
108 strbuf_release(&sb);
110 else
111 die(_("unsupported command listing type '%s'"), spec);
112 spec += len;
113 if (*spec == ',')
114 spec++;
116 for (i = 0; i < list.nr; i++)
117 puts(list.items[i].string);
118 string_list_clear(&list, 0);
119 return 0;
122 static void commit_pager_choice(void)
124 switch (use_pager) {
125 case 0:
126 setenv("GIT_PAGER", "cat", 1);
127 break;
128 case 1:
129 setup_pager();
130 break;
131 default:
132 break;
136 void setup_auto_pager(const char *cmd, int def)
138 if (use_pager != -1 || pager_in_use())
139 return;
140 use_pager = check_pager_config(cmd);
141 if (use_pager == -1)
142 use_pager = def;
143 commit_pager_choice();
146 static int handle_options(const char ***argv, int *argc, int *envchanged)
148 const char **orig_argv = *argv;
150 while (*argc > 0) {
151 const char *cmd = (*argv)[0];
152 if (cmd[0] != '-')
153 break;
156 * For legacy reasons, the "version" and "help"
157 * commands can be written with "--" prepended
158 * to make them look like flags.
160 if (!strcmp(cmd, "--help") || !strcmp(cmd, "-h") ||
161 !strcmp(cmd, "--version") || !strcmp(cmd, "-v"))
162 break;
165 * Check remaining flags.
167 if (skip_prefix(cmd, "--exec-path", &cmd)) {
168 if (*cmd == '=')
169 git_set_exec_path(cmd + 1);
170 else {
171 puts(git_exec_path());
172 trace2_cmd_name("_query_");
173 exit(0);
175 } else if (!strcmp(cmd, "--html-path")) {
176 puts(system_path(GIT_HTML_PATH));
177 trace2_cmd_name("_query_");
178 exit(0);
179 } else if (!strcmp(cmd, "--man-path")) {
180 puts(system_path(GIT_MAN_PATH));
181 trace2_cmd_name("_query_");
182 exit(0);
183 } else if (!strcmp(cmd, "--info-path")) {
184 puts(system_path(GIT_INFO_PATH));
185 trace2_cmd_name("_query_");
186 exit(0);
187 } else if (!strcmp(cmd, "-p") || !strcmp(cmd, "--paginate")) {
188 use_pager = 1;
189 } else if (!strcmp(cmd, "-P") || !strcmp(cmd, "--no-pager")) {
190 use_pager = 0;
191 if (envchanged)
192 *envchanged = 1;
193 } else if (!strcmp(cmd, "--no-lazy-fetch")) {
194 fetch_if_missing = 0;
195 setenv(NO_LAZY_FETCH_ENVIRONMENT, "1", 1);
196 if (envchanged)
197 *envchanged = 1;
198 } else if (!strcmp(cmd, "--no-replace-objects")) {
199 disable_replace_refs();
200 setenv(NO_REPLACE_OBJECTS_ENVIRONMENT, "1", 1);
201 if (envchanged)
202 *envchanged = 1;
203 } else if (!strcmp(cmd, "--git-dir")) {
204 if (*argc < 2) {
205 fprintf(stderr, _("no directory given for '%s' option\n" ), "--git-dir");
206 usage(git_usage_string);
208 setenv(GIT_DIR_ENVIRONMENT, (*argv)[1], 1);
209 if (envchanged)
210 *envchanged = 1;
211 (*argv)++;
212 (*argc)--;
213 } else if (skip_prefix(cmd, "--git-dir=", &cmd)) {
214 setenv(GIT_DIR_ENVIRONMENT, cmd, 1);
215 if (envchanged)
216 *envchanged = 1;
217 } else if (!strcmp(cmd, "--namespace")) {
218 if (*argc < 2) {
219 fprintf(stderr, _("no namespace given for --namespace\n" ));
220 usage(git_usage_string);
222 setenv(GIT_NAMESPACE_ENVIRONMENT, (*argv)[1], 1);
223 if (envchanged)
224 *envchanged = 1;
225 (*argv)++;
226 (*argc)--;
227 } else if (skip_prefix(cmd, "--namespace=", &cmd)) {
228 setenv(GIT_NAMESPACE_ENVIRONMENT, cmd, 1);
229 if (envchanged)
230 *envchanged = 1;
231 } else if (!strcmp(cmd, "--work-tree")) {
232 if (*argc < 2) {
233 fprintf(stderr, _("no directory given for '%s' option\n" ), "--work-tree");
234 usage(git_usage_string);
236 setenv(GIT_WORK_TREE_ENVIRONMENT, (*argv)[1], 1);
237 if (envchanged)
238 *envchanged = 1;
239 (*argv)++;
240 (*argc)--;
241 } else if (skip_prefix(cmd, "--work-tree=", &cmd)) {
242 setenv(GIT_WORK_TREE_ENVIRONMENT, cmd, 1);
243 if (envchanged)
244 *envchanged = 1;
245 } else if (!strcmp(cmd, "--bare")) {
246 char *cwd = xgetcwd();
247 is_bare_repository_cfg = 1;
248 setenv(GIT_DIR_ENVIRONMENT, cwd, 0);
249 free(cwd);
250 setenv(GIT_IMPLICIT_WORK_TREE_ENVIRONMENT, "0", 1);
251 if (envchanged)
252 *envchanged = 1;
253 } else if (!strcmp(cmd, "-c")) {
254 if (*argc < 2) {
255 fprintf(stderr, _("-c expects a configuration string\n" ));
256 usage(git_usage_string);
258 git_config_push_parameter((*argv)[1]);
259 (*argv)++;
260 (*argc)--;
261 } else if (!strcmp(cmd, "--config-env")) {
262 if (*argc < 2) {
263 fprintf(stderr, _("no config key given for --config-env\n" ));
264 usage(git_usage_string);
266 git_config_push_env((*argv)[1]);
267 (*argv)++;
268 (*argc)--;
269 } else if (skip_prefix(cmd, "--config-env=", &cmd)) {
270 git_config_push_env(cmd);
271 } else if (!strcmp(cmd, "--literal-pathspecs")) {
272 setenv(GIT_LITERAL_PATHSPECS_ENVIRONMENT, "1", 1);
273 if (envchanged)
274 *envchanged = 1;
275 } else if (!strcmp(cmd, "--no-literal-pathspecs")) {
276 setenv(GIT_LITERAL_PATHSPECS_ENVIRONMENT, "0", 1);
277 if (envchanged)
278 *envchanged = 1;
279 } else if (!strcmp(cmd, "--glob-pathspecs")) {
280 setenv(GIT_GLOB_PATHSPECS_ENVIRONMENT, "1", 1);
281 if (envchanged)
282 *envchanged = 1;
283 } else if (!strcmp(cmd, "--noglob-pathspecs")) {
284 setenv(GIT_NOGLOB_PATHSPECS_ENVIRONMENT, "1", 1);
285 if (envchanged)
286 *envchanged = 1;
287 } else if (!strcmp(cmd, "--icase-pathspecs")) {
288 setenv(GIT_ICASE_PATHSPECS_ENVIRONMENT, "1", 1);
289 if (envchanged)
290 *envchanged = 1;
291 } else if (!strcmp(cmd, "--no-optional-locks")) {
292 setenv(GIT_OPTIONAL_LOCKS_ENVIRONMENT, "0", 1);
293 if (envchanged)
294 *envchanged = 1;
295 } else if (!strcmp(cmd, "--shallow-file")) {
296 (*argv)++;
297 (*argc)--;
298 set_alternate_shallow_file(the_repository, (*argv)[0], 1);
299 if (envchanged)
300 *envchanged = 1;
301 } else if (!strcmp(cmd, "-C")) {
302 if (*argc < 2) {
303 fprintf(stderr, _("no directory given for '%s' option\n" ), "-C");
304 usage(git_usage_string);
306 if ((*argv)[1][0]) {
307 if (chdir((*argv)[1]))
308 die_errno("cannot change to '%s'", (*argv)[1]);
309 if (envchanged)
310 *envchanged = 1;
312 (*argv)++;
313 (*argc)--;
314 } else if (skip_prefix(cmd, "--list-cmds=", &cmd)) {
315 trace2_cmd_name("_query_");
316 if (!strcmp(cmd, "parseopt")) {
317 struct string_list list = STRING_LIST_INIT_DUP;
318 int i;
320 list_builtins(&list, NO_PARSEOPT);
321 for (i = 0; i < list.nr; i++)
322 printf("%s ", list.items[i].string);
323 string_list_clear(&list, 0);
324 exit(0);
325 } else {
326 exit(list_cmds(cmd));
328 } else if (!strcmp(cmd, "--attr-source")) {
329 if (*argc < 2) {
330 fprintf(stderr, _("no attribute source given for --attr-source\n" ));
331 usage(git_usage_string);
333 setenv(GIT_ATTR_SOURCE_ENVIRONMENT, (*argv)[1], 1);
334 if (envchanged)
335 *envchanged = 1;
336 (*argv)++;
337 (*argc)--;
338 } else if (skip_prefix(cmd, "--attr-source=", &cmd)) {
339 set_git_attr_source(cmd);
340 setenv(GIT_ATTR_SOURCE_ENVIRONMENT, cmd, 1);
341 if (envchanged)
342 *envchanged = 1;
343 } else if (!strcmp(cmd, "--no-advice")) {
344 setenv(GIT_ADVICE_ENVIRONMENT, "0", 1);
345 if (envchanged)
346 *envchanged = 1;
347 } else {
348 fprintf(stderr, _("unknown option: %s\n"), cmd);
349 usage(git_usage_string);
352 (*argv)++;
353 (*argc)--;
355 return (*argv) - orig_argv;
358 static int handle_alias(int *argcp, const char ***argv)
360 int envchanged = 0, ret = 0, saved_errno = errno;
361 int count, option_count;
362 const char **new_argv;
363 const char *alias_command;
364 char *alias_string;
366 alias_command = (*argv)[0];
367 alias_string = alias_lookup(alias_command);
368 if (alias_string) {
369 if (*argcp > 1 && !strcmp((*argv)[1], "-h"))
370 fprintf_ln(stderr, _("'%s' is aliased to '%s'"),
371 alias_command, alias_string);
372 if (alias_string[0] == '!') {
373 struct child_process child = CHILD_PROCESS_INIT;
374 int nongit_ok;
376 /* Aliases expect GIT_PREFIX, GIT_DIR etc to be set */
377 setup_git_directory_gently(&nongit_ok);
379 commit_pager_choice();
381 child.use_shell = 1;
382 child.clean_on_exit = 1;
383 child.wait_after_clean = 1;
384 child.trace2_child_class = "shell_alias";
385 strvec_push(&child.args, alias_string + 1);
386 strvec_pushv(&child.args, (*argv) + 1);
388 trace2_cmd_alias(alias_command, child.args.v);
389 trace2_cmd_name("_run_shell_alias_");
391 ret = run_command(&child);
392 if (ret >= 0) /* normal exit */
393 exit(ret);
395 die_errno(_("while expanding alias '%s': '%s'"),
396 alias_command, alias_string + 1);
398 count = split_cmdline(alias_string, &new_argv);
399 if (count < 0)
400 die(_("bad alias.%s string: %s"), alias_command,
401 _(split_cmdline_strerror(count)));
402 option_count = handle_options(&new_argv, &count, &envchanged);
403 if (envchanged)
404 die(_("alias '%s' changes environment variables.\n"
405 "You can use '!git' in the alias to do this"),
406 alias_command);
407 MOVE_ARRAY(new_argv - option_count, new_argv, count);
408 new_argv -= option_count;
410 if (count < 1)
411 die(_("empty alias for %s"), alias_command);
413 if (!strcmp(alias_command, new_argv[0]))
414 die(_("recursive alias: %s"), alias_command);
416 trace_argv_printf(new_argv,
417 "trace: alias expansion: %s =>",
418 alias_command);
420 REALLOC_ARRAY(new_argv, count + *argcp);
421 /* insert after command name */
422 COPY_ARRAY(new_argv + count, *argv + 1, *argcp);
424 trace2_cmd_alias(alias_command, new_argv);
426 *argv = new_argv;
427 *argcp += count - 1;
429 ret = 1;
432 errno = saved_errno;
434 return ret;
437 static int run_builtin(struct cmd_struct *p, int argc, const char **argv)
439 int status, help;
440 struct stat st;
441 const char *prefix;
442 int run_setup = (p->option & (RUN_SETUP | RUN_SETUP_GENTLY));
444 help = argc == 2 && !strcmp(argv[1], "-h");
445 if (help && (run_setup & RUN_SETUP))
446 /* demote to GENTLY to allow 'git cmd -h' outside repo */
447 run_setup = RUN_SETUP_GENTLY;
449 if (run_setup & RUN_SETUP) {
450 prefix = setup_git_directory();
451 } else if (run_setup & RUN_SETUP_GENTLY) {
452 int nongit_ok;
453 prefix = setup_git_directory_gently(&nongit_ok);
454 } else {
455 prefix = NULL;
457 assert(!prefix || *prefix);
458 precompose_argv_prefix(argc, argv, NULL);
459 if (use_pager == -1 && run_setup &&
460 !(p->option & DELAY_PAGER_CONFIG))
461 use_pager = check_pager_config(p->cmd);
462 if (use_pager == -1 && p->option & USE_PAGER)
463 use_pager = 1;
464 if (run_setup && startup_info->have_repository)
465 /* get_git_dir() may set up repo, avoid that */
466 trace_repo_setup();
467 commit_pager_choice();
469 if (!help && p->option & NEED_WORK_TREE)
470 setup_work_tree();
472 trace_argv_printf(argv, "trace: built-in: git");
473 trace2_cmd_name(p->cmd);
475 validate_cache_entries(the_repository->index);
476 status = p->fn(argc, argv, prefix);
477 validate_cache_entries(the_repository->index);
479 if (status)
480 return status;
482 /* Somebody closed stdout? */
483 if (fstat(fileno(stdout), &st))
484 return 0;
485 /* Ignore write errors for pipes and sockets.. */
486 if (S_ISFIFO(st.st_mode) || S_ISSOCK(st.st_mode))
487 return 0;
489 /* Check for ENOSPC and EIO errors.. */
490 if (fflush(stdout))
491 die_errno(_("write failure on standard output"));
492 if (ferror(stdout))
493 die(_("unknown write failure on standard output"));
494 if (fclose(stdout))
495 die_errno(_("close failed on standard output"));
496 return 0;
499 static struct cmd_struct commands[] = {
500 { "add", cmd_add, RUN_SETUP | NEED_WORK_TREE },
501 { "am", cmd_am, RUN_SETUP | NEED_WORK_TREE },
502 { "annotate", cmd_annotate, RUN_SETUP },
503 { "apply", cmd_apply, RUN_SETUP_GENTLY },
504 { "archive", cmd_archive, RUN_SETUP_GENTLY },
505 { "bisect", cmd_bisect, RUN_SETUP },
506 { "blame", cmd_blame, RUN_SETUP },
507 { "branch", cmd_branch, RUN_SETUP | DELAY_PAGER_CONFIG },
508 { "bugreport", cmd_bugreport, RUN_SETUP_GENTLY },
509 { "bundle", cmd_bundle, RUN_SETUP_GENTLY },
510 { "cat-file", cmd_cat_file, RUN_SETUP },
511 { "check-attr", cmd_check_attr, RUN_SETUP },
512 { "check-ignore", cmd_check_ignore, RUN_SETUP | NEED_WORK_TREE },
513 { "check-mailmap", cmd_check_mailmap, RUN_SETUP },
514 { "check-ref-format", cmd_check_ref_format, NO_PARSEOPT },
515 { "checkout", cmd_checkout, RUN_SETUP | NEED_WORK_TREE },
516 { "checkout--worker", cmd_checkout__worker,
517 RUN_SETUP | NEED_WORK_TREE },
518 { "checkout-index", cmd_checkout_index,
519 RUN_SETUP | NEED_WORK_TREE},
520 { "cherry", cmd_cherry, RUN_SETUP },
521 { "cherry-pick", cmd_cherry_pick, RUN_SETUP | NEED_WORK_TREE },
522 { "clean", cmd_clean, RUN_SETUP | NEED_WORK_TREE },
523 { "clone", cmd_clone },
524 { "column", cmd_column, RUN_SETUP_GENTLY },
525 { "commit", cmd_commit, RUN_SETUP | NEED_WORK_TREE },
526 { "commit-graph", cmd_commit_graph, RUN_SETUP },
527 { "commit-tree", cmd_commit_tree, RUN_SETUP },
528 { "config", cmd_config, RUN_SETUP_GENTLY | DELAY_PAGER_CONFIG },
529 { "count-objects", cmd_count_objects, RUN_SETUP },
530 { "credential", cmd_credential, RUN_SETUP_GENTLY | NO_PARSEOPT },
531 { "credential-cache", cmd_credential_cache },
532 { "credential-cache--daemon", cmd_credential_cache_daemon },
533 { "credential-store", cmd_credential_store },
534 { "describe", cmd_describe, RUN_SETUP },
535 { "diagnose", cmd_diagnose, RUN_SETUP_GENTLY },
536 { "diff", cmd_diff, NO_PARSEOPT },
537 { "diff-files", cmd_diff_files, RUN_SETUP | NEED_WORK_TREE | NO_PARSEOPT },
538 { "diff-index", cmd_diff_index, RUN_SETUP | NO_PARSEOPT },
539 { "diff-tree", cmd_diff_tree, RUN_SETUP | NO_PARSEOPT },
540 { "difftool", cmd_difftool, RUN_SETUP_GENTLY },
541 { "fast-export", cmd_fast_export, RUN_SETUP },
542 { "fast-import", cmd_fast_import, RUN_SETUP | NO_PARSEOPT },
543 { "fetch", cmd_fetch, RUN_SETUP },
544 { "fetch-pack", cmd_fetch_pack, RUN_SETUP | NO_PARSEOPT },
545 { "fmt-merge-msg", cmd_fmt_merge_msg, RUN_SETUP },
546 { "for-each-ref", cmd_for_each_ref, RUN_SETUP },
547 { "for-each-repo", cmd_for_each_repo, RUN_SETUP_GENTLY },
548 { "format-patch", cmd_format_patch, RUN_SETUP },
549 { "fsck", cmd_fsck, RUN_SETUP },
550 { "fsck-objects", cmd_fsck, RUN_SETUP },
551 { "fsmonitor--daemon", cmd_fsmonitor__daemon, RUN_SETUP },
552 { "gc", cmd_gc, RUN_SETUP },
553 { "get-tar-commit-id", cmd_get_tar_commit_id, NO_PARSEOPT },
554 { "grep", cmd_grep, RUN_SETUP_GENTLY },
555 { "hash-object", cmd_hash_object },
556 { "help", cmd_help },
557 { "hook", cmd_hook, RUN_SETUP },
558 { "index-pack", cmd_index_pack, RUN_SETUP_GENTLY | NO_PARSEOPT },
559 { "init", cmd_init_db },
560 { "init-db", cmd_init_db },
561 { "interpret-trailers", cmd_interpret_trailers, RUN_SETUP_GENTLY },
562 { "log", cmd_log, RUN_SETUP },
563 { "ls-files", cmd_ls_files, RUN_SETUP },
564 { "ls-remote", cmd_ls_remote, RUN_SETUP_GENTLY },
565 { "ls-tree", cmd_ls_tree, RUN_SETUP },
566 { "mailinfo", cmd_mailinfo, RUN_SETUP_GENTLY },
567 { "mailsplit", cmd_mailsplit, NO_PARSEOPT },
568 { "maintenance", cmd_maintenance, RUN_SETUP },
569 { "merge", cmd_merge, RUN_SETUP | NEED_WORK_TREE },
570 { "merge-base", cmd_merge_base, RUN_SETUP },
571 { "merge-file", cmd_merge_file, RUN_SETUP_GENTLY },
572 { "merge-index", cmd_merge_index, RUN_SETUP | NO_PARSEOPT },
573 { "merge-ours", cmd_merge_ours, RUN_SETUP | NO_PARSEOPT },
574 { "merge-recursive", cmd_merge_recursive, RUN_SETUP | NEED_WORK_TREE | NO_PARSEOPT },
575 { "merge-recursive-ours", cmd_merge_recursive, RUN_SETUP | NEED_WORK_TREE | NO_PARSEOPT },
576 { "merge-recursive-theirs", cmd_merge_recursive, RUN_SETUP | NEED_WORK_TREE | NO_PARSEOPT },
577 { "merge-subtree", cmd_merge_recursive, RUN_SETUP | NEED_WORK_TREE | NO_PARSEOPT },
578 { "merge-tree", cmd_merge_tree, RUN_SETUP },
579 { "mktag", cmd_mktag, RUN_SETUP },
580 { "mktree", cmd_mktree, RUN_SETUP },
581 { "multi-pack-index", cmd_multi_pack_index, RUN_SETUP },
582 { "mv", cmd_mv, RUN_SETUP | NEED_WORK_TREE },
583 { "name-rev", cmd_name_rev, RUN_SETUP },
584 { "notes", cmd_notes, RUN_SETUP },
585 { "pack-objects", cmd_pack_objects, RUN_SETUP },
586 { "pack-redundant", cmd_pack_redundant, RUN_SETUP | NO_PARSEOPT },
587 { "pack-refs", cmd_pack_refs, RUN_SETUP },
588 { "patch-id", cmd_patch_id, RUN_SETUP_GENTLY | NO_PARSEOPT },
589 { "pickaxe", cmd_blame, RUN_SETUP },
590 { "prune", cmd_prune, RUN_SETUP },
591 { "prune-packed", cmd_prune_packed, RUN_SETUP },
592 { "pull", cmd_pull, RUN_SETUP | NEED_WORK_TREE },
593 { "push", cmd_push, RUN_SETUP },
594 { "range-diff", cmd_range_diff, RUN_SETUP | USE_PAGER },
595 { "read-tree", cmd_read_tree, RUN_SETUP },
596 { "rebase", cmd_rebase, RUN_SETUP | NEED_WORK_TREE },
597 { "receive-pack", cmd_receive_pack },
598 { "reflog", cmd_reflog, RUN_SETUP },
599 { "refs", cmd_refs, RUN_SETUP },
600 { "remote", cmd_remote, RUN_SETUP },
601 { "remote-ext", cmd_remote_ext, NO_PARSEOPT },
602 { "remote-fd", cmd_remote_fd, NO_PARSEOPT },
603 { "repack", cmd_repack, RUN_SETUP },
604 { "replace", cmd_replace, RUN_SETUP },
605 { "replay", cmd_replay, RUN_SETUP },
606 { "rerere", cmd_rerere, RUN_SETUP },
607 { "reset", cmd_reset, RUN_SETUP },
608 { "restore", cmd_restore, RUN_SETUP | NEED_WORK_TREE },
609 { "rev-list", cmd_rev_list, RUN_SETUP | NO_PARSEOPT },
610 { "rev-parse", cmd_rev_parse, NO_PARSEOPT },
611 { "revert", cmd_revert, RUN_SETUP | NEED_WORK_TREE },
612 { "rm", cmd_rm, RUN_SETUP },
613 { "send-pack", cmd_send_pack, RUN_SETUP },
614 { "shortlog", cmd_shortlog, RUN_SETUP_GENTLY | USE_PAGER },
615 { "show", cmd_show, RUN_SETUP },
616 { "show-branch", cmd_show_branch, RUN_SETUP },
617 { "show-index", cmd_show_index, RUN_SETUP_GENTLY },
618 { "show-ref", cmd_show_ref, RUN_SETUP },
619 { "sparse-checkout", cmd_sparse_checkout, RUN_SETUP },
620 { "stage", cmd_add, RUN_SETUP | NEED_WORK_TREE },
621 { "stash", cmd_stash, RUN_SETUP | NEED_WORK_TREE },
622 { "status", cmd_status, RUN_SETUP | NEED_WORK_TREE },
623 { "stripspace", cmd_stripspace },
624 { "submodule--helper", cmd_submodule__helper, RUN_SETUP },
625 { "switch", cmd_switch, RUN_SETUP | NEED_WORK_TREE },
626 { "symbolic-ref", cmd_symbolic_ref, RUN_SETUP },
627 { "tag", cmd_tag, RUN_SETUP | DELAY_PAGER_CONFIG },
628 { "unpack-file", cmd_unpack_file, RUN_SETUP | NO_PARSEOPT },
629 { "unpack-objects", cmd_unpack_objects, RUN_SETUP | NO_PARSEOPT },
630 { "update-index", cmd_update_index, RUN_SETUP },
631 { "update-ref", cmd_update_ref, RUN_SETUP },
632 { "update-server-info", cmd_update_server_info, RUN_SETUP },
633 { "upload-archive", cmd_upload_archive, NO_PARSEOPT },
634 { "upload-archive--writer", cmd_upload_archive_writer, NO_PARSEOPT },
635 { "upload-pack", cmd_upload_pack },
636 { "var", cmd_var, RUN_SETUP_GENTLY | NO_PARSEOPT },
637 { "verify-commit", cmd_verify_commit, RUN_SETUP },
638 { "verify-pack", cmd_verify_pack },
639 { "verify-tag", cmd_verify_tag, RUN_SETUP },
640 { "version", cmd_version },
641 { "whatchanged", cmd_whatchanged, RUN_SETUP },
642 { "worktree", cmd_worktree, RUN_SETUP },
643 { "write-tree", cmd_write_tree, RUN_SETUP },
646 static struct cmd_struct *get_builtin(const char *s)
648 int i;
649 for (i = 0; i < ARRAY_SIZE(commands); i++) {
650 struct cmd_struct *p = commands + i;
651 if (!strcmp(s, p->cmd))
652 return p;
654 return NULL;
657 int is_builtin(const char *s)
659 return !!get_builtin(s);
662 static void list_builtins(struct string_list *out, unsigned int exclude_option)
664 int i;
665 for (i = 0; i < ARRAY_SIZE(commands); i++) {
666 if (exclude_option &&
667 (commands[i].option & exclude_option))
668 continue;
669 string_list_append(out, commands[i].cmd);
673 void load_builtin_commands(const char *prefix, struct cmdnames *cmds)
675 const char *name;
676 int i;
679 * Callers can ask for a subset of the commands based on a certain
680 * prefix, which is then dropped from the added names. The names in
681 * the `commands[]` array do not have the `git-` prefix, though,
682 * therefore we must expect the `prefix` to at least start with `git-`.
684 if (!skip_prefix(prefix, "git-", &prefix))
685 BUG("prefix '%s' must start with 'git-'", prefix);
687 for (i = 0; i < ARRAY_SIZE(commands); i++)
688 if (skip_prefix(commands[i].cmd, prefix, &name))
689 add_cmdname(cmds, name, strlen(name));
692 #ifdef STRIP_EXTENSION
693 static void strip_extension(const char **argv)
695 size_t len;
697 if (strip_suffix(argv[0], STRIP_EXTENSION, &len))
698 argv[0] = xmemdupz(argv[0], len);
700 #else
701 #define strip_extension(cmd)
702 #endif
704 static void handle_builtin(int argc, const char **argv)
706 struct strvec args = STRVEC_INIT;
707 const char *cmd;
708 struct cmd_struct *builtin;
710 strip_extension(argv);
711 cmd = argv[0];
713 /* Turn "git cmd --help" into "git help --exclude-guides cmd" */
714 if (argc > 1 && !strcmp(argv[1], "--help")) {
715 int i;
717 argv[1] = argv[0];
718 argv[0] = cmd = "help";
720 for (i = 0; i < argc; i++) {
721 strvec_push(&args, argv[i]);
722 if (!i)
723 strvec_push(&args, "--exclude-guides");
726 argc++;
727 argv = args.v;
730 builtin = get_builtin(cmd);
731 if (builtin)
732 exit(run_builtin(builtin, argc, argv));
733 strvec_clear(&args);
736 static void execv_dashed_external(const char **argv)
738 struct child_process cmd = CHILD_PROCESS_INIT;
739 int status;
741 if (use_pager == -1 && !is_builtin(argv[0]))
742 use_pager = check_pager_config(argv[0]);
743 commit_pager_choice();
745 strvec_pushf(&cmd.args, "git-%s", argv[0]);
746 strvec_pushv(&cmd.args, argv + 1);
747 cmd.clean_on_exit = 1;
748 cmd.wait_after_clean = 1;
749 cmd.silent_exec_failure = 1;
750 cmd.trace2_child_class = "dashed";
752 trace2_cmd_name("_run_dashed_");
755 * The code in run_command() logs trace2 child_start/child_exit
756 * events, so we do not need to report exec/exec_result events here.
758 trace_argv_printf(cmd.args.v, "trace: exec:");
761 * If we fail because the command is not found, it is
762 * OK to return. Otherwise, we just pass along the status code,
763 * or our usual generic code if we were not even able to exec
764 * the program.
766 status = run_command(&cmd);
769 * If the child process ran and we are now going to exit, emit a
770 * generic string as our trace2 command verb to indicate that we
771 * launched a dashed command.
773 if (status >= 0)
774 exit(status);
775 else if (errno != ENOENT)
776 exit(128);
779 static int run_argv(int *argcp, const char ***argv)
781 int done_alias = 0;
782 struct string_list cmd_list = STRING_LIST_INIT_NODUP;
783 struct string_list_item *seen;
785 while (1) {
787 * If we tried alias and futzed with our environment,
788 * it no longer is safe to invoke builtins directly in
789 * general. We have to spawn them as dashed externals.
791 * NEEDSWORK: if we can figure out cases
792 * where it is safe to do, we can avoid spawning a new
793 * process.
795 if (!done_alias)
796 handle_builtin(*argcp, *argv);
797 else if (get_builtin(**argv)) {
798 struct child_process cmd = CHILD_PROCESS_INIT;
799 int i;
802 * The current process is committed to launching a
803 * child process to run the command named in (**argv)
804 * and exiting. Log a generic string as the trace2
805 * command verb to indicate this. Note that the child
806 * process will log the actual verb when it runs.
808 trace2_cmd_name("_run_git_alias_");
810 commit_pager_choice();
812 strvec_push(&cmd.args, "git");
813 for (i = 0; i < *argcp; i++)
814 strvec_push(&cmd.args, (*argv)[i]);
816 trace_argv_printf(cmd.args.v, "trace: exec:");
819 * if we fail because the command is not found, it is
820 * OK to return. Otherwise, we just pass along the status code.
822 cmd.silent_exec_failure = 1;
823 cmd.clean_on_exit = 1;
824 cmd.wait_after_clean = 1;
825 cmd.trace2_child_class = "git_alias";
826 i = run_command(&cmd);
827 if (i >= 0 || errno != ENOENT)
828 exit(i);
829 die("could not execute builtin %s", **argv);
832 /* .. then try the external ones */
833 execv_dashed_external(*argv);
835 seen = unsorted_string_list_lookup(&cmd_list, *argv[0]);
836 if (seen) {
837 int i;
838 struct strbuf sb = STRBUF_INIT;
839 for (i = 0; i < cmd_list.nr; i++) {
840 struct string_list_item *item = &cmd_list.items[i];
842 strbuf_addf(&sb, "\n %s", item->string);
843 if (item == seen)
844 strbuf_addstr(&sb, " <==");
845 else if (i == cmd_list.nr - 1)
846 strbuf_addstr(&sb, " ==>");
848 die(_("alias loop detected: expansion of '%s' does"
849 " not terminate:%s"), cmd_list.items[0].string, sb.buf);
852 string_list_append(&cmd_list, *argv[0]);
855 * It could be an alias -- this works around the insanity
856 * of overriding "git log" with "git show" by having
857 * alias.log = show
859 if (!handle_alias(argcp, argv))
860 break;
861 done_alias = 1;
864 string_list_clear(&cmd_list, 0);
866 return done_alias;
869 int cmd_main(int argc, const char **argv)
871 const char *cmd;
872 int done_help = 0;
874 cmd = argv[0];
875 if (!cmd)
876 cmd = "git-help";
877 else {
878 const char *slash = find_last_dir_sep(cmd);
879 if (slash)
880 cmd = slash + 1;
883 trace_command_performance(argv);
886 * "git-xxxx" is the same as "git xxxx", but we obviously:
888 * - cannot take flags in between the "git" and the "xxxx".
889 * - cannot execute it externally (since it would just do
890 * the same thing over again)
892 * So we just directly call the builtin handler, and die if
893 * that one cannot handle it.
895 if (skip_prefix(cmd, "git-", &cmd)) {
896 argv[0] = cmd;
897 handle_builtin(argc, argv);
898 die(_("cannot handle %s as a builtin"), cmd);
901 /* Look for flags.. */
902 argv++;
903 argc--;
904 handle_options(&argv, &argc, NULL);
906 if (!argc) {
907 /* The user didn't specify a command; give them help */
908 commit_pager_choice();
909 printf(_("usage: %s\n\n"), git_usage_string);
910 list_common_cmds_help();
911 printf("\n%s\n", _(git_more_info_string));
912 exit(1);
915 if (!strcmp("--version", argv[0]) || !strcmp("-v", argv[0]))
916 argv[0] = "version";
917 else if (!strcmp("--help", argv[0]) || !strcmp("-h", argv[0]))
918 argv[0] = "help";
920 cmd = argv[0];
923 * We use PATH to find git commands, but we prepend some higher
924 * precedence paths: the "--exec-path" option, the GIT_EXEC_PATH
925 * environment, and the $(gitexecdir) from the Makefile at build
926 * time.
928 setup_path();
930 while (1) {
931 int was_alias = run_argv(&argc, &argv);
932 if (errno != ENOENT)
933 break;
934 if (was_alias) {
935 fprintf(stderr, _("expansion of alias '%s' failed; "
936 "'%s' is not a git command\n"),
937 cmd, argv[0]);
938 exit(1);
940 if (!done_help) {
941 cmd = argv[0] = help_unknown_cmd(cmd);
942 done_help = 1;
943 } else
944 break;
947 fprintf(stderr, _("failed to run command '%s': %s\n"),
948 cmd, strerror(errno));
950 return 1;