refs / files-backend.con commit refs: move for_each_*ref* functions into common code (9377059)
   1#include "../cache.h"
   2#include "../refs.h"
   3#include "refs-internal.h"
   4#include "../lockfile.h"
   5#include "../object.h"
   6#include "../dir.h"
   7
   8struct ref_lock {
   9        char *ref_name;
  10        char *orig_ref_name;
  11        struct lock_file *lk;
  12        struct object_id old_oid;
  13};
  14
  15struct ref_entry;
  16
  17/*
  18 * Information used (along with the information in ref_entry) to
  19 * describe a single cached reference.  This data structure only
  20 * occurs embedded in a union in struct ref_entry, and only when
  21 * (ref_entry->flag & REF_DIR) is zero.
  22 */
  23struct ref_value {
  24        /*
  25         * The name of the object to which this reference resolves
  26         * (which may be a tag object).  If REF_ISBROKEN, this is
  27         * null.  If REF_ISSYMREF, then this is the name of the object
  28         * referred to by the last reference in the symlink chain.
  29         */
  30        struct object_id oid;
  31
  32        /*
  33         * If REF_KNOWS_PEELED, then this field holds the peeled value
  34         * of this reference, or null if the reference is known not to
  35         * be peelable.  See the documentation for peel_ref() for an
  36         * exact definition of "peelable".
  37         */
  38        struct object_id peeled;
  39};
  40
  41struct ref_cache;
  42
  43/*
  44 * Information used (along with the information in ref_entry) to
  45 * describe a level in the hierarchy of references.  This data
  46 * structure only occurs embedded in a union in struct ref_entry, and
  47 * only when (ref_entry.flag & REF_DIR) is set.  In that case,
  48 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references
  49 * in the directory have already been read:
  50 *
  51 *     (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose
  52 *         or packed references, already read.
  53 *
  54 *     (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose
  55 *         references that hasn't been read yet (nor has any of its
  56 *         subdirectories).
  57 *
  58 * Entries within a directory are stored within a growable array of
  59 * pointers to ref_entries (entries, nr, alloc).  Entries 0 <= i <
  60 * sorted are sorted by their component name in strcmp() order and the
  61 * remaining entries are unsorted.
  62 *
  63 * Loose references are read lazily, one directory at a time.  When a
  64 * directory of loose references is read, then all of the references
  65 * in that directory are stored, and REF_INCOMPLETE stubs are created
  66 * for any subdirectories, but the subdirectories themselves are not
  67 * read.  The reading is triggered by get_ref_dir().
  68 */
  69struct ref_dir {
  70        int nr, alloc;
  71
  72        /*
  73         * Entries with index 0 <= i < sorted are sorted by name.  New
  74         * entries are appended to the list unsorted, and are sorted
  75         * only when required; thus we avoid the need to sort the list
  76         * after the addition of every reference.
  77         */
  78        int sorted;
  79
  80        /* A pointer to the ref_cache that contains this ref_dir. */
  81        struct ref_cache *ref_cache;
  82
  83        struct ref_entry **entries;
  84};
  85
  86/*
  87 * Bit values for ref_entry::flag.  REF_ISSYMREF=0x01,
  88 * REF_ISPACKED=0x02, REF_ISBROKEN=0x04 and REF_BAD_NAME=0x08 are
  89 * public values; see refs.h.
  90 */
  91
  92/*
  93 * The field ref_entry->u.value.peeled of this value entry contains
  94 * the correct peeled value for the reference, which might be
  95 * null_sha1 if the reference is not a tag or if it is broken.
  96 */
  97#define REF_KNOWS_PEELED 0x10
  98
  99/* ref_entry represents a directory of references */
 100#define REF_DIR 0x20
 101
 102/*
 103 * Entry has not yet been read from disk (used only for REF_DIR
 104 * entries representing loose references)
 105 */
 106#define REF_INCOMPLETE 0x40
 107
 108/*
 109 * A ref_entry represents either a reference or a "subdirectory" of
 110 * references.
 111 *
 112 * Each directory in the reference namespace is represented by a
 113 * ref_entry with (flags & REF_DIR) set and containing a subdir member
 114 * that holds the entries in that directory that have been read so
 115 * far.  If (flags & REF_INCOMPLETE) is set, then the directory and
 116 * its subdirectories haven't been read yet.  REF_INCOMPLETE is only
 117 * used for loose reference directories.
 118 *
 119 * References are represented by a ref_entry with (flags & REF_DIR)
 120 * unset and a value member that describes the reference's value.  The
 121 * flag member is at the ref_entry level, but it is also needed to
 122 * interpret the contents of the value field (in other words, a
 123 * ref_value object is not very much use without the enclosing
 124 * ref_entry).
 125 *
 126 * Reference names cannot end with slash and directories' names are
 127 * always stored with a trailing slash (except for the top-level
 128 * directory, which is always denoted by "").  This has two nice
 129 * consequences: (1) when the entries in each subdir are sorted
 130 * lexicographically by name (as they usually are), the references in
 131 * a whole tree can be generated in lexicographic order by traversing
 132 * the tree in left-to-right, depth-first order; (2) the names of
 133 * references and subdirectories cannot conflict, and therefore the
 134 * presence of an empty subdirectory does not block the creation of a
 135 * similarly-named reference.  (The fact that reference names with the
 136 * same leading components can conflict *with each other* is a
 137 * separate issue that is regulated by verify_refname_available().)
 138 *
 139 * Please note that the name field contains the fully-qualified
 140 * reference (or subdirectory) name.  Space could be saved by only
 141 * storing the relative names.  But that would require the full names
 142 * to be generated on the fly when iterating in do_for_each_ref(), and
 143 * would break callback functions, who have always been able to assume
 144 * that the name strings that they are passed will not be freed during
 145 * the iteration.
 146 */
 147struct ref_entry {
 148        unsigned char flag; /* ISSYMREF? ISPACKED? */
 149        union {
 150                struct ref_value value; /* if not (flags&REF_DIR) */
 151                struct ref_dir subdir; /* if (flags&REF_DIR) */
 152        } u;
 153        /*
 154         * The full name of the reference (e.g., "refs/heads/master")
 155         * or the full name of the directory with a trailing slash
 156         * (e.g., "refs/heads/"):
 157         */
 158        char name[FLEX_ARRAY];
 159};
 160
 161static void read_loose_refs(const char *dirname, struct ref_dir *dir);
 162static int search_ref_dir(struct ref_dir *dir, const char *refname, size_t len);
 163static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache,
 164                                          const char *dirname, size_t len,
 165                                          int incomplete);
 166static void add_entry_to_dir(struct ref_dir *dir, struct ref_entry *entry);
 167
 168static struct ref_dir *get_ref_dir(struct ref_entry *entry)
 169{
 170        struct ref_dir *dir;
 171        assert(entry->flag & REF_DIR);
 172        dir = &entry->u.subdir;
 173        if (entry->flag & REF_INCOMPLETE) {
 174                read_loose_refs(entry->name, dir);
 175
 176                /*
 177                 * Manually add refs/bisect, which, being
 178                 * per-worktree, might not appear in the directory
 179                 * listing for refs/ in the main repo.
 180                 */
 181                if (!strcmp(entry->name, "refs/")) {
 182                        int pos = search_ref_dir(dir, "refs/bisect/", 12);
 183                        if (pos < 0) {
 184                                struct ref_entry *child_entry;
 185                                child_entry = create_dir_entry(dir->ref_cache,
 186                                                               "refs/bisect/",
 187                                                               12, 1);
 188                                add_entry_to_dir(dir, child_entry);
 189                                read_loose_refs("refs/bisect",
 190                                                &child_entry->u.subdir);
 191                        }
 192                }
 193                entry->flag &= ~REF_INCOMPLETE;
 194        }
 195        return dir;
 196}
 197
 198static struct ref_entry *create_ref_entry(const char *refname,
 199                                          const unsigned char *sha1, int flag,
 200                                          int check_name)
 201{
 202        struct ref_entry *ref;
 203
 204        if (check_name &&
 205            check_refname_format(refname, REFNAME_ALLOW_ONELEVEL))
 206                die("Reference has invalid format: '%s'", refname);
 207        FLEX_ALLOC_STR(ref, name, refname);
 208        hashcpy(ref->u.value.oid.hash, sha1);
 209        oidclr(&ref->u.value.peeled);
 210        ref->flag = flag;
 211        return ref;
 212}
 213
 214static void clear_ref_dir(struct ref_dir *dir);
 215
 216static void free_ref_entry(struct ref_entry *entry)
 217{
 218        if (entry->flag & REF_DIR) {
 219                /*
 220                 * Do not use get_ref_dir() here, as that might
 221                 * trigger the reading of loose refs.
 222                 */
 223                clear_ref_dir(&entry->u.subdir);
 224        }
 225        free(entry);
 226}
 227
 228/*
 229 * Add a ref_entry to the end of dir (unsorted).  Entry is always
 230 * stored directly in dir; no recursion into subdirectories is
 231 * done.
 232 */
 233static void add_entry_to_dir(struct ref_dir *dir, struct ref_entry *entry)
 234{
 235        ALLOC_GROW(dir->entries, dir->nr + 1, dir->alloc);
 236        dir->entries[dir->nr++] = entry;
 237        /* optimize for the case that entries are added in order */
 238        if (dir->nr == 1 ||
 239            (dir->nr == dir->sorted + 1 &&
 240             strcmp(dir->entries[dir->nr - 2]->name,
 241                    dir->entries[dir->nr - 1]->name) < 0))
 242                dir->sorted = dir->nr;
 243}
 244
 245/*
 246 * Clear and free all entries in dir, recursively.
 247 */
 248static void clear_ref_dir(struct ref_dir *dir)
 249{
 250        int i;
 251        for (i = 0; i < dir->nr; i++)
 252                free_ref_entry(dir->entries[i]);
 253        free(dir->entries);
 254        dir->sorted = dir->nr = dir->alloc = 0;
 255        dir->entries = NULL;
 256}
 257
 258/*
 259 * Create a struct ref_entry object for the specified dirname.
 260 * dirname is the name of the directory with a trailing slash (e.g.,
 261 * "refs/heads/") or "" for the top-level directory.
 262 */
 263static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache,
 264                                          const char *dirname, size_t len,
 265                                          int incomplete)
 266{
 267        struct ref_entry *direntry;
 268        FLEX_ALLOC_MEM(direntry, name, dirname, len);
 269        direntry->u.subdir.ref_cache = ref_cache;
 270        direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE : 0);
 271        return direntry;
 272}
 273
 274static int ref_entry_cmp(const void *a, const void *b)
 275{
 276        struct ref_entry *one = *(struct ref_entry **)a;
 277        struct ref_entry *two = *(struct ref_entry **)b;
 278        return strcmp(one->name, two->name);
 279}
 280
 281static void sort_ref_dir(struct ref_dir *dir);
 282
 283struct string_slice {
 284        size_t len;
 285        const char *str;
 286};
 287
 288static int ref_entry_cmp_sslice(const void *key_, const void *ent_)
 289{
 290        const struct string_slice *key = key_;
 291        const struct ref_entry *ent = *(const struct ref_entry * const *)ent_;
 292        int cmp = strncmp(key->str, ent->name, key->len);
 293        if (cmp)
 294                return cmp;
 295        return '\0' - (unsigned char)ent->name[key->len];
 296}
 297
 298/*
 299 * Return the index of the entry with the given refname from the
 300 * ref_dir (non-recursively), sorting dir if necessary.  Return -1 if
 301 * no such entry is found.  dir must already be complete.
 302 */
 303static int search_ref_dir(struct ref_dir *dir, const char *refname, size_t len)
 304{
 305        struct ref_entry **r;
 306        struct string_slice key;
 307
 308        if (refname == NULL || !dir->nr)
 309                return -1;
 310
 311        sort_ref_dir(dir);
 312        key.len = len;
 313        key.str = refname;
 314        r = bsearch(&key, dir->entries, dir->nr, sizeof(*dir->entries),
 315                    ref_entry_cmp_sslice);
 316
 317        if (r == NULL)
 318                return -1;
 319
 320        return r - dir->entries;
 321}
 322
 323/*
 324 * Search for a directory entry directly within dir (without
 325 * recursing).  Sort dir if necessary.  subdirname must be a directory
 326 * name (i.e., end in '/').  If mkdir is set, then create the
 327 * directory if it is missing; otherwise, return NULL if the desired
 328 * directory cannot be found.  dir must already be complete.
 329 */
 330static struct ref_dir *search_for_subdir(struct ref_dir *dir,
 331                                         const char *subdirname, size_t len,
 332                                         int mkdir)
 333{
 334        int entry_index = search_ref_dir(dir, subdirname, len);
 335        struct ref_entry *entry;
 336        if (entry_index == -1) {
 337                if (!mkdir)
 338                        return NULL;
 339                /*
 340                 * Since dir is complete, the absence of a subdir
 341                 * means that the subdir really doesn't exist;
 342                 * therefore, create an empty record for it but mark
 343                 * the record complete.
 344                 */
 345                entry = create_dir_entry(dir->ref_cache, subdirname, len, 0);
 346                add_entry_to_dir(dir, entry);
 347        } else {
 348                entry = dir->entries[entry_index];
 349        }
 350        return get_ref_dir(entry);
 351}
 352
 353/*
 354 * If refname is a reference name, find the ref_dir within the dir
 355 * tree that should hold refname.  If refname is a directory name
 356 * (i.e., ends in '/'), then return that ref_dir itself.  dir must
 357 * represent the top-level directory and must already be complete.
 358 * Sort ref_dirs and recurse into subdirectories as necessary.  If
 359 * mkdir is set, then create any missing directories; otherwise,
 360 * return NULL if the desired directory cannot be found.
 361 */
 362static struct ref_dir *find_containing_dir(struct ref_dir *dir,
 363                                           const char *refname, int mkdir)
 364{
 365        const char *slash;
 366        for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) {
 367                size_t dirnamelen = slash - refname + 1;
 368                struct ref_dir *subdir;
 369                subdir = search_for_subdir(dir, refname, dirnamelen, mkdir);
 370                if (!subdir) {
 371                        dir = NULL;
 372                        break;
 373                }
 374                dir = subdir;
 375        }
 376
 377        return dir;
 378}
 379
 380/*
 381 * Find the value entry with the given name in dir, sorting ref_dirs
 382 * and recursing into subdirectories as necessary.  If the name is not
 383 * found or it corresponds to a directory entry, return NULL.
 384 */
 385static struct ref_entry *find_ref(struct ref_dir *dir, const char *refname)
 386{
 387        int entry_index;
 388        struct ref_entry *entry;
 389        dir = find_containing_dir(dir, refname, 0);
 390        if (!dir)
 391                return NULL;
 392        entry_index = search_ref_dir(dir, refname, strlen(refname));
 393        if (entry_index == -1)
 394                return NULL;
 395        entry = dir->entries[entry_index];
 396        return (entry->flag & REF_DIR) ? NULL : entry;
 397}
 398
 399/*
 400 * Remove the entry with the given name from dir, recursing into
 401 * subdirectories as necessary.  If refname is the name of a directory
 402 * (i.e., ends with '/'), then remove the directory and its contents.
 403 * If the removal was successful, return the number of entries
 404 * remaining in the directory entry that contained the deleted entry.
 405 * If the name was not found, return -1.  Please note that this
 406 * function only deletes the entry from the cache; it does not delete
 407 * it from the filesystem or ensure that other cache entries (which
 408 * might be symbolic references to the removed entry) are updated.
 409 * Nor does it remove any containing dir entries that might be made
 410 * empty by the removal.  dir must represent the top-level directory
 411 * and must already be complete.
 412 */
 413static int remove_entry(struct ref_dir *dir, const char *refname)
 414{
 415        int refname_len = strlen(refname);
 416        int entry_index;
 417        struct ref_entry *entry;
 418        int is_dir = refname[refname_len - 1] == '/';
 419        if (is_dir) {
 420                /*
 421                 * refname represents a reference directory.  Remove
 422                 * the trailing slash; otherwise we will get the
 423                 * directory *representing* refname rather than the
 424                 * one *containing* it.
 425                 */
 426                char *dirname = xmemdupz(refname, refname_len - 1);
 427                dir = find_containing_dir(dir, dirname, 0);
 428                free(dirname);
 429        } else {
 430                dir = find_containing_dir(dir, refname, 0);
 431        }
 432        if (!dir)
 433                return -1;
 434        entry_index = search_ref_dir(dir, refname, refname_len);
 435        if (entry_index == -1)
 436                return -1;
 437        entry = dir->entries[entry_index];
 438
 439        memmove(&dir->entries[entry_index],
 440                &dir->entries[entry_index + 1],
 441                (dir->nr - entry_index - 1) * sizeof(*dir->entries)
 442                );
 443        dir->nr--;
 444        if (dir->sorted > entry_index)
 445                dir->sorted--;
 446        free_ref_entry(entry);
 447        return dir->nr;
 448}
 449
 450/*
 451 * Add a ref_entry to the ref_dir (unsorted), recursing into
 452 * subdirectories as necessary.  dir must represent the top-level
 453 * directory.  Return 0 on success.
 454 */
 455static int add_ref(struct ref_dir *dir, struct ref_entry *ref)
 456{
 457        dir = find_containing_dir(dir, ref->name, 1);
 458        if (!dir)
 459                return -1;
 460        add_entry_to_dir(dir, ref);
 461        return 0;
 462}
 463
 464/*
 465 * Emit a warning and return true iff ref1 and ref2 have the same name
 466 * and the same sha1.  Die if they have the same name but different
 467 * sha1s.
 468 */
 469static int is_dup_ref(const struct ref_entry *ref1, const struct ref_entry *ref2)
 470{
 471        if (strcmp(ref1->name, ref2->name))
 472                return 0;
 473
 474        /* Duplicate name; make sure that they don't conflict: */
 475
 476        if ((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR))
 477                /* This is impossible by construction */
 478                die("Reference directory conflict: %s", ref1->name);
 479
 480        if (oidcmp(&ref1->u.value.oid, &ref2->u.value.oid))
 481                die("Duplicated ref, and SHA1s don't match: %s", ref1->name);
 482
 483        warning("Duplicated ref: %s", ref1->name);
 484        return 1;
 485}
 486
 487/*
 488 * Sort the entries in dir non-recursively (if they are not already
 489 * sorted) and remove any duplicate entries.
 490 */
 491static void sort_ref_dir(struct ref_dir *dir)
 492{
 493        int i, j;
 494        struct ref_entry *last = NULL;
 495
 496        /*
 497         * This check also prevents passing a zero-length array to qsort(),
 498         * which is a problem on some platforms.
 499         */
 500        if (dir->sorted == dir->nr)
 501                return;
 502
 503        qsort(dir->entries, dir->nr, sizeof(*dir->entries), ref_entry_cmp);
 504
 505        /* Remove any duplicates: */
 506        for (i = 0, j = 0; j < dir->nr; j++) {
 507                struct ref_entry *entry = dir->entries[j];
 508                if (last && is_dup_ref(last, entry))
 509                        free_ref_entry(entry);
 510                else
 511                        last = dir->entries[i++] = entry;
 512        }
 513        dir->sorted = dir->nr = i;
 514}
 515
 516/*
 517 * Return true iff the reference described by entry can be resolved to
 518 * an object in the database.  Emit a warning if the referred-to
 519 * object does not exist.
 520 */
 521static int ref_resolves_to_object(struct ref_entry *entry)
 522{
 523        if (entry->flag & REF_ISBROKEN)
 524                return 0;
 525        if (!has_sha1_file(entry->u.value.oid.hash)) {
 526                error("%s does not point to a valid object!", entry->name);
 527                return 0;
 528        }
 529        return 1;
 530}
 531
 532/*
 533 * current_ref is a performance hack: when iterating over references
 534 * using the for_each_ref*() functions, current_ref is set to the
 535 * current reference's entry before calling the callback function.  If
 536 * the callback function calls peel_ref(), then peel_ref() first
 537 * checks whether the reference to be peeled is the current reference
 538 * (it usually is) and if so, returns that reference's peeled version
 539 * if it is available.  This avoids a refname lookup in a common case.
 540 */
 541static struct ref_entry *current_ref;
 542
 543typedef int each_ref_entry_fn(struct ref_entry *entry, void *cb_data);
 544
 545struct ref_entry_cb {
 546        const char *base;
 547        int trim;
 548        int flags;
 549        each_ref_fn *fn;
 550        void *cb_data;
 551};
 552
 553/*
 554 * Handle one reference in a do_for_each_ref*()-style iteration,
 555 * calling an each_ref_fn for each entry.
 556 */
 557static int do_one_ref(struct ref_entry *entry, void *cb_data)
 558{
 559        struct ref_entry_cb *data = cb_data;
 560        struct ref_entry *old_current_ref;
 561        int retval;
 562
 563        if (!starts_with(entry->name, data->base))
 564                return 0;
 565
 566        if (!(data->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&
 567              !ref_resolves_to_object(entry))
 568                return 0;
 569
 570        /* Store the old value, in case this is a recursive call: */
 571        old_current_ref = current_ref;
 572        current_ref = entry;
 573        retval = data->fn(entry->name + data->trim, &entry->u.value.oid,
 574                          entry->flag, data->cb_data);
 575        current_ref = old_current_ref;
 576        return retval;
 577}
 578
 579/*
 580 * Call fn for each reference in dir that has index in the range
 581 * offset <= index < dir->nr.  Recurse into subdirectories that are in
 582 * that index range, sorting them before iterating.  This function
 583 * does not sort dir itself; it should be sorted beforehand.  fn is
 584 * called for all references, including broken ones.
 585 */
 586static int do_for_each_entry_in_dir(struct ref_dir *dir, int offset,
 587                                    each_ref_entry_fn fn, void *cb_data)
 588{
 589        int i;
 590        assert(dir->sorted == dir->nr);
 591        for (i = offset; i < dir->nr; i++) {
 592                struct ref_entry *entry = dir->entries[i];
 593                int retval;
 594                if (entry->flag & REF_DIR) {
 595                        struct ref_dir *subdir = get_ref_dir(entry);
 596                        sort_ref_dir(subdir);
 597                        retval = do_for_each_entry_in_dir(subdir, 0, fn, cb_data);
 598                } else {
 599                        retval = fn(entry, cb_data);
 600                }
 601                if (retval)
 602                        return retval;
 603        }
 604        return 0;
 605}
 606
 607/*
 608 * Call fn for each reference in the union of dir1 and dir2, in order
 609 * by refname.  Recurse into subdirectories.  If a value entry appears
 610 * in both dir1 and dir2, then only process the version that is in
 611 * dir2.  The input dirs must already be sorted, but subdirs will be
 612 * sorted as needed.  fn is called for all references, including
 613 * broken ones.
 614 */
 615static int do_for_each_entry_in_dirs(struct ref_dir *dir1,
 616                                     struct ref_dir *dir2,
 617                                     each_ref_entry_fn fn, void *cb_data)
 618{
 619        int retval;
 620        int i1 = 0, i2 = 0;
 621
 622        assert(dir1->sorted == dir1->nr);
 623        assert(dir2->sorted == dir2->nr);
 624        while (1) {
 625                struct ref_entry *e1, *e2;
 626                int cmp;
 627                if (i1 == dir1->nr) {
 628                        return do_for_each_entry_in_dir(dir2, i2, fn, cb_data);
 629                }
 630                if (i2 == dir2->nr) {
 631                        return do_for_each_entry_in_dir(dir1, i1, fn, cb_data);
 632                }
 633                e1 = dir1->entries[i1];
 634                e2 = dir2->entries[i2];
 635                cmp = strcmp(e1->name, e2->name);
 636                if (cmp == 0) {
 637                        if ((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) {
 638                                /* Both are directories; descend them in parallel. */
 639                                struct ref_dir *subdir1 = get_ref_dir(e1);
 640                                struct ref_dir *subdir2 = get_ref_dir(e2);
 641                                sort_ref_dir(subdir1);
 642                                sort_ref_dir(subdir2);
 643                                retval = do_for_each_entry_in_dirs(
 644                                                subdir1, subdir2, fn, cb_data);
 645                                i1++;
 646                                i2++;
 647                        } else if (!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) {
 648                                /* Both are references; ignore the one from dir1. */
 649                                retval = fn(e2, cb_data);
 650                                i1++;
 651                                i2++;
 652                        } else {
 653                                die("conflict between reference and directory: %s",
 654                                    e1->name);
 655                        }
 656                } else {
 657                        struct ref_entry *e;
 658                        if (cmp < 0) {
 659                                e = e1;
 660                                i1++;
 661                        } else {
 662                                e = e2;
 663                                i2++;
 664                        }
 665                        if (e->flag & REF_DIR) {
 666                                struct ref_dir *subdir = get_ref_dir(e);
 667                                sort_ref_dir(subdir);
 668                                retval = do_for_each_entry_in_dir(
 669                                                subdir, 0, fn, cb_data);
 670                        } else {
 671                                retval = fn(e, cb_data);
 672                        }
 673                }
 674                if (retval)
 675                        return retval;
 676        }
 677}
 678
 679/*
 680 * Load all of the refs from the dir into our in-memory cache. The hard work
 681 * of loading loose refs is done by get_ref_dir(), so we just need to recurse
 682 * through all of the sub-directories. We do not even need to care about
 683 * sorting, as traversal order does not matter to us.
 684 */
 685static void prime_ref_dir(struct ref_dir *dir)
 686{
 687        int i;
 688        for (i = 0; i < dir->nr; i++) {
 689                struct ref_entry *entry = dir->entries[i];
 690                if (entry->flag & REF_DIR)
 691                        prime_ref_dir(get_ref_dir(entry));
 692        }
 693}
 694
 695struct nonmatching_ref_data {
 696        const struct string_list *skip;
 697        const char *conflicting_refname;
 698};
 699
 700static int nonmatching_ref_fn(struct ref_entry *entry, void *vdata)
 701{
 702        struct nonmatching_ref_data *data = vdata;
 703
 704        if (data->skip && string_list_has_string(data->skip, entry->name))
 705                return 0;
 706
 707        data->conflicting_refname = entry->name;
 708        return 1;
 709}
 710
 711/*
 712 * Return 0 if a reference named refname could be created without
 713 * conflicting with the name of an existing reference in dir.
 714 * See verify_refname_available for more information.
 715 */
 716static int verify_refname_available_dir(const char *refname,
 717                                        const struct string_list *extras,
 718                                        const struct string_list *skip,
 719                                        struct ref_dir *dir,
 720                                        struct strbuf *err)
 721{
 722        const char *slash;
 723        const char *extra_refname;
 724        int pos;
 725        struct strbuf dirname = STRBUF_INIT;
 726        int ret = -1;
 727
 728        /*
 729         * For the sake of comments in this function, suppose that
 730         * refname is "refs/foo/bar".
 731         */
 732
 733        assert(err);
 734
 735        strbuf_grow(&dirname, strlen(refname) + 1);
 736        for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) {
 737                /* Expand dirname to the new prefix, not including the trailing slash: */
 738                strbuf_add(&dirname, refname + dirname.len, slash - refname - dirname.len);
 739
 740                /*
 741                 * We are still at a leading dir of the refname (e.g.,
 742                 * "refs/foo"; if there is a reference with that name,
 743                 * it is a conflict, *unless* it is in skip.
 744                 */
 745                if (dir) {
 746                        pos = search_ref_dir(dir, dirname.buf, dirname.len);
 747                        if (pos >= 0 &&
 748                            (!skip || !string_list_has_string(skip, dirname.buf))) {
 749                                /*
 750                                 * We found a reference whose name is
 751                                 * a proper prefix of refname; e.g.,
 752                                 * "refs/foo", and is not in skip.
 753                                 */
 754                                strbuf_addf(err, "'%s' exists; cannot create '%s'",
 755                                            dirname.buf, refname);
 756                                goto cleanup;
 757                        }
 758                }
 759
 760                if (extras && string_list_has_string(extras, dirname.buf) &&
 761                    (!skip || !string_list_has_string(skip, dirname.buf))) {
 762                        strbuf_addf(err, "cannot process '%s' and '%s' at the same time",
 763                                    refname, dirname.buf);
 764                        goto cleanup;
 765                }
 766
 767                /*
 768                 * Otherwise, we can try to continue our search with
 769                 * the next component. So try to look up the
 770                 * directory, e.g., "refs/foo/". If we come up empty,
 771                 * we know there is nothing under this whole prefix,
 772                 * but even in that case we still have to continue the
 773                 * search for conflicts with extras.
 774                 */
 775                strbuf_addch(&dirname, '/');
 776                if (dir) {
 777                        pos = search_ref_dir(dir, dirname.buf, dirname.len);
 778                        if (pos < 0) {
 779                                /*
 780                                 * There was no directory "refs/foo/",
 781                                 * so there is nothing under this
 782                                 * whole prefix. So there is no need
 783                                 * to continue looking for conflicting
 784                                 * references. But we need to continue
 785                                 * looking for conflicting extras.
 786                                 */
 787                                dir = NULL;
 788                        } else {
 789                                dir = get_ref_dir(dir->entries[pos]);
 790                        }
 791                }
 792        }
 793
 794        /*
 795         * We are at the leaf of our refname (e.g., "refs/foo/bar").
 796         * There is no point in searching for a reference with that
 797         * name, because a refname isn't considered to conflict with
 798         * itself. But we still need to check for references whose
 799         * names are in the "refs/foo/bar/" namespace, because they
 800         * *do* conflict.
 801         */
 802        strbuf_addstr(&dirname, refname + dirname.len);
 803        strbuf_addch(&dirname, '/');
 804
 805        if (dir) {
 806                pos = search_ref_dir(dir, dirname.buf, dirname.len);
 807
 808                if (pos >= 0) {
 809                        /*
 810                         * We found a directory named "$refname/"
 811                         * (e.g., "refs/foo/bar/"). It is a problem
 812                         * iff it contains any ref that is not in
 813                         * "skip".
 814                         */
 815                        struct nonmatching_ref_data data;
 816
 817                        data.skip = skip;
 818                        data.conflicting_refname = NULL;
 819                        dir = get_ref_dir(dir->entries[pos]);
 820                        sort_ref_dir(dir);
 821                        if (do_for_each_entry_in_dir(dir, 0, nonmatching_ref_fn, &data)) {
 822                                strbuf_addf(err, "'%s' exists; cannot create '%s'",
 823                                            data.conflicting_refname, refname);
 824                                goto cleanup;
 825                        }
 826                }
 827        }
 828
 829        extra_refname = find_descendant_ref(dirname.buf, extras, skip);
 830        if (extra_refname)
 831                strbuf_addf(err, "cannot process '%s' and '%s' at the same time",
 832                            refname, extra_refname);
 833        else
 834                ret = 0;
 835
 836cleanup:
 837        strbuf_release(&dirname);
 838        return ret;
 839}
 840
 841struct packed_ref_cache {
 842        struct ref_entry *root;
 843
 844        /*
 845         * Count of references to the data structure in this instance,
 846         * including the pointer from ref_cache::packed if any.  The
 847         * data will not be freed as long as the reference count is
 848         * nonzero.
 849         */
 850        unsigned int referrers;
 851
 852        /*
 853         * Iff the packed-refs file associated with this instance is
 854         * currently locked for writing, this points at the associated
 855         * lock (which is owned by somebody else).  The referrer count
 856         * is also incremented when the file is locked and decremented
 857         * when it is unlocked.
 858         */
 859        struct lock_file *lock;
 860
 861        /* The metadata from when this packed-refs cache was read */
 862        struct stat_validity validity;
 863};
 864
 865/*
 866 * Future: need to be in "struct repository"
 867 * when doing a full libification.
 868 */
 869static struct ref_cache {
 870        struct ref_cache *next;
 871        struct ref_entry *loose;
 872        struct packed_ref_cache *packed;
 873        /*
 874         * The submodule name, or "" for the main repo.  We allocate
 875         * length 1 rather than FLEX_ARRAY so that the main ref_cache
 876         * is initialized correctly.
 877         */
 878        char name[1];
 879} ref_cache, *submodule_ref_caches;
 880
 881/* Lock used for the main packed-refs file: */
 882static struct lock_file packlock;
 883
 884/*
 885 * Increment the reference count of *packed_refs.
 886 */
 887static void acquire_packed_ref_cache(struct packed_ref_cache *packed_refs)
 888{
 889        packed_refs->referrers++;
 890}
 891
 892/*
 893 * Decrease the reference count of *packed_refs.  If it goes to zero,
 894 * free *packed_refs and return true; otherwise return false.
 895 */
 896static int release_packed_ref_cache(struct packed_ref_cache *packed_refs)
 897{
 898        if (!--packed_refs->referrers) {
 899                free_ref_entry(packed_refs->root);
 900                stat_validity_clear(&packed_refs->validity);
 901                free(packed_refs);
 902                return 1;
 903        } else {
 904                return 0;
 905        }
 906}
 907
 908static void clear_packed_ref_cache(struct ref_cache *refs)
 909{
 910        if (refs->packed) {
 911                struct packed_ref_cache *packed_refs = refs->packed;
 912
 913                if (packed_refs->lock)
 914                        die("internal error: packed-ref cache cleared while locked");
 915                refs->packed = NULL;
 916                release_packed_ref_cache(packed_refs);
 917        }
 918}
 919
 920static void clear_loose_ref_cache(struct ref_cache *refs)
 921{
 922        if (refs->loose) {
 923                free_ref_entry(refs->loose);
 924                refs->loose = NULL;
 925        }
 926}
 927
 928/*
 929 * Create a new submodule ref cache and add it to the internal
 930 * set of caches.
 931 */
 932static struct ref_cache *create_ref_cache(const char *submodule)
 933{
 934        struct ref_cache *refs;
 935        if (!submodule)
 936                submodule = "";
 937        FLEX_ALLOC_STR(refs, name, submodule);
 938        refs->next = submodule_ref_caches;
 939        submodule_ref_caches = refs;
 940        return refs;
 941}
 942
 943static struct ref_cache *lookup_ref_cache(const char *submodule)
 944{
 945        struct ref_cache *refs;
 946
 947        if (!submodule || !*submodule)
 948                return &ref_cache;
 949
 950        for (refs = submodule_ref_caches; refs; refs = refs->next)
 951                if (!strcmp(submodule, refs->name))
 952                        return refs;
 953        return NULL;
 954}
 955
 956/*
 957 * Return a pointer to a ref_cache for the specified submodule. For
 958 * the main repository, use submodule==NULL. The returned structure
 959 * will be allocated and initialized but not necessarily populated; it
 960 * should not be freed.
 961 */
 962static struct ref_cache *get_ref_cache(const char *submodule)
 963{
 964        struct ref_cache *refs = lookup_ref_cache(submodule);
 965        if (!refs)
 966                refs = create_ref_cache(submodule);
 967        return refs;
 968}
 969
 970/* The length of a peeled reference line in packed-refs, including EOL: */
 971#define PEELED_LINE_LENGTH 42
 972
 973/*
 974 * The packed-refs header line that we write out.  Perhaps other
 975 * traits will be added later.  The trailing space is required.
 976 */
 977static const char PACKED_REFS_HEADER[] =
 978        "# pack-refs with: peeled fully-peeled \n";
 979
 980/*
 981 * Parse one line from a packed-refs file.  Write the SHA1 to sha1.
 982 * Return a pointer to the refname within the line (null-terminated),
 983 * or NULL if there was a problem.
 984 */
 985static const char *parse_ref_line(struct strbuf *line, unsigned char *sha1)
 986{
 987        const char *ref;
 988
 989        /*
 990         * 42: the answer to everything.
 991         *
 992         * In this case, it happens to be the answer to
 993         *  40 (length of sha1 hex representation)
 994         *  +1 (space in between hex and name)
 995         *  +1 (newline at the end of the line)
 996         */
 997        if (line->len <= 42)
 998                return NULL;
 999
1000        if (get_sha1_hex(line->buf, sha1) < 0)
1001                return NULL;
1002        if (!isspace(line->buf[40]))
1003                return NULL;
1004
1005        ref = line->buf + 41;
1006        if (isspace(*ref))
1007                return NULL;
1008
1009        if (line->buf[line->len - 1] != '\n')
1010                return NULL;
1011        line->buf[--line->len] = 0;
1012
1013        return ref;
1014}
1015
1016/*
1017 * Read f, which is a packed-refs file, into dir.
1018 *
1019 * A comment line of the form "# pack-refs with: " may contain zero or
1020 * more traits. We interpret the traits as follows:
1021 *
1022 *   No traits:
1023 *
1024 *      Probably no references are peeled. But if the file contains a
1025 *      peeled value for a reference, we will use it.
1026 *
1027 *   peeled:
1028 *
1029 *      References under "refs/tags/", if they *can* be peeled, *are*
1030 *      peeled in this file. References outside of "refs/tags/" are
1031 *      probably not peeled even if they could have been, but if we find
1032 *      a peeled value for such a reference we will use it.
1033 *
1034 *   fully-peeled:
1035 *
1036 *      All references in the file that can be peeled are peeled.
1037 *      Inversely (and this is more important), any references in the
1038 *      file for which no peeled value is recorded is not peelable. This
1039 *      trait should typically be written alongside "peeled" for
1040 *      compatibility with older clients, but we do not require it
1041 *      (i.e., "peeled" is a no-op if "fully-peeled" is set).
1042 */
1043static void read_packed_refs(FILE *f, struct ref_dir *dir)
1044{
1045        struct ref_entry *last = NULL;
1046        struct strbuf line = STRBUF_INIT;
1047        enum { PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;
1048
1049        while (strbuf_getwholeline(&line, f, '\n') != EOF) {
1050                unsigned char sha1[20];
1051                const char *refname;
1052                const char *traits;
1053
1054                if (skip_prefix(line.buf, "# pack-refs with:", &traits)) {
1055                        if (strstr(traits, " fully-peeled "))
1056                                peeled = PEELED_FULLY;
1057                        else if (strstr(traits, " peeled "))
1058                                peeled = PEELED_TAGS;
1059                        /* perhaps other traits later as well */
1060                        continue;
1061                }
1062
1063                refname = parse_ref_line(&line, sha1);
1064                if (refname) {
1065                        int flag = REF_ISPACKED;
1066
1067                        if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1068                                if (!refname_is_safe(refname))
1069                                        die("packed refname is dangerous: %s", refname);
1070                                hashclr(sha1);
1071                                flag |= REF_BAD_NAME | REF_ISBROKEN;
1072                        }
1073                        last = create_ref_entry(refname, sha1, flag, 0);
1074                        if (peeled == PEELED_FULLY ||
1075                            (peeled == PEELED_TAGS && starts_with(refname, "refs/tags/")))
1076                                last->flag |= REF_KNOWS_PEELED;
1077                        add_ref(dir, last);
1078                        continue;
1079                }
1080                if (last &&
1081                    line.buf[0] == '^' &&
1082                    line.len == PEELED_LINE_LENGTH &&
1083                    line.buf[PEELED_LINE_LENGTH - 1] == '\n' &&
1084                    !get_sha1_hex(line.buf + 1, sha1)) {
1085                        hashcpy(last->u.value.peeled.hash, sha1);
1086                        /*
1087                         * Regardless of what the file header said,
1088                         * we definitely know the value of *this*
1089                         * reference:
1090                         */
1091                        last->flag |= REF_KNOWS_PEELED;
1092                }
1093        }
1094
1095        strbuf_release(&line);
1096}
1097
1098/*
1099 * Get the packed_ref_cache for the specified ref_cache, creating it
1100 * if necessary.
1101 */
1102static struct packed_ref_cache *get_packed_ref_cache(struct ref_cache *refs)
1103{
1104        char *packed_refs_file;
1105
1106        if (*refs->name)
1107                packed_refs_file = git_pathdup_submodule(refs->name, "packed-refs");
1108        else
1109                packed_refs_file = git_pathdup("packed-refs");
1110
1111        if (refs->packed &&
1112            !stat_validity_check(&refs->packed->validity, packed_refs_file))
1113                clear_packed_ref_cache(refs);
1114
1115        if (!refs->packed) {
1116                FILE *f;
1117
1118                refs->packed = xcalloc(1, sizeof(*refs->packed));
1119                acquire_packed_ref_cache(refs->packed);
1120                refs->packed->root = create_dir_entry(refs, "", 0, 0);
1121                f = fopen(packed_refs_file, "r");
1122                if (f) {
1123                        stat_validity_update(&refs->packed->validity, fileno(f));
1124                        read_packed_refs(f, get_ref_dir(refs->packed->root));
1125                        fclose(f);
1126                }
1127        }
1128        free(packed_refs_file);
1129        return refs->packed;
1130}
1131
1132static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)
1133{
1134        return get_ref_dir(packed_ref_cache->root);
1135}
1136
1137static struct ref_dir *get_packed_refs(struct ref_cache *refs)
1138{
1139        return get_packed_ref_dir(get_packed_ref_cache(refs));
1140}
1141
1142/*
1143 * Add a reference to the in-memory packed reference cache.  This may
1144 * only be called while the packed-refs file is locked (see
1145 * lock_packed_refs()).  To actually write the packed-refs file, call
1146 * commit_packed_refs().
1147 */
1148static void add_packed_ref(const char *refname, const unsigned char *sha1)
1149{
1150        struct packed_ref_cache *packed_ref_cache =
1151                get_packed_ref_cache(&ref_cache);
1152
1153        if (!packed_ref_cache->lock)
1154                die("internal error: packed refs not locked");
1155        add_ref(get_packed_ref_dir(packed_ref_cache),
1156                create_ref_entry(refname, sha1, REF_ISPACKED, 1));
1157}
1158
1159/*
1160 * Read the loose references from the namespace dirname into dir
1161 * (without recursing).  dirname must end with '/'.  dir must be the
1162 * directory entry corresponding to dirname.
1163 */
1164static void read_loose_refs(const char *dirname, struct ref_dir *dir)
1165{
1166        struct ref_cache *refs = dir->ref_cache;
1167        DIR *d;
1168        struct dirent *de;
1169        int dirnamelen = strlen(dirname);
1170        struct strbuf refname;
1171        struct strbuf path = STRBUF_INIT;
1172        size_t path_baselen;
1173
1174        if (*refs->name)
1175                strbuf_git_path_submodule(&path, refs->name, "%s", dirname);
1176        else
1177                strbuf_git_path(&path, "%s", dirname);
1178        path_baselen = path.len;
1179
1180        d = opendir(path.buf);
1181        if (!d) {
1182                strbuf_release(&path);
1183                return;
1184        }
1185
1186        strbuf_init(&refname, dirnamelen + 257);
1187        strbuf_add(&refname, dirname, dirnamelen);
1188
1189        while ((de = readdir(d)) != NULL) {
1190                unsigned char sha1[20];
1191                struct stat st;
1192                int flag;
1193
1194                if (de->d_name[0] == '.')
1195                        continue;
1196                if (ends_with(de->d_name, ".lock"))
1197                        continue;
1198                strbuf_addstr(&refname, de->d_name);
1199                strbuf_addstr(&path, de->d_name);
1200                if (stat(path.buf, &st) < 0) {
1201                        ; /* silently ignore */
1202                } else if (S_ISDIR(st.st_mode)) {
1203                        strbuf_addch(&refname, '/');
1204                        add_entry_to_dir(dir,
1205                                         create_dir_entry(refs, refname.buf,
1206                                                          refname.len, 1));
1207                } else {
1208                        int read_ok;
1209
1210                        if (*refs->name) {
1211                                hashclr(sha1);
1212                                flag = 0;
1213                                read_ok = !resolve_gitlink_ref(refs->name,
1214                                                               refname.buf, sha1);
1215                        } else {
1216                                read_ok = !read_ref_full(refname.buf,
1217                                                         RESOLVE_REF_READING,
1218                                                         sha1, &flag);
1219                        }
1220
1221                        if (!read_ok) {
1222                                hashclr(sha1);
1223                                flag |= REF_ISBROKEN;
1224                        } else if (is_null_sha1(sha1)) {
1225                                /*
1226                                 * It is so astronomically unlikely
1227                                 * that NULL_SHA1 is the SHA-1 of an
1228                                 * actual object that we consider its
1229                                 * appearance in a loose reference
1230                                 * file to be repo corruption
1231                                 * (probably due to a software bug).
1232                                 */
1233                                flag |= REF_ISBROKEN;
1234                        }
1235
1236                        if (check_refname_format(refname.buf,
1237                                                 REFNAME_ALLOW_ONELEVEL)) {
1238                                if (!refname_is_safe(refname.buf))
1239                                        die("loose refname is dangerous: %s", refname.buf);
1240                                hashclr(sha1);
1241                                flag |= REF_BAD_NAME | REF_ISBROKEN;
1242                        }
1243                        add_entry_to_dir(dir,
1244                                         create_ref_entry(refname.buf, sha1, flag, 0));
1245                }
1246                strbuf_setlen(&refname, dirnamelen);
1247                strbuf_setlen(&path, path_baselen);
1248        }
1249        strbuf_release(&refname);
1250        strbuf_release(&path);
1251        closedir(d);
1252}
1253
1254static struct ref_dir *get_loose_refs(struct ref_cache *refs)
1255{
1256        if (!refs->loose) {
1257                /*
1258                 * Mark the top-level directory complete because we
1259                 * are about to read the only subdirectory that can
1260                 * hold references:
1261                 */
1262                refs->loose = create_dir_entry(refs, "", 0, 0);
1263                /*
1264                 * Create an incomplete entry for "refs/":
1265                 */
1266                add_entry_to_dir(get_ref_dir(refs->loose),
1267                                 create_dir_entry(refs, "refs/", 5, 1));
1268        }
1269        return get_ref_dir(refs->loose);
1270}
1271
1272/* We allow "recursive" symbolic refs. Only within reason, though */
1273#define MAXDEPTH 5
1274#define MAXREFLEN (1024)
1275
1276/*
1277 * Called by resolve_gitlink_ref_recursive() after it failed to read
1278 * from the loose refs in ref_cache refs. Find <refname> in the
1279 * packed-refs file for the submodule.
1280 */
1281static int resolve_gitlink_packed_ref(struct ref_cache *refs,
1282                                      const char *refname, unsigned char *sha1)
1283{
1284        struct ref_entry *ref;
1285        struct ref_dir *dir = get_packed_refs(refs);
1286
1287        ref = find_ref(dir, refname);
1288        if (ref == NULL)
1289                return -1;
1290
1291        hashcpy(sha1, ref->u.value.oid.hash);
1292        return 0;
1293}
1294
1295static int resolve_gitlink_ref_recursive(struct ref_cache *refs,
1296                                         const char *refname, unsigned char *sha1,
1297                                         int recursion)
1298{
1299        int fd, len;
1300        char buffer[128], *p;
1301        char *path;
1302
1303        if (recursion > MAXDEPTH || strlen(refname) > MAXREFLEN)
1304                return -1;
1305        path = *refs->name
1306                ? git_pathdup_submodule(refs->name, "%s", refname)
1307                : git_pathdup("%s", refname);
1308        fd = open(path, O_RDONLY);
1309        free(path);
1310        if (fd < 0)
1311                return resolve_gitlink_packed_ref(refs, refname, sha1);
1312
1313        len = read(fd, buffer, sizeof(buffer)-1);
1314        close(fd);
1315        if (len < 0)
1316                return -1;
1317        while (len && isspace(buffer[len-1]))
1318                len--;
1319        buffer[len] = 0;
1320
1321        /* Was it a detached head or an old-fashioned symlink? */
1322        if (!get_sha1_hex(buffer, sha1))
1323                return 0;
1324
1325        /* Symref? */
1326        if (strncmp(buffer, "ref:", 4))
1327                return -1;
1328        p = buffer + 4;
1329        while (isspace(*p))
1330                p++;
1331
1332        return resolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);
1333}
1334
1335int resolve_gitlink_ref(const char *path, const char *refname, unsigned char *sha1)
1336{
1337        int len = strlen(path), retval;
1338        struct strbuf submodule = STRBUF_INIT;
1339        struct ref_cache *refs;
1340
1341        while (len && path[len-1] == '/')
1342                len--;
1343        if (!len)
1344                return -1;
1345
1346        strbuf_add(&submodule, path, len);
1347        refs = lookup_ref_cache(submodule.buf);
1348        if (!refs) {
1349                if (!is_nonbare_repository_dir(&submodule)) {
1350                        strbuf_release(&submodule);
1351                        return -1;
1352                }
1353                refs = create_ref_cache(submodule.buf);
1354        }
1355        strbuf_release(&submodule);
1356
1357        retval = resolve_gitlink_ref_recursive(refs, refname, sha1, 0);
1358        return retval;
1359}
1360
1361/*
1362 * Return the ref_entry for the given refname from the packed
1363 * references.  If it does not exist, return NULL.
1364 */
1365static struct ref_entry *get_packed_ref(const char *refname)
1366{
1367        return find_ref(get_packed_refs(&ref_cache), refname);
1368}
1369
1370/*
1371 * A loose ref file doesn't exist; check for a packed ref.  The
1372 * options are forwarded from resolve_safe_unsafe().
1373 */
1374static int resolve_missing_loose_ref(const char *refname,
1375                                     int resolve_flags,
1376                                     unsigned char *sha1,
1377                                     int *flags)
1378{
1379        struct ref_entry *entry;
1380
1381        /*
1382         * The loose reference file does not exist; check for a packed
1383         * reference.
1384         */
1385        entry = get_packed_ref(refname);
1386        if (entry) {
1387                hashcpy(sha1, entry->u.value.oid.hash);
1388                if (flags)
1389                        *flags |= REF_ISPACKED;
1390                return 0;
1391        }
1392        /* The reference is not a packed reference, either. */
1393        if (resolve_flags & RESOLVE_REF_READING) {
1394                errno = ENOENT;
1395                return -1;
1396        } else {
1397                hashclr(sha1);
1398                return 0;
1399        }
1400}
1401
1402/* This function needs to return a meaningful errno on failure */
1403static const char *resolve_ref_1(const char *refname,
1404                                 int resolve_flags,
1405                                 unsigned char *sha1,
1406                                 int *flags,
1407                                 struct strbuf *sb_refname,
1408                                 struct strbuf *sb_path,
1409                                 struct strbuf *sb_contents)
1410{
1411        int depth = MAXDEPTH;
1412        int bad_name = 0;
1413
1414        if (flags)
1415                *flags = 0;
1416
1417        if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1418                if (flags)
1419                        *flags |= REF_BAD_NAME;
1420
1421                if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1422                    !refname_is_safe(refname)) {
1423                        errno = EINVAL;
1424                        return NULL;
1425                }
1426                /*
1427                 * dwim_ref() uses REF_ISBROKEN to distinguish between
1428                 * missing refs and refs that were present but invalid,
1429                 * to complain about the latter to stderr.
1430                 *
1431                 * We don't know whether the ref exists, so don't set
1432                 * REF_ISBROKEN yet.
1433                 */
1434                bad_name = 1;
1435        }
1436        for (;;) {
1437                const char *path;
1438                struct stat st;
1439                char *buf;
1440                int fd;
1441
1442                if (--depth < 0) {
1443                        errno = ELOOP;
1444                        return NULL;
1445                }
1446
1447                strbuf_reset(sb_path);
1448                strbuf_git_path(sb_path, "%s", refname);
1449                path = sb_path->buf;
1450
1451                /*
1452                 * We might have to loop back here to avoid a race
1453                 * condition: first we lstat() the file, then we try
1454                 * to read it as a link or as a file.  But if somebody
1455                 * changes the type of the file (file <-> directory
1456                 * <-> symlink) between the lstat() and reading, then
1457                 * we don't want to report that as an error but rather
1458                 * try again starting with the lstat().
1459                 */
1460        stat_ref:
1461                if (lstat(path, &st) < 0) {
1462                        if (errno != ENOENT)
1463                                return NULL;
1464                        if (resolve_missing_loose_ref(refname, resolve_flags,
1465                                                      sha1, flags))
1466                                return NULL;
1467                        if (bad_name) {
1468                                hashclr(sha1);
1469                                if (flags)
1470                                        *flags |= REF_ISBROKEN;
1471                        }
1472                        return refname;
1473                }
1474
1475                /* Follow "normalized" - ie "refs/.." symlinks by hand */
1476                if (S_ISLNK(st.st_mode)) {
1477                        strbuf_reset(sb_contents);
1478                        if (strbuf_readlink(sb_contents, path, 0) < 0) {
1479                                if (errno == ENOENT || errno == EINVAL)
1480                                        /* inconsistent with lstat; retry */
1481                                        goto stat_ref;
1482                                else
1483                                        return NULL;
1484                        }
1485                        if (starts_with(sb_contents->buf, "refs/") &&
1486                            !check_refname_format(sb_contents->buf, 0)) {
1487                                strbuf_swap(sb_refname, sb_contents);
1488                                refname = sb_refname->buf;
1489                                if (flags)
1490                                        *flags |= REF_ISSYMREF;
1491                                if (resolve_flags & RESOLVE_REF_NO_RECURSE) {
1492                                        hashclr(sha1);
1493                                        return refname;
1494                                }
1495                                continue;
1496                        }
1497                }
1498
1499                /* Is it a directory? */
1500                if (S_ISDIR(st.st_mode)) {
1501                        errno = EISDIR;
1502                        return NULL;
1503                }
1504
1505                /*
1506                 * Anything else, just open it and try to use it as
1507                 * a ref
1508                 */
1509                fd = open(path, O_RDONLY);
1510                if (fd < 0) {
1511                        if (errno == ENOENT)
1512                                /* inconsistent with lstat; retry */
1513                                goto stat_ref;
1514                        else
1515                                return NULL;
1516                }
1517                strbuf_reset(sb_contents);
1518                if (strbuf_read(sb_contents, fd, 256) < 0) {
1519                        int save_errno = errno;
1520                        close(fd);
1521                        errno = save_errno;
1522                        return NULL;
1523                }
1524                close(fd);
1525                strbuf_rtrim(sb_contents);
1526
1527                /*
1528                 * Is it a symbolic ref?
1529                 */
1530                if (!starts_with(sb_contents->buf, "ref:")) {
1531                        /*
1532                         * Please note that FETCH_HEAD has a second
1533                         * line containing other data.
1534                         */
1535                        if (get_sha1_hex(sb_contents->buf, sha1) ||
1536                            (sb_contents->buf[40] != '\0' && !isspace(sb_contents->buf[40]))) {
1537                                if (flags)
1538                                        *flags |= REF_ISBROKEN;
1539                                errno = EINVAL;
1540                                return NULL;
1541                        }
1542                        if (bad_name) {
1543                                hashclr(sha1);
1544                                if (flags)
1545                                        *flags |= REF_ISBROKEN;
1546                        }
1547                        return refname;
1548                }
1549                if (flags)
1550                        *flags |= REF_ISSYMREF;
1551                buf = sb_contents->buf + 4;
1552                while (isspace(*buf))
1553                        buf++;
1554                strbuf_reset(sb_refname);
1555                strbuf_addstr(sb_refname, buf);
1556                refname = sb_refname->buf;
1557                if (resolve_flags & RESOLVE_REF_NO_RECURSE) {
1558                        hashclr(sha1);
1559                        return refname;
1560                }
1561                if (check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {
1562                        if (flags)
1563                                *flags |= REF_ISBROKEN;
1564
1565                        if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1566                            !refname_is_safe(buf)) {
1567                                errno = EINVAL;
1568                                return NULL;
1569                        }
1570                        bad_name = 1;
1571                }
1572        }
1573}
1574
1575const char *resolve_ref_unsafe(const char *refname, int resolve_flags,
1576                               unsigned char *sha1, int *flags)
1577{
1578        static struct strbuf sb_refname = STRBUF_INIT;
1579        struct strbuf sb_contents = STRBUF_INIT;
1580        struct strbuf sb_path = STRBUF_INIT;
1581        const char *ret;
1582
1583        ret = resolve_ref_1(refname, resolve_flags, sha1, flags,
1584                            &sb_refname, &sb_path, &sb_contents);
1585        strbuf_release(&sb_path);
1586        strbuf_release(&sb_contents);
1587        return ret;
1588}
1589
1590/*
1591 * Peel the entry (if possible) and return its new peel_status.  If
1592 * repeel is true, re-peel the entry even if there is an old peeled
1593 * value that is already stored in it.
1594 *
1595 * It is OK to call this function with a packed reference entry that
1596 * might be stale and might even refer to an object that has since
1597 * been garbage-collected.  In such a case, if the entry has
1598 * REF_KNOWS_PEELED then leave the status unchanged and return
1599 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.
1600 */
1601static enum peel_status peel_entry(struct ref_entry *entry, int repeel)
1602{
1603        enum peel_status status;
1604
1605        if (entry->flag & REF_KNOWS_PEELED) {
1606                if (repeel) {
1607                        entry->flag &= ~REF_KNOWS_PEELED;
1608                        oidclr(&entry->u.value.peeled);
1609                } else {
1610                        return is_null_oid(&entry->u.value.peeled) ?
1611                                PEEL_NON_TAG : PEEL_PEELED;
1612                }
1613        }
1614        if (entry->flag & REF_ISBROKEN)
1615                return PEEL_BROKEN;
1616        if (entry->flag & REF_ISSYMREF)
1617                return PEEL_IS_SYMREF;
1618
1619        status = peel_object(entry->u.value.oid.hash, entry->u.value.peeled.hash);
1620        if (status == PEEL_PEELED || status == PEEL_NON_TAG)
1621                entry->flag |= REF_KNOWS_PEELED;
1622        return status;
1623}
1624
1625int peel_ref(const char *refname, unsigned char *sha1)
1626{
1627        int flag;
1628        unsigned char base[20];
1629
1630        if (current_ref && (current_ref->name == refname
1631                            || !strcmp(current_ref->name, refname))) {
1632                if (peel_entry(current_ref, 0))
1633                        return -1;
1634                hashcpy(sha1, current_ref->u.value.peeled.hash);
1635                return 0;
1636        }
1637
1638        if (read_ref_full(refname, RESOLVE_REF_READING, base, &flag))
1639                return -1;
1640
1641        /*
1642         * If the reference is packed, read its ref_entry from the
1643         * cache in the hope that we already know its peeled value.
1644         * We only try this optimization on packed references because
1645         * (a) forcing the filling of the loose reference cache could
1646         * be expensive and (b) loose references anyway usually do not
1647         * have REF_KNOWS_PEELED.
1648         */
1649        if (flag & REF_ISPACKED) {
1650                struct ref_entry *r = get_packed_ref(refname);
1651                if (r) {
1652                        if (peel_entry(r, 0))
1653                                return -1;
1654                        hashcpy(sha1, r->u.value.peeled.hash);
1655                        return 0;
1656                }
1657        }
1658
1659        return peel_object(base, sha1);
1660}
1661
1662/*
1663 * Call fn for each reference in the specified ref_cache, omitting
1664 * references not in the containing_dir of base.  fn is called for all
1665 * references, including broken ones.  If fn ever returns a non-zero
1666 * value, stop the iteration and return that value; otherwise, return
1667 * 0.
1668 */
1669static int do_for_each_entry(struct ref_cache *refs, const char *base,
1670                             each_ref_entry_fn fn, void *cb_data)
1671{
1672        struct packed_ref_cache *packed_ref_cache;
1673        struct ref_dir *loose_dir;
1674        struct ref_dir *packed_dir;
1675        int retval = 0;
1676
1677        /*
1678         * We must make sure that all loose refs are read before accessing the
1679         * packed-refs file; this avoids a race condition in which loose refs
1680         * are migrated to the packed-refs file by a simultaneous process, but
1681         * our in-memory view is from before the migration. get_packed_ref_cache()
1682         * takes care of making sure our view is up to date with what is on
1683         * disk.
1684         */
1685        loose_dir = get_loose_refs(refs);
1686        if (base && *base) {
1687                loose_dir = find_containing_dir(loose_dir, base, 0);
1688        }
1689        if (loose_dir)
1690                prime_ref_dir(loose_dir);
1691
1692        packed_ref_cache = get_packed_ref_cache(refs);
1693        acquire_packed_ref_cache(packed_ref_cache);
1694        packed_dir = get_packed_ref_dir(packed_ref_cache);
1695        if (base && *base) {
1696                packed_dir = find_containing_dir(packed_dir, base, 0);
1697        }
1698
1699        if (packed_dir && loose_dir) {
1700                sort_ref_dir(packed_dir);
1701                sort_ref_dir(loose_dir);
1702                retval = do_for_each_entry_in_dirs(
1703                                packed_dir, loose_dir, fn, cb_data);
1704        } else if (packed_dir) {
1705                sort_ref_dir(packed_dir);
1706                retval = do_for_each_entry_in_dir(
1707                                packed_dir, 0, fn, cb_data);
1708        } else if (loose_dir) {
1709                sort_ref_dir(loose_dir);
1710                retval = do_for_each_entry_in_dir(
1711                                loose_dir, 0, fn, cb_data);
1712        }
1713
1714        release_packed_ref_cache(packed_ref_cache);
1715        return retval;
1716}
1717
1718/*
1719 * Call fn for each reference in the specified ref_cache for which the
1720 * refname begins with base.  If trim is non-zero, then trim that many
1721 * characters off the beginning of each refname before passing the
1722 * refname to fn.  flags can be DO_FOR_EACH_INCLUDE_BROKEN to include
1723 * broken references in the iteration.  If fn ever returns a non-zero
1724 * value, stop the iteration and return that value; otherwise, return
1725 * 0.
1726 */
1727int do_for_each_ref(const char *submodule, const char *base,
1728                    each_ref_fn fn, int trim, int flags, void *cb_data)
1729{
1730        struct ref_entry_cb data;
1731        struct ref_cache *refs;
1732
1733        refs = get_ref_cache(submodule);
1734        data.base = base;
1735        data.trim = trim;
1736        data.flags = flags;
1737        data.fn = fn;
1738        data.cb_data = cb_data;
1739
1740        if (ref_paranoia < 0)
1741                ref_paranoia = git_env_bool("GIT_REF_PARANOIA", 0);
1742        if (ref_paranoia)
1743                data.flags |= DO_FOR_EACH_INCLUDE_BROKEN;
1744
1745        return do_for_each_entry(refs, base, do_one_ref, &data);
1746}
1747
1748static void unlock_ref(struct ref_lock *lock)
1749{
1750        /* Do not free lock->lk -- atexit() still looks at them */
1751        if (lock->lk)
1752                rollback_lock_file(lock->lk);
1753        free(lock->ref_name);
1754        free(lock->orig_ref_name);
1755        free(lock);
1756}
1757
1758/*
1759 * Verify that the reference locked by lock has the value old_sha1.
1760 * Fail if the reference doesn't exist and mustexist is set. Return 0
1761 * on success. On error, write an error message to err, set errno, and
1762 * return a negative value.
1763 */
1764static int verify_lock(struct ref_lock *lock,
1765                       const unsigned char *old_sha1, int mustexist,
1766                       struct strbuf *err)
1767{
1768        assert(err);
1769
1770        if (read_ref_full(lock->ref_name,
1771                          mustexist ? RESOLVE_REF_READING : 0,
1772                          lock->old_oid.hash, NULL)) {
1773                if (old_sha1) {
1774                        int save_errno = errno;
1775                        strbuf_addf(err, "can't verify ref %s", lock->ref_name);
1776                        errno = save_errno;
1777                        return -1;
1778                } else {
1779                        hashclr(lock->old_oid.hash);
1780                        return 0;
1781                }
1782        }
1783        if (old_sha1 && hashcmp(lock->old_oid.hash, old_sha1)) {
1784                strbuf_addf(err, "ref %s is at %s but expected %s",
1785                            lock->ref_name,
1786                            sha1_to_hex(lock->old_oid.hash),
1787                            sha1_to_hex(old_sha1));
1788                errno = EBUSY;
1789                return -1;
1790        }
1791        return 0;
1792}
1793
1794static int remove_empty_directories(struct strbuf *path)
1795{
1796        /*
1797         * we want to create a file but there is a directory there;
1798         * if that is an empty directory (or a directory that contains
1799         * only empty directories), remove them.
1800         */
1801        return remove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);
1802}
1803
1804/*
1805 * Locks a ref returning the lock on success and NULL on failure.
1806 * On failure errno is set to something meaningful.
1807 */
1808static struct ref_lock *lock_ref_sha1_basic(const char *refname,
1809                                            const unsigned char *old_sha1,
1810                                            const struct string_list *extras,
1811                                            const struct string_list *skip,
1812                                            unsigned int flags, int *type_p,
1813                                            struct strbuf *err)
1814{
1815        struct strbuf ref_file = STRBUF_INIT;
1816        struct strbuf orig_ref_file = STRBUF_INIT;
1817        const char *orig_refname = refname;
1818        struct ref_lock *lock;
1819        int last_errno = 0;
1820        int type;
1821        int lflags = 0;
1822        int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
1823        int resolve_flags = 0;
1824        int attempts_remaining = 3;
1825
1826        assert(err);
1827
1828        lock = xcalloc(1, sizeof(struct ref_lock));
1829
1830        if (mustexist)
1831                resolve_flags |= RESOLVE_REF_READING;
1832        if (flags & REF_DELETING)
1833                resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;
1834        if (flags & REF_NODEREF) {
1835                resolve_flags |= RESOLVE_REF_NO_RECURSE;
1836                lflags |= LOCK_NO_DEREF;
1837        }
1838
1839        refname = resolve_ref_unsafe(refname, resolve_flags,
1840                                     lock->old_oid.hash, &type);
1841        if (!refname && errno == EISDIR) {
1842                /*
1843                 * we are trying to lock foo but we used to
1844                 * have foo/bar which now does not exist;
1845                 * it is normal for the empty directory 'foo'
1846                 * to remain.
1847                 */
1848                strbuf_git_path(&orig_ref_file, "%s", orig_refname);
1849                if (remove_empty_directories(&orig_ref_file)) {
1850                        last_errno = errno;
1851                        if (!verify_refname_available_dir(orig_refname, extras, skip,
1852                                                          get_loose_refs(&ref_cache), err))
1853                                strbuf_addf(err, "there are still refs under '%s'",
1854                                            orig_refname);
1855                        goto error_return;
1856                }
1857                refname = resolve_ref_unsafe(orig_refname, resolve_flags,
1858                                             lock->old_oid.hash, &type);
1859        }
1860        if (type_p)
1861            *type_p = type;
1862        if (!refname) {
1863                last_errno = errno;
1864                if (last_errno != ENOTDIR ||
1865                    !verify_refname_available_dir(orig_refname, extras, skip,
1866                                                  get_loose_refs(&ref_cache), err))
1867                        strbuf_addf(err, "unable to resolve reference %s: %s",
1868                                    orig_refname, strerror(last_errno));
1869
1870                goto error_return;
1871        }
1872
1873        if (flags & REF_NODEREF)
1874                refname = orig_refname;
1875
1876        /*
1877         * If the ref did not exist and we are creating it, make sure
1878         * there is no existing packed ref whose name begins with our
1879         * refname, nor a packed ref whose name is a proper prefix of
1880         * our refname.
1881         */
1882        if (is_null_oid(&lock->old_oid) &&
1883            verify_refname_available_dir(refname, extras, skip,
1884                                         get_packed_refs(&ref_cache), err)) {
1885                last_errno = ENOTDIR;
1886                goto error_return;
1887        }
1888
1889        lock->lk = xcalloc(1, sizeof(struct lock_file));
1890
1891        lock->ref_name = xstrdup(refname);
1892        lock->orig_ref_name = xstrdup(orig_refname);
1893        strbuf_git_path(&ref_file, "%s", refname);
1894
1895 retry:
1896        switch (safe_create_leading_directories_const(ref_file.buf)) {
1897        case SCLD_OK:
1898                break; /* success */
1899        case SCLD_VANISHED:
1900                if (--attempts_remaining > 0)
1901                        goto retry;
1902                /* fall through */
1903        default:
1904                last_errno = errno;
1905                strbuf_addf(err, "unable to create directory for %s",
1906                            ref_file.buf);
1907                goto error_return;
1908        }
1909
1910        if (hold_lock_file_for_update(lock->lk, ref_file.buf, lflags) < 0) {
1911                last_errno = errno;
1912                if (errno == ENOENT && --attempts_remaining > 0)
1913                        /*
1914                         * Maybe somebody just deleted one of the
1915                         * directories leading to ref_file.  Try
1916                         * again:
1917                         */
1918                        goto retry;
1919                else {
1920                        unable_to_lock_message(ref_file.buf, errno, err);
1921                        goto error_return;
1922                }
1923        }
1924        if (verify_lock(lock, old_sha1, mustexist, err)) {
1925                last_errno = errno;
1926                goto error_return;
1927        }
1928        goto out;
1929
1930 error_return:
1931        unlock_ref(lock);
1932        lock = NULL;
1933
1934 out:
1935        strbuf_release(&ref_file);
1936        strbuf_release(&orig_ref_file);
1937        errno = last_errno;
1938        return lock;
1939}
1940
1941/*
1942 * Write an entry to the packed-refs file for the specified refname.
1943 * If peeled is non-NULL, write it as the entry's peeled value.
1944 */
1945static void write_packed_entry(FILE *fh, char *refname, unsigned char *sha1,
1946                               unsigned char *peeled)
1947{
1948        fprintf_or_die(fh, "%s %s\n", sha1_to_hex(sha1), refname);
1949        if (peeled)
1950                fprintf_or_die(fh, "^%s\n", sha1_to_hex(peeled));
1951}
1952
1953/*
1954 * An each_ref_entry_fn that writes the entry to a packed-refs file.
1955 */
1956static int write_packed_entry_fn(struct ref_entry *entry, void *cb_data)
1957{
1958        enum peel_status peel_status = peel_entry(entry, 0);
1959
1960        if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)
1961                error("internal error: %s is not a valid packed reference!",
1962                      entry->name);
1963        write_packed_entry(cb_data, entry->name, entry->u.value.oid.hash,
1964                           peel_status == PEEL_PEELED ?
1965                           entry->u.value.peeled.hash : NULL);
1966        return 0;
1967}
1968
1969/*
1970 * Lock the packed-refs file for writing. Flags is passed to
1971 * hold_lock_file_for_update(). Return 0 on success. On errors, set
1972 * errno appropriately and return a nonzero value.
1973 */
1974static int lock_packed_refs(int flags)
1975{
1976        static int timeout_configured = 0;
1977        static int timeout_value = 1000;
1978
1979        struct packed_ref_cache *packed_ref_cache;
1980
1981        if (!timeout_configured) {
1982                git_config_get_int("core.packedrefstimeout", &timeout_value);
1983                timeout_configured = 1;
1984        }
1985
1986        if (hold_lock_file_for_update_timeout(
1987                            &packlock, git_path("packed-refs"),
1988                            flags, timeout_value) < 0)
1989                return -1;
1990        /*
1991         * Get the current packed-refs while holding the lock.  If the
1992         * packed-refs file has been modified since we last read it,
1993         * this will automatically invalidate the cache and re-read
1994         * the packed-refs file.
1995         */
1996        packed_ref_cache = get_packed_ref_cache(&ref_cache);
1997        packed_ref_cache->lock = &packlock;
1998        /* Increment the reference count to prevent it from being freed: */
1999        acquire_packed_ref_cache(packed_ref_cache);
2000        return 0;
2001}
2002
2003/*
2004 * Write the current version of the packed refs cache from memory to
2005 * disk. The packed-refs file must already be locked for writing (see
2006 * lock_packed_refs()). Return zero on success. On errors, set errno
2007 * and return a nonzero value
2008 */
2009static int commit_packed_refs(void)
2010{
2011        struct packed_ref_cache *packed_ref_cache =
2012                get_packed_ref_cache(&ref_cache);
2013        int error = 0;
2014        int save_errno = 0;
2015        FILE *out;
2016
2017        if (!packed_ref_cache->lock)
2018                die("internal error: packed-refs not locked");
2019
2020        out = fdopen_lock_file(packed_ref_cache->lock, "w");
2021        if (!out)
2022                die_errno("unable to fdopen packed-refs descriptor");
2023
2024        fprintf_or_die(out, "%s", PACKED_REFS_HEADER);
2025        do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),
2026                                 0, write_packed_entry_fn, out);
2027
2028        if (commit_lock_file(packed_ref_cache->lock)) {
2029                save_errno = errno;
2030                error = -1;
2031        }
2032        packed_ref_cache->lock = NULL;
2033        release_packed_ref_cache(packed_ref_cache);
2034        errno = save_errno;
2035        return error;
2036}
2037
2038/*
2039 * Rollback the lockfile for the packed-refs file, and discard the
2040 * in-memory packed reference cache.  (The packed-refs file will be
2041 * read anew if it is needed again after this function is called.)
2042 */
2043static void rollback_packed_refs(void)
2044{
2045        struct packed_ref_cache *packed_ref_cache =
2046                get_packed_ref_cache(&ref_cache);
2047
2048        if (!packed_ref_cache->lock)
2049                die("internal error: packed-refs not locked");
2050        rollback_lock_file(packed_ref_cache->lock);
2051        packed_ref_cache->lock = NULL;
2052        release_packed_ref_cache(packed_ref_cache);
2053        clear_packed_ref_cache(&ref_cache);
2054}
2055
2056struct ref_to_prune {
2057        struct ref_to_prune *next;
2058        unsigned char sha1[20];
2059        char name[FLEX_ARRAY];
2060};
2061
2062struct pack_refs_cb_data {
2063        unsigned int flags;
2064        struct ref_dir *packed_refs;
2065        struct ref_to_prune *ref_to_prune;
2066};
2067
2068/*
2069 * An each_ref_entry_fn that is run over loose references only.  If
2070 * the loose reference can be packed, add an entry in the packed ref
2071 * cache.  If the reference should be pruned, also add it to
2072 * ref_to_prune in the pack_refs_cb_data.
2073 */
2074static int pack_if_possible_fn(struct ref_entry *entry, void *cb_data)
2075{
2076        struct pack_refs_cb_data *cb = cb_data;
2077        enum peel_status peel_status;
2078        struct ref_entry *packed_entry;
2079        int is_tag_ref = starts_with(entry->name, "refs/tags/");
2080
2081        /* Do not pack per-worktree refs: */
2082        if (ref_type(entry->name) != REF_TYPE_NORMAL)
2083                return 0;
2084
2085        /* ALWAYS pack tags */
2086        if (!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)
2087                return 0;
2088
2089        /* Do not pack symbolic or broken refs: */
2090        if ((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))
2091                return 0;
2092
2093        /* Add a packed ref cache entry equivalent to the loose entry. */
2094        peel_status = peel_entry(entry, 1);
2095        if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)
2096                die("internal error peeling reference %s (%s)",
2097                    entry->name, oid_to_hex(&entry->u.value.oid));
2098        packed_entry = find_ref(cb->packed_refs, entry->name);
2099        if (packed_entry) {
2100                /* Overwrite existing packed entry with info from loose entry */
2101                packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;
2102                oidcpy(&packed_entry->u.value.oid, &entry->u.value.oid);
2103        } else {
2104                packed_entry = create_ref_entry(entry->name, entry->u.value.oid.hash,
2105                                                REF_ISPACKED | REF_KNOWS_PEELED, 0);
2106                add_ref(cb->packed_refs, packed_entry);
2107        }
2108        oidcpy(&packed_entry->u.value.peeled, &entry->u.value.peeled);
2109
2110        /* Schedule the loose reference for pruning if requested. */
2111        if ((cb->flags & PACK_REFS_PRUNE)) {
2112                struct ref_to_prune *n;
2113                FLEX_ALLOC_STR(n, name, entry->name);
2114                hashcpy(n->sha1, entry->u.value.oid.hash);
2115                n->next = cb->ref_to_prune;
2116                cb->ref_to_prune = n;
2117        }
2118        return 0;
2119}
2120
2121/*
2122 * Remove empty parents, but spare refs/ and immediate subdirs.
2123 * Note: munges *name.
2124 */
2125static void try_remove_empty_parents(char *name)
2126{
2127        char *p, *q;
2128        int i;
2129        p = name;
2130        for (i = 0; i < 2; i++) { /* refs/{heads,tags,...}/ */
2131                while (*p && *p != '/')
2132                        p++;
2133                /* tolerate duplicate slashes; see check_refname_format() */
2134                while (*p == '/')
2135                        p++;
2136        }
2137        for (q = p; *q; q++)
2138                ;
2139        while (1) {
2140                while (q > p && *q != '/')
2141                        q--;
2142                while (q > p && *(q-1) == '/')
2143                        q--;
2144                if (q == p)
2145                        break;
2146                *q = '\0';
2147                if (rmdir(git_path("%s", name)))
2148                        break;
2149        }
2150}
2151
2152/* make sure nobody touched the ref, and unlink */
2153static void prune_ref(struct ref_to_prune *r)
2154{
2155        struct ref_transaction *transaction;
2156        struct strbuf err = STRBUF_INIT;
2157
2158        if (check_refname_format(r->name, 0))
2159                return;
2160
2161        transaction = ref_transaction_begin(&err);
2162        if (!transaction ||
2163            ref_transaction_delete(transaction, r->name, r->sha1,
2164                                   REF_ISPRUNING, NULL, &err) ||
2165            ref_transaction_commit(transaction, &err)) {
2166                ref_transaction_free(transaction);
2167                error("%s", err.buf);
2168                strbuf_release(&err);
2169                return;
2170        }
2171        ref_transaction_free(transaction);
2172        strbuf_release(&err);
2173        try_remove_empty_parents(r->name);
2174}
2175
2176static void prune_refs(struct ref_to_prune *r)
2177{
2178        while (r) {
2179                prune_ref(r);
2180                r = r->next;
2181        }
2182}
2183
2184int pack_refs(unsigned int flags)
2185{
2186        struct pack_refs_cb_data cbdata;
2187
2188        memset(&cbdata, 0, sizeof(cbdata));
2189        cbdata.flags = flags;
2190
2191        lock_packed_refs(LOCK_DIE_ON_ERROR);
2192        cbdata.packed_refs = get_packed_refs(&ref_cache);
2193
2194        do_for_each_entry_in_dir(get_loose_refs(&ref_cache), 0,
2195                                 pack_if_possible_fn, &cbdata);
2196
2197        if (commit_packed_refs())
2198                die_errno("unable to overwrite old ref-pack file");
2199
2200        prune_refs(cbdata.ref_to_prune);
2201        return 0;
2202}
2203
2204/*
2205 * Rewrite the packed-refs file, omitting any refs listed in
2206 * 'refnames'. On error, leave packed-refs unchanged, write an error
2207 * message to 'err', and return a nonzero value.
2208 *
2209 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.
2210 */
2211static int repack_without_refs(struct string_list *refnames, struct strbuf *err)
2212{
2213        struct ref_dir *packed;
2214        struct string_list_item *refname;
2215        int ret, needs_repacking = 0, removed = 0;
2216
2217        assert(err);
2218
2219        /* Look for a packed ref */
2220        for_each_string_list_item(refname, refnames) {
2221                if (get_packed_ref(refname->string)) {
2222                        needs_repacking = 1;
2223                        break;
2224                }
2225        }
2226
2227        /* Avoid locking if we have nothing to do */
2228        if (!needs_repacking)
2229                return 0; /* no refname exists in packed refs */
2230
2231        if (lock_packed_refs(0)) {
2232                unable_to_lock_message(git_path("packed-refs"), errno, err);
2233                return -1;
2234        }
2235        packed = get_packed_refs(&ref_cache);
2236
2237        /* Remove refnames from the cache */
2238        for_each_string_list_item(refname, refnames)
2239                if (remove_entry(packed, refname->string) != -1)
2240                        removed = 1;
2241        if (!removed) {
2242                /*
2243                 * All packed entries disappeared while we were
2244                 * acquiring the lock.
2245                 */
2246                rollback_packed_refs();
2247                return 0;
2248        }
2249
2250        /* Write what remains */
2251        ret = commit_packed_refs();
2252        if (ret)
2253                strbuf_addf(err, "unable to overwrite old ref-pack file: %s",
2254                            strerror(errno));
2255        return ret;
2256}
2257
2258static int delete_ref_loose(struct ref_lock *lock, int flag, struct strbuf *err)
2259{
2260        assert(err);
2261
2262        if (!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {
2263                /*
2264                 * loose.  The loose file name is the same as the
2265                 * lockfile name, minus ".lock":
2266                 */
2267                char *loose_filename = get_locked_file_path(lock->lk);
2268                int res = unlink_or_msg(loose_filename, err);
2269                free(loose_filename);
2270                if (res)
2271                        return 1;
2272        }
2273        return 0;
2274}
2275
2276int delete_refs(struct string_list *refnames)
2277{
2278        struct strbuf err = STRBUF_INIT;
2279        int i, result = 0;
2280
2281        if (!refnames->nr)
2282                return 0;
2283
2284        result = repack_without_refs(refnames, &err);
2285        if (result) {
2286                /*
2287                 * If we failed to rewrite the packed-refs file, then
2288                 * it is unsafe to try to remove loose refs, because
2289                 * doing so might expose an obsolete packed value for
2290                 * a reference that might even point at an object that
2291                 * has been garbage collected.
2292                 */
2293                if (refnames->nr == 1)
2294                        error(_("could not delete reference %s: %s"),
2295                              refnames->items[0].string, err.buf);
2296                else
2297                        error(_("could not delete references: %s"), err.buf);
2298
2299                goto out;
2300        }
2301
2302        for (i = 0; i < refnames->nr; i++) {
2303                const char *refname = refnames->items[i].string;
2304
2305                if (delete_ref(refname, NULL, 0))
2306                        result |= error(_("could not remove reference %s"), refname);
2307        }
2308
2309out:
2310        strbuf_release(&err);
2311        return result;
2312}
2313
2314/*
2315 * People using contrib's git-new-workdir have .git/logs/refs ->
2316 * /some/other/path/.git/logs/refs, and that may live on another device.
2317 *
2318 * IOW, to avoid cross device rename errors, the temporary renamed log must
2319 * live into logs/refs.
2320 */
2321#define TMP_RENAMED_LOG  "logs/refs/.tmp-renamed-log"
2322
2323static int rename_tmp_log(const char *newrefname)
2324{
2325        int attempts_remaining = 4;
2326        struct strbuf path = STRBUF_INIT;
2327        int ret = -1;
2328
2329 retry:
2330        strbuf_reset(&path);
2331        strbuf_git_path(&path, "logs/%s", newrefname);
2332        switch (safe_create_leading_directories_const(path.buf)) {
2333        case SCLD_OK:
2334                break; /* success */
2335        case SCLD_VANISHED:
2336                if (--attempts_remaining > 0)
2337                        goto retry;
2338                /* fall through */
2339        default:
2340                error("unable to create directory for %s", newrefname);
2341                goto out;
2342        }
2343
2344        if (rename(git_path(TMP_RENAMED_LOG), path.buf)) {
2345                if ((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining > 0) {
2346                        /*
2347                         * rename(a, b) when b is an existing
2348                         * directory ought to result in ISDIR, but
2349                         * Solaris 5.8 gives ENOTDIR.  Sheesh.
2350                         */
2351                        if (remove_empty_directories(&path)) {
2352                                error("Directory not empty: logs/%s", newrefname);
2353                                goto out;
2354                        }
2355                        goto retry;
2356                } else if (errno == ENOENT && --attempts_remaining > 0) {
2357                        /*
2358                         * Maybe another process just deleted one of
2359                         * the directories in the path to newrefname.
2360                         * Try again from the beginning.
2361                         */
2362                        goto retry;
2363                } else {
2364                        error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s: %s",
2365                                newrefname, strerror(errno));
2366                        goto out;
2367                }
2368        }
2369        ret = 0;
2370out:
2371        strbuf_release(&path);
2372        return ret;
2373}
2374
2375int verify_refname_available(const char *newname,
2376                             struct string_list *extras,
2377                             struct string_list *skip,
2378                             struct strbuf *err)
2379{
2380        struct ref_dir *packed_refs = get_packed_refs(&ref_cache);
2381        struct ref_dir *loose_refs = get_loose_refs(&ref_cache);
2382
2383        if (verify_refname_available_dir(newname, extras, skip,
2384                                         packed_refs, err) ||
2385            verify_refname_available_dir(newname, extras, skip,
2386                                         loose_refs, err))
2387                return -1;
2388
2389        return 0;
2390}
2391
2392static int write_ref_to_lockfile(struct ref_lock *lock,
2393                                 const unsigned char *sha1, struct strbuf *err);
2394static int commit_ref_update(struct ref_lock *lock,
2395                             const unsigned char *sha1, const char *logmsg,
2396                             int flags, struct strbuf *err);
2397
2398int rename_ref(const char *oldrefname, const char *newrefname, const char *logmsg)
2399{
2400        unsigned char sha1[20], orig_sha1[20];
2401        int flag = 0, logmoved = 0;
2402        struct ref_lock *lock;
2403        struct stat loginfo;
2404        int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);
2405        const char *symref = NULL;
2406        struct strbuf err = STRBUF_INIT;
2407
2408        if (log && S_ISLNK(loginfo.st_mode))
2409                return error("reflog for %s is a symlink", oldrefname);
2410
2411        symref = resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING,
2412                                    orig_sha1, &flag);
2413        if (flag & REF_ISSYMREF)
2414                return error("refname %s is a symbolic ref, renaming it is not supported",
2415                        oldrefname);
2416        if (!symref)
2417                return error("refname %s not found", oldrefname);
2418
2419        if (!rename_ref_available(oldrefname, newrefname))
2420                return 1;
2421
2422        if (log && rename(git_path("logs/%s", oldrefname), git_path(TMP_RENAMED_LOG)))
2423                return error("unable to move logfile logs/%s to "TMP_RENAMED_LOG": %s",
2424                        oldrefname, strerror(errno));
2425
2426        if (delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {
2427                error("unable to delete old %s", oldrefname);
2428                goto rollback;
2429        }
2430
2431        if (!read_ref_full(newrefname, RESOLVE_REF_READING, sha1, NULL) &&
2432            delete_ref(newrefname, sha1, REF_NODEREF)) {
2433                if (errno==EISDIR) {
2434                        struct strbuf path = STRBUF_INIT;
2435                        int result;
2436
2437                        strbuf_git_path(&path, "%s", newrefname);
2438                        result = remove_empty_directories(&path);
2439                        strbuf_release(&path);
2440
2441                        if (result) {
2442                                error("Directory not empty: %s", newrefname);
2443                                goto rollback;
2444                        }
2445                } else {
2446                        error("unable to delete existing %s", newrefname);
2447                        goto rollback;
2448                }
2449        }
2450
2451        if (log && rename_tmp_log(newrefname))
2452                goto rollback;
2453
2454        logmoved = log;
2455
2456        lock = lock_ref_sha1_basic(newrefname, NULL, NULL, NULL, 0, NULL, &err);
2457        if (!lock) {
2458                error("unable to rename '%s' to '%s': %s", oldrefname, newrefname, err.buf);
2459                strbuf_release(&err);
2460                goto rollback;
2461        }
2462        hashcpy(lock->old_oid.hash, orig_sha1);
2463
2464        if (write_ref_to_lockfile(lock, orig_sha1, &err) ||
2465            commit_ref_update(lock, orig_sha1, logmsg, 0, &err)) {
2466                error("unable to write current sha1 into %s: %s", newrefname, err.buf);
2467                strbuf_release(&err);
2468                goto rollback;
2469        }
2470
2471        return 0;
2472
2473 rollback:
2474        lock = lock_ref_sha1_basic(oldrefname, NULL, NULL, NULL, 0, NULL, &err);
2475        if (!lock) {
2476                error("unable to lock %s for rollback: %s", oldrefname, err.buf);
2477                strbuf_release(&err);
2478                goto rollbacklog;
2479        }
2480
2481        flag = log_all_ref_updates;
2482        log_all_ref_updates = 0;
2483        if (write_ref_to_lockfile(lock, orig_sha1, &err) ||
2484            commit_ref_update(lock, orig_sha1, NULL, 0, &err)) {
2485                error("unable to write current sha1 into %s: %s", oldrefname, err.buf);
2486                strbuf_release(&err);
2487        }
2488        log_all_ref_updates = flag;
2489
2490 rollbacklog:
2491        if (logmoved && rename(git_path("logs/%s", newrefname), git_path("logs/%s", oldrefname)))
2492                error("unable to restore logfile %s from %s: %s",
2493                        oldrefname, newrefname, strerror(errno));
2494        if (!logmoved && log &&
2495            rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", oldrefname)))
2496                error("unable to restore logfile %s from "TMP_RENAMED_LOG": %s",
2497                        oldrefname, strerror(errno));
2498
2499        return 1;
2500}
2501
2502static int close_ref(struct ref_lock *lock)
2503{
2504        if (close_lock_file(lock->lk))
2505                return -1;
2506        return 0;
2507}
2508
2509static int commit_ref(struct ref_lock *lock)
2510{
2511        if (commit_lock_file(lock->lk))
2512                return -1;
2513        return 0;
2514}
2515
2516/*
2517 * Create a reflog for a ref.  If force_create = 0, the reflog will
2518 * only be created for certain refs (those for which
2519 * should_autocreate_reflog returns non-zero.  Otherwise, create it
2520 * regardless of the ref name.  Fill in *err and return -1 on failure.
2521 */
2522static int log_ref_setup(const char *refname, struct strbuf *logfile, struct strbuf *err, int force_create)
2523{
2524        int logfd, oflags = O_APPEND | O_WRONLY;
2525
2526        strbuf_git_path(logfile, "logs/%s", refname);
2527        if (force_create || should_autocreate_reflog(refname)) {
2528                if (safe_create_leading_directories(logfile->buf) < 0) {
2529                        strbuf_addf(err, "unable to create directory for %s: "
2530                                    "%s", logfile->buf, strerror(errno));
2531                        return -1;
2532                }
2533                oflags |= O_CREAT;
2534        }
2535
2536        logfd = open(logfile->buf, oflags, 0666);
2537        if (logfd < 0) {
2538                if (!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))
2539                        return 0;
2540
2541                if (errno == EISDIR) {
2542                        if (remove_empty_directories(logfile)) {
2543                                strbuf_addf(err, "There are still logs under "
2544                                            "'%s'", logfile->buf);
2545                                return -1;
2546                        }
2547                        logfd = open(logfile->buf, oflags, 0666);
2548                }
2549
2550                if (logfd < 0) {
2551                        strbuf_addf(err, "unable to append to %s: %s",
2552                                    logfile->buf, strerror(errno));
2553                        return -1;
2554                }
2555        }
2556
2557        adjust_shared_perm(logfile->buf);
2558        close(logfd);
2559        return 0;
2560}
2561
2562
2563int safe_create_reflog(const char *refname, int force_create, struct strbuf *err)
2564{
2565        int ret;
2566        struct strbuf sb = STRBUF_INIT;
2567
2568        ret = log_ref_setup(refname, &sb, err, force_create);
2569        strbuf_release(&sb);
2570        return ret;
2571}
2572
2573static int log_ref_write_fd(int fd, const unsigned char *old_sha1,
2574                            const unsigned char *new_sha1,
2575                            const char *committer, const char *msg)
2576{
2577        int msglen, written;
2578        unsigned maxlen, len;
2579        char *logrec;
2580
2581        msglen = msg ? strlen(msg) : 0;
2582        maxlen = strlen(committer) + msglen + 100;
2583        logrec = xmalloc(maxlen);
2584        len = xsnprintf(logrec, maxlen, "%s %s %s\n",
2585                        sha1_to_hex(old_sha1),
2586                        sha1_to_hex(new_sha1),
2587                        committer);
2588        if (msglen)
2589                len += copy_reflog_msg(logrec + len - 1, msg) - 1;
2590
2591        written = len <= maxlen ? write_in_full(fd, logrec, len) : -1;
2592        free(logrec);
2593        if (written != len)
2594                return -1;
2595
2596        return 0;
2597}
2598
2599static int log_ref_write_1(const char *refname, const unsigned char *old_sha1,
2600                           const unsigned char *new_sha1, const char *msg,
2601                           struct strbuf *logfile, int flags,
2602                           struct strbuf *err)
2603{
2604        int logfd, result, oflags = O_APPEND | O_WRONLY;
2605
2606        if (log_all_ref_updates < 0)
2607                log_all_ref_updates = !is_bare_repository();
2608
2609        result = log_ref_setup(refname, logfile, err, flags & REF_FORCE_CREATE_REFLOG);
2610
2611        if (result)
2612                return result;
2613
2614        logfd = open(logfile->buf, oflags);
2615        if (logfd < 0)
2616                return 0;
2617        result = log_ref_write_fd(logfd, old_sha1, new_sha1,
2618                                  git_committer_info(0), msg);
2619        if (result) {
2620                strbuf_addf(err, "unable to append to %s: %s", logfile->buf,
2621                            strerror(errno));
2622                close(logfd);
2623                return -1;
2624        }
2625        if (close(logfd)) {
2626                strbuf_addf(err, "unable to append to %s: %s", logfile->buf,
2627                            strerror(errno));
2628                return -1;
2629        }
2630        return 0;
2631}
2632
2633static int log_ref_write(const char *refname, const unsigned char *old_sha1,
2634                         const unsigned char *new_sha1, const char *msg,
2635                         int flags, struct strbuf *err)
2636{
2637        return files_log_ref_write(refname, old_sha1, new_sha1, msg, flags,
2638                                   err);
2639}
2640
2641int files_log_ref_write(const char *refname, const unsigned char *old_sha1,
2642                        const unsigned char *new_sha1, const char *msg,
2643                        int flags, struct strbuf *err)
2644{
2645        struct strbuf sb = STRBUF_INIT;
2646        int ret = log_ref_write_1(refname, old_sha1, new_sha1, msg, &sb, flags,
2647                                  err);
2648        strbuf_release(&sb);
2649        return ret;
2650}
2651
2652/*
2653 * Write sha1 into the open lockfile, then close the lockfile. On
2654 * errors, rollback the lockfile, fill in *err and
2655 * return -1.
2656 */
2657static int write_ref_to_lockfile(struct ref_lock *lock,
2658                                 const unsigned char *sha1, struct strbuf *err)
2659{
2660        static char term = '\n';
2661        struct object *o;
2662        int fd;
2663
2664        o = parse_object(sha1);
2665        if (!o) {
2666                strbuf_addf(err,
2667                            "Trying to write ref %s with nonexistent object %s",
2668                            lock->ref_name, sha1_to_hex(sha1));
2669                unlock_ref(lock);
2670                return -1;
2671        }
2672        if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
2673                strbuf_addf(err,
2674                            "Trying to write non-commit object %s to branch %s",
2675                            sha1_to_hex(sha1), lock->ref_name);
2676                unlock_ref(lock);
2677                return -1;
2678        }
2679        fd = get_lock_file_fd(lock->lk);
2680        if (write_in_full(fd, sha1_to_hex(sha1), 40) != 40 ||
2681            write_in_full(fd, &term, 1) != 1 ||
2682            close_ref(lock) < 0) {
2683                strbuf_addf(err,
2684                            "Couldn't write %s", get_lock_file_path(lock->lk));
2685                unlock_ref(lock);
2686                return -1;
2687        }
2688        return 0;
2689}
2690
2691/*
2692 * Commit a change to a loose reference that has already been written
2693 * to the loose reference lockfile. Also update the reflogs if
2694 * necessary, using the specified lockmsg (which can be NULL).
2695 */
2696static int commit_ref_update(struct ref_lock *lock,
2697                             const unsigned char *sha1, const char *logmsg,
2698                             int flags, struct strbuf *err)
2699{
2700        clear_loose_ref_cache(&ref_cache);
2701        if (log_ref_write(lock->ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) < 0 ||
2702            (strcmp(lock->ref_name, lock->orig_ref_name) &&
2703             log_ref_write(lock->orig_ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) < 0)) {
2704                char *old_msg = strbuf_detach(err, NULL);
2705                strbuf_addf(err, "Cannot update the ref '%s': %s",
2706                            lock->ref_name, old_msg);
2707                free(old_msg);
2708                unlock_ref(lock);
2709                return -1;
2710        }
2711        if (strcmp(lock->orig_ref_name, "HEAD") != 0) {
2712                /*
2713                 * Special hack: If a branch is updated directly and HEAD
2714                 * points to it (may happen on the remote side of a push
2715                 * for example) then logically the HEAD reflog should be
2716                 * updated too.
2717                 * A generic solution implies reverse symref information,
2718                 * but finding all symrefs pointing to the given branch
2719                 * would be rather costly for this rare event (the direct
2720                 * update of a branch) to be worth it.  So let's cheat and
2721                 * check with HEAD only which should cover 99% of all usage
2722                 * scenarios (even 100% of the default ones).
2723                 */
2724                unsigned char head_sha1[20];
2725                int head_flag;
2726                const char *head_ref;
2727                head_ref = resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
2728                                              head_sha1, &head_flag);
2729                if (head_ref && (head_flag & REF_ISSYMREF) &&
2730                    !strcmp(head_ref, lock->ref_name)) {
2731                        struct strbuf log_err = STRBUF_INIT;
2732                        if (log_ref_write("HEAD", lock->old_oid.hash, sha1,
2733                                          logmsg, 0, &log_err)) {
2734                                error("%s", log_err.buf);
2735                                strbuf_release(&log_err);
2736                        }
2737                }
2738        }
2739        if (commit_ref(lock)) {
2740                error("Couldn't set %s", lock->ref_name);
2741                unlock_ref(lock);
2742                return -1;
2743        }
2744
2745        unlock_ref(lock);
2746        return 0;
2747}
2748
2749static int create_ref_symlink(struct ref_lock *lock, const char *target)
2750{
2751        int ret = -1;
2752#ifndef NO_SYMLINK_HEAD
2753        char *ref_path = get_locked_file_path(lock->lk);
2754        unlink(ref_path);
2755        ret = symlink(target, ref_path);
2756        free(ref_path);
2757
2758        if (ret)
2759                fprintf(stderr, "no symlink - falling back to symbolic ref\n");
2760#endif
2761        return ret;
2762}
2763
2764static void update_symref_reflog(struct ref_lock *lock, const char *refname,
2765                                 const char *target, const char *logmsg)
2766{
2767        struct strbuf err = STRBUF_INIT;
2768        unsigned char new_sha1[20];
2769        if (logmsg && !read_ref(target, new_sha1) &&
2770            log_ref_write(refname, lock->old_oid.hash, new_sha1, logmsg, 0, &err)) {
2771                error("%s", err.buf);
2772                strbuf_release(&err);
2773        }
2774}
2775
2776static int create_symref_locked(struct ref_lock *lock, const char *refname,
2777                                const char *target, const char *logmsg)
2778{
2779        if (prefer_symlink_refs && !create_ref_symlink(lock, target)) {
2780                update_symref_reflog(lock, refname, target, logmsg);
2781                return 0;
2782        }
2783
2784        if (!fdopen_lock_file(lock->lk, "w"))
2785                return error("unable to fdopen %s: %s",
2786                             lock->lk->tempfile.filename.buf, strerror(errno));
2787
2788        update_symref_reflog(lock, refname, target, logmsg);
2789
2790        /* no error check; commit_ref will check ferror */
2791        fprintf(lock->lk->tempfile.fp, "ref: %s\n", target);
2792        if (commit_ref(lock) < 0)
2793                return error("unable to write symref for %s: %s", refname,
2794                             strerror(errno));
2795        return 0;
2796}
2797
2798int create_symref(const char *refname, const char *target, const char *logmsg)
2799{
2800        struct strbuf err = STRBUF_INIT;
2801        struct ref_lock *lock;
2802        int ret;
2803
2804        lock = lock_ref_sha1_basic(refname, NULL, NULL, NULL, REF_NODEREF, NULL,
2805                                   &err);
2806        if (!lock) {
2807                error("%s", err.buf);
2808                strbuf_release(&err);
2809                return -1;
2810        }
2811
2812        ret = create_symref_locked(lock, refname, target, logmsg);
2813        unlock_ref(lock);
2814        return ret;
2815}
2816
2817int reflog_exists(const char *refname)
2818{
2819        struct stat st;
2820
2821        return !lstat(git_path("logs/%s", refname), &st) &&
2822                S_ISREG(st.st_mode);
2823}
2824
2825int delete_reflog(const char *refname)
2826{
2827        return remove_path(git_path("logs/%s", refname));
2828}
2829
2830static int show_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn, void *cb_data)
2831{
2832        unsigned char osha1[20], nsha1[20];
2833        char *email_end, *message;
2834        unsigned long timestamp;
2835        int tz;
2836
2837        /* old SP new SP name <email> SP time TAB msg LF */
2838        if (sb->len < 83 || sb->buf[sb->len - 1] != '\n' ||
2839            get_sha1_hex(sb->buf, osha1) || sb->buf[40] != ' ' ||
2840            get_sha1_hex(sb->buf + 41, nsha1) || sb->buf[81] != ' ' ||
2841            !(email_end = strchr(sb->buf + 82, '>')) ||
2842            email_end[1] != ' ' ||
2843            !(timestamp = strtoul(email_end + 2, &message, 10)) ||
2844            !message || message[0] != ' ' ||
2845            (message[1] != '+' && message[1] != '-') ||
2846            !isdigit(message[2]) || !isdigit(message[3]) ||
2847            !isdigit(message[4]) || !isdigit(message[5]))
2848                return 0; /* corrupt? */
2849        email_end[1] = '\0';
2850        tz = strtol(message + 1, NULL, 10);
2851        if (message[6] != '\t')
2852                message += 6;
2853        else
2854                message += 7;
2855        return fn(osha1, nsha1, sb->buf + 82, timestamp, tz, message, cb_data);
2856}
2857
2858static char *find_beginning_of_line(char *bob, char *scan)
2859{
2860        while (bob < scan && *(--scan) != '\n')
2861                ; /* keep scanning backwards */
2862        /*
2863         * Return either beginning of the buffer, or LF at the end of
2864         * the previous line.
2865         */
2866        return scan;
2867}
2868
2869int for_each_reflog_ent_reverse(const char *refname, each_reflog_ent_fn fn, void *cb_data)
2870{
2871        struct strbuf sb = STRBUF_INIT;
2872        FILE *logfp;
2873        long pos;
2874        int ret = 0, at_tail = 1;
2875
2876        logfp = fopen(git_path("logs/%s", refname), "r");
2877        if (!logfp)
2878                return -1;
2879
2880        /* Jump to the end */
2881        if (fseek(logfp, 0, SEEK_END) < 0)
2882                return error("cannot seek back reflog for %s: %s",
2883                             refname, strerror(errno));
2884        pos = ftell(logfp);
2885        while (!ret && 0 < pos) {
2886                int cnt;
2887                size_t nread;
2888                char buf[BUFSIZ];
2889                char *endp, *scanp;
2890
2891                /* Fill next block from the end */
2892                cnt = (sizeof(buf) < pos) ? sizeof(buf) : pos;
2893                if (fseek(logfp, pos - cnt, SEEK_SET))
2894                        return error("cannot seek back reflog for %s: %s",
2895                                     refname, strerror(errno));
2896                nread = fread(buf, cnt, 1, logfp);
2897                if (nread != 1)
2898                        return error("cannot read %d bytes from reflog for %s: %s",
2899                                     cnt, refname, strerror(errno));
2900                pos -= cnt;
2901
2902                scanp = endp = buf + cnt;
2903                if (at_tail && scanp[-1] == '\n')
2904                        /* Looking at the final LF at the end of the file */
2905                        scanp--;
2906                at_tail = 0;
2907
2908                while (buf < scanp) {
2909                        /*
2910                         * terminating LF of the previous line, or the beginning
2911                         * of the buffer.
2912                         */
2913                        char *bp;
2914
2915                        bp = find_beginning_of_line(buf, scanp);
2916
2917                        if (*bp == '\n') {
2918                                /*
2919                                 * The newline is the end of the previous line,
2920                                 * so we know we have complete line starting
2921                                 * at (bp + 1). Prefix it onto any prior data
2922                                 * we collected for the line and process it.
2923                                 */
2924                                strbuf_splice(&sb, 0, 0, bp + 1, endp - (bp + 1));
2925                                scanp = bp;
2926                                endp = bp + 1;
2927                                ret = show_one_reflog_ent(&sb, fn, cb_data);
2928                                strbuf_reset(&sb);
2929                                if (ret)
2930                                        break;
2931                        } else if (!pos) {
2932                                /*
2933                                 * We are at the start of the buffer, and the
2934                                 * start of the file; there is no previous
2935                                 * line, and we have everything for this one.
2936                                 * Process it, and we can end the loop.
2937                                 */
2938                                strbuf_splice(&sb, 0, 0, buf, endp - buf);
2939                                ret = show_one_reflog_ent(&sb, fn, cb_data);
2940                                strbuf_reset(&sb);
2941                                break;
2942                        }
2943
2944                        if (bp == buf) {
2945                                /*
2946                                 * We are at the start of the buffer, and there
2947                                 * is more file to read backwards. Which means
2948                                 * we are in the middle of a line. Note that we
2949                                 * may get here even if *bp was a newline; that
2950                                 * just means we are at the exact end of the
2951                                 * previous line, rather than some spot in the
2952                                 * middle.
2953                                 *
2954                                 * Save away what we have to be combined with
2955                                 * the data from the next read.
2956                                 */
2957                                strbuf_splice(&sb, 0, 0, buf, endp - buf);
2958                                break;
2959                        }
2960                }
2961
2962        }
2963        if (!ret && sb.len)
2964                die("BUG: reverse reflog parser had leftover data");
2965
2966        fclose(logfp);
2967        strbuf_release(&sb);
2968        return ret;
2969}
2970
2971int for_each_reflog_ent(const char *refname, each_reflog_ent_fn fn, void *cb_data)
2972{
2973        FILE *logfp;
2974        struct strbuf sb = STRBUF_INIT;
2975        int ret = 0;
2976
2977        logfp = fopen(git_path("logs/%s", refname), "r");
2978        if (!logfp)
2979                return -1;
2980
2981        while (!ret && !strbuf_getwholeline(&sb, logfp, '\n'))
2982                ret = show_one_reflog_ent(&sb, fn, cb_data);
2983        fclose(logfp);
2984        strbuf_release(&sb);
2985        return ret;
2986}
2987/*
2988 * Call fn for each reflog in the namespace indicated by name.  name
2989 * must be empty or end with '/'.  Name will be used as a scratch
2990 * space, but its contents will be restored before return.
2991 */
2992static int do_for_each_reflog(struct strbuf *name, each_ref_fn fn, void *cb_data)
2993{
2994        DIR *d = opendir(git_path("logs/%s", name->buf));
2995        int retval = 0;
2996        struct dirent *de;
2997        int oldlen = name->len;
2998
2999        if (!d)
3000                return name->len ? errno : 0;
3001
3002        while ((de = readdir(d)) != NULL) {
3003                struct stat st;
3004
3005                if (de->d_name[0] == '.')
3006                        continue;
3007                if (ends_with(de->d_name, ".lock"))
3008                        continue;
3009                strbuf_addstr(name, de->d_name);
3010                if (stat(git_path("logs/%s", name->buf), &st) < 0) {
3011                        ; /* silently ignore */
3012                } else {
3013                        if (S_ISDIR(st.st_mode)) {
3014                                strbuf_addch(name, '/');
3015                                retval = do_for_each_reflog(name, fn, cb_data);
3016                        } else {
3017                                struct object_id oid;
3018
3019                                if (read_ref_full(name->buf, 0, oid.hash, NULL))
3020                                        retval = error("bad ref for %s", name->buf);
3021                                else
3022                                        retval = fn(name->buf, &oid, 0, cb_data);
3023                        }
3024                        if (retval)
3025                                break;
3026                }
3027                strbuf_setlen(name, oldlen);
3028        }
3029        closedir(d);
3030        return retval;
3031}
3032
3033int for_each_reflog(each_ref_fn fn, void *cb_data)
3034{
3035        int retval;
3036        struct strbuf name;
3037        strbuf_init(&name, PATH_MAX);
3038        retval = do_for_each_reflog(&name, fn, cb_data);
3039        strbuf_release(&name);
3040        return retval;
3041}
3042
3043static int ref_update_reject_duplicates(struct string_list *refnames,
3044                                        struct strbuf *err)
3045{
3046        int i, n = refnames->nr;
3047
3048        assert(err);
3049
3050        for (i = 1; i < n; i++)
3051                if (!strcmp(refnames->items[i - 1].string, refnames->items[i].string)) {
3052                        strbuf_addf(err,
3053                                    "Multiple updates for ref '%s' not allowed.",
3054                                    refnames->items[i].string);
3055                        return 1;
3056                }
3057        return 0;
3058}
3059
3060int ref_transaction_commit(struct ref_transaction *transaction,
3061                           struct strbuf *err)
3062{
3063        int ret = 0, i;
3064        int n = transaction->nr;
3065        struct ref_update **updates = transaction->updates;
3066        struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;
3067        struct string_list_item *ref_to_delete;
3068        struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
3069
3070        assert(err);
3071
3072        if (transaction->state != REF_TRANSACTION_OPEN)
3073                die("BUG: commit called for transaction that is not open");
3074
3075        if (!n) {
3076                transaction->state = REF_TRANSACTION_CLOSED;
3077                return 0;
3078        }
3079
3080        /* Fail if a refname appears more than once in the transaction: */
3081        for (i = 0; i < n; i++)
3082                string_list_append(&affected_refnames, updates[i]->refname);
3083        string_list_sort(&affected_refnames);
3084        if (ref_update_reject_duplicates(&affected_refnames, err)) {
3085                ret = TRANSACTION_GENERIC_ERROR;
3086                goto cleanup;
3087        }
3088
3089        /*
3090         * Acquire all locks, verify old values if provided, check
3091         * that new values are valid, and write new values to the
3092         * lockfiles, ready to be activated. Only keep one lockfile
3093         * open at a time to avoid running out of file descriptors.
3094         */
3095        for (i = 0; i < n; i++) {
3096                struct ref_update *update = updates[i];
3097
3098                if ((update->flags & REF_HAVE_NEW) &&
3099                    is_null_sha1(update->new_sha1))
3100                        update->flags |= REF_DELETING;
3101                update->lock = lock_ref_sha1_basic(
3102                                update->refname,
3103                                ((update->flags & REF_HAVE_OLD) ?
3104                                 update->old_sha1 : NULL),
3105                                &affected_refnames, NULL,
3106                                update->flags,
3107                                &update->type,
3108                                err);
3109                if (!update->lock) {
3110                        char *reason;
3111
3112                        ret = (errno == ENOTDIR)
3113                                ? TRANSACTION_NAME_CONFLICT
3114                                : TRANSACTION_GENERIC_ERROR;
3115                        reason = strbuf_detach(err, NULL);
3116                        strbuf_addf(err, "cannot lock ref '%s': %s",
3117                                    update->refname, reason);
3118                        free(reason);
3119                        goto cleanup;
3120                }
3121                if ((update->flags & REF_HAVE_NEW) &&
3122                    !(update->flags & REF_DELETING)) {
3123                        int overwriting_symref = ((update->type & REF_ISSYMREF) &&
3124                                                  (update->flags & REF_NODEREF));
3125
3126                        if (!overwriting_symref &&
3127                            !hashcmp(update->lock->old_oid.hash, update->new_sha1)) {
3128                                /*
3129                                 * The reference already has the desired
3130                                 * value, so we don't need to write it.
3131                                 */
3132                        } else if (write_ref_to_lockfile(update->lock,
3133                                                         update->new_sha1,
3134                                                         err)) {
3135                                char *write_err = strbuf_detach(err, NULL);
3136
3137                                /*
3138                                 * The lock was freed upon failure of
3139                                 * write_ref_to_lockfile():
3140                                 */
3141                                update->lock = NULL;
3142                                strbuf_addf(err,
3143                                            "cannot update the ref '%s': %s",
3144                                            update->refname, write_err);
3145                                free(write_err);
3146                                ret = TRANSACTION_GENERIC_ERROR;
3147                                goto cleanup;
3148                        } else {
3149                                update->flags |= REF_NEEDS_COMMIT;
3150                        }
3151                }
3152                if (!(update->flags & REF_NEEDS_COMMIT)) {
3153                        /*
3154                         * We didn't have to write anything to the lockfile.
3155                         * Close it to free up the file descriptor:
3156                         */
3157                        if (close_ref(update->lock)) {
3158                                strbuf_addf(err, "Couldn't close %s.lock",
3159                                            update->refname);
3160                                goto cleanup;
3161                        }
3162                }
3163        }
3164
3165        /* Perform updates first so live commits remain referenced */
3166        for (i = 0; i < n; i++) {
3167                struct ref_update *update = updates[i];
3168
3169                if (update->flags & REF_NEEDS_COMMIT) {
3170                        if (commit_ref_update(update->lock,
3171                                              update->new_sha1, update->msg,
3172                                              update->flags, err)) {
3173                                /* freed by commit_ref_update(): */
3174                                update->lock = NULL;
3175                                ret = TRANSACTION_GENERIC_ERROR;
3176                                goto cleanup;
3177                        } else {
3178                                /* freed by commit_ref_update(): */
3179                                update->lock = NULL;
3180                        }
3181                }
3182        }
3183
3184        /* Perform deletes now that updates are safely completed */
3185        for (i = 0; i < n; i++) {
3186                struct ref_update *update = updates[i];
3187
3188                if (update->flags & REF_DELETING) {
3189                        if (delete_ref_loose(update->lock, update->type, err)) {
3190                                ret = TRANSACTION_GENERIC_ERROR;
3191                                goto cleanup;
3192                        }
3193
3194                        if (!(update->flags & REF_ISPRUNING))
3195                                string_list_append(&refs_to_delete,
3196                                                   update->lock->ref_name);
3197                }
3198        }
3199
3200        if (repack_without_refs(&refs_to_delete, err)) {
3201                ret = TRANSACTION_GENERIC_ERROR;
3202                goto cleanup;
3203        }
3204        for_each_string_list_item(ref_to_delete, &refs_to_delete)
3205                unlink_or_warn(git_path("logs/%s", ref_to_delete->string));
3206        clear_loose_ref_cache(&ref_cache);
3207
3208cleanup:
3209        transaction->state = REF_TRANSACTION_CLOSED;
3210
3211        for (i = 0; i < n; i++)
3212                if (updates[i]->lock)
3213                        unlock_ref(updates[i]->lock);
3214        string_list_clear(&refs_to_delete, 0);
3215        string_list_clear(&affected_refnames, 0);
3216        return ret;
3217}
3218
3219static int ref_present(const char *refname,
3220                       const struct object_id *oid, int flags, void *cb_data)
3221{
3222        struct string_list *affected_refnames = cb_data;
3223
3224        return string_list_has_string(affected_refnames, refname);
3225}
3226
3227int initial_ref_transaction_commit(struct ref_transaction *transaction,
3228                                   struct strbuf *err)
3229{
3230        int ret = 0, i;
3231        int n = transaction->nr;
3232        struct ref_update **updates = transaction->updates;
3233        struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
3234
3235        assert(err);
3236
3237        if (transaction->state != REF_TRANSACTION_OPEN)
3238                die("BUG: commit called for transaction that is not open");
3239
3240        /* Fail if a refname appears more than once in the transaction: */
3241        for (i = 0; i < n; i++)
3242                string_list_append(&affected_refnames, updates[i]->refname);
3243        string_list_sort(&affected_refnames);
3244        if (ref_update_reject_duplicates(&affected_refnames, err)) {
3245                ret = TRANSACTION_GENERIC_ERROR;
3246                goto cleanup;
3247        }
3248
3249        /*
3250         * It's really undefined to call this function in an active
3251         * repository or when there are existing references: we are
3252         * only locking and changing packed-refs, so (1) any
3253         * simultaneous processes might try to change a reference at
3254         * the same time we do, and (2) any existing loose versions of
3255         * the references that we are setting would have precedence
3256         * over our values. But some remote helpers create the remote
3257         * "HEAD" and "master" branches before calling this function,
3258         * so here we really only check that none of the references
3259         * that we are creating already exists.
3260         */
3261        if (for_each_rawref(ref_present, &affected_refnames))
3262                die("BUG: initial ref transaction called with existing refs");
3263
3264        for (i = 0; i < n; i++) {
3265                struct ref_update *update = updates[i];
3266
3267                if ((update->flags & REF_HAVE_OLD) &&
3268                    !is_null_sha1(update->old_sha1))
3269                        die("BUG: initial ref transaction with old_sha1 set");
3270                if (verify_refname_available(update->refname,
3271                                             &affected_refnames, NULL,
3272                                             err)) {
3273                        ret = TRANSACTION_NAME_CONFLICT;
3274                        goto cleanup;
3275                }
3276        }
3277
3278        if (lock_packed_refs(0)) {
3279                strbuf_addf(err, "unable to lock packed-refs file: %s",
3280                            strerror(errno));
3281                ret = TRANSACTION_GENERIC_ERROR;
3282                goto cleanup;
3283        }
3284
3285        for (i = 0; i < n; i++) {
3286                struct ref_update *update = updates[i];
3287
3288                if ((update->flags & REF_HAVE_NEW) &&
3289                    !is_null_sha1(update->new_sha1))
3290                        add_packed_ref(update->refname, update->new_sha1);
3291        }
3292
3293        if (commit_packed_refs()) {
3294                strbuf_addf(err, "unable to commit packed-refs file: %s",
3295                            strerror(errno));
3296                ret = TRANSACTION_GENERIC_ERROR;
3297                goto cleanup;
3298        }
3299
3300cleanup:
3301        transaction->state = REF_TRANSACTION_CLOSED;
3302        string_list_clear(&affected_refnames, 0);
3303        return ret;
3304}
3305
3306struct expire_reflog_cb {
3307        unsigned int flags;
3308        reflog_expiry_should_prune_fn *should_prune_fn;
3309        void *policy_cb;
3310        FILE *newlog;
3311        unsigned char last_kept_sha1[20];
3312};
3313
3314static int expire_reflog_ent(unsigned char *osha1, unsigned char *nsha1,
3315                             const char *email, unsigned long timestamp, int tz,
3316                             const char *message, void *cb_data)
3317{
3318        struct expire_reflog_cb *cb = cb_data;
3319        struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;
3320
3321        if (cb->flags & EXPIRE_REFLOGS_REWRITE)
3322                osha1 = cb->last_kept_sha1;
3323
3324        if ((*cb->should_prune_fn)(osha1, nsha1, email, timestamp, tz,
3325                                   message, policy_cb)) {
3326                if (!cb->newlog)
3327                        printf("would prune %s", message);
3328                else if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
3329                        printf("prune %s", message);
3330        } else {
3331                if (cb->newlog) {
3332                        fprintf(cb->newlog, "%s %s %s %lu %+05d\t%s",
3333                                sha1_to_hex(osha1), sha1_to_hex(nsha1),
3334                                email, timestamp, tz, message);
3335                        hashcpy(cb->last_kept_sha1, nsha1);
3336                }
3337                if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
3338                        printf("keep %s", message);
3339        }
3340        return 0;
3341}
3342
3343int reflog_expire(const char *refname, const unsigned char *sha1,
3344                 unsigned int flags,
3345                 reflog_expiry_prepare_fn prepare_fn,
3346                 reflog_expiry_should_prune_fn should_prune_fn,
3347                 reflog_expiry_cleanup_fn cleanup_fn,
3348                 void *policy_cb_data)
3349{
3350        static struct lock_file reflog_lock;
3351        struct expire_reflog_cb cb;
3352        struct ref_lock *lock;
3353        char *log_file;
3354        int status = 0;
3355        int type;
3356        struct strbuf err = STRBUF_INIT;
3357
3358        memset(&cb, 0, sizeof(cb));
3359        cb.flags = flags;
3360        cb.policy_cb = policy_cb_data;
3361        cb.should_prune_fn = should_prune_fn;
3362
3363        /*
3364         * The reflog file is locked by holding the lock on the
3365         * reference itself, plus we might need to update the
3366         * reference if --updateref was specified:
3367         */
3368        lock = lock_ref_sha1_basic(refname, sha1, NULL, NULL, 0, &type, &err);
3369        if (!lock) {
3370                error("cannot lock ref '%s': %s", refname, err.buf);
3371                strbuf_release(&err);
3372                return -1;
3373        }
3374        if (!reflog_exists(refname)) {
3375                unlock_ref(lock);
3376                return 0;
3377        }
3378
3379        log_file = git_pathdup("logs/%s", refname);
3380        if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
3381                /*
3382                 * Even though holding $GIT_DIR/logs/$reflog.lock has
3383                 * no locking implications, we use the lock_file
3384                 * machinery here anyway because it does a lot of the
3385                 * work we need, including cleaning up if the program
3386                 * exits unexpectedly.
3387                 */
3388                if (hold_lock_file_for_update(&reflog_lock, log_file, 0) < 0) {
3389                        struct strbuf err = STRBUF_INIT;
3390                        unable_to_lock_message(log_file, errno, &err);
3391                        error("%s", err.buf);
3392                        strbuf_release(&err);
3393                        goto failure;
3394                }
3395                cb.newlog = fdopen_lock_file(&reflog_lock, "w");
3396                if (!cb.newlog) {
3397                        error("cannot fdopen %s (%s)",
3398                              get_lock_file_path(&reflog_lock), strerror(errno));
3399                        goto failure;
3400                }
3401        }
3402
3403        (*prepare_fn)(refname, sha1, cb.policy_cb);
3404        for_each_reflog_ent(refname, expire_reflog_ent, &cb);
3405        (*cleanup_fn)(cb.policy_cb);
3406
3407        if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
3408                /*
3409                 * It doesn't make sense to adjust a reference pointed
3410                 * to by a symbolic ref based on expiring entries in
3411                 * the symbolic reference's reflog. Nor can we update
3412                 * a reference if there are no remaining reflog
3413                 * entries.
3414                 */
3415                int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&
3416                        !(type & REF_ISSYMREF) &&
3417                        !is_null_sha1(cb.last_kept_sha1);
3418
3419                if (close_lock_file(&reflog_lock)) {
3420                        status |= error("couldn't write %s: %s", log_file,
3421                                        strerror(errno));
3422                } else if (update &&
3423                           (write_in_full(get_lock_file_fd(lock->lk),
3424                                sha1_to_hex(cb.last_kept_sha1), 40) != 40 ||
3425                            write_str_in_full(get_lock_file_fd(lock->lk), "\n") != 1 ||
3426                            close_ref(lock) < 0)) {
3427                        status |= error("couldn't write %s",
3428                                        get_lock_file_path(lock->lk));
3429                        rollback_lock_file(&reflog_lock);
3430                } else if (commit_lock_file(&reflog_lock)) {
3431                        status |= error("unable to write reflog '%s' (%s)",
3432                                        log_file, strerror(errno));
3433                } else if (update && commit_ref(lock)) {
3434                        status |= error("couldn't set %s", lock->ref_name);
3435                }
3436        }
3437        free(log_file);
3438        unlock_ref(lock);
3439        return status;
3440
3441 failure:
3442        rollback_lock_file(&reflog_lock);
3443        free(log_file);
3444        unlock_ref(lock);
3445        return -1;
3446}