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