builtin-rev-parse.con commit Let 'git <command> -h' show usage without a git dir (99caeed)
   1/*
   2 * rev-parse.c
   3 *
   4 * Copyright (C) Linus Torvalds, 2005
   5 */
   6#include "cache.h"
   7#include "commit.h"
   8#include "refs.h"
   9#include "quote.h"
  10#include "builtin.h"
  11#include "parse-options.h"
  12
  13#define DO_REVS         1
  14#define DO_NOREV        2
  15#define DO_FLAGS        4
  16#define DO_NONFLAGS     8
  17static int filter = ~0;
  18
  19static const char *def;
  20
  21#define NORMAL 0
  22#define REVERSED 1
  23static int show_type = NORMAL;
  24
  25#define SHOW_SYMBOLIC_ASIS 1
  26#define SHOW_SYMBOLIC_FULL 2
  27static int symbolic;
  28static int abbrev;
  29static int abbrev_ref;
  30static int abbrev_ref_strict;
  31static int output_sq;
  32
  33/*
  34 * Some arguments are relevant "revision" arguments,
  35 * others are about output format or other details.
  36 * This sorts it all out.
  37 */
  38static int is_rev_argument(const char *arg)
  39{
  40        static const char *rev_args[] = {
  41                "--all",
  42                "--bisect",
  43                "--dense",
  44                "--branches",
  45                "--header",
  46                "--max-age=",
  47                "--max-count=",
  48                "--min-age=",
  49                "--no-merges",
  50                "--objects",
  51                "--objects-edge",
  52                "--parents",
  53                "--pretty",
  54                "--remotes",
  55                "--sparse",
  56                "--tags",
  57                "--topo-order",
  58                "--date-order",
  59                "--unpacked",
  60                NULL
  61        };
  62        const char **p = rev_args;
  63
  64        /* accept -<digit>, like traditional "head" */
  65        if ((*arg == '-') && isdigit(arg[1]))
  66                return 1;
  67
  68        for (;;) {
  69                const char *str = *p++;
  70                int len;
  71                if (!str)
  72                        return 0;
  73                len = strlen(str);
  74                if (!strcmp(arg, str) ||
  75                    (str[len-1] == '=' && !strncmp(arg, str, len)))
  76                        return 1;
  77        }
  78}
  79
  80/* Output argument as a string, either SQ or normal */
  81static void show(const char *arg)
  82{
  83        if (output_sq) {
  84                int sq = '\'', ch;
  85
  86                putchar(sq);
  87                while ((ch = *arg++)) {
  88                        if (ch == sq)
  89                                fputs("'\\'", stdout);
  90                        putchar(ch);
  91                }
  92                putchar(sq);
  93                putchar(' ');
  94        }
  95        else
  96                puts(arg);
  97}
  98
  99/* Like show(), but with a negation prefix according to type */
 100static void show_with_type(int type, const char *arg)
 101{
 102        if (type != show_type)
 103                putchar('^');
 104        show(arg);
 105}
 106
 107/* Output a revision, only if filter allows it */
 108static void show_rev(int type, const unsigned char *sha1, const char *name)
 109{
 110        if (!(filter & DO_REVS))
 111                return;
 112        def = NULL;
 113
 114        if ((symbolic || abbrev_ref) && name) {
 115                if (symbolic == SHOW_SYMBOLIC_FULL || abbrev_ref) {
 116                        unsigned char discard[20];
 117                        char *full;
 118
 119                        switch (dwim_ref(name, strlen(name), discard, &full)) {
 120                        case 0:
 121                                /*
 122                                 * Not found -- not a ref.  We could
 123                                 * emit "name" here, but symbolic-full
 124                                 * users are interested in finding the
 125                                 * refs spelled in full, and they would
 126                                 * need to filter non-refs if we did so.
 127                                 */
 128                                break;
 129                        case 1: /* happy */
 130                                if (abbrev_ref)
 131                                        full = shorten_unambiguous_ref(full,
 132                                                abbrev_ref_strict);
 133                                show_with_type(type, full);
 134                                break;
 135                        default: /* ambiguous */
 136                                error("refname '%s' is ambiguous", name);
 137                                break;
 138                        }
 139                } else {
 140                        show_with_type(type, name);
 141                }
 142        }
 143        else if (abbrev)
 144                show_with_type(type, find_unique_abbrev(sha1, abbrev));
 145        else
 146                show_with_type(type, sha1_to_hex(sha1));
 147}
 148
 149/* Output a flag, only if filter allows it. */
 150static int show_flag(const char *arg)
 151{
 152        if (!(filter & DO_FLAGS))
 153                return 0;
 154        if (filter & (is_rev_argument(arg) ? DO_REVS : DO_NOREV)) {
 155                show(arg);
 156                return 1;
 157        }
 158        return 0;
 159}
 160
 161static int show_default(void)
 162{
 163        const char *s = def;
 164
 165        if (s) {
 166                unsigned char sha1[20];
 167
 168                def = NULL;
 169                if (!get_sha1(s, sha1)) {
 170                        show_rev(NORMAL, sha1, s);
 171                        return 1;
 172                }
 173        }
 174        return 0;
 175}
 176
 177static int show_reference(const char *refname, const unsigned char *sha1, int flag, void *cb_data)
 178{
 179        show_rev(NORMAL, sha1, refname);
 180        return 0;
 181}
 182
 183static void show_datestring(const char *flag, const char *datestr)
 184{
 185        static char buffer[100];
 186
 187        /* date handling requires both flags and revs */
 188        if ((filter & (DO_FLAGS | DO_REVS)) != (DO_FLAGS | DO_REVS))
 189                return;
 190        snprintf(buffer, sizeof(buffer), "%s%lu", flag, approxidate(datestr));
 191        show(buffer);
 192}
 193
 194static int show_file(const char *arg)
 195{
 196        show_default();
 197        if ((filter & (DO_NONFLAGS|DO_NOREV)) == (DO_NONFLAGS|DO_NOREV)) {
 198                show(arg);
 199                return 1;
 200        }
 201        return 0;
 202}
 203
 204static int try_difference(const char *arg)
 205{
 206        char *dotdot;
 207        unsigned char sha1[20];
 208        unsigned char end[20];
 209        const char *next;
 210        const char *this;
 211        int symmetric;
 212
 213        if (!(dotdot = strstr(arg, "..")))
 214                return 0;
 215        next = dotdot + 2;
 216        this = arg;
 217        symmetric = (*next == '.');
 218
 219        *dotdot = 0;
 220        next += symmetric;
 221
 222        if (!*next)
 223                next = "HEAD";
 224        if (dotdot == arg)
 225                this = "HEAD";
 226        if (!get_sha1(this, sha1) && !get_sha1(next, end)) {
 227                show_rev(NORMAL, end, next);
 228                show_rev(symmetric ? NORMAL : REVERSED, sha1, this);
 229                if (symmetric) {
 230                        struct commit_list *exclude;
 231                        struct commit *a, *b;
 232                        a = lookup_commit_reference(sha1);
 233                        b = lookup_commit_reference(end);
 234                        exclude = get_merge_bases(a, b, 1);
 235                        while (exclude) {
 236                                struct commit_list *n = exclude->next;
 237                                show_rev(REVERSED,
 238                                         exclude->item->object.sha1,NULL);
 239                                free(exclude);
 240                                exclude = n;
 241                        }
 242                }
 243                return 1;
 244        }
 245        *dotdot = '.';
 246        return 0;
 247}
 248
 249static int try_parent_shorthands(const char *arg)
 250{
 251        char *dotdot;
 252        unsigned char sha1[20];
 253        struct commit *commit;
 254        struct commit_list *parents;
 255        int parents_only;
 256
 257        if ((dotdot = strstr(arg, "^!")))
 258                parents_only = 0;
 259        else if ((dotdot = strstr(arg, "^@")))
 260                parents_only = 1;
 261
 262        if (!dotdot || dotdot[2])
 263                return 0;
 264
 265        *dotdot = 0;
 266        if (get_sha1(arg, sha1))
 267                return 0;
 268
 269        if (!parents_only)
 270                show_rev(NORMAL, sha1, arg);
 271        commit = lookup_commit_reference(sha1);
 272        for (parents = commit->parents; parents; parents = parents->next)
 273                show_rev(parents_only ? NORMAL : REVERSED,
 274                                parents->item->object.sha1, arg);
 275
 276        return 1;
 277}
 278
 279static int parseopt_dump(const struct option *o, const char *arg, int unset)
 280{
 281        struct strbuf *parsed = o->value;
 282        if (unset)
 283                strbuf_addf(parsed, " --no-%s", o->long_name);
 284        else if (o->short_name)
 285                strbuf_addf(parsed, " -%c", o->short_name);
 286        else
 287                strbuf_addf(parsed, " --%s", o->long_name);
 288        if (arg) {
 289                strbuf_addch(parsed, ' ');
 290                sq_quote_buf(parsed, arg);
 291        }
 292        return 0;
 293}
 294
 295static const char *skipspaces(const char *s)
 296{
 297        while (isspace(*s))
 298                s++;
 299        return s;
 300}
 301
 302static int cmd_parseopt(int argc, const char **argv, const char *prefix)
 303{
 304        static int keep_dashdash = 0, stop_at_non_option = 0;
 305        static char const * const parseopt_usage[] = {
 306                "git rev-parse --parseopt [options] -- [<args>...]",
 307                NULL
 308        };
 309        static struct option parseopt_opts[] = {
 310                OPT_BOOLEAN(0, "keep-dashdash", &keep_dashdash,
 311                                        "keep the `--` passed as an arg"),
 312                OPT_BOOLEAN(0, "stop-at-non-option", &stop_at_non_option,
 313                                        "stop parsing after the "
 314                                        "first non-option argument"),
 315                OPT_END(),
 316        };
 317
 318        struct strbuf sb = STRBUF_INIT, parsed = STRBUF_INIT;
 319        const char **usage = NULL;
 320        struct option *opts = NULL;
 321        int onb = 0, osz = 0, unb = 0, usz = 0;
 322
 323        strbuf_addstr(&parsed, "set --");
 324        argc = parse_options(argc, argv, prefix, parseopt_opts, parseopt_usage,
 325                             PARSE_OPT_KEEP_DASHDASH);
 326        if (argc < 1 || strcmp(argv[0], "--"))
 327                usage_with_options(parseopt_usage, parseopt_opts);
 328
 329        /* get the usage up to the first line with a -- on it */
 330        for (;;) {
 331                if (strbuf_getline(&sb, stdin, '\n') == EOF)
 332                        die("premature end of input");
 333                ALLOC_GROW(usage, unb + 1, usz);
 334                if (!strcmp("--", sb.buf)) {
 335                        if (unb < 1)
 336                                die("no usage string given before the `--' separator");
 337                        usage[unb] = NULL;
 338                        break;
 339                }
 340                usage[unb++] = strbuf_detach(&sb, NULL);
 341        }
 342
 343        /* parse: (<short>|<short>,<long>|<long>)[=?]? SP+ <help> */
 344        while (strbuf_getline(&sb, stdin, '\n') != EOF) {
 345                const char *s;
 346                struct option *o;
 347
 348                if (!sb.len)
 349                        continue;
 350
 351                ALLOC_GROW(opts, onb + 1, osz);
 352                memset(opts + onb, 0, sizeof(opts[onb]));
 353
 354                o = &opts[onb++];
 355                s = strchr(sb.buf, ' ');
 356                if (!s || *sb.buf == ' ') {
 357                        o->type = OPTION_GROUP;
 358                        o->help = xstrdup(skipspaces(sb.buf));
 359                        continue;
 360                }
 361
 362                o->type = OPTION_CALLBACK;
 363                o->help = xstrdup(skipspaces(s));
 364                o->value = &parsed;
 365                o->flags = PARSE_OPT_NOARG;
 366                o->callback = &parseopt_dump;
 367                while (s > sb.buf && strchr("*=?!", s[-1])) {
 368                        switch (*--s) {
 369                        case '=':
 370                                o->flags &= ~PARSE_OPT_NOARG;
 371                                break;
 372                        case '?':
 373                                o->flags &= ~PARSE_OPT_NOARG;
 374                                o->flags |= PARSE_OPT_OPTARG;
 375                                break;
 376                        case '!':
 377                                o->flags |= PARSE_OPT_NONEG;
 378                                break;
 379                        case '*':
 380                                o->flags |= PARSE_OPT_HIDDEN;
 381                                break;
 382                        }
 383                }
 384
 385                if (s - sb.buf == 1) /* short option only */
 386                        o->short_name = *sb.buf;
 387                else if (sb.buf[1] != ',') /* long option only */
 388                        o->long_name = xmemdupz(sb.buf, s - sb.buf);
 389                else {
 390                        o->short_name = *sb.buf;
 391                        o->long_name = xmemdupz(sb.buf + 2, s - sb.buf - 2);
 392                }
 393        }
 394        strbuf_release(&sb);
 395
 396        /* put an OPT_END() */
 397        ALLOC_GROW(opts, onb + 1, osz);
 398        memset(opts + onb, 0, sizeof(opts[onb]));
 399        argc = parse_options(argc, argv, prefix, opts, usage,
 400                        keep_dashdash ? PARSE_OPT_KEEP_DASHDASH : 0 |
 401                        stop_at_non_option ? PARSE_OPT_STOP_AT_NON_OPTION : 0);
 402
 403        strbuf_addf(&parsed, " --");
 404        sq_quote_argv(&parsed, argv, 0);
 405        puts(parsed.buf);
 406        return 0;
 407}
 408
 409static int cmd_sq_quote(int argc, const char **argv)
 410{
 411        struct strbuf buf = STRBUF_INIT;
 412
 413        if (argc)
 414                sq_quote_argv(&buf, argv, 0);
 415        printf("%s\n", buf.buf);
 416        strbuf_release(&buf);
 417
 418        return 0;
 419}
 420
 421static void die_no_single_rev(int quiet)
 422{
 423        if (quiet)
 424                exit(1);
 425        else
 426                die("Needed a single revision");
 427}
 428
 429static const char builtin_rev_parse_usage[] =
 430"git rev-parse --parseopt [options] -- [<args>...]\n"
 431"   or: git rev-parse --sq-quote [<arg>...]\n"
 432"   or: git rev-parse [options] [<arg>...]\n"
 433"\n"
 434"Run \"git rev-parse --parseopt -h\" for more information on the first usage.";
 435
 436int cmd_rev_parse(int argc, const char **argv, const char *prefix)
 437{
 438        int i, as_is = 0, verify = 0, quiet = 0, revs_count = 0, type = 0;
 439        unsigned char sha1[20];
 440        const char *name = NULL;
 441
 442        if (argc > 1 && !strcmp("--parseopt", argv[1]))
 443                return cmd_parseopt(argc - 1, argv + 1, prefix);
 444
 445        if (argc > 1 && !strcmp("--sq-quote", argv[1]))
 446                return cmd_sq_quote(argc - 2, argv + 2);
 447
 448        if (argc > 1 && !strcmp("-h", argv[1]))
 449                usage(builtin_rev_parse_usage);
 450
 451        prefix = setup_git_directory();
 452        git_config(git_default_config, NULL);
 453        for (i = 1; i < argc; i++) {
 454                const char *arg = argv[i];
 455
 456                if (as_is) {
 457                        if (show_file(arg) && as_is < 2)
 458                                verify_filename(prefix, arg);
 459                        continue;
 460                }
 461                if (!strcmp(arg,"-n")) {
 462                        if (++i >= argc)
 463                                die("-n requires an argument");
 464                        if ((filter & DO_FLAGS) && (filter & DO_REVS)) {
 465                                show(arg);
 466                                show(argv[i]);
 467                        }
 468                        continue;
 469                }
 470                if (!prefixcmp(arg, "-n")) {
 471                        if ((filter & DO_FLAGS) && (filter & DO_REVS))
 472                                show(arg);
 473                        continue;
 474                }
 475
 476                if (*arg == '-') {
 477                        if (!strcmp(arg, "--")) {
 478                                as_is = 2;
 479                                /* Pass on the "--" if we show anything but files.. */
 480                                if (filter & (DO_FLAGS | DO_REVS))
 481                                        show_file(arg);
 482                                continue;
 483                        }
 484                        if (!strcmp(arg, "--default")) {
 485                                def = argv[i+1];
 486                                i++;
 487                                continue;
 488                        }
 489                        if (!strcmp(arg, "--revs-only")) {
 490                                filter &= ~DO_NOREV;
 491                                continue;
 492                        }
 493                        if (!strcmp(arg, "--no-revs")) {
 494                                filter &= ~DO_REVS;
 495                                continue;
 496                        }
 497                        if (!strcmp(arg, "--flags")) {
 498                                filter &= ~DO_NONFLAGS;
 499                                continue;
 500                        }
 501                        if (!strcmp(arg, "--no-flags")) {
 502                                filter &= ~DO_FLAGS;
 503                                continue;
 504                        }
 505                        if (!strcmp(arg, "--verify")) {
 506                                filter &= ~(DO_FLAGS|DO_NOREV);
 507                                verify = 1;
 508                                continue;
 509                        }
 510                        if (!strcmp(arg, "--quiet") || !strcmp(arg, "-q")) {
 511                                quiet = 1;
 512                                continue;
 513                        }
 514                        if (!strcmp(arg, "--short") ||
 515                            !prefixcmp(arg, "--short=")) {
 516                                filter &= ~(DO_FLAGS|DO_NOREV);
 517                                verify = 1;
 518                                abbrev = DEFAULT_ABBREV;
 519                                if (arg[7] == '=')
 520                                        abbrev = strtoul(arg + 8, NULL, 10);
 521                                if (abbrev < MINIMUM_ABBREV)
 522                                        abbrev = MINIMUM_ABBREV;
 523                                else if (40 <= abbrev)
 524                                        abbrev = 40;
 525                                continue;
 526                        }
 527                        if (!strcmp(arg, "--sq")) {
 528                                output_sq = 1;
 529                                continue;
 530                        }
 531                        if (!strcmp(arg, "--not")) {
 532                                show_type ^= REVERSED;
 533                                continue;
 534                        }
 535                        if (!strcmp(arg, "--symbolic")) {
 536                                symbolic = SHOW_SYMBOLIC_ASIS;
 537                                continue;
 538                        }
 539                        if (!strcmp(arg, "--symbolic-full-name")) {
 540                                symbolic = SHOW_SYMBOLIC_FULL;
 541                                continue;
 542                        }
 543                        if (!prefixcmp(arg, "--abbrev-ref") &&
 544                            (!arg[12] || arg[12] == '=')) {
 545                                abbrev_ref = 1;
 546                                abbrev_ref_strict = warn_ambiguous_refs;
 547                                if (arg[12] == '=') {
 548                                        if (!strcmp(arg + 13, "strict"))
 549                                                abbrev_ref_strict = 1;
 550                                        else if (!strcmp(arg + 13, "loose"))
 551                                                abbrev_ref_strict = 0;
 552                                        else
 553                                                die("unknown mode for %s", arg);
 554                                }
 555                                continue;
 556                        }
 557                        if (!strcmp(arg, "--all")) {
 558                                for_each_ref(show_reference, NULL);
 559                                continue;
 560                        }
 561                        if (!strcmp(arg, "--branches")) {
 562                                for_each_branch_ref(show_reference, NULL);
 563                                continue;
 564                        }
 565                        if (!strcmp(arg, "--tags")) {
 566                                for_each_tag_ref(show_reference, NULL);
 567                                continue;
 568                        }
 569                        if (!strcmp(arg, "--remotes")) {
 570                                for_each_remote_ref(show_reference, NULL);
 571                                continue;
 572                        }
 573                        if (!strcmp(arg, "--show-prefix")) {
 574                                if (prefix)
 575                                        puts(prefix);
 576                                continue;
 577                        }
 578                        if (!strcmp(arg, "--show-cdup")) {
 579                                const char *pfx = prefix;
 580                                if (!is_inside_work_tree()) {
 581                                        const char *work_tree =
 582                                                get_git_work_tree();
 583                                        if (work_tree)
 584                                                printf("%s\n", work_tree);
 585                                        continue;
 586                                }
 587                                while (pfx) {
 588                                        pfx = strchr(pfx, '/');
 589                                        if (pfx) {
 590                                                pfx++;
 591                                                printf("../");
 592                                        }
 593                                }
 594                                putchar('\n');
 595                                continue;
 596                        }
 597                        if (!strcmp(arg, "--git-dir")) {
 598                                const char *gitdir = getenv(GIT_DIR_ENVIRONMENT);
 599                                static char cwd[PATH_MAX];
 600                                if (gitdir) {
 601                                        puts(gitdir);
 602                                        continue;
 603                                }
 604                                if (!prefix) {
 605                                        puts(".git");
 606                                        continue;
 607                                }
 608                                if (!getcwd(cwd, PATH_MAX))
 609                                        die_errno("unable to get current working directory");
 610                                printf("%s/.git\n", cwd);
 611                                continue;
 612                        }
 613                        if (!strcmp(arg, "--is-inside-git-dir")) {
 614                                printf("%s\n", is_inside_git_dir() ? "true"
 615                                                : "false");
 616                                continue;
 617                        }
 618                        if (!strcmp(arg, "--is-inside-work-tree")) {
 619                                printf("%s\n", is_inside_work_tree() ? "true"
 620                                                : "false");
 621                                continue;
 622                        }
 623                        if (!strcmp(arg, "--is-bare-repository")) {
 624                                printf("%s\n", is_bare_repository() ? "true"
 625                                                : "false");
 626                                continue;
 627                        }
 628                        if (!prefixcmp(arg, "--since=")) {
 629                                show_datestring("--max-age=", arg+8);
 630                                continue;
 631                        }
 632                        if (!prefixcmp(arg, "--after=")) {
 633                                show_datestring("--max-age=", arg+8);
 634                                continue;
 635                        }
 636                        if (!prefixcmp(arg, "--before=")) {
 637                                show_datestring("--min-age=", arg+9);
 638                                continue;
 639                        }
 640                        if (!prefixcmp(arg, "--until=")) {
 641                                show_datestring("--min-age=", arg+8);
 642                                continue;
 643                        }
 644                        if (show_flag(arg) && verify)
 645                                die_no_single_rev(quiet);
 646                        continue;
 647                }
 648
 649                /* Not a flag argument */
 650                if (try_difference(arg))
 651                        continue;
 652                if (try_parent_shorthands(arg))
 653                        continue;
 654                name = arg;
 655                type = NORMAL;
 656                if (*arg == '^') {
 657                        name++;
 658                        type = REVERSED;
 659                }
 660                if (!get_sha1(name, sha1)) {
 661                        if (verify)
 662                                revs_count++;
 663                        else
 664                                show_rev(type, sha1, name);
 665                        continue;
 666                }
 667                if (verify)
 668                        die_no_single_rev(quiet);
 669                as_is = 1;
 670                if (!show_file(arg))
 671                        continue;
 672                verify_filename(prefix, arg);
 673        }
 674        if (verify) {
 675                if (revs_count == 1) {
 676                        show_rev(type, sha1, name);
 677                        return 0;
 678                } else if (revs_count == 0 && show_default())
 679                        return 0;
 680                die_no_single_rev(quiet);
 681        } else
 682                show_default();
 683        return 0;
 684}