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