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