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