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