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