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