refs / files-backend.con commit Merge branch 'jc/am-i-v-fix' into maint (28eec80)
   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
 936/*
 937 * Create a new submodule ref cache and add it to the internal
 938 * set of caches.
 939 */
 940static struct ref_cache *create_ref_cache(const char *submodule)
 941{
 942        int len;
 943        struct ref_cache *refs;
 944        if (!submodule)
 945                submodule = "";
 946        len = strlen(submodule) + 1;
 947        refs = xcalloc(1, sizeof(struct ref_cache) + len);
 948        memcpy(refs->name, submodule, len);
 949        refs->next = submodule_ref_caches;
 950        submodule_ref_caches = refs;
 951        return refs;
 952}
 953
 954static struct ref_cache *lookup_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        return NULL;
 965}
 966
 967/*
 968 * Return a pointer to a ref_cache for the specified submodule. For
 969 * the main repository, use submodule==NULL. The returned structure
 970 * will be allocated and initialized but not necessarily populated; it
 971 * should not be freed.
 972 */
 973static struct ref_cache *get_ref_cache(const char *submodule)
 974{
 975        struct ref_cache *refs = lookup_ref_cache(submodule);
 976        if (!refs)
 977                refs = create_ref_cache(submodule);
 978        return refs;
 979}
 980
 981/* The length of a peeled reference line in packed-refs, including EOL: */
 982#define PEELED_LINE_LENGTH 42
 983
 984/*
 985 * The packed-refs header line that we write out.  Perhaps other
 986 * traits will be added later.  The trailing space is required.
 987 */
 988static const char PACKED_REFS_HEADER[] =
 989        "# pack-refs with: peeled fully-peeled \n";
 990
 991/*
 992 * Parse one line from a packed-refs file.  Write the SHA1 to sha1.
 993 * Return a pointer to the refname within the line (null-terminated),
 994 * or NULL if there was a problem.
 995 */
 996static const char *parse_ref_line(struct strbuf *line, unsigned char *sha1)
 997{
 998        const char *ref;
 999
1000        /*
1001         * 42: the answer to everything.
1002         *
1003         * In this case, it happens to be the answer to
1004         *  40 (length of sha1 hex representation)
1005         *  +1 (space in between hex and name)
1006         *  +1 (newline at the end of the line)
1007         */
1008        if (line->len <= 42)
1009                return NULL;
1010
1011        if (get_sha1_hex(line->buf, sha1) < 0)
1012                return NULL;
1013        if (!isspace(line->buf[40]))
1014                return NULL;
1015
1016        ref = line->buf + 41;
1017        if (isspace(*ref))
1018                return NULL;
1019
1020        if (line->buf[line->len - 1] != '\n')
1021                return NULL;
1022        line->buf[--line->len] = 0;
1023
1024        return ref;
1025}
1026
1027/*
1028 * Read f, which is a packed-refs file, into dir.
1029 *
1030 * A comment line of the form "# pack-refs with: " may contain zero or
1031 * more traits. We interpret the traits as follows:
1032 *
1033 *   No traits:
1034 *
1035 *      Probably no references are peeled. But if the file contains a
1036 *      peeled value for a reference, we will use it.
1037 *
1038 *   peeled:
1039 *
1040 *      References under "refs/tags/", if they *can* be peeled, *are*
1041 *      peeled in this file. References outside of "refs/tags/" are
1042 *      probably not peeled even if they could have been, but if we find
1043 *      a peeled value for such a reference we will use it.
1044 *
1045 *   fully-peeled:
1046 *
1047 *      All references in the file that can be peeled are peeled.
1048 *      Inversely (and this is more important), any references in the
1049 *      file for which no peeled value is recorded is not peelable. This
1050 *      trait should typically be written alongside "peeled" for
1051 *      compatibility with older clients, but we do not require it
1052 *      (i.e., "peeled" is a no-op if "fully-peeled" is set).
1053 */
1054static void read_packed_refs(FILE *f, struct ref_dir *dir)
1055{
1056        struct ref_entry *last = NULL;
1057        struct strbuf line = STRBUF_INIT;
1058        enum { PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;
1059
1060        while (strbuf_getwholeline(&line, f, '\n') != EOF) {
1061                unsigned char sha1[20];
1062                const char *refname;
1063                const char *traits;
1064
1065                if (skip_prefix(line.buf, "# pack-refs with:", &traits)) {
1066                        if (strstr(traits, " fully-peeled "))
1067                                peeled = PEELED_FULLY;
1068                        else if (strstr(traits, " peeled "))
1069                                peeled = PEELED_TAGS;
1070                        /* perhaps other traits later as well */
1071                        continue;
1072                }
1073
1074                refname = parse_ref_line(&line, sha1);
1075                if (refname) {
1076                        int flag = REF_ISPACKED;
1077
1078                        if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1079                                if (!refname_is_safe(refname))
1080                                        die("packed refname is dangerous: %s", refname);
1081                                hashclr(sha1);
1082                                flag |= REF_BAD_NAME | REF_ISBROKEN;
1083                        }
1084                        last = create_ref_entry(refname, sha1, flag, 0);
1085                        if (peeled == PEELED_FULLY ||
1086                            (peeled == PEELED_TAGS && starts_with(refname, "refs/tags/")))
1087                                last->flag |= REF_KNOWS_PEELED;
1088                        add_ref(dir, last);
1089                        continue;
1090                }
1091                if (last &&
1092                    line.buf[0] == '^' &&
1093                    line.len == PEELED_LINE_LENGTH &&
1094                    line.buf[PEELED_LINE_LENGTH - 1] == '\n' &&
1095                    !get_sha1_hex(line.buf + 1, sha1)) {
1096                        hashcpy(last->u.value.peeled.hash, sha1);
1097                        /*
1098                         * Regardless of what the file header said,
1099                         * we definitely know the value of *this*
1100                         * reference:
1101                         */
1102                        last->flag |= REF_KNOWS_PEELED;
1103                }
1104        }
1105
1106        strbuf_release(&line);
1107}
1108
1109/*
1110 * Get the packed_ref_cache for the specified ref_cache, creating it
1111 * if necessary.
1112 */
1113static struct packed_ref_cache *get_packed_ref_cache(struct ref_cache *refs)
1114{
1115        char *packed_refs_file;
1116
1117        if (*refs->name)
1118                packed_refs_file = git_pathdup_submodule(refs->name, "packed-refs");
1119        else
1120                packed_refs_file = git_pathdup("packed-refs");
1121
1122        if (refs->packed &&
1123            !stat_validity_check(&refs->packed->validity, packed_refs_file))
1124                clear_packed_ref_cache(refs);
1125
1126        if (!refs->packed) {
1127                FILE *f;
1128
1129                refs->packed = xcalloc(1, sizeof(*refs->packed));
1130                acquire_packed_ref_cache(refs->packed);
1131                refs->packed->root = create_dir_entry(refs, "", 0, 0);
1132                f = fopen(packed_refs_file, "r");
1133                if (f) {
1134                        stat_validity_update(&refs->packed->validity, fileno(f));
1135                        read_packed_refs(f, get_ref_dir(refs->packed->root));
1136                        fclose(f);
1137                }
1138        }
1139        free(packed_refs_file);
1140        return refs->packed;
1141}
1142
1143static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)
1144{
1145        return get_ref_dir(packed_ref_cache->root);
1146}
1147
1148static struct ref_dir *get_packed_refs(struct ref_cache *refs)
1149{
1150        return get_packed_ref_dir(get_packed_ref_cache(refs));
1151}
1152
1153/*
1154 * Add a reference to the in-memory packed reference cache.  This may
1155 * only be called while the packed-refs file is locked (see
1156 * lock_packed_refs()).  To actually write the packed-refs file, call
1157 * commit_packed_refs().
1158 */
1159static void add_packed_ref(const char *refname, const unsigned char *sha1)
1160{
1161        struct packed_ref_cache *packed_ref_cache =
1162                get_packed_ref_cache(&ref_cache);
1163
1164        if (!packed_ref_cache->lock)
1165                die("internal error: packed refs not locked");
1166        add_ref(get_packed_ref_dir(packed_ref_cache),
1167                create_ref_entry(refname, sha1, REF_ISPACKED, 1));
1168}
1169
1170/*
1171 * Read the loose references from the namespace dirname into dir
1172 * (without recursing).  dirname must end with '/'.  dir must be the
1173 * directory entry corresponding to dirname.
1174 */
1175static void read_loose_refs(const char *dirname, struct ref_dir *dir)
1176{
1177        struct ref_cache *refs = dir->ref_cache;
1178        DIR *d;
1179        struct dirent *de;
1180        int dirnamelen = strlen(dirname);
1181        struct strbuf refname;
1182        struct strbuf path = STRBUF_INIT;
1183        size_t path_baselen;
1184
1185        if (*refs->name)
1186                strbuf_git_path_submodule(&path, refs->name, "%s", dirname);
1187        else
1188                strbuf_git_path(&path, "%s", dirname);
1189        path_baselen = path.len;
1190
1191        d = opendir(path.buf);
1192        if (!d) {
1193                strbuf_release(&path);
1194                return;
1195        }
1196
1197        strbuf_init(&refname, dirnamelen + 257);
1198        strbuf_add(&refname, dirname, dirnamelen);
1199
1200        while ((de = readdir(d)) != NULL) {
1201                unsigned char sha1[20];
1202                struct stat st;
1203                int flag;
1204
1205                if (de->d_name[0] == '.')
1206                        continue;
1207                if (ends_with(de->d_name, ".lock"))
1208                        continue;
1209                strbuf_addstr(&refname, de->d_name);
1210                strbuf_addstr(&path, de->d_name);
1211                if (stat(path.buf, &st) < 0) {
1212                        ; /* silently ignore */
1213                } else if (S_ISDIR(st.st_mode)) {
1214                        strbuf_addch(&refname, '/');
1215                        add_entry_to_dir(dir,
1216                                         create_dir_entry(refs, refname.buf,
1217                                                          refname.len, 1));
1218                } else {
1219                        int read_ok;
1220
1221                        if (*refs->name) {
1222                                hashclr(sha1);
1223                                flag = 0;
1224                                read_ok = !resolve_gitlink_ref(refs->name,
1225                                                               refname.buf, sha1);
1226                        } else {
1227                                read_ok = !read_ref_full(refname.buf,
1228                                                         RESOLVE_REF_READING,
1229                                                         sha1, &flag);
1230                        }
1231
1232                        if (!read_ok) {
1233                                hashclr(sha1);
1234                                flag |= REF_ISBROKEN;
1235                        } else if (is_null_sha1(sha1)) {
1236                                /*
1237                                 * It is so astronomically unlikely
1238                                 * that NULL_SHA1 is the SHA-1 of an
1239                                 * actual object that we consider its
1240                                 * appearance in a loose reference
1241                                 * file to be repo corruption
1242                                 * (probably due to a software bug).
1243                                 */
1244                                flag |= REF_ISBROKEN;
1245                        }
1246
1247                        if (check_refname_format(refname.buf,
1248                                                 REFNAME_ALLOW_ONELEVEL)) {
1249                                if (!refname_is_safe(refname.buf))
1250                                        die("loose refname is dangerous: %s", refname.buf);
1251                                hashclr(sha1);
1252                                flag |= REF_BAD_NAME | REF_ISBROKEN;
1253                        }
1254                        add_entry_to_dir(dir,
1255                                         create_ref_entry(refname.buf, sha1, flag, 0));
1256                }
1257                strbuf_setlen(&refname, dirnamelen);
1258                strbuf_setlen(&path, path_baselen);
1259        }
1260        strbuf_release(&refname);
1261        strbuf_release(&path);
1262        closedir(d);
1263}
1264
1265static struct ref_dir *get_loose_refs(struct ref_cache *refs)
1266{
1267        if (!refs->loose) {
1268                /*
1269                 * Mark the top-level directory complete because we
1270                 * are about to read the only subdirectory that can
1271                 * hold references:
1272                 */
1273                refs->loose = create_dir_entry(refs, "", 0, 0);
1274                /*
1275                 * Create an incomplete entry for "refs/":
1276                 */
1277                add_entry_to_dir(get_ref_dir(refs->loose),
1278                                 create_dir_entry(refs, "refs/", 5, 1));
1279        }
1280        return get_ref_dir(refs->loose);
1281}
1282
1283/* We allow "recursive" symbolic refs. Only within reason, though */
1284#define MAXDEPTH 5
1285#define MAXREFLEN (1024)
1286
1287/*
1288 * Called by resolve_gitlink_ref_recursive() after it failed to read
1289 * from the loose refs in ref_cache refs. Find <refname> in the
1290 * packed-refs file for the submodule.
1291 */
1292static int resolve_gitlink_packed_ref(struct ref_cache *refs,
1293                                      const char *refname, unsigned char *sha1)
1294{
1295        struct ref_entry *ref;
1296        struct ref_dir *dir = get_packed_refs(refs);
1297
1298        ref = find_ref(dir, refname);
1299        if (ref == NULL)
1300                return -1;
1301
1302        hashcpy(sha1, ref->u.value.oid.hash);
1303        return 0;
1304}
1305
1306static int resolve_gitlink_ref_recursive(struct ref_cache *refs,
1307                                         const char *refname, unsigned char *sha1,
1308                                         int recursion)
1309{
1310        int fd, len;
1311        char buffer[128], *p;
1312        char *path;
1313
1314        if (recursion > MAXDEPTH || strlen(refname) > MAXREFLEN)
1315                return -1;
1316        path = *refs->name
1317                ? git_pathdup_submodule(refs->name, "%s", refname)
1318                : git_pathdup("%s", refname);
1319        fd = open(path, O_RDONLY);
1320        free(path);
1321        if (fd < 0)
1322                return resolve_gitlink_packed_ref(refs, refname, sha1);
1323
1324        len = read(fd, buffer, sizeof(buffer)-1);
1325        close(fd);
1326        if (len < 0)
1327                return -1;
1328        while (len && isspace(buffer[len-1]))
1329                len--;
1330        buffer[len] = 0;
1331
1332        /* Was it a detached head or an old-fashioned symlink? */
1333        if (!get_sha1_hex(buffer, sha1))
1334                return 0;
1335
1336        /* Symref? */
1337        if (strncmp(buffer, "ref:", 4))
1338                return -1;
1339        p = buffer + 4;
1340        while (isspace(*p))
1341                p++;
1342
1343        return resolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);
1344}
1345
1346int resolve_gitlink_ref(const char *path, const char *refname, unsigned char *sha1)
1347{
1348        int len = strlen(path), retval;
1349        struct strbuf submodule = STRBUF_INIT;
1350        struct ref_cache *refs;
1351
1352        while (len && path[len-1] == '/')
1353                len--;
1354        if (!len)
1355                return -1;
1356
1357        strbuf_add(&submodule, path, len);
1358        refs = lookup_ref_cache(submodule.buf);
1359        if (!refs) {
1360                if (!is_nonbare_repository_dir(&submodule)) {
1361                        strbuf_release(&submodule);
1362                        return -1;
1363                }
1364                refs = create_ref_cache(submodule.buf);
1365        }
1366        strbuf_release(&submodule);
1367
1368        retval = resolve_gitlink_ref_recursive(refs, refname, sha1, 0);
1369        return retval;
1370}
1371
1372/*
1373 * Return the ref_entry for the given refname from the packed
1374 * references.  If it does not exist, return NULL.
1375 */
1376static struct ref_entry *get_packed_ref(const char *refname)
1377{
1378        return find_ref(get_packed_refs(&ref_cache), refname);
1379}
1380
1381/*
1382 * A loose ref file doesn't exist; check for a packed ref.  The
1383 * options are forwarded from resolve_safe_unsafe().
1384 */
1385static int resolve_missing_loose_ref(const char *refname,
1386                                     int resolve_flags,
1387                                     unsigned char *sha1,
1388                                     int *flags)
1389{
1390        struct ref_entry *entry;
1391
1392        /*
1393         * The loose reference file does not exist; check for a packed
1394         * reference.
1395         */
1396        entry = get_packed_ref(refname);
1397        if (entry) {
1398                hashcpy(sha1, entry->u.value.oid.hash);
1399                if (flags)
1400                        *flags |= REF_ISPACKED;
1401                return 0;
1402        }
1403        /* The reference is not a packed reference, either. */
1404        if (resolve_flags & RESOLVE_REF_READING) {
1405                errno = ENOENT;
1406                return -1;
1407        } else {
1408                hashclr(sha1);
1409                return 0;
1410        }
1411}
1412
1413/* This function needs to return a meaningful errno on failure */
1414static const char *resolve_ref_1(const char *refname,
1415                                 int resolve_flags,
1416                                 unsigned char *sha1,
1417                                 int *flags,
1418                                 struct strbuf *sb_refname,
1419                                 struct strbuf *sb_path,
1420                                 struct strbuf *sb_contents)
1421{
1422        int depth = MAXDEPTH;
1423        int bad_name = 0;
1424
1425        if (flags)
1426                *flags = 0;
1427
1428        if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1429                if (flags)
1430                        *flags |= REF_BAD_NAME;
1431
1432                if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1433                    !refname_is_safe(refname)) {
1434                        errno = EINVAL;
1435                        return NULL;
1436                }
1437                /*
1438                 * dwim_ref() uses REF_ISBROKEN to distinguish between
1439                 * missing refs and refs that were present but invalid,
1440                 * to complain about the latter to stderr.
1441                 *
1442                 * We don't know whether the ref exists, so don't set
1443                 * REF_ISBROKEN yet.
1444                 */
1445                bad_name = 1;
1446        }
1447        for (;;) {
1448                const char *path;
1449                struct stat st;
1450                char *buf;
1451                int fd;
1452
1453                if (--depth < 0) {
1454                        errno = ELOOP;
1455                        return NULL;
1456                }
1457
1458                strbuf_reset(sb_path);
1459                strbuf_git_path(sb_path, "%s", refname);
1460                path = sb_path->buf;
1461
1462                /*
1463                 * We might have to loop back here to avoid a race
1464                 * condition: first we lstat() the file, then we try
1465                 * to read it as a link or as a file.  But if somebody
1466                 * changes the type of the file (file <-> directory
1467                 * <-> symlink) between the lstat() and reading, then
1468                 * we don't want to report that as an error but rather
1469                 * try again starting with the lstat().
1470                 */
1471        stat_ref:
1472                if (lstat(path, &st) < 0) {
1473                        if (errno != ENOENT)
1474                                return NULL;
1475                        if (resolve_missing_loose_ref(refname, resolve_flags,
1476                                                      sha1, flags))
1477                                return NULL;
1478                        if (bad_name) {
1479                                hashclr(sha1);
1480                                if (flags)
1481                                        *flags |= REF_ISBROKEN;
1482                        }
1483                        return refname;
1484                }
1485
1486                /* Follow "normalized" - ie "refs/.." symlinks by hand */
1487                if (S_ISLNK(st.st_mode)) {
1488                        strbuf_reset(sb_contents);
1489                        if (strbuf_readlink(sb_contents, path, 0) < 0) {
1490                                if (errno == ENOENT || errno == EINVAL)
1491                                        /* inconsistent with lstat; retry */
1492                                        goto stat_ref;
1493                                else
1494                                        return NULL;
1495                        }
1496                        if (starts_with(sb_contents->buf, "refs/") &&
1497                            !check_refname_format(sb_contents->buf, 0)) {
1498                                strbuf_swap(sb_refname, sb_contents);
1499                                refname = sb_refname->buf;
1500                                if (flags)
1501                                        *flags |= REF_ISSYMREF;
1502                                if (resolve_flags & RESOLVE_REF_NO_RECURSE) {
1503                                        hashclr(sha1);
1504                                        return refname;
1505                                }
1506                                continue;
1507                        }
1508                }
1509
1510                /* Is it a directory? */
1511                if (S_ISDIR(st.st_mode)) {
1512                        errno = EISDIR;
1513                        return NULL;
1514                }
1515
1516                /*
1517                 * Anything else, just open it and try to use it as
1518                 * a ref
1519                 */
1520                fd = open(path, O_RDONLY);
1521                if (fd < 0) {
1522                        if (errno == ENOENT)
1523                                /* inconsistent with lstat; retry */
1524                                goto stat_ref;
1525                        else
1526                                return NULL;
1527                }
1528                strbuf_reset(sb_contents);
1529                if (strbuf_read(sb_contents, fd, 256) < 0) {
1530                        int save_errno = errno;
1531                        close(fd);
1532                        errno = save_errno;
1533                        return NULL;
1534                }
1535                close(fd);
1536                strbuf_rtrim(sb_contents);
1537
1538                /*
1539                 * Is it a symbolic ref?
1540                 */
1541                if (!starts_with(sb_contents->buf, "ref:")) {
1542                        /*
1543                         * Please note that FETCH_HEAD has a second
1544                         * line containing other data.
1545                         */
1546                        if (get_sha1_hex(sb_contents->buf, sha1) ||
1547                            (sb_contents->buf[40] != '\0' && !isspace(sb_contents->buf[40]))) {
1548                                if (flags)
1549                                        *flags |= REF_ISBROKEN;
1550                                errno = EINVAL;
1551                                return NULL;
1552                        }
1553                        if (bad_name) {
1554                                hashclr(sha1);
1555                                if (flags)
1556                                        *flags |= REF_ISBROKEN;
1557                        }
1558                        return refname;
1559                }
1560                if (flags)
1561                        *flags |= REF_ISSYMREF;
1562                buf = sb_contents->buf + 4;
1563                while (isspace(*buf))
1564                        buf++;
1565                strbuf_reset(sb_refname);
1566                strbuf_addstr(sb_refname, buf);
1567                refname = sb_refname->buf;
1568                if (resolve_flags & RESOLVE_REF_NO_RECURSE) {
1569                        hashclr(sha1);
1570                        return refname;
1571                }
1572                if (check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {
1573                        if (flags)
1574                                *flags |= REF_ISBROKEN;
1575
1576                        if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1577                            !refname_is_safe(buf)) {
1578                                errno = EINVAL;
1579                                return NULL;
1580                        }
1581                        bad_name = 1;
1582                }
1583        }
1584}
1585
1586const char *resolve_ref_unsafe(const char *refname, int resolve_flags,
1587                               unsigned char *sha1, int *flags)
1588{
1589        static struct strbuf sb_refname = STRBUF_INIT;
1590        struct strbuf sb_contents = STRBUF_INIT;
1591        struct strbuf sb_path = STRBUF_INIT;
1592        const char *ret;
1593
1594        ret = resolve_ref_1(refname, resolve_flags, sha1, flags,
1595                            &sb_refname, &sb_path, &sb_contents);
1596        strbuf_release(&sb_path);
1597        strbuf_release(&sb_contents);
1598        return ret;
1599}
1600
1601/*
1602 * Peel the entry (if possible) and return its new peel_status.  If
1603 * repeel is true, re-peel the entry even if there is an old peeled
1604 * value that is already stored in it.
1605 *
1606 * It is OK to call this function with a packed reference entry that
1607 * might be stale and might even refer to an object that has since
1608 * been garbage-collected.  In such a case, if the entry has
1609 * REF_KNOWS_PEELED then leave the status unchanged and return
1610 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.
1611 */
1612static enum peel_status peel_entry(struct ref_entry *entry, int repeel)
1613{
1614        enum peel_status status;
1615
1616        if (entry->flag & REF_KNOWS_PEELED) {
1617                if (repeel) {
1618                        entry->flag &= ~REF_KNOWS_PEELED;
1619                        oidclr(&entry->u.value.peeled);
1620                } else {
1621                        return is_null_oid(&entry->u.value.peeled) ?
1622                                PEEL_NON_TAG : PEEL_PEELED;
1623                }
1624        }
1625        if (entry->flag & REF_ISBROKEN)
1626                return PEEL_BROKEN;
1627        if (entry->flag & REF_ISSYMREF)
1628                return PEEL_IS_SYMREF;
1629
1630        status = peel_object(entry->u.value.oid.hash, entry->u.value.peeled.hash);
1631        if (status == PEEL_PEELED || status == PEEL_NON_TAG)
1632                entry->flag |= REF_KNOWS_PEELED;
1633        return status;
1634}
1635
1636int peel_ref(const char *refname, unsigned char *sha1)
1637{
1638        int flag;
1639        unsigned char base[20];
1640
1641        if (current_ref && (current_ref->name == refname
1642                            || !strcmp(current_ref->name, refname))) {
1643                if (peel_entry(current_ref, 0))
1644                        return -1;
1645                hashcpy(sha1, current_ref->u.value.peeled.hash);
1646                return 0;
1647        }
1648
1649        if (read_ref_full(refname, RESOLVE_REF_READING, base, &flag))
1650                return -1;
1651
1652        /*
1653         * If the reference is packed, read its ref_entry from the
1654         * cache in the hope that we already know its peeled value.
1655         * We only try this optimization on packed references because
1656         * (a) forcing the filling of the loose reference cache could
1657         * be expensive and (b) loose references anyway usually do not
1658         * have REF_KNOWS_PEELED.
1659         */
1660        if (flag & REF_ISPACKED) {
1661                struct ref_entry *r = get_packed_ref(refname);
1662                if (r) {
1663                        if (peel_entry(r, 0))
1664                                return -1;
1665                        hashcpy(sha1, r->u.value.peeled.hash);
1666                        return 0;
1667                }
1668        }
1669
1670        return peel_object(base, sha1);
1671}
1672
1673/*
1674 * Call fn for each reference in the specified ref_cache, omitting
1675 * references not in the containing_dir of base.  fn is called for all
1676 * references, including broken ones.  If fn ever returns a non-zero
1677 * value, stop the iteration and return that value; otherwise, return
1678 * 0.
1679 */
1680static int do_for_each_entry(struct ref_cache *refs, const char *base,
1681                             each_ref_entry_fn fn, void *cb_data)
1682{
1683        struct packed_ref_cache *packed_ref_cache;
1684        struct ref_dir *loose_dir;
1685        struct ref_dir *packed_dir;
1686        int retval = 0;
1687
1688        /*
1689         * We must make sure that all loose refs are read before accessing the
1690         * packed-refs file; this avoids a race condition in which loose refs
1691         * are migrated to the packed-refs file by a simultaneous process, but
1692         * our in-memory view is from before the migration. get_packed_ref_cache()
1693         * takes care of making sure our view is up to date with what is on
1694         * disk.
1695         */
1696        loose_dir = get_loose_refs(refs);
1697        if (base && *base) {
1698                loose_dir = find_containing_dir(loose_dir, base, 0);
1699        }
1700        if (loose_dir)
1701                prime_ref_dir(loose_dir);
1702
1703        packed_ref_cache = get_packed_ref_cache(refs);
1704        acquire_packed_ref_cache(packed_ref_cache);
1705        packed_dir = get_packed_ref_dir(packed_ref_cache);
1706        if (base && *base) {
1707                packed_dir = find_containing_dir(packed_dir, base, 0);
1708        }
1709
1710        if (packed_dir && loose_dir) {
1711                sort_ref_dir(packed_dir);
1712                sort_ref_dir(loose_dir);
1713                retval = do_for_each_entry_in_dirs(
1714                                packed_dir, loose_dir, fn, cb_data);
1715        } else if (packed_dir) {
1716                sort_ref_dir(packed_dir);
1717                retval = do_for_each_entry_in_dir(
1718                                packed_dir, 0, fn, cb_data);
1719        } else if (loose_dir) {
1720                sort_ref_dir(loose_dir);
1721                retval = do_for_each_entry_in_dir(
1722                                loose_dir, 0, fn, cb_data);
1723        }
1724
1725        release_packed_ref_cache(packed_ref_cache);
1726        return retval;
1727}
1728
1729/*
1730 * Call fn for each reference in the specified ref_cache for which the
1731 * refname begins with base.  If trim is non-zero, then trim that many
1732 * characters off the beginning of each refname before passing the
1733 * refname to fn.  flags can be DO_FOR_EACH_INCLUDE_BROKEN to include
1734 * broken references in the iteration.  If fn ever returns a non-zero
1735 * value, stop the iteration and return that value; otherwise, return
1736 * 0.
1737 */
1738static int do_for_each_ref(struct ref_cache *refs, const char *base,
1739                           each_ref_fn fn, int trim, int flags, void *cb_data)
1740{
1741        struct ref_entry_cb data;
1742        data.base = base;
1743        data.trim = trim;
1744        data.flags = flags;
1745        data.fn = fn;
1746        data.cb_data = cb_data;
1747
1748        if (ref_paranoia < 0)
1749                ref_paranoia = git_env_bool("GIT_REF_PARANOIA", 0);
1750        if (ref_paranoia)
1751                data.flags |= DO_FOR_EACH_INCLUDE_BROKEN;
1752
1753        return do_for_each_entry(refs, base, do_one_ref, &data);
1754}
1755
1756static int do_head_ref(const char *submodule, each_ref_fn fn, void *cb_data)
1757{
1758        struct object_id oid;
1759        int flag;
1760
1761        if (submodule) {
1762                if (resolve_gitlink_ref(submodule, "HEAD", oid.hash) == 0)
1763                        return fn("HEAD", &oid, 0, cb_data);
1764
1765                return 0;
1766        }
1767
1768        if (!read_ref_full("HEAD", RESOLVE_REF_READING, oid.hash, &flag))
1769                return fn("HEAD", &oid, flag, cb_data);
1770
1771        return 0;
1772}
1773
1774int head_ref(each_ref_fn fn, void *cb_data)
1775{
1776        return do_head_ref(NULL, fn, cb_data);
1777}
1778
1779int head_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1780{
1781        return do_head_ref(submodule, fn, cb_data);
1782}
1783
1784int for_each_ref(each_ref_fn fn, void *cb_data)
1785{
1786        return do_for_each_ref(&ref_cache, "", fn, 0, 0, cb_data);
1787}
1788
1789int for_each_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1790{
1791        return do_for_each_ref(get_ref_cache(submodule), "", fn, 0, 0, cb_data);
1792}
1793
1794int for_each_ref_in(const char *prefix, each_ref_fn fn, void *cb_data)
1795{
1796        return do_for_each_ref(&ref_cache, prefix, fn, strlen(prefix), 0, cb_data);
1797}
1798
1799int for_each_fullref_in(const char *prefix, each_ref_fn fn, void *cb_data, unsigned int broken)
1800{
1801        unsigned int flag = 0;
1802
1803        if (broken)
1804                flag = DO_FOR_EACH_INCLUDE_BROKEN;
1805        return do_for_each_ref(&ref_cache, prefix, fn, 0, flag, cb_data);
1806}
1807
1808int for_each_ref_in_submodule(const char *submodule, const char *prefix,
1809                each_ref_fn fn, void *cb_data)
1810{
1811        return do_for_each_ref(get_ref_cache(submodule), prefix, fn, strlen(prefix), 0, cb_data);
1812}
1813
1814int for_each_replace_ref(each_ref_fn fn, void *cb_data)
1815{
1816        return do_for_each_ref(&ref_cache, git_replace_ref_base, fn,
1817                               strlen(git_replace_ref_base), 0, cb_data);
1818}
1819
1820int for_each_namespaced_ref(each_ref_fn fn, void *cb_data)
1821{
1822        struct strbuf buf = STRBUF_INIT;
1823        int ret;
1824        strbuf_addf(&buf, "%srefs/", get_git_namespace());
1825        ret = do_for_each_ref(&ref_cache, buf.buf, fn, 0, 0, cb_data);
1826        strbuf_release(&buf);
1827        return ret;
1828}
1829
1830int for_each_rawref(each_ref_fn fn, void *cb_data)
1831{
1832        return do_for_each_ref(&ref_cache, "", fn, 0,
1833                               DO_FOR_EACH_INCLUDE_BROKEN, cb_data);
1834}
1835
1836static void unlock_ref(struct ref_lock *lock)
1837{
1838        /* Do not free lock->lk -- atexit() still looks at them */
1839        if (lock->lk)
1840                rollback_lock_file(lock->lk);
1841        free(lock->ref_name);
1842        free(lock->orig_ref_name);
1843        free(lock);
1844}
1845
1846/*
1847 * Verify that the reference locked by lock has the value old_sha1.
1848 * Fail if the reference doesn't exist and mustexist is set. Return 0
1849 * on success. On error, write an error message to err, set errno, and
1850 * return a negative value.
1851 */
1852static int verify_lock(struct ref_lock *lock,
1853                       const unsigned char *old_sha1, int mustexist,
1854                       struct strbuf *err)
1855{
1856        assert(err);
1857
1858        if (read_ref_full(lock->ref_name,
1859                          mustexist ? RESOLVE_REF_READING : 0,
1860                          lock->old_oid.hash, NULL)) {
1861                int save_errno = errno;
1862                strbuf_addf(err, "can't verify ref %s", lock->ref_name);
1863                errno = save_errno;
1864                return -1;
1865        }
1866        if (hashcmp(lock->old_oid.hash, old_sha1)) {
1867                strbuf_addf(err, "ref %s is at %s but expected %s",
1868                            lock->ref_name,
1869                            sha1_to_hex(lock->old_oid.hash),
1870                            sha1_to_hex(old_sha1));
1871                errno = EBUSY;
1872                return -1;
1873        }
1874        return 0;
1875}
1876
1877static int remove_empty_directories(struct strbuf *path)
1878{
1879        /*
1880         * we want to create a file but there is a directory there;
1881         * if that is an empty directory (or a directory that contains
1882         * only empty directories), remove them.
1883         */
1884        return remove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);
1885}
1886
1887/*
1888 * Locks a ref returning the lock on success and NULL on failure.
1889 * On failure errno is set to something meaningful.
1890 */
1891static struct ref_lock *lock_ref_sha1_basic(const char *refname,
1892                                            const unsigned char *old_sha1,
1893                                            const struct string_list *extras,
1894                                            const struct string_list *skip,
1895                                            unsigned int flags, int *type_p,
1896                                            struct strbuf *err)
1897{
1898        struct strbuf ref_file = STRBUF_INIT;
1899        struct strbuf orig_ref_file = STRBUF_INIT;
1900        const char *orig_refname = refname;
1901        struct ref_lock *lock;
1902        int last_errno = 0;
1903        int type, lflags;
1904        int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
1905        int resolve_flags = 0;
1906        int attempts_remaining = 3;
1907
1908        assert(err);
1909
1910        lock = xcalloc(1, sizeof(struct ref_lock));
1911
1912        if (mustexist)
1913                resolve_flags |= RESOLVE_REF_READING;
1914        if (flags & REF_DELETING) {
1915                resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;
1916                if (flags & REF_NODEREF)
1917                        resolve_flags |= RESOLVE_REF_NO_RECURSE;
1918        }
1919
1920        refname = resolve_ref_unsafe(refname, resolve_flags,
1921                                     lock->old_oid.hash, &type);
1922        if (!refname && errno == EISDIR) {
1923                /*
1924                 * we are trying to lock foo but we used to
1925                 * have foo/bar which now does not exist;
1926                 * it is normal for the empty directory 'foo'
1927                 * to remain.
1928                 */
1929                strbuf_git_path(&orig_ref_file, "%s", orig_refname);
1930                if (remove_empty_directories(&orig_ref_file)) {
1931                        last_errno = errno;
1932                        if (!verify_refname_available_dir(orig_refname, extras, skip,
1933                                                          get_loose_refs(&ref_cache), err))
1934                                strbuf_addf(err, "there are still refs under '%s'",
1935                                            orig_refname);
1936                        goto error_return;
1937                }
1938                refname = resolve_ref_unsafe(orig_refname, resolve_flags,
1939                                             lock->old_oid.hash, &type);
1940        }
1941        if (type_p)
1942            *type_p = type;
1943        if (!refname) {
1944                last_errno = errno;
1945                if (last_errno != ENOTDIR ||
1946                    !verify_refname_available_dir(orig_refname, extras, skip,
1947                                                  get_loose_refs(&ref_cache), err))
1948                        strbuf_addf(err, "unable to resolve reference %s: %s",
1949                                    orig_refname, strerror(last_errno));
1950
1951                goto error_return;
1952        }
1953        /*
1954         * If the ref did not exist and we are creating it, make sure
1955         * there is no existing packed ref whose name begins with our
1956         * refname, nor a packed ref whose name is a proper prefix of
1957         * our refname.
1958         */
1959        if (is_null_oid(&lock->old_oid) &&
1960            verify_refname_available_dir(refname, extras, skip,
1961                                         get_packed_refs(&ref_cache), err)) {
1962                last_errno = ENOTDIR;
1963                goto error_return;
1964        }
1965
1966        lock->lk = xcalloc(1, sizeof(struct lock_file));
1967
1968        lflags = 0;
1969        if (flags & REF_NODEREF) {
1970                refname = orig_refname;
1971                lflags |= LOCK_NO_DEREF;
1972        }
1973        lock->ref_name = xstrdup(refname);
1974        lock->orig_ref_name = xstrdup(orig_refname);
1975        strbuf_git_path(&ref_file, "%s", refname);
1976
1977 retry:
1978        switch (safe_create_leading_directories_const(ref_file.buf)) {
1979        case SCLD_OK:
1980                break; /* success */
1981        case SCLD_VANISHED:
1982                if (--attempts_remaining > 0)
1983                        goto retry;
1984                /* fall through */
1985        default:
1986                last_errno = errno;
1987                strbuf_addf(err, "unable to create directory for %s",
1988                            ref_file.buf);
1989                goto error_return;
1990        }
1991
1992        if (hold_lock_file_for_update(lock->lk, ref_file.buf, lflags) < 0) {
1993                last_errno = errno;
1994                if (errno == ENOENT && --attempts_remaining > 0)
1995                        /*
1996                         * Maybe somebody just deleted one of the
1997                         * directories leading to ref_file.  Try
1998                         * again:
1999                         */
2000                        goto retry;
2001                else {
2002                        unable_to_lock_message(ref_file.buf, errno, err);
2003                        goto error_return;
2004                }
2005        }
2006        if (old_sha1 && verify_lock(lock, old_sha1, mustexist, err)) {
2007                last_errno = errno;
2008                goto error_return;
2009        }
2010        goto out;
2011
2012 error_return:
2013        unlock_ref(lock);
2014        lock = NULL;
2015
2016 out:
2017        strbuf_release(&ref_file);
2018        strbuf_release(&orig_ref_file);
2019        errno = last_errno;
2020        return lock;
2021}
2022
2023/*
2024 * Write an entry to the packed-refs file for the specified refname.
2025 * If peeled is non-NULL, write it as the entry's peeled value.
2026 */
2027static void write_packed_entry(FILE *fh, char *refname, unsigned char *sha1,
2028                               unsigned char *peeled)
2029{
2030        fprintf_or_die(fh, "%s %s\n", sha1_to_hex(sha1), refname);
2031        if (peeled)
2032                fprintf_or_die(fh, "^%s\n", sha1_to_hex(peeled));
2033}
2034
2035/*
2036 * An each_ref_entry_fn that writes the entry to a packed-refs file.
2037 */
2038static int write_packed_entry_fn(struct ref_entry *entry, void *cb_data)
2039{
2040        enum peel_status peel_status = peel_entry(entry, 0);
2041
2042        if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)
2043                error("internal error: %s is not a valid packed reference!",
2044                      entry->name);
2045        write_packed_entry(cb_data, entry->name, entry->u.value.oid.hash,
2046                           peel_status == PEEL_PEELED ?
2047                           entry->u.value.peeled.hash : NULL);
2048        return 0;
2049}
2050
2051/*
2052 * Lock the packed-refs file for writing. Flags is passed to
2053 * hold_lock_file_for_update(). Return 0 on success. On errors, set
2054 * errno appropriately and return a nonzero value.
2055 */
2056static int lock_packed_refs(int flags)
2057{
2058        static int timeout_configured = 0;
2059        static int timeout_value = 1000;
2060
2061        struct packed_ref_cache *packed_ref_cache;
2062
2063        if (!timeout_configured) {
2064                git_config_get_int("core.packedrefstimeout", &timeout_value);
2065                timeout_configured = 1;
2066        }
2067
2068        if (hold_lock_file_for_update_timeout(
2069                            &packlock, git_path("packed-refs"),
2070                            flags, timeout_value) < 0)
2071                return -1;
2072        /*
2073         * Get the current packed-refs while holding the lock.  If the
2074         * packed-refs file has been modified since we last read it,
2075         * this will automatically invalidate the cache and re-read
2076         * the packed-refs file.
2077         */
2078        packed_ref_cache = get_packed_ref_cache(&ref_cache);
2079        packed_ref_cache->lock = &packlock;
2080        /* Increment the reference count to prevent it from being freed: */
2081        acquire_packed_ref_cache(packed_ref_cache);
2082        return 0;
2083}
2084
2085/*
2086 * Write the current version of the packed refs cache from memory to
2087 * disk. The packed-refs file must already be locked for writing (see
2088 * lock_packed_refs()). Return zero on success. On errors, set errno
2089 * and return a nonzero value
2090 */
2091static int commit_packed_refs(void)
2092{
2093        struct packed_ref_cache *packed_ref_cache =
2094                get_packed_ref_cache(&ref_cache);
2095        int error = 0;
2096        int save_errno = 0;
2097        FILE *out;
2098
2099        if (!packed_ref_cache->lock)
2100                die("internal error: packed-refs not locked");
2101
2102        out = fdopen_lock_file(packed_ref_cache->lock, "w");
2103        if (!out)
2104                die_errno("unable to fdopen packed-refs descriptor");
2105
2106        fprintf_or_die(out, "%s", PACKED_REFS_HEADER);
2107        do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),
2108                                 0, write_packed_entry_fn, out);
2109
2110        if (commit_lock_file(packed_ref_cache->lock)) {
2111                save_errno = errno;
2112                error = -1;
2113        }
2114        packed_ref_cache->lock = NULL;
2115        release_packed_ref_cache(packed_ref_cache);
2116        errno = save_errno;
2117        return error;
2118}
2119
2120/*
2121 * Rollback the lockfile for the packed-refs file, and discard the
2122 * in-memory packed reference cache.  (The packed-refs file will be
2123 * read anew if it is needed again after this function is called.)
2124 */
2125static void rollback_packed_refs(void)
2126{
2127        struct packed_ref_cache *packed_ref_cache =
2128                get_packed_ref_cache(&ref_cache);
2129
2130        if (!packed_ref_cache->lock)
2131                die("internal error: packed-refs not locked");
2132        rollback_lock_file(packed_ref_cache->lock);
2133        packed_ref_cache->lock = NULL;
2134        release_packed_ref_cache(packed_ref_cache);
2135        clear_packed_ref_cache(&ref_cache);
2136}
2137
2138struct ref_to_prune {
2139        struct ref_to_prune *next;
2140        unsigned char sha1[20];
2141        char name[FLEX_ARRAY];
2142};
2143
2144struct pack_refs_cb_data {
2145        unsigned int flags;
2146        struct ref_dir *packed_refs;
2147        struct ref_to_prune *ref_to_prune;
2148};
2149
2150/*
2151 * An each_ref_entry_fn that is run over loose references only.  If
2152 * the loose reference can be packed, add an entry in the packed ref
2153 * cache.  If the reference should be pruned, also add it to
2154 * ref_to_prune in the pack_refs_cb_data.
2155 */
2156static int pack_if_possible_fn(struct ref_entry *entry, void *cb_data)
2157{
2158        struct pack_refs_cb_data *cb = cb_data;
2159        enum peel_status peel_status;
2160        struct ref_entry *packed_entry;
2161        int is_tag_ref = starts_with(entry->name, "refs/tags/");
2162
2163        /* Do not pack per-worktree refs: */
2164        if (ref_type(entry->name) != REF_TYPE_NORMAL)
2165                return 0;
2166
2167        /* ALWAYS pack tags */
2168        if (!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)
2169                return 0;
2170
2171        /* Do not pack symbolic or broken refs: */
2172        if ((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))
2173                return 0;
2174
2175        /* Add a packed ref cache entry equivalent to the loose entry. */
2176        peel_status = peel_entry(entry, 1);
2177        if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)
2178                die("internal error peeling reference %s (%s)",
2179                    entry->name, oid_to_hex(&entry->u.value.oid));
2180        packed_entry = find_ref(cb->packed_refs, entry->name);
2181        if (packed_entry) {
2182                /* Overwrite existing packed entry with info from loose entry */
2183                packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;
2184                oidcpy(&packed_entry->u.value.oid, &entry->u.value.oid);
2185        } else {
2186                packed_entry = create_ref_entry(entry->name, entry->u.value.oid.hash,
2187                                                REF_ISPACKED | REF_KNOWS_PEELED, 0);
2188                add_ref(cb->packed_refs, packed_entry);
2189        }
2190        oidcpy(&packed_entry->u.value.peeled, &entry->u.value.peeled);
2191
2192        /* Schedule the loose reference for pruning if requested. */
2193        if ((cb->flags & PACK_REFS_PRUNE)) {
2194                int namelen = strlen(entry->name) + 1;
2195                struct ref_to_prune *n = xcalloc(1, sizeof(*n) + namelen);
2196                hashcpy(n->sha1, entry->u.value.oid.hash);
2197                memcpy(n->name, entry->name, namelen); /* includes NUL */
2198                n->next = cb->ref_to_prune;
2199                cb->ref_to_prune = n;
2200        }
2201        return 0;
2202}
2203
2204/*
2205 * Remove empty parents, but spare refs/ and immediate subdirs.
2206 * Note: munges *name.
2207 */
2208static void try_remove_empty_parents(char *name)
2209{
2210        char *p, *q;
2211        int i;
2212        p = name;
2213        for (i = 0; i < 2; i++) { /* refs/{heads,tags,...}/ */
2214                while (*p && *p != '/')
2215                        p++;
2216                /* tolerate duplicate slashes; see check_refname_format() */
2217                while (*p == '/')
2218                        p++;
2219        }
2220        for (q = p; *q; q++)
2221                ;
2222        while (1) {
2223                while (q > p && *q != '/')
2224                        q--;
2225                while (q > p && *(q-1) == '/')
2226                        q--;
2227                if (q == p)
2228                        break;
2229                *q = '\0';
2230                if (rmdir(git_path("%s", name)))
2231                        break;
2232        }
2233}
2234
2235/* make sure nobody touched the ref, and unlink */
2236static void prune_ref(struct ref_to_prune *r)
2237{
2238        struct ref_transaction *transaction;
2239        struct strbuf err = STRBUF_INIT;
2240
2241        if (check_refname_format(r->name, 0))
2242                return;
2243
2244        transaction = ref_transaction_begin(&err);
2245        if (!transaction ||
2246            ref_transaction_delete(transaction, r->name, r->sha1,
2247                                   REF_ISPRUNING, NULL, &err) ||
2248            ref_transaction_commit(transaction, &err)) {
2249                ref_transaction_free(transaction);
2250                error("%s", err.buf);
2251                strbuf_release(&err);
2252                return;
2253        }
2254        ref_transaction_free(transaction);
2255        strbuf_release(&err);
2256        try_remove_empty_parents(r->name);
2257}
2258
2259static void prune_refs(struct ref_to_prune *r)
2260{
2261        while (r) {
2262                prune_ref(r);
2263                r = r->next;
2264        }
2265}
2266
2267int pack_refs(unsigned int flags)
2268{
2269        struct pack_refs_cb_data cbdata;
2270
2271        memset(&cbdata, 0, sizeof(cbdata));
2272        cbdata.flags = flags;
2273
2274        lock_packed_refs(LOCK_DIE_ON_ERROR);
2275        cbdata.packed_refs = get_packed_refs(&ref_cache);
2276
2277        do_for_each_entry_in_dir(get_loose_refs(&ref_cache), 0,
2278                                 pack_if_possible_fn, &cbdata);
2279
2280        if (commit_packed_refs())
2281                die_errno("unable to overwrite old ref-pack file");
2282
2283        prune_refs(cbdata.ref_to_prune);
2284        return 0;
2285}
2286
2287/*
2288 * Rewrite the packed-refs file, omitting any refs listed in
2289 * 'refnames'. On error, leave packed-refs unchanged, write an error
2290 * message to 'err', and return a nonzero value.
2291 *
2292 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.
2293 */
2294static int repack_without_refs(struct string_list *refnames, struct strbuf *err)
2295{
2296        struct ref_dir *packed;
2297        struct string_list_item *refname;
2298        int ret, needs_repacking = 0, removed = 0;
2299
2300        assert(err);
2301
2302        /* Look for a packed ref */
2303        for_each_string_list_item(refname, refnames) {
2304                if (get_packed_ref(refname->string)) {
2305                        needs_repacking = 1;
2306                        break;
2307                }
2308        }
2309
2310        /* Avoid locking if we have nothing to do */
2311        if (!needs_repacking)
2312                return 0; /* no refname exists in packed refs */
2313
2314        if (lock_packed_refs(0)) {
2315                unable_to_lock_message(git_path("packed-refs"), errno, err);
2316                return -1;
2317        }
2318        packed = get_packed_refs(&ref_cache);
2319
2320        /* Remove refnames from the cache */
2321        for_each_string_list_item(refname, refnames)
2322                if (remove_entry(packed, refname->string) != -1)
2323                        removed = 1;
2324        if (!removed) {
2325                /*
2326                 * All packed entries disappeared while we were
2327                 * acquiring the lock.
2328                 */
2329                rollback_packed_refs();
2330                return 0;
2331        }
2332
2333        /* Write what remains */
2334        ret = commit_packed_refs();
2335        if (ret)
2336                strbuf_addf(err, "unable to overwrite old ref-pack file: %s",
2337                            strerror(errno));
2338        return ret;
2339}
2340
2341static int delete_ref_loose(struct ref_lock *lock, int flag, struct strbuf *err)
2342{
2343        assert(err);
2344
2345        if (!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {
2346                /*
2347                 * loose.  The loose file name is the same as the
2348                 * lockfile name, minus ".lock":
2349                 */
2350                char *loose_filename = get_locked_file_path(lock->lk);
2351                int res = unlink_or_msg(loose_filename, err);
2352                free(loose_filename);
2353                if (res)
2354                        return 1;
2355        }
2356        return 0;
2357}
2358
2359int delete_refs(struct string_list *refnames)
2360{
2361        struct strbuf err = STRBUF_INIT;
2362        int i, result = 0;
2363
2364        if (!refnames->nr)
2365                return 0;
2366
2367        result = repack_without_refs(refnames, &err);
2368        if (result) {
2369                /*
2370                 * If we failed to rewrite the packed-refs file, then
2371                 * it is unsafe to try to remove loose refs, because
2372                 * doing so might expose an obsolete packed value for
2373                 * a reference that might even point at an object that
2374                 * has been garbage collected.
2375                 */
2376                if (refnames->nr == 1)
2377                        error(_("could not delete reference %s: %s"),
2378                              refnames->items[0].string, err.buf);
2379                else
2380                        error(_("could not delete references: %s"), err.buf);
2381
2382                goto out;
2383        }
2384
2385        for (i = 0; i < refnames->nr; i++) {
2386                const char *refname = refnames->items[i].string;
2387
2388                if (delete_ref(refname, NULL, 0))
2389                        result |= error(_("could not remove reference %s"), refname);
2390        }
2391
2392out:
2393        strbuf_release(&err);
2394        return result;
2395}
2396
2397/*
2398 * People using contrib's git-new-workdir have .git/logs/refs ->
2399 * /some/other/path/.git/logs/refs, and that may live on another device.
2400 *
2401 * IOW, to avoid cross device rename errors, the temporary renamed log must
2402 * live into logs/refs.
2403 */
2404#define TMP_RENAMED_LOG  "logs/refs/.tmp-renamed-log"
2405
2406static int rename_tmp_log(const char *newrefname)
2407{
2408        int attempts_remaining = 4;
2409        struct strbuf path = STRBUF_INIT;
2410        int ret = -1;
2411
2412 retry:
2413        strbuf_reset(&path);
2414        strbuf_git_path(&path, "logs/%s", newrefname);
2415        switch (safe_create_leading_directories_const(path.buf)) {
2416        case SCLD_OK:
2417                break; /* success */
2418        case SCLD_VANISHED:
2419                if (--attempts_remaining > 0)
2420                        goto retry;
2421                /* fall through */
2422        default:
2423                error("unable to create directory for %s", newrefname);
2424                goto out;
2425        }
2426
2427        if (rename(git_path(TMP_RENAMED_LOG), path.buf)) {
2428                if ((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining > 0) {
2429                        /*
2430                         * rename(a, b) when b is an existing
2431                         * directory ought to result in ISDIR, but
2432                         * Solaris 5.8 gives ENOTDIR.  Sheesh.
2433                         */
2434                        if (remove_empty_directories(&path)) {
2435                                error("Directory not empty: logs/%s", newrefname);
2436                                goto out;
2437                        }
2438                        goto retry;
2439                } else if (errno == ENOENT && --attempts_remaining > 0) {
2440                        /*
2441                         * Maybe another process just deleted one of
2442                         * the directories in the path to newrefname.
2443                         * Try again from the beginning.
2444                         */
2445                        goto retry;
2446                } else {
2447                        error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s: %s",
2448                                newrefname, strerror(errno));
2449                        goto out;
2450                }
2451        }
2452        ret = 0;
2453out:
2454        strbuf_release(&path);
2455        return ret;
2456}
2457
2458int verify_refname_available(const char *newname,
2459                             struct string_list *extras,
2460                             struct string_list *skip,
2461                             struct strbuf *err)
2462{
2463        struct ref_dir *packed_refs = get_packed_refs(&ref_cache);
2464        struct ref_dir *loose_refs = get_loose_refs(&ref_cache);
2465
2466        if (verify_refname_available_dir(newname, extras, skip,
2467                                         packed_refs, err) ||
2468            verify_refname_available_dir(newname, extras, skip,
2469                                         loose_refs, err))
2470                return -1;
2471
2472        return 0;
2473}
2474
2475static int write_ref_to_lockfile(struct ref_lock *lock,
2476                                 const unsigned char *sha1, struct strbuf *err);
2477static int commit_ref_update(struct ref_lock *lock,
2478                             const unsigned char *sha1, const char *logmsg,
2479                             int flags, struct strbuf *err);
2480
2481int rename_ref(const char *oldrefname, const char *newrefname, const char *logmsg)
2482{
2483        unsigned char sha1[20], orig_sha1[20];
2484        int flag = 0, logmoved = 0;
2485        struct ref_lock *lock;
2486        struct stat loginfo;
2487        int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);
2488        const char *symref = NULL;
2489        struct strbuf err = STRBUF_INIT;
2490
2491        if (log && S_ISLNK(loginfo.st_mode))
2492                return error("reflog for %s is a symlink", oldrefname);
2493
2494        symref = resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING,
2495                                    orig_sha1, &flag);
2496        if (flag & REF_ISSYMREF)
2497                return error("refname %s is a symbolic ref, renaming it is not supported",
2498                        oldrefname);
2499        if (!symref)
2500                return error("refname %s not found", oldrefname);
2501
2502        if (!rename_ref_available(oldrefname, newrefname))
2503                return 1;
2504
2505        if (log && rename(git_path("logs/%s", oldrefname), git_path(TMP_RENAMED_LOG)))
2506                return error("unable to move logfile logs/%s to "TMP_RENAMED_LOG": %s",
2507                        oldrefname, strerror(errno));
2508
2509        if (delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {
2510                error("unable to delete old %s", oldrefname);
2511                goto rollback;
2512        }
2513
2514        if (!read_ref_full(newrefname, RESOLVE_REF_READING, sha1, NULL) &&
2515            delete_ref(newrefname, sha1, REF_NODEREF)) {
2516                if (errno==EISDIR) {
2517                        struct strbuf path = STRBUF_INIT;
2518                        int result;
2519
2520                        strbuf_git_path(&path, "%s", newrefname);
2521                        result = remove_empty_directories(&path);
2522                        strbuf_release(&path);
2523
2524                        if (result) {
2525                                error("Directory not empty: %s", newrefname);
2526                                goto rollback;
2527                        }
2528                } else {
2529                        error("unable to delete existing %s", newrefname);
2530                        goto rollback;
2531                }
2532        }
2533
2534        if (log && rename_tmp_log(newrefname))
2535                goto rollback;
2536
2537        logmoved = log;
2538
2539        lock = lock_ref_sha1_basic(newrefname, NULL, NULL, NULL, 0, NULL, &err);
2540        if (!lock) {
2541                error("unable to rename '%s' to '%s': %s", oldrefname, newrefname, err.buf);
2542                strbuf_release(&err);
2543                goto rollback;
2544        }
2545        hashcpy(lock->old_oid.hash, orig_sha1);
2546
2547        if (write_ref_to_lockfile(lock, orig_sha1, &err) ||
2548            commit_ref_update(lock, orig_sha1, logmsg, 0, &err)) {
2549                error("unable to write current sha1 into %s: %s", newrefname, err.buf);
2550                strbuf_release(&err);
2551                goto rollback;
2552        }
2553
2554        return 0;
2555
2556 rollback:
2557        lock = lock_ref_sha1_basic(oldrefname, NULL, NULL, NULL, 0, NULL, &err);
2558        if (!lock) {
2559                error("unable to lock %s for rollback: %s", oldrefname, err.buf);
2560                strbuf_release(&err);
2561                goto rollbacklog;
2562        }
2563
2564        flag = log_all_ref_updates;
2565        log_all_ref_updates = 0;
2566        if (write_ref_to_lockfile(lock, orig_sha1, &err) ||
2567            commit_ref_update(lock, orig_sha1, NULL, 0, &err)) {
2568                error("unable to write current sha1 into %s: %s", oldrefname, err.buf);
2569                strbuf_release(&err);
2570        }
2571        log_all_ref_updates = flag;
2572
2573 rollbacklog:
2574        if (logmoved && rename(git_path("logs/%s", newrefname), git_path("logs/%s", oldrefname)))
2575                error("unable to restore logfile %s from %s: %s",
2576                        oldrefname, newrefname, strerror(errno));
2577        if (!logmoved && log &&
2578            rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", oldrefname)))
2579                error("unable to restore logfile %s from "TMP_RENAMED_LOG": %s",
2580                        oldrefname, strerror(errno));
2581
2582        return 1;
2583}
2584
2585static int close_ref(struct ref_lock *lock)
2586{
2587        if (close_lock_file(lock->lk))
2588                return -1;
2589        return 0;
2590}
2591
2592static int commit_ref(struct ref_lock *lock)
2593{
2594        if (commit_lock_file(lock->lk))
2595                return -1;
2596        return 0;
2597}
2598
2599/*
2600 * Create a reflog for a ref.  If force_create = 0, the reflog will
2601 * only be created for certain refs (those for which
2602 * should_autocreate_reflog returns non-zero.  Otherwise, create it
2603 * regardless of the ref name.  Fill in *err and return -1 on failure.
2604 */
2605static int log_ref_setup(const char *refname, struct strbuf *logfile, struct strbuf *err, int force_create)
2606{
2607        int logfd, oflags = O_APPEND | O_WRONLY;
2608
2609        strbuf_git_path(logfile, "logs/%s", refname);
2610        if (force_create || should_autocreate_reflog(refname)) {
2611                if (safe_create_leading_directories(logfile->buf) < 0) {
2612                        strbuf_addf(err, "unable to create directory for %s: "
2613                                    "%s", logfile->buf, strerror(errno));
2614                        return -1;
2615                }
2616                oflags |= O_CREAT;
2617        }
2618
2619        logfd = open(logfile->buf, oflags, 0666);
2620        if (logfd < 0) {
2621                if (!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))
2622                        return 0;
2623
2624                if (errno == EISDIR) {
2625                        if (remove_empty_directories(logfile)) {
2626                                strbuf_addf(err, "There are still logs under "
2627                                            "'%s'", logfile->buf);
2628                                return -1;
2629                        }
2630                        logfd = open(logfile->buf, oflags, 0666);
2631                }
2632
2633                if (logfd < 0) {
2634                        strbuf_addf(err, "unable to append to %s: %s",
2635                                    logfile->buf, strerror(errno));
2636                        return -1;
2637                }
2638        }
2639
2640        adjust_shared_perm(logfile->buf);
2641        close(logfd);
2642        return 0;
2643}
2644
2645
2646int safe_create_reflog(const char *refname, int force_create, struct strbuf *err)
2647{
2648        int ret;
2649        struct strbuf sb = STRBUF_INIT;
2650
2651        ret = log_ref_setup(refname, &sb, err, force_create);
2652        strbuf_release(&sb);
2653        return ret;
2654}
2655
2656static int log_ref_write_fd(int fd, const unsigned char *old_sha1,
2657                            const unsigned char *new_sha1,
2658                            const char *committer, const char *msg)
2659{
2660        int msglen, written;
2661        unsigned maxlen, len;
2662        char *logrec;
2663
2664        msglen = msg ? strlen(msg) : 0;
2665        maxlen = strlen(committer) + msglen + 100;
2666        logrec = xmalloc(maxlen);
2667        len = xsnprintf(logrec, maxlen, "%s %s %s\n",
2668                        sha1_to_hex(old_sha1),
2669                        sha1_to_hex(new_sha1),
2670                        committer);
2671        if (msglen)
2672                len += copy_reflog_msg(logrec + len - 1, msg) - 1;
2673
2674        written = len <= maxlen ? write_in_full(fd, logrec, len) : -1;
2675        free(logrec);
2676        if (written != len)
2677                return -1;
2678
2679        return 0;
2680}
2681
2682static int log_ref_write_1(const char *refname, const unsigned char *old_sha1,
2683                           const unsigned char *new_sha1, const char *msg,
2684                           struct strbuf *logfile, int flags,
2685                           struct strbuf *err)
2686{
2687        int logfd, result, oflags = O_APPEND | O_WRONLY;
2688
2689        if (log_all_ref_updates < 0)
2690                log_all_ref_updates = !is_bare_repository();
2691
2692        result = log_ref_setup(refname, logfile, err, flags & REF_FORCE_CREATE_REFLOG);
2693
2694        if (result)
2695                return result;
2696
2697        logfd = open(logfile->buf, oflags);
2698        if (logfd < 0)
2699                return 0;
2700        result = log_ref_write_fd(logfd, old_sha1, new_sha1,
2701                                  git_committer_info(0), msg);
2702        if (result) {
2703                strbuf_addf(err, "unable to append to %s: %s", logfile->buf,
2704                            strerror(errno));
2705                close(logfd);
2706                return -1;
2707        }
2708        if (close(logfd)) {
2709                strbuf_addf(err, "unable to append to %s: %s", logfile->buf,
2710                            strerror(errno));
2711                return -1;
2712        }
2713        return 0;
2714}
2715
2716static int log_ref_write(const char *refname, const unsigned char *old_sha1,
2717                         const unsigned char *new_sha1, const char *msg,
2718                         int flags, struct strbuf *err)
2719{
2720        return files_log_ref_write(refname, old_sha1, new_sha1, msg, flags,
2721                                   err);
2722}
2723
2724int files_log_ref_write(const char *refname, const unsigned char *old_sha1,
2725                        const unsigned char *new_sha1, const char *msg,
2726                        int flags, struct strbuf *err)
2727{
2728        struct strbuf sb = STRBUF_INIT;
2729        int ret = log_ref_write_1(refname, old_sha1, new_sha1, msg, &sb, flags,
2730                                  err);
2731        strbuf_release(&sb);
2732        return ret;
2733}
2734
2735/*
2736 * Write sha1 into the open lockfile, then close the lockfile. On
2737 * errors, rollback the lockfile, fill in *err and
2738 * return -1.
2739 */
2740static int write_ref_to_lockfile(struct ref_lock *lock,
2741                                 const unsigned char *sha1, struct strbuf *err)
2742{
2743        static char term = '\n';
2744        struct object *o;
2745        int fd;
2746
2747        o = parse_object(sha1);
2748        if (!o) {
2749                strbuf_addf(err,
2750                            "Trying to write ref %s with nonexistent object %s",
2751                            lock->ref_name, sha1_to_hex(sha1));
2752                unlock_ref(lock);
2753                return -1;
2754        }
2755        if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
2756                strbuf_addf(err,
2757                            "Trying to write non-commit object %s to branch %s",
2758                            sha1_to_hex(sha1), lock->ref_name);
2759                unlock_ref(lock);
2760                return -1;
2761        }
2762        fd = get_lock_file_fd(lock->lk);
2763        if (write_in_full(fd, sha1_to_hex(sha1), 40) != 40 ||
2764            write_in_full(fd, &term, 1) != 1 ||
2765            close_ref(lock) < 0) {
2766                strbuf_addf(err,
2767                            "Couldn't write %s", get_lock_file_path(lock->lk));
2768                unlock_ref(lock);
2769                return -1;
2770        }
2771        return 0;
2772}
2773
2774/*
2775 * Commit a change to a loose reference that has already been written
2776 * to the loose reference lockfile. Also update the reflogs if
2777 * necessary, using the specified lockmsg (which can be NULL).
2778 */
2779static int commit_ref_update(struct ref_lock *lock,
2780                             const unsigned char *sha1, const char *logmsg,
2781                             int flags, struct strbuf *err)
2782{
2783        clear_loose_ref_cache(&ref_cache);
2784        if (log_ref_write(lock->ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) < 0 ||
2785            (strcmp(lock->ref_name, lock->orig_ref_name) &&
2786             log_ref_write(lock->orig_ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) < 0)) {
2787                char *old_msg = strbuf_detach(err, NULL);
2788                strbuf_addf(err, "Cannot update the ref '%s': %s",
2789                            lock->ref_name, old_msg);
2790                free(old_msg);
2791                unlock_ref(lock);
2792                return -1;
2793        }
2794        if (strcmp(lock->orig_ref_name, "HEAD") != 0) {
2795                /*
2796                 * Special hack: If a branch is updated directly and HEAD
2797                 * points to it (may happen on the remote side of a push
2798                 * for example) then logically the HEAD reflog should be
2799                 * updated too.
2800                 * A generic solution implies reverse symref information,
2801                 * but finding all symrefs pointing to the given branch
2802                 * would be rather costly for this rare event (the direct
2803                 * update of a branch) to be worth it.  So let's cheat and
2804                 * check with HEAD only which should cover 99% of all usage
2805                 * scenarios (even 100% of the default ones).
2806                 */
2807                unsigned char head_sha1[20];
2808                int head_flag;
2809                const char *head_ref;
2810                head_ref = resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
2811                                              head_sha1, &head_flag);
2812                if (head_ref && (head_flag & REF_ISSYMREF) &&
2813                    !strcmp(head_ref, lock->ref_name)) {
2814                        struct strbuf log_err = STRBUF_INIT;
2815                        if (log_ref_write("HEAD", lock->old_oid.hash, sha1,
2816                                          logmsg, 0, &log_err)) {
2817                                error("%s", log_err.buf);
2818                                strbuf_release(&log_err);
2819                        }
2820                }
2821        }
2822        if (commit_ref(lock)) {
2823                error("Couldn't set %s", lock->ref_name);
2824                unlock_ref(lock);
2825                return -1;
2826        }
2827
2828        unlock_ref(lock);
2829        return 0;
2830}
2831
2832int create_symref(const char *ref_target, const char *refs_heads_master,
2833                  const char *logmsg)
2834{
2835        char *lockpath = NULL;
2836        char ref[1000];
2837        int fd, len, written;
2838        char *git_HEAD = git_pathdup("%s", ref_target);
2839        unsigned char old_sha1[20], new_sha1[20];
2840        struct strbuf err = STRBUF_INIT;
2841
2842        if (logmsg && read_ref(ref_target, old_sha1))
2843                hashclr(old_sha1);
2844
2845        if (safe_create_leading_directories(git_HEAD) < 0)
2846                return error("unable to create directory for %s", git_HEAD);
2847
2848#ifndef NO_SYMLINK_HEAD
2849        if (prefer_symlink_refs) {
2850                unlink(git_HEAD);
2851                if (!symlink(refs_heads_master, git_HEAD))
2852                        goto done;
2853                fprintf(stderr, "no symlink - falling back to symbolic ref\n");
2854        }
2855#endif
2856
2857        len = snprintf(ref, sizeof(ref), "ref: %s\n", refs_heads_master);
2858        if (sizeof(ref) <= len) {
2859                error("refname too long: %s", refs_heads_master);
2860                goto error_free_return;
2861        }
2862        lockpath = mkpathdup("%s.lock", git_HEAD);
2863        fd = open(lockpath, O_CREAT | O_EXCL | O_WRONLY, 0666);
2864        if (fd < 0) {
2865                error("Unable to open %s for writing", lockpath);
2866                goto error_free_return;
2867        }
2868        written = write_in_full(fd, ref, len);
2869        if (close(fd) != 0 || written != len) {
2870                error("Unable to write to %s", lockpath);
2871                goto error_unlink_return;
2872        }
2873        if (rename(lockpath, git_HEAD) < 0) {
2874                error("Unable to create %s", git_HEAD);
2875                goto error_unlink_return;
2876        }
2877        if (adjust_shared_perm(git_HEAD)) {
2878                error("Unable to fix permissions on %s", lockpath);
2879        error_unlink_return:
2880                unlink_or_warn(lockpath);
2881        error_free_return:
2882                free(lockpath);
2883                free(git_HEAD);
2884                return -1;
2885        }
2886        free(lockpath);
2887
2888#ifndef NO_SYMLINK_HEAD
2889        done:
2890#endif
2891        if (logmsg && !read_ref(refs_heads_master, new_sha1) &&
2892                log_ref_write(ref_target, old_sha1, new_sha1, logmsg, 0, &err)) {
2893                error("%s", err.buf);
2894                strbuf_release(&err);
2895        }
2896
2897        free(git_HEAD);
2898        return 0;
2899}
2900
2901int reflog_exists(const char *refname)
2902{
2903        struct stat st;
2904
2905        return !lstat(git_path("logs/%s", refname), &st) &&
2906                S_ISREG(st.st_mode);
2907}
2908
2909int delete_reflog(const char *refname)
2910{
2911        return remove_path(git_path("logs/%s", refname));
2912}
2913
2914static int show_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn, void *cb_data)
2915{
2916        unsigned char osha1[20], nsha1[20];
2917        char *email_end, *message;
2918        unsigned long timestamp;
2919        int tz;
2920
2921        /* old SP new SP name <email> SP time TAB msg LF */
2922        if (sb->len < 83 || sb->buf[sb->len - 1] != '\n' ||
2923            get_sha1_hex(sb->buf, osha1) || sb->buf[40] != ' ' ||
2924            get_sha1_hex(sb->buf + 41, nsha1) || sb->buf[81] != ' ' ||
2925            !(email_end = strchr(sb->buf + 82, '>')) ||
2926            email_end[1] != ' ' ||
2927            !(timestamp = strtoul(email_end + 2, &message, 10)) ||
2928            !message || message[0] != ' ' ||
2929            (message[1] != '+' && message[1] != '-') ||
2930            !isdigit(message[2]) || !isdigit(message[3]) ||
2931            !isdigit(message[4]) || !isdigit(message[5]))
2932                return 0; /* corrupt? */
2933        email_end[1] = '\0';
2934        tz = strtol(message + 1, NULL, 10);
2935        if (message[6] != '\t')
2936                message += 6;
2937        else
2938                message += 7;
2939        return fn(osha1, nsha1, sb->buf + 82, timestamp, tz, message, cb_data);
2940}
2941
2942static char *find_beginning_of_line(char *bob, char *scan)
2943{
2944        while (bob < scan && *(--scan) != '\n')
2945                ; /* keep scanning backwards */
2946        /*
2947         * Return either beginning of the buffer, or LF at the end of
2948         * the previous line.
2949         */
2950        return scan;
2951}
2952
2953int for_each_reflog_ent_reverse(const char *refname, each_reflog_ent_fn fn, void *cb_data)
2954{
2955        struct strbuf sb = STRBUF_INIT;
2956        FILE *logfp;
2957        long pos;
2958        int ret = 0, at_tail = 1;
2959
2960        logfp = fopen(git_path("logs/%s", refname), "r");
2961        if (!logfp)
2962                return -1;
2963
2964        /* Jump to the end */
2965        if (fseek(logfp, 0, SEEK_END) < 0)
2966                return error("cannot seek back reflog for %s: %s",
2967                             refname, strerror(errno));
2968        pos = ftell(logfp);
2969        while (!ret && 0 < pos) {
2970                int cnt;
2971                size_t nread;
2972                char buf[BUFSIZ];
2973                char *endp, *scanp;
2974
2975                /* Fill next block from the end */
2976                cnt = (sizeof(buf) < pos) ? sizeof(buf) : pos;
2977                if (fseek(logfp, pos - cnt, SEEK_SET))
2978                        return error("cannot seek back reflog for %s: %s",
2979                                     refname, strerror(errno));
2980                nread = fread(buf, cnt, 1, logfp);
2981                if (nread != 1)
2982                        return error("cannot read %d bytes from reflog for %s: %s",
2983                                     cnt, refname, strerror(errno));
2984                pos -= cnt;
2985
2986                scanp = endp = buf + cnt;
2987                if (at_tail && scanp[-1] == '\n')
2988                        /* Looking at the final LF at the end of the file */
2989                        scanp--;
2990                at_tail = 0;
2991
2992                while (buf < scanp) {
2993                        /*
2994                         * terminating LF of the previous line, or the beginning
2995                         * of the buffer.
2996                         */
2997                        char *bp;
2998
2999                        bp = find_beginning_of_line(buf, scanp);
3000
3001                        if (*bp == '\n') {
3002                                /*
3003                                 * The newline is the end of the previous line,
3004                                 * so we know we have complete line starting
3005                                 * at (bp + 1). Prefix it onto any prior data
3006                                 * we collected for the line and process it.
3007                                 */
3008                                strbuf_splice(&sb, 0, 0, bp + 1, endp - (bp + 1));
3009                                scanp = bp;
3010                                endp = bp + 1;
3011                                ret = show_one_reflog_ent(&sb, fn, cb_data);
3012                                strbuf_reset(&sb);
3013                                if (ret)
3014                                        break;
3015                        } else if (!pos) {
3016                                /*
3017                                 * We are at the start of the buffer, and the
3018                                 * start of the file; there is no previous
3019                                 * line, and we have everything for this one.
3020                                 * Process it, and we can end the loop.
3021                                 */
3022                                strbuf_splice(&sb, 0, 0, buf, endp - buf);
3023                                ret = show_one_reflog_ent(&sb, fn, cb_data);
3024                                strbuf_reset(&sb);
3025                                break;
3026                        }
3027
3028                        if (bp == buf) {
3029                                /*
3030                                 * We are at the start of the buffer, and there
3031                                 * is more file to read backwards. Which means
3032                                 * we are in the middle of a line. Note that we
3033                                 * may get here even if *bp was a newline; that
3034                                 * just means we are at the exact end of the
3035                                 * previous line, rather than some spot in the
3036                                 * middle.
3037                                 *
3038                                 * Save away what we have to be combined with
3039                                 * the data from the next read.
3040                                 */
3041                                strbuf_splice(&sb, 0, 0, buf, endp - buf);
3042                                break;
3043                        }
3044                }
3045
3046        }
3047        if (!ret && sb.len)
3048                die("BUG: reverse reflog parser had leftover data");
3049
3050        fclose(logfp);
3051        strbuf_release(&sb);
3052        return ret;
3053}
3054
3055int for_each_reflog_ent(const char *refname, each_reflog_ent_fn fn, void *cb_data)
3056{
3057        FILE *logfp;
3058        struct strbuf sb = STRBUF_INIT;
3059        int ret = 0;
3060
3061        logfp = fopen(git_path("logs/%s", refname), "r");
3062        if (!logfp)
3063                return -1;
3064
3065        while (!ret && !strbuf_getwholeline(&sb, logfp, '\n'))
3066                ret = show_one_reflog_ent(&sb, fn, cb_data);
3067        fclose(logfp);
3068        strbuf_release(&sb);
3069        return ret;
3070}
3071/*
3072 * Call fn for each reflog in the namespace indicated by name.  name
3073 * must be empty or end with '/'.  Name will be used as a scratch
3074 * space, but its contents will be restored before return.
3075 */
3076static int do_for_each_reflog(struct strbuf *name, each_ref_fn fn, void *cb_data)
3077{
3078        DIR *d = opendir(git_path("logs/%s", name->buf));
3079        int retval = 0;
3080        struct dirent *de;
3081        int oldlen = name->len;
3082
3083        if (!d)
3084                return name->len ? errno : 0;
3085
3086        while ((de = readdir(d)) != NULL) {
3087                struct stat st;
3088
3089                if (de->d_name[0] == '.')
3090                        continue;
3091                if (ends_with(de->d_name, ".lock"))
3092                        continue;
3093                strbuf_addstr(name, de->d_name);
3094                if (stat(git_path("logs/%s", name->buf), &st) < 0) {
3095                        ; /* silently ignore */
3096                } else {
3097                        if (S_ISDIR(st.st_mode)) {
3098                                strbuf_addch(name, '/');
3099                                retval = do_for_each_reflog(name, fn, cb_data);
3100                        } else {
3101                                struct object_id oid;
3102
3103                                if (read_ref_full(name->buf, 0, oid.hash, NULL))
3104                                        retval = error("bad ref for %s", name->buf);
3105                                else
3106                                        retval = fn(name->buf, &oid, 0, cb_data);
3107                        }
3108                        if (retval)
3109                                break;
3110                }
3111                strbuf_setlen(name, oldlen);
3112        }
3113        closedir(d);
3114        return retval;
3115}
3116
3117int for_each_reflog(each_ref_fn fn, void *cb_data)
3118{
3119        int retval;
3120        struct strbuf name;
3121        strbuf_init(&name, PATH_MAX);
3122        retval = do_for_each_reflog(&name, fn, cb_data);
3123        strbuf_release(&name);
3124        return retval;
3125}
3126
3127static int ref_update_reject_duplicates(struct string_list *refnames,
3128                                        struct strbuf *err)
3129{
3130        int i, n = refnames->nr;
3131
3132        assert(err);
3133
3134        for (i = 1; i < n; i++)
3135                if (!strcmp(refnames->items[i - 1].string, refnames->items[i].string)) {
3136                        strbuf_addf(err,
3137                                    "Multiple updates for ref '%s' not allowed.",
3138                                    refnames->items[i].string);
3139                        return 1;
3140                }
3141        return 0;
3142}
3143
3144int ref_transaction_commit(struct ref_transaction *transaction,
3145                           struct strbuf *err)
3146{
3147        int ret = 0, i;
3148        int n = transaction->nr;
3149        struct ref_update **updates = transaction->updates;
3150        struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;
3151        struct string_list_item *ref_to_delete;
3152        struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
3153
3154        assert(err);
3155
3156        if (transaction->state != REF_TRANSACTION_OPEN)
3157                die("BUG: commit called for transaction that is not open");
3158
3159        if (!n) {
3160                transaction->state = REF_TRANSACTION_CLOSED;
3161                return 0;
3162        }
3163
3164        /* Fail if a refname appears more than once in the transaction: */
3165        for (i = 0; i < n; i++)
3166                string_list_append(&affected_refnames, updates[i]->refname);
3167        string_list_sort(&affected_refnames);
3168        if (ref_update_reject_duplicates(&affected_refnames, err)) {
3169                ret = TRANSACTION_GENERIC_ERROR;
3170                goto cleanup;
3171        }
3172
3173        /*
3174         * Acquire all locks, verify old values if provided, check
3175         * that new values are valid, and write new values to the
3176         * lockfiles, ready to be activated. Only keep one lockfile
3177         * open at a time to avoid running out of file descriptors.
3178         */
3179        for (i = 0; i < n; i++) {
3180                struct ref_update *update = updates[i];
3181
3182                if ((update->flags & REF_HAVE_NEW) &&
3183                    is_null_sha1(update->new_sha1))
3184                        update->flags |= REF_DELETING;
3185                update->lock = lock_ref_sha1_basic(
3186                                update->refname,
3187                                ((update->flags & REF_HAVE_OLD) ?
3188                                 update->old_sha1 : NULL),
3189                                &affected_refnames, NULL,
3190                                update->flags,
3191                                &update->type,
3192                                err);
3193                if (!update->lock) {
3194                        char *reason;
3195
3196                        ret = (errno == ENOTDIR)
3197                                ? TRANSACTION_NAME_CONFLICT
3198                                : TRANSACTION_GENERIC_ERROR;
3199                        reason = strbuf_detach(err, NULL);
3200                        strbuf_addf(err, "cannot lock ref '%s': %s",
3201                                    update->refname, reason);
3202                        free(reason);
3203                        goto cleanup;
3204                }
3205                if ((update->flags & REF_HAVE_NEW) &&
3206                    !(update->flags & REF_DELETING)) {
3207                        int overwriting_symref = ((update->type & REF_ISSYMREF) &&
3208                                                  (update->flags & REF_NODEREF));
3209
3210                        if (!overwriting_symref &&
3211                            !hashcmp(update->lock->old_oid.hash, update->new_sha1)) {
3212                                /*
3213                                 * The reference already has the desired
3214                                 * value, so we don't need to write it.
3215                                 */
3216                        } else if (write_ref_to_lockfile(update->lock,
3217                                                         update->new_sha1,
3218                                                         err)) {
3219                                char *write_err = strbuf_detach(err, NULL);
3220
3221                                /*
3222                                 * The lock was freed upon failure of
3223                                 * write_ref_to_lockfile():
3224                                 */
3225                                update->lock = NULL;
3226                                strbuf_addf(err,
3227                                            "cannot update the ref '%s': %s",
3228                                            update->refname, write_err);
3229                                free(write_err);
3230                                ret = TRANSACTION_GENERIC_ERROR;
3231                                goto cleanup;
3232                        } else {
3233                                update->flags |= REF_NEEDS_COMMIT;
3234                        }
3235                }
3236                if (!(update->flags & REF_NEEDS_COMMIT)) {
3237                        /*
3238                         * We didn't have to write anything to the lockfile.
3239                         * Close it to free up the file descriptor:
3240                         */
3241                        if (close_ref(update->lock)) {
3242                                strbuf_addf(err, "Couldn't close %s.lock",
3243                                            update->refname);
3244                                goto cleanup;
3245                        }
3246                }
3247        }
3248
3249        /* Perform updates first so live commits remain referenced */
3250        for (i = 0; i < n; i++) {
3251                struct ref_update *update = updates[i];
3252
3253                if (update->flags & REF_NEEDS_COMMIT) {
3254                        if (commit_ref_update(update->lock,
3255                                              update->new_sha1, update->msg,
3256                                              update->flags, err)) {
3257                                /* freed by commit_ref_update(): */
3258                                update->lock = NULL;
3259                                ret = TRANSACTION_GENERIC_ERROR;
3260                                goto cleanup;
3261                        } else {
3262                                /* freed by commit_ref_update(): */
3263                                update->lock = NULL;
3264                        }
3265                }
3266        }
3267
3268        /* Perform deletes now that updates are safely completed */
3269        for (i = 0; i < n; i++) {
3270                struct ref_update *update = updates[i];
3271
3272                if (update->flags & REF_DELETING) {
3273                        if (delete_ref_loose(update->lock, update->type, err)) {
3274                                ret = TRANSACTION_GENERIC_ERROR;
3275                                goto cleanup;
3276                        }
3277
3278                        if (!(update->flags & REF_ISPRUNING))
3279                                string_list_append(&refs_to_delete,
3280                                                   update->lock->ref_name);
3281                }
3282        }
3283
3284        if (repack_without_refs(&refs_to_delete, err)) {
3285                ret = TRANSACTION_GENERIC_ERROR;
3286                goto cleanup;
3287        }
3288        for_each_string_list_item(ref_to_delete, &refs_to_delete)
3289                unlink_or_warn(git_path("logs/%s", ref_to_delete->string));
3290        clear_loose_ref_cache(&ref_cache);
3291
3292cleanup:
3293        transaction->state = REF_TRANSACTION_CLOSED;
3294
3295        for (i = 0; i < n; i++)
3296                if (updates[i]->lock)
3297                        unlock_ref(updates[i]->lock);
3298        string_list_clear(&refs_to_delete, 0);
3299        string_list_clear(&affected_refnames, 0);
3300        return ret;
3301}
3302
3303static int ref_present(const char *refname,
3304                       const struct object_id *oid, int flags, void *cb_data)
3305{
3306        struct string_list *affected_refnames = cb_data;
3307
3308        return string_list_has_string(affected_refnames, refname);
3309}
3310
3311int initial_ref_transaction_commit(struct ref_transaction *transaction,
3312                                   struct strbuf *err)
3313{
3314        int ret = 0, i;
3315        int n = transaction->nr;
3316        struct ref_update **updates = transaction->updates;
3317        struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
3318
3319        assert(err);
3320
3321        if (transaction->state != REF_TRANSACTION_OPEN)
3322                die("BUG: commit called for transaction that is not open");
3323
3324        /* Fail if a refname appears more than once in the transaction: */
3325        for (i = 0; i < n; i++)
3326                string_list_append(&affected_refnames, updates[i]->refname);
3327        string_list_sort(&affected_refnames);
3328        if (ref_update_reject_duplicates(&affected_refnames, err)) {
3329                ret = TRANSACTION_GENERIC_ERROR;
3330                goto cleanup;
3331        }
3332
3333        /*
3334         * It's really undefined to call this function in an active
3335         * repository or when there are existing references: we are
3336         * only locking and changing packed-refs, so (1) any
3337         * simultaneous processes might try to change a reference at
3338         * the same time we do, and (2) any existing loose versions of
3339         * the references that we are setting would have precedence
3340         * over our values. But some remote helpers create the remote
3341         * "HEAD" and "master" branches before calling this function,
3342         * so here we really only check that none of the references
3343         * that we are creating already exists.
3344         */
3345        if (for_each_rawref(ref_present, &affected_refnames))
3346                die("BUG: initial ref transaction called with existing refs");
3347
3348        for (i = 0; i < n; i++) {
3349                struct ref_update *update = updates[i];
3350
3351                if ((update->flags & REF_HAVE_OLD) &&
3352                    !is_null_sha1(update->old_sha1))
3353                        die("BUG: initial ref transaction with old_sha1 set");
3354                if (verify_refname_available(update->refname,
3355                                             &affected_refnames, NULL,
3356                                             err)) {
3357                        ret = TRANSACTION_NAME_CONFLICT;
3358                        goto cleanup;
3359                }
3360        }
3361
3362        if (lock_packed_refs(0)) {
3363                strbuf_addf(err, "unable to lock packed-refs file: %s",
3364                            strerror(errno));
3365                ret = TRANSACTION_GENERIC_ERROR;
3366                goto cleanup;
3367        }
3368
3369        for (i = 0; i < n; i++) {
3370                struct ref_update *update = updates[i];
3371
3372                if ((update->flags & REF_HAVE_NEW) &&
3373                    !is_null_sha1(update->new_sha1))
3374                        add_packed_ref(update->refname, update->new_sha1);
3375        }
3376
3377        if (commit_packed_refs()) {
3378                strbuf_addf(err, "unable to commit packed-refs file: %s",
3379                            strerror(errno));
3380                ret = TRANSACTION_GENERIC_ERROR;
3381                goto cleanup;
3382        }
3383
3384cleanup:
3385        transaction->state = REF_TRANSACTION_CLOSED;
3386        string_list_clear(&affected_refnames, 0);
3387        return ret;
3388}
3389
3390struct expire_reflog_cb {
3391        unsigned int flags;
3392        reflog_expiry_should_prune_fn *should_prune_fn;
3393        void *policy_cb;
3394        FILE *newlog;
3395        unsigned char last_kept_sha1[20];
3396};
3397
3398static int expire_reflog_ent(unsigned char *osha1, unsigned char *nsha1,
3399                             const char *email, unsigned long timestamp, int tz,
3400                             const char *message, void *cb_data)
3401{
3402        struct expire_reflog_cb *cb = cb_data;
3403        struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;
3404
3405        if (cb->flags & EXPIRE_REFLOGS_REWRITE)
3406                osha1 = cb->last_kept_sha1;
3407
3408        if ((*cb->should_prune_fn)(osha1, nsha1, email, timestamp, tz,
3409                                   message, policy_cb)) {
3410                if (!cb->newlog)
3411                        printf("would prune %s", message);
3412                else if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
3413                        printf("prune %s", message);
3414        } else {
3415                if (cb->newlog) {
3416                        fprintf(cb->newlog, "%s %s %s %lu %+05d\t%s",
3417                                sha1_to_hex(osha1), sha1_to_hex(nsha1),
3418                                email, timestamp, tz, message);
3419                        hashcpy(cb->last_kept_sha1, nsha1);
3420                }
3421                if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
3422                        printf("keep %s", message);
3423        }
3424        return 0;
3425}
3426
3427int reflog_expire(const char *refname, const unsigned char *sha1,
3428                 unsigned int flags,
3429                 reflog_expiry_prepare_fn prepare_fn,
3430                 reflog_expiry_should_prune_fn should_prune_fn,
3431                 reflog_expiry_cleanup_fn cleanup_fn,
3432                 void *policy_cb_data)
3433{
3434        static struct lock_file reflog_lock;
3435        struct expire_reflog_cb cb;
3436        struct ref_lock *lock;
3437        char *log_file;
3438        int status = 0;
3439        int type;
3440        struct strbuf err = STRBUF_INIT;
3441
3442        memset(&cb, 0, sizeof(cb));
3443        cb.flags = flags;
3444        cb.policy_cb = policy_cb_data;
3445        cb.should_prune_fn = should_prune_fn;
3446
3447        /*
3448         * The reflog file is locked by holding the lock on the
3449         * reference itself, plus we might need to update the
3450         * reference if --updateref was specified:
3451         */
3452        lock = lock_ref_sha1_basic(refname, sha1, NULL, NULL, 0, &type, &err);
3453        if (!lock) {
3454                error("cannot lock ref '%s': %s", refname, err.buf);
3455                strbuf_release(&err);
3456                return -1;
3457        }
3458        if (!reflog_exists(refname)) {
3459                unlock_ref(lock);
3460                return 0;
3461        }
3462
3463        log_file = git_pathdup("logs/%s", refname);
3464        if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
3465                /*
3466                 * Even though holding $GIT_DIR/logs/$reflog.lock has
3467                 * no locking implications, we use the lock_file
3468                 * machinery here anyway because it does a lot of the
3469                 * work we need, including cleaning up if the program
3470                 * exits unexpectedly.
3471                 */
3472                if (hold_lock_file_for_update(&reflog_lock, log_file, 0) < 0) {
3473                        struct strbuf err = STRBUF_INIT;
3474                        unable_to_lock_message(log_file, errno, &err);
3475                        error("%s", err.buf);
3476                        strbuf_release(&err);
3477                        goto failure;
3478                }
3479                cb.newlog = fdopen_lock_file(&reflog_lock, "w");
3480                if (!cb.newlog) {
3481                        error("cannot fdopen %s (%s)",
3482                              get_lock_file_path(&reflog_lock), strerror(errno));
3483                        goto failure;
3484                }
3485        }
3486
3487        (*prepare_fn)(refname, sha1, cb.policy_cb);
3488        for_each_reflog_ent(refname, expire_reflog_ent, &cb);
3489        (*cleanup_fn)(cb.policy_cb);
3490
3491        if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
3492                /*
3493                 * It doesn't make sense to adjust a reference pointed
3494                 * to by a symbolic ref based on expiring entries in
3495                 * the symbolic reference's reflog. Nor can we update
3496                 * a reference if there are no remaining reflog
3497                 * entries.
3498                 */
3499                int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&
3500                        !(type & REF_ISSYMREF) &&
3501                        !is_null_sha1(cb.last_kept_sha1);
3502
3503                if (close_lock_file(&reflog_lock)) {
3504                        status |= error("couldn't write %s: %s", log_file,
3505                                        strerror(errno));
3506                } else if (update &&
3507                           (write_in_full(get_lock_file_fd(lock->lk),
3508                                sha1_to_hex(cb.last_kept_sha1), 40) != 40 ||
3509                            write_str_in_full(get_lock_file_fd(lock->lk), "\n") != 1 ||
3510                            close_ref(lock) < 0)) {
3511                        status |= error("couldn't write %s",
3512                                        get_lock_file_path(lock->lk));
3513                        rollback_lock_file(&reflog_lock);
3514                } else if (commit_lock_file(&reflog_lock)) {
3515                        status |= error("unable to write reflog '%s' (%s)",
3516                                        log_file, strerror(errno));
3517                } else if (update && commit_ref(lock)) {
3518                        status |= error("couldn't set %s", lock->ref_name);
3519                }
3520        }
3521        free(log_file);
3522        unlock_ref(lock);
3523        return status;
3524
3525 failure:
3526        rollback_lock_file(&reflog_lock);
3527        free(log_file);
3528        unlock_ref(lock);
3529        return -1;
3530}