refs.con commit add_ref(): add docstring (6af1038)
   1#include "cache.h"
   2#include "refs.h"
   3#include "object.h"
   4#include "tag.h"
   5#include "dir.h"
   6
   7/* ISSYMREF=0x01, ISPACKED=0x02 and ISBROKEN=0x04 are public interfaces */
   8#define REF_KNOWS_PEELED 0x10
   9
  10struct ref_entry {
  11        unsigned char flag; /* ISSYMREF? ISPACKED? */
  12        unsigned char sha1[20];
  13        unsigned char peeled[20];
  14        /* The full name of the reference (e.g., "refs/heads/master"): */
  15        char name[FLEX_ARRAY];
  16};
  17
  18struct ref_array {
  19        int nr, alloc;
  20        struct ref_entry **refs;
  21};
  22
  23/*
  24 * Parse one line from a packed-refs file.  Write the SHA1 to sha1.
  25 * Return a pointer to the refname within the line (null-terminated),
  26 * or NULL if there was a problem.
  27 */
  28static const char *parse_ref_line(char *line, unsigned char *sha1)
  29{
  30        /*
  31         * 42: the answer to everything.
  32         *
  33         * In this case, it happens to be the answer to
  34         *  40 (length of sha1 hex representation)
  35         *  +1 (space in between hex and name)
  36         *  +1 (newline at the end of the line)
  37         */
  38        int len = strlen(line) - 42;
  39
  40        if (len <= 0)
  41                return NULL;
  42        if (get_sha1_hex(line, sha1) < 0)
  43                return NULL;
  44        if (!isspace(line[40]))
  45                return NULL;
  46        line += 41;
  47        if (isspace(*line))
  48                return NULL;
  49        if (line[len] != '\n')
  50                return NULL;
  51        line[len] = 0;
  52
  53        return line;
  54}
  55
  56/* Add a ref_entry to the end of the ref_array (unsorted). */
  57static void add_ref(const char *refname, const unsigned char *sha1,
  58                    int flag, int check_name, struct ref_array *refs,
  59                    struct ref_entry **new_entry)
  60{
  61        int len;
  62        struct ref_entry *entry;
  63
  64        /* Allocate it and add it in.. */
  65        len = strlen(refname) + 1;
  66        entry = xmalloc(sizeof(struct ref_entry) + len);
  67        hashcpy(entry->sha1, sha1);
  68        hashclr(entry->peeled);
  69        if (check_name &&
  70            check_refname_format(refname, REFNAME_ALLOW_ONELEVEL|REFNAME_DOT_COMPONENT))
  71                die("Reference has invalid format: '%s'", refname);
  72        memcpy(entry->name, refname, len);
  73        entry->flag = flag;
  74        if (new_entry)
  75                *new_entry = entry;
  76        ALLOC_GROW(refs->refs, refs->nr + 1, refs->alloc);
  77        refs->refs[refs->nr++] = entry;
  78}
  79
  80static int ref_entry_cmp(const void *a, const void *b)
  81{
  82        struct ref_entry *one = *(struct ref_entry **)a;
  83        struct ref_entry *two = *(struct ref_entry **)b;
  84        return strcmp(one->name, two->name);
  85}
  86
  87static void sort_ref_array(struct ref_array *array)
  88{
  89        int i = 0, j = 1;
  90
  91        /* Nothing to sort unless there are at least two entries */
  92        if (array->nr < 2)
  93                return;
  94
  95        qsort(array->refs, array->nr, sizeof(*array->refs), ref_entry_cmp);
  96
  97        /* Remove any duplicates from the ref_array */
  98        for (; j < array->nr; j++) {
  99                struct ref_entry *a = array->refs[i];
 100                struct ref_entry *b = array->refs[j];
 101                if (!strcmp(a->name, b->name)) {
 102                        if (hashcmp(a->sha1, b->sha1))
 103                                die("Duplicated ref, and SHA1s don't match: %s",
 104                                    a->name);
 105                        warning("Duplicated ref: %s", a->name);
 106                        free(b);
 107                        continue;
 108                }
 109                i++;
 110                array->refs[i] = array->refs[j];
 111        }
 112        array->nr = i + 1;
 113}
 114
 115static struct ref_entry *search_ref_array(struct ref_array *array, const char *refname)
 116{
 117        struct ref_entry *e, **r;
 118        int len;
 119
 120        if (refname == NULL)
 121                return NULL;
 122
 123        if (!array->nr)
 124                return NULL;
 125
 126        len = strlen(refname) + 1;
 127        e = xmalloc(sizeof(struct ref_entry) + len);
 128        memcpy(e->name, refname, len);
 129
 130        r = bsearch(&e, array->refs, array->nr, sizeof(*array->refs), ref_entry_cmp);
 131
 132        free(e);
 133
 134        if (r == NULL)
 135                return NULL;
 136
 137        return *r;
 138}
 139
 140/*
 141 * Future: need to be in "struct repository"
 142 * when doing a full libification.
 143 */
 144static struct ref_cache {
 145        struct ref_cache *next;
 146        char did_loose;
 147        char did_packed;
 148        struct ref_array loose;
 149        struct ref_array packed;
 150        /* The submodule name, or "" for the main repo. */
 151        char name[FLEX_ARRAY];
 152} *ref_cache;
 153
 154static struct ref_entry *current_ref;
 155
 156static struct ref_array extra_refs;
 157
 158static void clear_ref_array(struct ref_array *array)
 159{
 160        int i;
 161        for (i = 0; i < array->nr; i++)
 162                free(array->refs[i]);
 163        free(array->refs);
 164        array->nr = array->alloc = 0;
 165        array->refs = NULL;
 166}
 167
 168static void clear_packed_ref_cache(struct ref_cache *refs)
 169{
 170        if (refs->did_packed)
 171                clear_ref_array(&refs->packed);
 172        refs->did_packed = 0;
 173}
 174
 175static void clear_loose_ref_cache(struct ref_cache *refs)
 176{
 177        if (refs->did_loose)
 178                clear_ref_array(&refs->loose);
 179        refs->did_loose = 0;
 180}
 181
 182static struct ref_cache *create_ref_cache(const char *submodule)
 183{
 184        int len;
 185        struct ref_cache *refs;
 186        if (!submodule)
 187                submodule = "";
 188        len = strlen(submodule) + 1;
 189        refs = xcalloc(1, sizeof(struct ref_cache) + len);
 190        memcpy(refs->name, submodule, len);
 191        return refs;
 192}
 193
 194/*
 195 * Return a pointer to a ref_cache for the specified submodule. For
 196 * the main repository, use submodule==NULL. The returned structure
 197 * will be allocated and initialized but not necessarily populated; it
 198 * should not be freed.
 199 */
 200static struct ref_cache *get_ref_cache(const char *submodule)
 201{
 202        struct ref_cache *refs = ref_cache;
 203        if (!submodule)
 204                submodule = "";
 205        while (refs) {
 206                if (!strcmp(submodule, refs->name))
 207                        return refs;
 208                refs = refs->next;
 209        }
 210
 211        refs = create_ref_cache(submodule);
 212        refs->next = ref_cache;
 213        ref_cache = refs;
 214        return refs;
 215}
 216
 217void invalidate_ref_cache(const char *submodule)
 218{
 219        struct ref_cache *refs = get_ref_cache(submodule);
 220        clear_packed_ref_cache(refs);
 221        clear_loose_ref_cache(refs);
 222}
 223
 224static void read_packed_refs(FILE *f, struct ref_array *array)
 225{
 226        struct ref_entry *last = NULL;
 227        char refline[PATH_MAX];
 228        int flag = REF_ISPACKED;
 229
 230        while (fgets(refline, sizeof(refline), f)) {
 231                unsigned char sha1[20];
 232                const char *refname;
 233                static const char header[] = "# pack-refs with:";
 234
 235                if (!strncmp(refline, header, sizeof(header)-1)) {
 236                        const char *traits = refline + sizeof(header) - 1;
 237                        if (strstr(traits, " peeled "))
 238                                flag |= REF_KNOWS_PEELED;
 239                        /* perhaps other traits later as well */
 240                        continue;
 241                }
 242
 243                refname = parse_ref_line(refline, sha1);
 244                if (refname) {
 245                        add_ref(refname, sha1, flag, 1, array, &last);
 246                        continue;
 247                }
 248                if (last &&
 249                    refline[0] == '^' &&
 250                    strlen(refline) == 42 &&
 251                    refline[41] == '\n' &&
 252                    !get_sha1_hex(refline + 1, sha1))
 253                        hashcpy(last->peeled, sha1);
 254        }
 255        sort_ref_array(array);
 256}
 257
 258void add_extra_ref(const char *refname, const unsigned char *sha1, int flag)
 259{
 260        add_ref(refname, sha1, flag, 0, &extra_refs, NULL);
 261}
 262
 263void clear_extra_refs(void)
 264{
 265        clear_ref_array(&extra_refs);
 266}
 267
 268static struct ref_array *get_packed_refs(const char *submodule)
 269{
 270        struct ref_cache *refs = get_ref_cache(submodule);
 271
 272        if (!refs->did_packed) {
 273                const char *packed_refs_file;
 274                FILE *f;
 275
 276                if (submodule)
 277                        packed_refs_file = git_path_submodule(submodule, "packed-refs");
 278                else
 279                        packed_refs_file = git_path("packed-refs");
 280                f = fopen(packed_refs_file, "r");
 281                if (f) {
 282                        read_packed_refs(f, &refs->packed);
 283                        fclose(f);
 284                }
 285                refs->did_packed = 1;
 286        }
 287        return &refs->packed;
 288}
 289
 290static void get_ref_dir(const char *submodule, const char *base,
 291                        struct ref_array *array)
 292{
 293        DIR *dir;
 294        const char *path;
 295
 296        if (submodule)
 297                path = git_path_submodule(submodule, "%s", base);
 298        else
 299                path = git_path("%s", base);
 300
 301
 302        dir = opendir(path);
 303
 304        if (dir) {
 305                struct dirent *de;
 306                int baselen = strlen(base);
 307                char *refname = xmalloc(baselen + 257);
 308
 309                memcpy(refname, base, baselen);
 310                if (baselen && base[baselen-1] != '/')
 311                        refname[baselen++] = '/';
 312
 313                while ((de = readdir(dir)) != NULL) {
 314                        unsigned char sha1[20];
 315                        struct stat st;
 316                        int flag;
 317                        int namelen;
 318                        const char *refdir;
 319
 320                        if (de->d_name[0] == '.')
 321                                continue;
 322                        namelen = strlen(de->d_name);
 323                        if (namelen > 255)
 324                                continue;
 325                        if (has_extension(de->d_name, ".lock"))
 326                                continue;
 327                        memcpy(refname + baselen, de->d_name, namelen+1);
 328                        refdir = submodule
 329                                ? git_path_submodule(submodule, "%s", refname)
 330                                : git_path("%s", refname);
 331                        if (stat(refdir, &st) < 0)
 332                                continue;
 333                        if (S_ISDIR(st.st_mode)) {
 334                                get_ref_dir(submodule, refname, array);
 335                                continue;
 336                        }
 337                        if (submodule) {
 338                                hashclr(sha1);
 339                                flag = 0;
 340                                if (resolve_gitlink_ref(submodule, refname, sha1) < 0) {
 341                                        hashclr(sha1);
 342                                        flag |= REF_ISBROKEN;
 343                                }
 344                        } else if (read_ref_full(refname, sha1, 1, &flag)) {
 345                                hashclr(sha1);
 346                                flag |= REF_ISBROKEN;
 347                        }
 348                        add_ref(refname, sha1, flag, 1, array, NULL);
 349                }
 350                free(refname);
 351                closedir(dir);
 352        }
 353}
 354
 355struct warn_if_dangling_data {
 356        FILE *fp;
 357        const char *refname;
 358        const char *msg_fmt;
 359};
 360
 361static int warn_if_dangling_symref(const char *refname, const unsigned char *sha1,
 362                                   int flags, void *cb_data)
 363{
 364        struct warn_if_dangling_data *d = cb_data;
 365        const char *resolves_to;
 366        unsigned char junk[20];
 367
 368        if (!(flags & REF_ISSYMREF))
 369                return 0;
 370
 371        resolves_to = resolve_ref(refname, junk, 0, NULL);
 372        if (!resolves_to || strcmp(resolves_to, d->refname))
 373                return 0;
 374
 375        fprintf(d->fp, d->msg_fmt, refname);
 376        return 0;
 377}
 378
 379void warn_dangling_symref(FILE *fp, const char *msg_fmt, const char *refname)
 380{
 381        struct warn_if_dangling_data data;
 382
 383        data.fp = fp;
 384        data.refname = refname;
 385        data.msg_fmt = msg_fmt;
 386        for_each_rawref(warn_if_dangling_symref, &data);
 387}
 388
 389static struct ref_array *get_loose_refs(const char *submodule)
 390{
 391        struct ref_cache *refs = get_ref_cache(submodule);
 392
 393        if (!refs->did_loose) {
 394                get_ref_dir(submodule, "refs", &refs->loose);
 395                sort_ref_array(&refs->loose);
 396                refs->did_loose = 1;
 397        }
 398        return &refs->loose;
 399}
 400
 401/* We allow "recursive" symbolic refs. Only within reason, though */
 402#define MAXDEPTH 5
 403#define MAXREFLEN (1024)
 404
 405/*
 406 * Called by resolve_gitlink_ref_recursive() after it failed to read
 407 * from "name", which is "module/.git/<refname>". Find <refname> in
 408 * the packed-refs file for the submodule.
 409 */
 410static int resolve_gitlink_packed_ref(char *name, int pathlen,
 411                                      const char *refname, unsigned char *sha1)
 412{
 413        int retval = -1;
 414        struct ref_entry *ref;
 415        struct ref_array *array;
 416
 417        /* being defensive: resolve_gitlink_ref() did this for us */
 418        if (pathlen < 6 || memcmp(name + pathlen - 6, "/.git/", 6))
 419                die("Oops");
 420        name[pathlen - 6] = '\0'; /* make it path to the submodule */
 421        array = get_packed_refs(name);
 422        ref = search_ref_array(array, refname);
 423        if (ref != NULL) {
 424                memcpy(sha1, ref->sha1, 20);
 425                retval = 0;
 426        }
 427        return retval;
 428}
 429
 430static int resolve_gitlink_ref_recursive(char *name, int pathlen,
 431                                         const char *refname, unsigned char *sha1,
 432                                         int recursion)
 433{
 434        int fd, len = strlen(refname);
 435        char buffer[128], *p;
 436
 437        if (recursion > MAXDEPTH || len > MAXREFLEN)
 438                return -1;
 439        memcpy(name + pathlen, refname, len+1);
 440        fd = open(name, O_RDONLY);
 441        if (fd < 0)
 442                return resolve_gitlink_packed_ref(name, pathlen, refname, sha1);
 443
 444        len = read(fd, buffer, sizeof(buffer)-1);
 445        close(fd);
 446        if (len < 0)
 447                return -1;
 448        while (len && isspace(buffer[len-1]))
 449                len--;
 450        buffer[len] = 0;
 451
 452        /* Was it a detached head or an old-fashioned symlink? */
 453        if (!get_sha1_hex(buffer, sha1))
 454                return 0;
 455
 456        /* Symref? */
 457        if (strncmp(buffer, "ref:", 4))
 458                return -1;
 459        p = buffer + 4;
 460        while (isspace(*p))
 461                p++;
 462
 463        return resolve_gitlink_ref_recursive(name, pathlen, p, sha1, recursion+1);
 464}
 465
 466int resolve_gitlink_ref(const char *path, const char *refname, unsigned char *sha1)
 467{
 468        int len = strlen(path), retval;
 469        char *gitdir;
 470        const char *tmp;
 471
 472        while (len && path[len-1] == '/')
 473                len--;
 474        if (!len)
 475                return -1;
 476        gitdir = xmalloc(len + MAXREFLEN + 8);
 477        memcpy(gitdir, path, len);
 478        memcpy(gitdir + len, "/.git", 6);
 479        len += 5;
 480
 481        tmp = read_gitfile(gitdir);
 482        if (tmp) {
 483                free(gitdir);
 484                len = strlen(tmp);
 485                gitdir = xmalloc(len + MAXREFLEN + 3);
 486                memcpy(gitdir, tmp, len);
 487        }
 488        gitdir[len] = '/';
 489        gitdir[++len] = '\0';
 490        retval = resolve_gitlink_ref_recursive(gitdir, len, refname, sha1, 0);
 491        free(gitdir);
 492        return retval;
 493}
 494
 495/*
 496 * Try to read ref from the packed references.  On success, set sha1
 497 * and return 0; otherwise, return -1.
 498 */
 499static int get_packed_ref(const char *refname, unsigned char *sha1)
 500{
 501        struct ref_array *packed = get_packed_refs(NULL);
 502        struct ref_entry *entry = search_ref_array(packed, refname);
 503        if (entry) {
 504                hashcpy(sha1, entry->sha1);
 505                return 0;
 506        }
 507        return -1;
 508}
 509
 510const char *resolve_ref(const char *refname, unsigned char *sha1, int reading, int *flag)
 511{
 512        int depth = MAXDEPTH;
 513        ssize_t len;
 514        char buffer[256];
 515        static char refname_buffer[256];
 516
 517        if (flag)
 518                *flag = 0;
 519
 520        if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL))
 521                return NULL;
 522
 523        for (;;) {
 524                char path[PATH_MAX];
 525                struct stat st;
 526                char *buf;
 527                int fd;
 528
 529                if (--depth < 0)
 530                        return NULL;
 531
 532                git_snpath(path, sizeof(path), "%s", refname);
 533
 534                if (lstat(path, &st) < 0) {
 535                        if (errno != ENOENT)
 536                                return NULL;
 537                        /*
 538                         * The loose reference file does not exist;
 539                         * check for a packed reference.
 540                         */
 541                        if (!get_packed_ref(refname, sha1)) {
 542                                if (flag)
 543                                        *flag |= REF_ISPACKED;
 544                                return refname;
 545                        }
 546                        /* The reference is not a packed reference, either. */
 547                        if (reading) {
 548                                return NULL;
 549                        } else {
 550                                hashclr(sha1);
 551                                return refname;
 552                        }
 553                }
 554
 555                /* Follow "normalized" - ie "refs/.." symlinks by hand */
 556                if (S_ISLNK(st.st_mode)) {
 557                        len = readlink(path, buffer, sizeof(buffer)-1);
 558                        if (len < 0)
 559                                return NULL;
 560                        buffer[len] = 0;
 561                        if (!prefixcmp(buffer, "refs/") &&
 562                                        !check_refname_format(buffer, 0)) {
 563                                strcpy(refname_buffer, buffer);
 564                                refname = refname_buffer;
 565                                if (flag)
 566                                        *flag |= REF_ISSYMREF;
 567                                continue;
 568                        }
 569                }
 570
 571                /* Is it a directory? */
 572                if (S_ISDIR(st.st_mode)) {
 573                        errno = EISDIR;
 574                        return NULL;
 575                }
 576
 577                /*
 578                 * Anything else, just open it and try to use it as
 579                 * a ref
 580                 */
 581                fd = open(path, O_RDONLY);
 582                if (fd < 0)
 583                        return NULL;
 584                len = read_in_full(fd, buffer, sizeof(buffer)-1);
 585                close(fd);
 586                if (len < 0)
 587                        return NULL;
 588                while (len && isspace(buffer[len-1]))
 589                        len--;
 590                buffer[len] = '\0';
 591
 592                /*
 593                 * Is it a symbolic ref?
 594                 */
 595                if (prefixcmp(buffer, "ref:"))
 596                        break;
 597                if (flag)
 598                        *flag |= REF_ISSYMREF;
 599                buf = buffer + 4;
 600                while (isspace(*buf))
 601                        buf++;
 602                if (check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {
 603                        if (flag)
 604                                *flag |= REF_ISBROKEN;
 605                        return NULL;
 606                }
 607                refname = strcpy(refname_buffer, buf);
 608        }
 609        /* Please note that FETCH_HEAD has a second line containing other data. */
 610        if (get_sha1_hex(buffer, sha1) || (buffer[40] != '\0' && !isspace(buffer[40]))) {
 611                if (flag)
 612                        *flag |= REF_ISBROKEN;
 613                return NULL;
 614        }
 615        return refname;
 616}
 617
 618/* The argument to filter_refs */
 619struct ref_filter {
 620        const char *pattern;
 621        each_ref_fn *fn;
 622        void *cb_data;
 623};
 624
 625int read_ref_full(const char *refname, unsigned char *sha1, int reading, int *flags)
 626{
 627        if (resolve_ref(refname, sha1, reading, flags))
 628                return 0;
 629        return -1;
 630}
 631
 632int read_ref(const char *refname, unsigned char *sha1)
 633{
 634        return read_ref_full(refname, sha1, 1, NULL);
 635}
 636
 637#define DO_FOR_EACH_INCLUDE_BROKEN 01
 638static int do_one_ref(const char *base, each_ref_fn fn, int trim,
 639                      int flags, void *cb_data, struct ref_entry *entry)
 640{
 641        if (prefixcmp(entry->name, base))
 642                return 0;
 643
 644        if (!(flags & DO_FOR_EACH_INCLUDE_BROKEN)) {
 645                if (entry->flag & REF_ISBROKEN)
 646                        return 0; /* ignore broken refs e.g. dangling symref */
 647                if (!has_sha1_file(entry->sha1)) {
 648                        error("%s does not point to a valid object!", entry->name);
 649                        return 0;
 650                }
 651        }
 652        current_ref = entry;
 653        return fn(entry->name + trim, entry->sha1, entry->flag, cb_data);
 654}
 655
 656static int filter_refs(const char *refname, const unsigned char *sha1, int flags,
 657                       void *data)
 658{
 659        struct ref_filter *filter = (struct ref_filter *)data;
 660        if (fnmatch(filter->pattern, refname, 0))
 661                return 0;
 662        return filter->fn(refname, sha1, flags, filter->cb_data);
 663}
 664
 665int peel_ref(const char *refname, unsigned char *sha1)
 666{
 667        int flag;
 668        unsigned char base[20];
 669        struct object *o;
 670
 671        if (current_ref && (current_ref->name == refname
 672                || !strcmp(current_ref->name, refname))) {
 673                if (current_ref->flag & REF_KNOWS_PEELED) {
 674                        hashcpy(sha1, current_ref->peeled);
 675                        return 0;
 676                }
 677                hashcpy(base, current_ref->sha1);
 678                goto fallback;
 679        }
 680
 681        if (read_ref_full(refname, base, 1, &flag))
 682                return -1;
 683
 684        if ((flag & REF_ISPACKED)) {
 685                struct ref_array *array = get_packed_refs(NULL);
 686                struct ref_entry *r = search_ref_array(array, refname);
 687
 688                if (r != NULL && r->flag & REF_KNOWS_PEELED) {
 689                        hashcpy(sha1, r->peeled);
 690                        return 0;
 691                }
 692        }
 693
 694fallback:
 695        o = parse_object(base);
 696        if (o && o->type == OBJ_TAG) {
 697                o = deref_tag(o, refname, 0);
 698                if (o) {
 699                        hashcpy(sha1, o->sha1);
 700                        return 0;
 701                }
 702        }
 703        return -1;
 704}
 705
 706static int do_for_each_ref(const char *submodule, const char *base, each_ref_fn fn,
 707                           int trim, int flags, void *cb_data)
 708{
 709        int retval = 0, i, p = 0, l = 0;
 710        struct ref_array *packed = get_packed_refs(submodule);
 711        struct ref_array *loose = get_loose_refs(submodule);
 712
 713        struct ref_array *extra = &extra_refs;
 714
 715        for (i = 0; i < extra->nr; i++)
 716                retval = do_one_ref(base, fn, trim, flags, cb_data, extra->refs[i]);
 717
 718        while (p < packed->nr && l < loose->nr) {
 719                struct ref_entry *entry;
 720                int cmp = strcmp(packed->refs[p]->name, loose->refs[l]->name);
 721                if (!cmp) {
 722                        p++;
 723                        continue;
 724                }
 725                if (cmp > 0) {
 726                        entry = loose->refs[l++];
 727                } else {
 728                        entry = packed->refs[p++];
 729                }
 730                retval = do_one_ref(base, fn, trim, flags, cb_data, entry);
 731                if (retval)
 732                        goto end_each;
 733        }
 734
 735        if (l < loose->nr) {
 736                p = l;
 737                packed = loose;
 738        }
 739
 740        for (; p < packed->nr; p++) {
 741                retval = do_one_ref(base, fn, trim, flags, cb_data, packed->refs[p]);
 742                if (retval)
 743                        goto end_each;
 744        }
 745
 746end_each:
 747        current_ref = NULL;
 748        return retval;
 749}
 750
 751
 752static int do_head_ref(const char *submodule, each_ref_fn fn, void *cb_data)
 753{
 754        unsigned char sha1[20];
 755        int flag;
 756
 757        if (submodule) {
 758                if (resolve_gitlink_ref(submodule, "HEAD", sha1) == 0)
 759                        return fn("HEAD", sha1, 0, cb_data);
 760
 761                return 0;
 762        }
 763
 764        if (!read_ref_full("HEAD", sha1, 1, &flag))
 765                return fn("HEAD", sha1, flag, cb_data);
 766
 767        return 0;
 768}
 769
 770int head_ref(each_ref_fn fn, void *cb_data)
 771{
 772        return do_head_ref(NULL, fn, cb_data);
 773}
 774
 775int head_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
 776{
 777        return do_head_ref(submodule, fn, cb_data);
 778}
 779
 780int for_each_ref(each_ref_fn fn, void *cb_data)
 781{
 782        return do_for_each_ref(NULL, "", fn, 0, 0, cb_data);
 783}
 784
 785int for_each_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
 786{
 787        return do_for_each_ref(submodule, "", fn, 0, 0, cb_data);
 788}
 789
 790int for_each_ref_in(const char *prefix, each_ref_fn fn, void *cb_data)
 791{
 792        return do_for_each_ref(NULL, prefix, fn, strlen(prefix), 0, cb_data);
 793}
 794
 795int for_each_ref_in_submodule(const char *submodule, const char *prefix,
 796                each_ref_fn fn, void *cb_data)
 797{
 798        return do_for_each_ref(submodule, prefix, fn, strlen(prefix), 0, cb_data);
 799}
 800
 801int for_each_tag_ref(each_ref_fn fn, void *cb_data)
 802{
 803        return for_each_ref_in("refs/tags/", fn, cb_data);
 804}
 805
 806int for_each_tag_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
 807{
 808        return for_each_ref_in_submodule(submodule, "refs/tags/", fn, cb_data);
 809}
 810
 811int for_each_branch_ref(each_ref_fn fn, void *cb_data)
 812{
 813        return for_each_ref_in("refs/heads/", fn, cb_data);
 814}
 815
 816int for_each_branch_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
 817{
 818        return for_each_ref_in_submodule(submodule, "refs/heads/", fn, cb_data);
 819}
 820
 821int for_each_remote_ref(each_ref_fn fn, void *cb_data)
 822{
 823        return for_each_ref_in("refs/remotes/", fn, cb_data);
 824}
 825
 826int for_each_remote_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
 827{
 828        return for_each_ref_in_submodule(submodule, "refs/remotes/", fn, cb_data);
 829}
 830
 831int for_each_replace_ref(each_ref_fn fn, void *cb_data)
 832{
 833        return do_for_each_ref(NULL, "refs/replace/", fn, 13, 0, cb_data);
 834}
 835
 836int head_ref_namespaced(each_ref_fn fn, void *cb_data)
 837{
 838        struct strbuf buf = STRBUF_INIT;
 839        int ret = 0;
 840        unsigned char sha1[20];
 841        int flag;
 842
 843        strbuf_addf(&buf, "%sHEAD", get_git_namespace());
 844        if (!read_ref_full(buf.buf, sha1, 1, &flag))
 845                ret = fn(buf.buf, sha1, flag, cb_data);
 846        strbuf_release(&buf);
 847
 848        return ret;
 849}
 850
 851int for_each_namespaced_ref(each_ref_fn fn, void *cb_data)
 852{
 853        struct strbuf buf = STRBUF_INIT;
 854        int ret;
 855        strbuf_addf(&buf, "%srefs/", get_git_namespace());
 856        ret = do_for_each_ref(NULL, buf.buf, fn, 0, 0, cb_data);
 857        strbuf_release(&buf);
 858        return ret;
 859}
 860
 861int for_each_glob_ref_in(each_ref_fn fn, const char *pattern,
 862        const char *prefix, void *cb_data)
 863{
 864        struct strbuf real_pattern = STRBUF_INIT;
 865        struct ref_filter filter;
 866        int ret;
 867
 868        if (!prefix && prefixcmp(pattern, "refs/"))
 869                strbuf_addstr(&real_pattern, "refs/");
 870        else if (prefix)
 871                strbuf_addstr(&real_pattern, prefix);
 872        strbuf_addstr(&real_pattern, pattern);
 873
 874        if (!has_glob_specials(pattern)) {
 875                /* Append implied '/' '*' if not present. */
 876                if (real_pattern.buf[real_pattern.len - 1] != '/')
 877                        strbuf_addch(&real_pattern, '/');
 878                /* No need to check for '*', there is none. */
 879                strbuf_addch(&real_pattern, '*');
 880        }
 881
 882        filter.pattern = real_pattern.buf;
 883        filter.fn = fn;
 884        filter.cb_data = cb_data;
 885        ret = for_each_ref(filter_refs, &filter);
 886
 887        strbuf_release(&real_pattern);
 888        return ret;
 889}
 890
 891int for_each_glob_ref(each_ref_fn fn, const char *pattern, void *cb_data)
 892{
 893        return for_each_glob_ref_in(fn, pattern, NULL, cb_data);
 894}
 895
 896int for_each_rawref(each_ref_fn fn, void *cb_data)
 897{
 898        return do_for_each_ref(NULL, "", fn, 0,
 899                               DO_FOR_EACH_INCLUDE_BROKEN, cb_data);
 900}
 901
 902/*
 903 * Make sure "ref" is something reasonable to have under ".git/refs/";
 904 * We do not like it if:
 905 *
 906 * - any path component of it begins with ".", or
 907 * - it has double dots "..", or
 908 * - it has ASCII control character, "~", "^", ":" or SP, anywhere, or
 909 * - it ends with a "/".
 910 * - it ends with ".lock"
 911 * - it contains a "\" (backslash)
 912 */
 913
 914/* Return true iff ch is not allowed in reference names. */
 915static inline int bad_ref_char(int ch)
 916{
 917        if (((unsigned) ch) <= ' ' || ch == 0x7f ||
 918            ch == '~' || ch == '^' || ch == ':' || ch == '\\')
 919                return 1;
 920        /* 2.13 Pattern Matching Notation */
 921        if (ch == '*' || ch == '?' || ch == '[') /* Unsupported */
 922                return 1;
 923        return 0;
 924}
 925
 926/*
 927 * Try to read one refname component from the front of refname.  Return
 928 * the length of the component found, or -1 if the component is not
 929 * legal.
 930 */
 931static int check_refname_component(const char *refname, int flags)
 932{
 933        const char *cp;
 934        char last = '\0';
 935
 936        for (cp = refname; ; cp++) {
 937                char ch = *cp;
 938                if (ch == '\0' || ch == '/')
 939                        break;
 940                if (bad_ref_char(ch))
 941                        return -1; /* Illegal character in refname. */
 942                if (last == '.' && ch == '.')
 943                        return -1; /* Refname contains "..". */
 944                if (last == '@' && ch == '{')
 945                        return -1; /* Refname contains "@{". */
 946                last = ch;
 947        }
 948        if (cp == refname)
 949                return -1; /* Component has zero length. */
 950        if (refname[0] == '.') {
 951                if (!(flags & REFNAME_DOT_COMPONENT))
 952                        return -1; /* Component starts with '.'. */
 953                /*
 954                 * Even if leading dots are allowed, don't allow "."
 955                 * as a component (".." is prevented by a rule above).
 956                 */
 957                if (refname[1] == '\0')
 958                        return -1; /* Component equals ".". */
 959        }
 960        if (cp - refname >= 5 && !memcmp(cp - 5, ".lock", 5))
 961                return -1; /* Refname ends with ".lock". */
 962        return cp - refname;
 963}
 964
 965int check_refname_format(const char *refname, int flags)
 966{
 967        int component_len, component_count = 0;
 968
 969        while (1) {
 970                /* We are at the start of a path component. */
 971                component_len = check_refname_component(refname, flags);
 972                if (component_len < 0) {
 973                        if ((flags & REFNAME_REFSPEC_PATTERN) &&
 974                                        refname[0] == '*' &&
 975                                        (refname[1] == '\0' || refname[1] == '/')) {
 976                                /* Accept one wildcard as a full refname component. */
 977                                flags &= ~REFNAME_REFSPEC_PATTERN;
 978                                component_len = 1;
 979                        } else {
 980                                return -1;
 981                        }
 982                }
 983                component_count++;
 984                if (refname[component_len] == '\0')
 985                        break;
 986                /* Skip to next component. */
 987                refname += component_len + 1;
 988        }
 989
 990        if (refname[component_len - 1] == '.')
 991                return -1; /* Refname ends with '.'. */
 992        if (!(flags & REFNAME_ALLOW_ONELEVEL) && component_count < 2)
 993                return -1; /* Refname has only one component. */
 994        return 0;
 995}
 996
 997const char *prettify_refname(const char *name)
 998{
 999        return name + (
1000                !prefixcmp(name, "refs/heads/") ? 11 :
1001                !prefixcmp(name, "refs/tags/") ? 10 :
1002                !prefixcmp(name, "refs/remotes/") ? 13 :
1003                0);
1004}
1005
1006const char *ref_rev_parse_rules[] = {
1007        "%.*s",
1008        "refs/%.*s",
1009        "refs/tags/%.*s",
1010        "refs/heads/%.*s",
1011        "refs/remotes/%.*s",
1012        "refs/remotes/%.*s/HEAD",
1013        NULL
1014};
1015
1016int refname_match(const char *abbrev_name, const char *full_name, const char **rules)
1017{
1018        const char **p;
1019        const int abbrev_name_len = strlen(abbrev_name);
1020
1021        for (p = rules; *p; p++) {
1022                if (!strcmp(full_name, mkpath(*p, abbrev_name_len, abbrev_name))) {
1023                        return 1;
1024                }
1025        }
1026
1027        return 0;
1028}
1029
1030static struct ref_lock *verify_lock(struct ref_lock *lock,
1031        const unsigned char *old_sha1, int mustexist)
1032{
1033        if (read_ref_full(lock->ref_name, lock->old_sha1, mustexist, NULL)) {
1034                error("Can't verify ref %s", lock->ref_name);
1035                unlock_ref(lock);
1036                return NULL;
1037        }
1038        if (hashcmp(lock->old_sha1, old_sha1)) {
1039                error("Ref %s is at %s but expected %s", lock->ref_name,
1040                        sha1_to_hex(lock->old_sha1), sha1_to_hex(old_sha1));
1041                unlock_ref(lock);
1042                return NULL;
1043        }
1044        return lock;
1045}
1046
1047static int remove_empty_directories(const char *file)
1048{
1049        /* we want to create a file but there is a directory there;
1050         * if that is an empty directory (or a directory that contains
1051         * only empty directories), remove them.
1052         */
1053        struct strbuf path;
1054        int result;
1055
1056        strbuf_init(&path, 20);
1057        strbuf_addstr(&path, file);
1058
1059        result = remove_dir_recursively(&path, REMOVE_DIR_EMPTY_ONLY);
1060
1061        strbuf_release(&path);
1062
1063        return result;
1064}
1065
1066/*
1067 * Return true iff a reference named refname could be created without
1068 * conflicting with the name of an existing reference.  If oldrefname
1069 * is non-NULL, ignore potential conflicts with oldrefname (e.g.,
1070 * because oldrefname is scheduled for deletion in the same
1071 * operation).
1072 */
1073static int is_refname_available(const char *refname, const char *oldrefname,
1074                                struct ref_array *array)
1075{
1076        int i, namlen = strlen(refname); /* e.g. 'foo/bar' */
1077        for (i = 0; i < array->nr; i++ ) {
1078                struct ref_entry *entry = array->refs[i];
1079                /* entry->name could be 'foo' or 'foo/bar/baz' */
1080                if (!oldrefname || strcmp(oldrefname, entry->name)) {
1081                        int len = strlen(entry->name);
1082                        int cmplen = (namlen < len) ? namlen : len;
1083                        const char *lead = (namlen < len) ? entry->name : refname;
1084                        if (!strncmp(refname, entry->name, cmplen) &&
1085                            lead[cmplen] == '/') {
1086                                error("'%s' exists; cannot create '%s'",
1087                                      entry->name, refname);
1088                                return 0;
1089                        }
1090                }
1091        }
1092        return 1;
1093}
1094
1095/*
1096 * *string and *len will only be substituted, and *string returned (for
1097 * later free()ing) if the string passed in is a magic short-hand form
1098 * to name a branch.
1099 */
1100static char *substitute_branch_name(const char **string, int *len)
1101{
1102        struct strbuf buf = STRBUF_INIT;
1103        int ret = interpret_branch_name(*string, &buf);
1104
1105        if (ret == *len) {
1106                size_t size;
1107                *string = strbuf_detach(&buf, &size);
1108                *len = size;
1109                return (char *)*string;
1110        }
1111
1112        return NULL;
1113}
1114
1115int dwim_ref(const char *str, int len, unsigned char *sha1, char **ref)
1116{
1117        char *last_branch = substitute_branch_name(&str, &len);
1118        const char **p, *r;
1119        int refs_found = 0;
1120
1121        *ref = NULL;
1122        for (p = ref_rev_parse_rules; *p; p++) {
1123                char fullref[PATH_MAX];
1124                unsigned char sha1_from_ref[20];
1125                unsigned char *this_result;
1126                int flag;
1127
1128                this_result = refs_found ? sha1_from_ref : sha1;
1129                mksnpath(fullref, sizeof(fullref), *p, len, str);
1130                r = resolve_ref(fullref, this_result, 1, &flag);
1131                if (r) {
1132                        if (!refs_found++)
1133                                *ref = xstrdup(r);
1134                        if (!warn_ambiguous_refs)
1135                                break;
1136                } else if ((flag & REF_ISSYMREF) && strcmp(fullref, "HEAD")) {
1137                        warning("ignoring dangling symref %s.", fullref);
1138                } else if ((flag & REF_ISBROKEN) && strchr(fullref, '/')) {
1139                        warning("ignoring broken ref %s.", fullref);
1140                }
1141        }
1142        free(last_branch);
1143        return refs_found;
1144}
1145
1146int dwim_log(const char *str, int len, unsigned char *sha1, char **log)
1147{
1148        char *last_branch = substitute_branch_name(&str, &len);
1149        const char **p;
1150        int logs_found = 0;
1151
1152        *log = NULL;
1153        for (p = ref_rev_parse_rules; *p; p++) {
1154                struct stat st;
1155                unsigned char hash[20];
1156                char path[PATH_MAX];
1157                const char *ref, *it;
1158
1159                mksnpath(path, sizeof(path), *p, len, str);
1160                ref = resolve_ref(path, hash, 1, NULL);
1161                if (!ref)
1162                        continue;
1163                if (!stat(git_path("logs/%s", path), &st) &&
1164                    S_ISREG(st.st_mode))
1165                        it = path;
1166                else if (strcmp(ref, path) &&
1167                         !stat(git_path("logs/%s", ref), &st) &&
1168                         S_ISREG(st.st_mode))
1169                        it = ref;
1170                else
1171                        continue;
1172                if (!logs_found++) {
1173                        *log = xstrdup(it);
1174                        hashcpy(sha1, hash);
1175                }
1176                if (!warn_ambiguous_refs)
1177                        break;
1178        }
1179        free(last_branch);
1180        return logs_found;
1181}
1182
1183static struct ref_lock *lock_ref_sha1_basic(const char *refname,
1184                                            const unsigned char *old_sha1,
1185                                            int flags, int *type_p)
1186{
1187        char *ref_file;
1188        const char *orig_refname = refname;
1189        struct ref_lock *lock;
1190        int last_errno = 0;
1191        int type, lflags;
1192        int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
1193        int missing = 0;
1194
1195        lock = xcalloc(1, sizeof(struct ref_lock));
1196        lock->lock_fd = -1;
1197
1198        refname = resolve_ref(refname, lock->old_sha1, mustexist, &type);
1199        if (!refname && errno == EISDIR) {
1200                /* we are trying to lock foo but we used to
1201                 * have foo/bar which now does not exist;
1202                 * it is normal for the empty directory 'foo'
1203                 * to remain.
1204                 */
1205                ref_file = git_path("%s", orig_refname);
1206                if (remove_empty_directories(ref_file)) {
1207                        last_errno = errno;
1208                        error("there are still refs under '%s'", orig_refname);
1209                        goto error_return;
1210                }
1211                refname = resolve_ref(orig_refname, lock->old_sha1, mustexist, &type);
1212        }
1213        if (type_p)
1214            *type_p = type;
1215        if (!refname) {
1216                last_errno = errno;
1217                error("unable to resolve reference %s: %s",
1218                        orig_refname, strerror(errno));
1219                goto error_return;
1220        }
1221        missing = is_null_sha1(lock->old_sha1);
1222        /* When the ref did not exist and we are creating it,
1223         * make sure there is no existing ref that is packed
1224         * whose name begins with our refname, nor a ref whose
1225         * name is a proper prefix of our refname.
1226         */
1227        if (missing &&
1228             !is_refname_available(refname, NULL, get_packed_refs(NULL))) {
1229                last_errno = ENOTDIR;
1230                goto error_return;
1231        }
1232
1233        lock->lk = xcalloc(1, sizeof(struct lock_file));
1234
1235        lflags = LOCK_DIE_ON_ERROR;
1236        if (flags & REF_NODEREF) {
1237                refname = orig_refname;
1238                lflags |= LOCK_NODEREF;
1239        }
1240        lock->ref_name = xstrdup(refname);
1241        lock->orig_ref_name = xstrdup(orig_refname);
1242        ref_file = git_path("%s", refname);
1243        if (missing)
1244                lock->force_write = 1;
1245        if ((flags & REF_NODEREF) && (type & REF_ISSYMREF))
1246                lock->force_write = 1;
1247
1248        if (safe_create_leading_directories(ref_file)) {
1249                last_errno = errno;
1250                error("unable to create directory for %s", ref_file);
1251                goto error_return;
1252        }
1253
1254        lock->lock_fd = hold_lock_file_for_update(lock->lk, ref_file, lflags);
1255        return old_sha1 ? verify_lock(lock, old_sha1, mustexist) : lock;
1256
1257 error_return:
1258        unlock_ref(lock);
1259        errno = last_errno;
1260        return NULL;
1261}
1262
1263struct ref_lock *lock_ref_sha1(const char *refname, const unsigned char *old_sha1)
1264{
1265        char refpath[PATH_MAX];
1266        if (check_refname_format(refname, 0))
1267                return NULL;
1268        strcpy(refpath, mkpath("refs/%s", refname));
1269        return lock_ref_sha1_basic(refpath, old_sha1, 0, NULL);
1270}
1271
1272struct ref_lock *lock_any_ref_for_update(const char *refname,
1273                                         const unsigned char *old_sha1, int flags)
1274{
1275        if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL))
1276                return NULL;
1277        return lock_ref_sha1_basic(refname, old_sha1, flags, NULL);
1278}
1279
1280static struct lock_file packlock;
1281
1282static int repack_without_ref(const char *refname)
1283{
1284        struct ref_array *packed;
1285        struct ref_entry *ref;
1286        int fd, i;
1287
1288        packed = get_packed_refs(NULL);
1289        ref = search_ref_array(packed, refname);
1290        if (ref == NULL)
1291                return 0;
1292        fd = hold_lock_file_for_update(&packlock, git_path("packed-refs"), 0);
1293        if (fd < 0) {
1294                unable_to_lock_error(git_path("packed-refs"), errno);
1295                return error("cannot delete '%s' from packed refs", refname);
1296        }
1297
1298        for (i = 0; i < packed->nr; i++) {
1299                char line[PATH_MAX + 100];
1300                int len;
1301
1302                ref = packed->refs[i];
1303
1304                if (!strcmp(refname, ref->name))
1305                        continue;
1306                len = snprintf(line, sizeof(line), "%s %s\n",
1307                               sha1_to_hex(ref->sha1), ref->name);
1308                /* this should not happen but just being defensive */
1309                if (len > sizeof(line))
1310                        die("too long a refname '%s'", ref->name);
1311                write_or_die(fd, line, len);
1312        }
1313        return commit_lock_file(&packlock);
1314}
1315
1316int delete_ref(const char *refname, const unsigned char *sha1, int delopt)
1317{
1318        struct ref_lock *lock;
1319        int err, i = 0, ret = 0, flag = 0;
1320
1321        lock = lock_ref_sha1_basic(refname, sha1, 0, &flag);
1322        if (!lock)
1323                return 1;
1324        if (!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {
1325                /* loose */
1326                const char *path;
1327
1328                if (!(delopt & REF_NODEREF)) {
1329                        i = strlen(lock->lk->filename) - 5; /* .lock */
1330                        lock->lk->filename[i] = 0;
1331                        path = lock->lk->filename;
1332                } else {
1333                        path = git_path("%s", refname);
1334                }
1335                err = unlink_or_warn(path);
1336                if (err && errno != ENOENT)
1337                        ret = 1;
1338
1339                if (!(delopt & REF_NODEREF))
1340                        lock->lk->filename[i] = '.';
1341        }
1342        /* removing the loose one could have resurrected an earlier
1343         * packed one.  Also, if it was not loose we need to repack
1344         * without it.
1345         */
1346        ret |= repack_without_ref(refname);
1347
1348        unlink_or_warn(git_path("logs/%s", lock->ref_name));
1349        invalidate_ref_cache(NULL);
1350        unlock_ref(lock);
1351        return ret;
1352}
1353
1354/*
1355 * People using contrib's git-new-workdir have .git/logs/refs ->
1356 * /some/other/path/.git/logs/refs, and that may live on another device.
1357 *
1358 * IOW, to avoid cross device rename errors, the temporary renamed log must
1359 * live into logs/refs.
1360 */
1361#define TMP_RENAMED_LOG  "logs/refs/.tmp-renamed-log"
1362
1363int rename_ref(const char *oldrefname, const char *newrefname, const char *logmsg)
1364{
1365        unsigned char sha1[20], orig_sha1[20];
1366        int flag = 0, logmoved = 0;
1367        struct ref_lock *lock;
1368        struct stat loginfo;
1369        int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);
1370        const char *symref = NULL;
1371
1372        if (log && S_ISLNK(loginfo.st_mode))
1373                return error("reflog for %s is a symlink", oldrefname);
1374
1375        symref = resolve_ref(oldrefname, orig_sha1, 1, &flag);
1376        if (flag & REF_ISSYMREF)
1377                return error("refname %s is a symbolic ref, renaming it is not supported",
1378                        oldrefname);
1379        if (!symref)
1380                return error("refname %s not found", oldrefname);
1381
1382        if (!is_refname_available(newrefname, oldrefname, get_packed_refs(NULL)))
1383                return 1;
1384
1385        if (!is_refname_available(newrefname, oldrefname, get_loose_refs(NULL)))
1386                return 1;
1387
1388        if (log && rename(git_path("logs/%s", oldrefname), git_path(TMP_RENAMED_LOG)))
1389                return error("unable to move logfile logs/%s to "TMP_RENAMED_LOG": %s",
1390                        oldrefname, strerror(errno));
1391
1392        if (delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {
1393                error("unable to delete old %s", oldrefname);
1394                goto rollback;
1395        }
1396
1397        if (!read_ref_full(newrefname, sha1, 1, &flag) &&
1398            delete_ref(newrefname, sha1, REF_NODEREF)) {
1399                if (errno==EISDIR) {
1400                        if (remove_empty_directories(git_path("%s", newrefname))) {
1401                                error("Directory not empty: %s", newrefname);
1402                                goto rollback;
1403                        }
1404                } else {
1405                        error("unable to delete existing %s", newrefname);
1406                        goto rollback;
1407                }
1408        }
1409
1410        if (log && safe_create_leading_directories(git_path("logs/%s", newrefname))) {
1411                error("unable to create directory for %s", newrefname);
1412                goto rollback;
1413        }
1414
1415 retry:
1416        if (log && rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", newrefname))) {
1417                if (errno==EISDIR || errno==ENOTDIR) {
1418                        /*
1419                         * rename(a, b) when b is an existing
1420                         * directory ought to result in ISDIR, but
1421                         * Solaris 5.8 gives ENOTDIR.  Sheesh.
1422                         */
1423                        if (remove_empty_directories(git_path("logs/%s", newrefname))) {
1424                                error("Directory not empty: logs/%s", newrefname);
1425                                goto rollback;
1426                        }
1427                        goto retry;
1428                } else {
1429                        error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s: %s",
1430                                newrefname, strerror(errno));
1431                        goto rollback;
1432                }
1433        }
1434        logmoved = log;
1435
1436        lock = lock_ref_sha1_basic(newrefname, NULL, 0, NULL);
1437        if (!lock) {
1438                error("unable to lock %s for update", newrefname);
1439                goto rollback;
1440        }
1441        lock->force_write = 1;
1442        hashcpy(lock->old_sha1, orig_sha1);
1443        if (write_ref_sha1(lock, orig_sha1, logmsg)) {
1444                error("unable to write current sha1 into %s", newrefname);
1445                goto rollback;
1446        }
1447
1448        return 0;
1449
1450 rollback:
1451        lock = lock_ref_sha1_basic(oldrefname, NULL, 0, NULL);
1452        if (!lock) {
1453                error("unable to lock %s for rollback", oldrefname);
1454                goto rollbacklog;
1455        }
1456
1457        lock->force_write = 1;
1458        flag = log_all_ref_updates;
1459        log_all_ref_updates = 0;
1460        if (write_ref_sha1(lock, orig_sha1, NULL))
1461                error("unable to write current sha1 into %s", oldrefname);
1462        log_all_ref_updates = flag;
1463
1464 rollbacklog:
1465        if (logmoved && rename(git_path("logs/%s", newrefname), git_path("logs/%s", oldrefname)))
1466                error("unable to restore logfile %s from %s: %s",
1467                        oldrefname, newrefname, strerror(errno));
1468        if (!logmoved && log &&
1469            rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", oldrefname)))
1470                error("unable to restore logfile %s from "TMP_RENAMED_LOG": %s",
1471                        oldrefname, strerror(errno));
1472
1473        return 1;
1474}
1475
1476int close_ref(struct ref_lock *lock)
1477{
1478        if (close_lock_file(lock->lk))
1479                return -1;
1480        lock->lock_fd = -1;
1481        return 0;
1482}
1483
1484int commit_ref(struct ref_lock *lock)
1485{
1486        if (commit_lock_file(lock->lk))
1487                return -1;
1488        lock->lock_fd = -1;
1489        return 0;
1490}
1491
1492void unlock_ref(struct ref_lock *lock)
1493{
1494        /* Do not free lock->lk -- atexit() still looks at them */
1495        if (lock->lk)
1496                rollback_lock_file(lock->lk);
1497        free(lock->ref_name);
1498        free(lock->orig_ref_name);
1499        free(lock);
1500}
1501
1502/*
1503 * copy the reflog message msg to buf, which has been allocated sufficiently
1504 * large, while cleaning up the whitespaces.  Especially, convert LF to space,
1505 * because reflog file is one line per entry.
1506 */
1507static int copy_msg(char *buf, const char *msg)
1508{
1509        char *cp = buf;
1510        char c;
1511        int wasspace = 1;
1512
1513        *cp++ = '\t';
1514        while ((c = *msg++)) {
1515                if (wasspace && isspace(c))
1516                        continue;
1517                wasspace = isspace(c);
1518                if (wasspace)
1519                        c = ' ';
1520                *cp++ = c;
1521        }
1522        while (buf < cp && isspace(cp[-1]))
1523                cp--;
1524        *cp++ = '\n';
1525        return cp - buf;
1526}
1527
1528int log_ref_setup(const char *refname, char *logfile, int bufsize)
1529{
1530        int logfd, oflags = O_APPEND | O_WRONLY;
1531
1532        git_snpath(logfile, bufsize, "logs/%s", refname);
1533        if (log_all_ref_updates &&
1534            (!prefixcmp(refname, "refs/heads/") ||
1535             !prefixcmp(refname, "refs/remotes/") ||
1536             !prefixcmp(refname, "refs/notes/") ||
1537             !strcmp(refname, "HEAD"))) {
1538                if (safe_create_leading_directories(logfile) < 0)
1539                        return error("unable to create directory for %s",
1540                                     logfile);
1541                oflags |= O_CREAT;
1542        }
1543
1544        logfd = open(logfile, oflags, 0666);
1545        if (logfd < 0) {
1546                if (!(oflags & O_CREAT) && errno == ENOENT)
1547                        return 0;
1548
1549                if ((oflags & O_CREAT) && errno == EISDIR) {
1550                        if (remove_empty_directories(logfile)) {
1551                                return error("There are still logs under '%s'",
1552                                             logfile);
1553                        }
1554                        logfd = open(logfile, oflags, 0666);
1555                }
1556
1557                if (logfd < 0)
1558                        return error("Unable to append to %s: %s",
1559                                     logfile, strerror(errno));
1560        }
1561
1562        adjust_shared_perm(logfile);
1563        close(logfd);
1564        return 0;
1565}
1566
1567static int log_ref_write(const char *refname, const unsigned char *old_sha1,
1568                         const unsigned char *new_sha1, const char *msg)
1569{
1570        int logfd, result, written, oflags = O_APPEND | O_WRONLY;
1571        unsigned maxlen, len;
1572        int msglen;
1573        char log_file[PATH_MAX];
1574        char *logrec;
1575        const char *committer;
1576
1577        if (log_all_ref_updates < 0)
1578                log_all_ref_updates = !is_bare_repository();
1579
1580        result = log_ref_setup(refname, log_file, sizeof(log_file));
1581        if (result)
1582                return result;
1583
1584        logfd = open(log_file, oflags);
1585        if (logfd < 0)
1586                return 0;
1587        msglen = msg ? strlen(msg) : 0;
1588        committer = git_committer_info(0);
1589        maxlen = strlen(committer) + msglen + 100;
1590        logrec = xmalloc(maxlen);
1591        len = sprintf(logrec, "%s %s %s\n",
1592                      sha1_to_hex(old_sha1),
1593                      sha1_to_hex(new_sha1),
1594                      committer);
1595        if (msglen)
1596                len += copy_msg(logrec + len - 1, msg) - 1;
1597        written = len <= maxlen ? write_in_full(logfd, logrec, len) : -1;
1598        free(logrec);
1599        if (close(logfd) != 0 || written != len)
1600                return error("Unable to append to %s", log_file);
1601        return 0;
1602}
1603
1604static int is_branch(const char *refname)
1605{
1606        return !strcmp(refname, "HEAD") || !prefixcmp(refname, "refs/heads/");
1607}
1608
1609int write_ref_sha1(struct ref_lock *lock,
1610        const unsigned char *sha1, const char *logmsg)
1611{
1612        static char term = '\n';
1613        struct object *o;
1614
1615        if (!lock)
1616                return -1;
1617        if (!lock->force_write && !hashcmp(lock->old_sha1, sha1)) {
1618                unlock_ref(lock);
1619                return 0;
1620        }
1621        o = parse_object(sha1);
1622        if (!o) {
1623                error("Trying to write ref %s with nonexistent object %s",
1624                        lock->ref_name, sha1_to_hex(sha1));
1625                unlock_ref(lock);
1626                return -1;
1627        }
1628        if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
1629                error("Trying to write non-commit object %s to branch %s",
1630                        sha1_to_hex(sha1), lock->ref_name);
1631                unlock_ref(lock);
1632                return -1;
1633        }
1634        if (write_in_full(lock->lock_fd, sha1_to_hex(sha1), 40) != 40 ||
1635            write_in_full(lock->lock_fd, &term, 1) != 1
1636                || close_ref(lock) < 0) {
1637                error("Couldn't write %s", lock->lk->filename);
1638                unlock_ref(lock);
1639                return -1;
1640        }
1641        clear_loose_ref_cache(get_ref_cache(NULL));
1642        if (log_ref_write(lock->ref_name, lock->old_sha1, sha1, logmsg) < 0 ||
1643            (strcmp(lock->ref_name, lock->orig_ref_name) &&
1644             log_ref_write(lock->orig_ref_name, lock->old_sha1, sha1, logmsg) < 0)) {
1645                unlock_ref(lock);
1646                return -1;
1647        }
1648        if (strcmp(lock->orig_ref_name, "HEAD") != 0) {
1649                /*
1650                 * Special hack: If a branch is updated directly and HEAD
1651                 * points to it (may happen on the remote side of a push
1652                 * for example) then logically the HEAD reflog should be
1653                 * updated too.
1654                 * A generic solution implies reverse symref information,
1655                 * but finding all symrefs pointing to the given branch
1656                 * would be rather costly for this rare event (the direct
1657                 * update of a branch) to be worth it.  So let's cheat and
1658                 * check with HEAD only which should cover 99% of all usage
1659                 * scenarios (even 100% of the default ones).
1660                 */
1661                unsigned char head_sha1[20];
1662                int head_flag;
1663                const char *head_ref;
1664                head_ref = resolve_ref("HEAD", head_sha1, 1, &head_flag);
1665                if (head_ref && (head_flag & REF_ISSYMREF) &&
1666                    !strcmp(head_ref, lock->ref_name))
1667                        log_ref_write("HEAD", lock->old_sha1, sha1, logmsg);
1668        }
1669        if (commit_ref(lock)) {
1670                error("Couldn't set %s", lock->ref_name);
1671                unlock_ref(lock);
1672                return -1;
1673        }
1674        unlock_ref(lock);
1675        return 0;
1676}
1677
1678int create_symref(const char *ref_target, const char *refs_heads_master,
1679                  const char *logmsg)
1680{
1681        const char *lockpath;
1682        char ref[1000];
1683        int fd, len, written;
1684        char *git_HEAD = git_pathdup("%s", ref_target);
1685        unsigned char old_sha1[20], new_sha1[20];
1686
1687        if (logmsg && read_ref(ref_target, old_sha1))
1688                hashclr(old_sha1);
1689
1690        if (safe_create_leading_directories(git_HEAD) < 0)
1691                return error("unable to create directory for %s", git_HEAD);
1692
1693#ifndef NO_SYMLINK_HEAD
1694        if (prefer_symlink_refs) {
1695                unlink(git_HEAD);
1696                if (!symlink(refs_heads_master, git_HEAD))
1697                        goto done;
1698                fprintf(stderr, "no symlink - falling back to symbolic ref\n");
1699        }
1700#endif
1701
1702        len = snprintf(ref, sizeof(ref), "ref: %s\n", refs_heads_master);
1703        if (sizeof(ref) <= len) {
1704                error("refname too long: %s", refs_heads_master);
1705                goto error_free_return;
1706        }
1707        lockpath = mkpath("%s.lock", git_HEAD);
1708        fd = open(lockpath, O_CREAT | O_EXCL | O_WRONLY, 0666);
1709        if (fd < 0) {
1710                error("Unable to open %s for writing", lockpath);
1711                goto error_free_return;
1712        }
1713        written = write_in_full(fd, ref, len);
1714        if (close(fd) != 0 || written != len) {
1715                error("Unable to write to %s", lockpath);
1716                goto error_unlink_return;
1717        }
1718        if (rename(lockpath, git_HEAD) < 0) {
1719                error("Unable to create %s", git_HEAD);
1720                goto error_unlink_return;
1721        }
1722        if (adjust_shared_perm(git_HEAD)) {
1723                error("Unable to fix permissions on %s", lockpath);
1724        error_unlink_return:
1725                unlink_or_warn(lockpath);
1726        error_free_return:
1727                free(git_HEAD);
1728                return -1;
1729        }
1730
1731#ifndef NO_SYMLINK_HEAD
1732        done:
1733#endif
1734        if (logmsg && !read_ref(refs_heads_master, new_sha1))
1735                log_ref_write(ref_target, old_sha1, new_sha1, logmsg);
1736
1737        free(git_HEAD);
1738        return 0;
1739}
1740
1741static char *ref_msg(const char *line, const char *endp)
1742{
1743        const char *ep;
1744        line += 82;
1745        ep = memchr(line, '\n', endp - line);
1746        if (!ep)
1747                ep = endp;
1748        return xmemdupz(line, ep - line);
1749}
1750
1751int read_ref_at(const char *refname, unsigned long at_time, int cnt,
1752                unsigned char *sha1, char **msg,
1753                unsigned long *cutoff_time, int *cutoff_tz, int *cutoff_cnt)
1754{
1755        const char *logfile, *logdata, *logend, *rec, *lastgt, *lastrec;
1756        char *tz_c;
1757        int logfd, tz, reccnt = 0;
1758        struct stat st;
1759        unsigned long date;
1760        unsigned char logged_sha1[20];
1761        void *log_mapped;
1762        size_t mapsz;
1763
1764        logfile = git_path("logs/%s", refname);
1765        logfd = open(logfile, O_RDONLY, 0);
1766        if (logfd < 0)
1767                die_errno("Unable to read log '%s'", logfile);
1768        fstat(logfd, &st);
1769        if (!st.st_size)
1770                die("Log %s is empty.", logfile);
1771        mapsz = xsize_t(st.st_size);
1772        log_mapped = xmmap(NULL, mapsz, PROT_READ, MAP_PRIVATE, logfd, 0);
1773        logdata = log_mapped;
1774        close(logfd);
1775
1776        lastrec = NULL;
1777        rec = logend = logdata + st.st_size;
1778        while (logdata < rec) {
1779                reccnt++;
1780                if (logdata < rec && *(rec-1) == '\n')
1781                        rec--;
1782                lastgt = NULL;
1783                while (logdata < rec && *(rec-1) != '\n') {
1784                        rec--;
1785                        if (*rec == '>')
1786                                lastgt = rec;
1787                }
1788                if (!lastgt)
1789                        die("Log %s is corrupt.", logfile);
1790                date = strtoul(lastgt + 1, &tz_c, 10);
1791                if (date <= at_time || cnt == 0) {
1792                        tz = strtoul(tz_c, NULL, 10);
1793                        if (msg)
1794                                *msg = ref_msg(rec, logend);
1795                        if (cutoff_time)
1796                                *cutoff_time = date;
1797                        if (cutoff_tz)
1798                                *cutoff_tz = tz;
1799                        if (cutoff_cnt)
1800                                *cutoff_cnt = reccnt - 1;
1801                        if (lastrec) {
1802                                if (get_sha1_hex(lastrec, logged_sha1))
1803                                        die("Log %s is corrupt.", logfile);
1804                                if (get_sha1_hex(rec + 41, sha1))
1805                                        die("Log %s is corrupt.", logfile);
1806                                if (hashcmp(logged_sha1, sha1)) {
1807                                        warning("Log %s has gap after %s.",
1808                                                logfile, show_date(date, tz, DATE_RFC2822));
1809                                }
1810                        }
1811                        else if (date == at_time) {
1812                                if (get_sha1_hex(rec + 41, sha1))
1813                                        die("Log %s is corrupt.", logfile);
1814                        }
1815                        else {
1816                                if (get_sha1_hex(rec + 41, logged_sha1))
1817                                        die("Log %s is corrupt.", logfile);
1818                                if (hashcmp(logged_sha1, sha1)) {
1819                                        warning("Log %s unexpectedly ended on %s.",
1820                                                logfile, show_date(date, tz, DATE_RFC2822));
1821                                }
1822                        }
1823                        munmap(log_mapped, mapsz);
1824                        return 0;
1825                }
1826                lastrec = rec;
1827                if (cnt > 0)
1828                        cnt--;
1829        }
1830
1831        rec = logdata;
1832        while (rec < logend && *rec != '>' && *rec != '\n')
1833                rec++;
1834        if (rec == logend || *rec == '\n')
1835                die("Log %s is corrupt.", logfile);
1836        date = strtoul(rec + 1, &tz_c, 10);
1837        tz = strtoul(tz_c, NULL, 10);
1838        if (get_sha1_hex(logdata, sha1))
1839                die("Log %s is corrupt.", logfile);
1840        if (is_null_sha1(sha1)) {
1841                if (get_sha1_hex(logdata + 41, sha1))
1842                        die("Log %s is corrupt.", logfile);
1843        }
1844        if (msg)
1845                *msg = ref_msg(logdata, logend);
1846        munmap(log_mapped, mapsz);
1847
1848        if (cutoff_time)
1849                *cutoff_time = date;
1850        if (cutoff_tz)
1851                *cutoff_tz = tz;
1852        if (cutoff_cnt)
1853                *cutoff_cnt = reccnt;
1854        return 1;
1855}
1856
1857int for_each_recent_reflog_ent(const char *refname, each_reflog_ent_fn fn, long ofs, void *cb_data)
1858{
1859        const char *logfile;
1860        FILE *logfp;
1861        struct strbuf sb = STRBUF_INIT;
1862        int ret = 0;
1863
1864        logfile = git_path("logs/%s", refname);
1865        logfp = fopen(logfile, "r");
1866        if (!logfp)
1867                return -1;
1868
1869        if (ofs) {
1870                struct stat statbuf;
1871                if (fstat(fileno(logfp), &statbuf) ||
1872                    statbuf.st_size < ofs ||
1873                    fseek(logfp, -ofs, SEEK_END) ||
1874                    strbuf_getwholeline(&sb, logfp, '\n')) {
1875                        fclose(logfp);
1876                        strbuf_release(&sb);
1877                        return -1;
1878                }
1879        }
1880
1881        while (!strbuf_getwholeline(&sb, logfp, '\n')) {
1882                unsigned char osha1[20], nsha1[20];
1883                char *email_end, *message;
1884                unsigned long timestamp;
1885                int tz;
1886
1887                /* old SP new SP name <email> SP time TAB msg LF */
1888                if (sb.len < 83 || sb.buf[sb.len - 1] != '\n' ||
1889                    get_sha1_hex(sb.buf, osha1) || sb.buf[40] != ' ' ||
1890                    get_sha1_hex(sb.buf + 41, nsha1) || sb.buf[81] != ' ' ||
1891                    !(email_end = strchr(sb.buf + 82, '>')) ||
1892                    email_end[1] != ' ' ||
1893                    !(timestamp = strtoul(email_end + 2, &message, 10)) ||
1894                    !message || message[0] != ' ' ||
1895                    (message[1] != '+' && message[1] != '-') ||
1896                    !isdigit(message[2]) || !isdigit(message[3]) ||
1897                    !isdigit(message[4]) || !isdigit(message[5]))
1898                        continue; /* corrupt? */
1899                email_end[1] = '\0';
1900                tz = strtol(message + 1, NULL, 10);
1901                if (message[6] != '\t')
1902                        message += 6;
1903                else
1904                        message += 7;
1905                ret = fn(osha1, nsha1, sb.buf + 82, timestamp, tz, message,
1906                         cb_data);
1907                if (ret)
1908                        break;
1909        }
1910        fclose(logfp);
1911        strbuf_release(&sb);
1912        return ret;
1913}
1914
1915int for_each_reflog_ent(const char *refname, each_reflog_ent_fn fn, void *cb_data)
1916{
1917        return for_each_recent_reflog_ent(refname, fn, 0, cb_data);
1918}
1919
1920static int do_for_each_reflog(const char *base, each_ref_fn fn, void *cb_data)
1921{
1922        DIR *dir = opendir(git_path("logs/%s", base));
1923        int retval = 0;
1924
1925        if (dir) {
1926                struct dirent *de;
1927                int baselen = strlen(base);
1928                char *log = xmalloc(baselen + 257);
1929
1930                memcpy(log, base, baselen);
1931                if (baselen && base[baselen-1] != '/')
1932                        log[baselen++] = '/';
1933
1934                while ((de = readdir(dir)) != NULL) {
1935                        struct stat st;
1936                        int namelen;
1937
1938                        if (de->d_name[0] == '.')
1939                                continue;
1940                        namelen = strlen(de->d_name);
1941                        if (namelen > 255)
1942                                continue;
1943                        if (has_extension(de->d_name, ".lock"))
1944                                continue;
1945                        memcpy(log + baselen, de->d_name, namelen+1);
1946                        if (stat(git_path("logs/%s", log), &st) < 0)
1947                                continue;
1948                        if (S_ISDIR(st.st_mode)) {
1949                                retval = do_for_each_reflog(log, fn, cb_data);
1950                        } else {
1951                                unsigned char sha1[20];
1952                                if (read_ref_full(log, sha1, 0, NULL))
1953                                        retval = error("bad ref for %s", log);
1954                                else
1955                                        retval = fn(log, sha1, 0, cb_data);
1956                        }
1957                        if (retval)
1958                                break;
1959                }
1960                free(log);
1961                closedir(dir);
1962        }
1963        else if (*base)
1964                return errno;
1965        return retval;
1966}
1967
1968int for_each_reflog(each_ref_fn fn, void *cb_data)
1969{
1970        return do_for_each_reflog("", fn, cb_data);
1971}
1972
1973int update_ref(const char *action, const char *refname,
1974                const unsigned char *sha1, const unsigned char *oldval,
1975                int flags, enum action_on_err onerr)
1976{
1977        static struct ref_lock *lock;
1978        lock = lock_any_ref_for_update(refname, oldval, flags);
1979        if (!lock) {
1980                const char *str = "Cannot lock the ref '%s'.";
1981                switch (onerr) {
1982                case MSG_ON_ERR: error(str, refname); break;
1983                case DIE_ON_ERR: die(str, refname); break;
1984                case QUIET_ON_ERR: break;
1985                }
1986                return 1;
1987        }
1988        if (write_ref_sha1(lock, sha1, action) < 0) {
1989                const char *str = "Cannot update the ref '%s'.";
1990                switch (onerr) {
1991                case MSG_ON_ERR: error(str, refname); break;
1992                case DIE_ON_ERR: die(str, refname); break;
1993                case QUIET_ON_ERR: break;
1994                }
1995                return 1;
1996        }
1997        return 0;
1998}
1999
2000int ref_exists(const char *refname)
2001{
2002        unsigned char sha1[20];
2003        return !!resolve_ref(refname, sha1, 1, NULL);
2004}
2005
2006struct ref *find_ref_by_name(const struct ref *list, const char *name)
2007{
2008        for ( ; list; list = list->next)
2009                if (!strcmp(list->name, name))
2010                        return (struct ref *)list;
2011        return NULL;
2012}
2013
2014/*
2015 * generate a format suitable for scanf from a ref_rev_parse_rules
2016 * rule, that is replace the "%.*s" spec with a "%s" spec
2017 */
2018static void gen_scanf_fmt(char *scanf_fmt, const char *rule)
2019{
2020        char *spec;
2021
2022        spec = strstr(rule, "%.*s");
2023        if (!spec || strstr(spec + 4, "%.*s"))
2024                die("invalid rule in ref_rev_parse_rules: %s", rule);
2025
2026        /* copy all until spec */
2027        strncpy(scanf_fmt, rule, spec - rule);
2028        scanf_fmt[spec - rule] = '\0';
2029        /* copy new spec */
2030        strcat(scanf_fmt, "%s");
2031        /* copy remaining rule */
2032        strcat(scanf_fmt, spec + 4);
2033
2034        return;
2035}
2036
2037char *shorten_unambiguous_ref(const char *refname, int strict)
2038{
2039        int i;
2040        static char **scanf_fmts;
2041        static int nr_rules;
2042        char *short_name;
2043
2044        /* pre generate scanf formats from ref_rev_parse_rules[] */
2045        if (!nr_rules) {
2046                size_t total_len = 0;
2047
2048                /* the rule list is NULL terminated, count them first */
2049                for (; ref_rev_parse_rules[nr_rules]; nr_rules++)
2050                        /* no +1 because strlen("%s") < strlen("%.*s") */
2051                        total_len += strlen(ref_rev_parse_rules[nr_rules]);
2052
2053                scanf_fmts = xmalloc(nr_rules * sizeof(char *) + total_len);
2054
2055                total_len = 0;
2056                for (i = 0; i < nr_rules; i++) {
2057                        scanf_fmts[i] = (char *)&scanf_fmts[nr_rules]
2058                                        + total_len;
2059                        gen_scanf_fmt(scanf_fmts[i], ref_rev_parse_rules[i]);
2060                        total_len += strlen(ref_rev_parse_rules[i]);
2061                }
2062        }
2063
2064        /* bail out if there are no rules */
2065        if (!nr_rules)
2066                return xstrdup(refname);
2067
2068        /* buffer for scanf result, at most refname must fit */
2069        short_name = xstrdup(refname);
2070
2071        /* skip first rule, it will always match */
2072        for (i = nr_rules - 1; i > 0 ; --i) {
2073                int j;
2074                int rules_to_fail = i;
2075                int short_name_len;
2076
2077                if (1 != sscanf(refname, scanf_fmts[i], short_name))
2078                        continue;
2079
2080                short_name_len = strlen(short_name);
2081
2082                /*
2083                 * in strict mode, all (except the matched one) rules
2084                 * must fail to resolve to a valid non-ambiguous ref
2085                 */
2086                if (strict)
2087                        rules_to_fail = nr_rules;
2088
2089                /*
2090                 * check if the short name resolves to a valid ref,
2091                 * but use only rules prior to the matched one
2092                 */
2093                for (j = 0; j < rules_to_fail; j++) {
2094                        const char *rule = ref_rev_parse_rules[j];
2095                        char refname[PATH_MAX];
2096
2097                        /* skip matched rule */
2098                        if (i == j)
2099                                continue;
2100
2101                        /*
2102                         * the short name is ambiguous, if it resolves
2103                         * (with this previous rule) to a valid ref
2104                         * read_ref() returns 0 on success
2105                         */
2106                        mksnpath(refname, sizeof(refname),
2107                                 rule, short_name_len, short_name);
2108                        if (ref_exists(refname))
2109                                break;
2110                }
2111
2112                /*
2113                 * short name is non-ambiguous if all previous rules
2114                 * haven't resolved to a valid ref
2115                 */
2116                if (j == rules_to_fail)
2117                        return short_name;
2118        }
2119
2120        free(short_name);
2121        return xstrdup(refname);
2122}