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