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