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