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