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