Coverage Report

Created: 2024-09-08 06:23

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