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