a3d9210cb057bd64242a988a23e4aa5aad5730d5
   1#include "../cache.h"
   2#include "../config.h"
   3#include "../refs.h"
   4#include "refs-internal.h"
   5#include "ref-cache.h"
   6#include "packed-backend.h"
   7#include "../iterator.h"
   8#include "../lockfile.h"
   9
  10struct packed_ref_store;
  11
  12struct packed_ref_cache {
  13        /*
  14         * A back-pointer to the packed_ref_store with which this
  15         * cache is associated:
  16         */
  17        struct packed_ref_store *refs;
  18
  19        struct ref_cache *cache;
  20
  21        /*
  22         * Count of references to the data structure in this instance,
  23         * including the pointer from files_ref_store::packed if any.
  24         * The data will not be freed as long as the reference count
  25         * is nonzero.
  26         */
  27        unsigned int referrers;
  28
  29        /* The metadata from when this packed-refs cache was read */
  30        struct stat_validity validity;
  31};
  32
  33/*
  34 * Increment the reference count of *packed_refs.
  35 */
  36static void acquire_packed_ref_cache(struct packed_ref_cache *packed_refs)
  37{
  38        packed_refs->referrers++;
  39}
  40
  41/*
  42 * Decrease the reference count of *packed_refs.  If it goes to zero,
  43 * free *packed_refs and return true; otherwise return false.
  44 */
  45static int release_packed_ref_cache(struct packed_ref_cache *packed_refs)
  46{
  47        if (!--packed_refs->referrers) {
  48                free_ref_cache(packed_refs->cache);
  49                stat_validity_clear(&packed_refs->validity);
  50                free(packed_refs);
  51                return 1;
  52        } else {
  53                return 0;
  54        }
  55}
  56
  57/*
  58 * A container for `packed-refs`-related data. It is not (yet) a
  59 * `ref_store`.
  60 */
  61struct packed_ref_store {
  62        struct ref_store base;
  63
  64        unsigned int store_flags;
  65
  66        /* The path of the "packed-refs" file: */
  67        char *path;
  68
  69        /*
  70         * A cache of the values read from the `packed-refs` file, if
  71         * it might still be current; otherwise, NULL.
  72         */
  73        struct packed_ref_cache *cache;
  74
  75        /*
  76         * Lock used for the "packed-refs" file. Note that this (and
  77         * thus the enclosing `packed_ref_store`) must not be freed.
  78         */
  79        struct lock_file lock;
  80
  81        /*
  82         * Temporary file used when rewriting new contents to the
  83         * "packed-refs" file. Note that this (and thus the enclosing
  84         * `packed_ref_store`) must not be freed.
  85         */
  86        struct tempfile tempfile;
  87};
  88
  89struct ref_store *packed_ref_store_create(const char *path,
  90                                          unsigned int store_flags)
  91{
  92        struct packed_ref_store *refs = xcalloc(1, sizeof(*refs));
  93        struct ref_store *ref_store = (struct ref_store *)refs;
  94
  95        base_ref_store_init(ref_store, &refs_be_packed);
  96        refs->store_flags = store_flags;
  97
  98        refs->path = xstrdup(path);
  99        return ref_store;
 100}
 101
 102/*
 103 * Downcast `ref_store` to `packed_ref_store`. Die if `ref_store` is
 104 * not a `packed_ref_store`. Also die if `packed_ref_store` doesn't
 105 * support at least the flags specified in `required_flags`. `caller`
 106 * is used in any necessary error messages.
 107 */
 108static struct packed_ref_store *packed_downcast(struct ref_store *ref_store,
 109                                                unsigned int required_flags,
 110                                                const char *caller)
 111{
 112        struct packed_ref_store *refs;
 113
 114        if (ref_store->be != &refs_be_packed)
 115                die("BUG: ref_store is type \"%s\" not \"packed\" in %s",
 116                    ref_store->be->name, caller);
 117
 118        refs = (struct packed_ref_store *)ref_store;
 119
 120        if ((refs->store_flags & required_flags) != required_flags)
 121                die("BUG: unallowed operation (%s), requires %x, has %x\n",
 122                    caller, required_flags, refs->store_flags);
 123
 124        return refs;
 125}
 126
 127static void clear_packed_ref_cache(struct packed_ref_store *refs)
 128{
 129        if (refs->cache) {
 130                struct packed_ref_cache *cache = refs->cache;
 131
 132                refs->cache = NULL;
 133                release_packed_ref_cache(cache);
 134        }
 135}
 136
 137/* The length of a peeled reference line in packed-refs, including EOL: */
 138#define PEELED_LINE_LENGTH 42
 139
 140/*
 141 * Parse one line from a packed-refs file.  Write the SHA1 to sha1.
 142 * Return a pointer to the refname within the line (null-terminated),
 143 * or NULL if there was a problem.
 144 */
 145static const char *parse_ref_line(struct strbuf *line, struct object_id *oid)
 146{
 147        const char *ref;
 148
 149        if (parse_oid_hex(line->buf, oid, &ref) < 0)
 150                return NULL;
 151        if (!isspace(*ref++))
 152                return NULL;
 153
 154        if (isspace(*ref))
 155                return NULL;
 156
 157        if (line->buf[line->len - 1] != '\n')
 158                return NULL;
 159        line->buf[--line->len] = 0;
 160
 161        return ref;
 162}
 163
 164/*
 165 * Read from the `packed-refs` file into a newly-allocated
 166 * `packed_ref_cache` and return it. The return value will already
 167 * have its reference count incremented.
 168 *
 169 * A comment line of the form "# pack-refs with: " may contain zero or
 170 * more traits. We interpret the traits as follows:
 171 *
 172 *   No traits:
 173 *
 174 *      Probably no references are peeled. But if the file contains a
 175 *      peeled value for a reference, we will use it.
 176 *
 177 *   peeled:
 178 *
 179 *      References under "refs/tags/", if they *can* be peeled, *are*
 180 *      peeled in this file. References outside of "refs/tags/" are
 181 *      probably not peeled even if they could have been, but if we find
 182 *      a peeled value for such a reference we will use it.
 183 *
 184 *   fully-peeled:
 185 *
 186 *      All references in the file that can be peeled are peeled.
 187 *      Inversely (and this is more important), any references in the
 188 *      file for which no peeled value is recorded is not peelable. This
 189 *      trait should typically be written alongside "peeled" for
 190 *      compatibility with older clients, but we do not require it
 191 *      (i.e., "peeled" is a no-op if "fully-peeled" is set).
 192 */
 193static struct packed_ref_cache *read_packed_refs(struct packed_ref_store *refs)
 194{
 195        FILE *f;
 196        struct packed_ref_cache *packed_refs = xcalloc(1, sizeof(*packed_refs));
 197        struct ref_entry *last = NULL;
 198        struct strbuf line = STRBUF_INIT;
 199        enum { PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;
 200        struct ref_dir *dir;
 201
 202        packed_refs->refs = refs;
 203        acquire_packed_ref_cache(packed_refs);
 204        packed_refs->cache = create_ref_cache(NULL, NULL);
 205        packed_refs->cache->root->flag &= ~REF_INCOMPLETE;
 206
 207        f = fopen(refs->path, "r");
 208        if (!f) {
 209                if (errno == ENOENT) {
 210                        /*
 211                         * This is OK; it just means that no
 212                         * "packed-refs" file has been written yet,
 213                         * which is equivalent to it being empty.
 214                         */
 215                        return packed_refs;
 216                } else {
 217                        die_errno("couldn't read %s", refs->path);
 218                }
 219        }
 220
 221        stat_validity_update(&packed_refs->validity, fileno(f));
 222
 223        dir = get_ref_dir(packed_refs->cache->root);
 224        while (strbuf_getwholeline(&line, f, '\n') != EOF) {
 225                struct object_id oid;
 226                const char *refname;
 227                const char *traits;
 228
 229                if (!line.len || line.buf[line.len - 1] != '\n')
 230                        die("unterminated line in %s: %s", refs->path, line.buf);
 231
 232                if (skip_prefix(line.buf, "# pack-refs with:", &traits)) {
 233                        if (strstr(traits, " fully-peeled "))
 234                                peeled = PEELED_FULLY;
 235                        else if (strstr(traits, " peeled "))
 236                                peeled = PEELED_TAGS;
 237                        /* perhaps other traits later as well */
 238                        continue;
 239                }
 240
 241                refname = parse_ref_line(&line, &oid);
 242                if (refname) {
 243                        int flag = REF_ISPACKED;
 244
 245                        if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
 246                                if (!refname_is_safe(refname))
 247                                        die("packed refname is dangerous: %s", refname);
 248                                oidclr(&oid);
 249                                flag |= REF_BAD_NAME | REF_ISBROKEN;
 250                        }
 251                        last = create_ref_entry(refname, &oid, flag);
 252                        if (peeled == PEELED_FULLY ||
 253                            (peeled == PEELED_TAGS && starts_with(refname, "refs/tags/")))
 254                                last->flag |= REF_KNOWS_PEELED;
 255                        add_ref_entry(dir, last);
 256                } else if (last &&
 257                    line.buf[0] == '^' &&
 258                    line.len == PEELED_LINE_LENGTH &&
 259                    line.buf[PEELED_LINE_LENGTH - 1] == '\n' &&
 260                    !get_oid_hex(line.buf + 1, &oid)) {
 261                        oidcpy(&last->u.value.peeled, &oid);
 262                        /*
 263                         * Regardless of what the file header said,
 264                         * we definitely know the value of *this*
 265                         * reference:
 266                         */
 267                        last->flag |= REF_KNOWS_PEELED;
 268                } else {
 269                        strbuf_setlen(&line, line.len - 1);
 270                        die("unexpected line in %s: %s", refs->path, line.buf);
 271                }
 272        }
 273
 274        fclose(f);
 275        strbuf_release(&line);
 276
 277        return packed_refs;
 278}
 279
 280/*
 281 * Check that the packed refs cache (if any) still reflects the
 282 * contents of the file. If not, clear the cache.
 283 */
 284static void validate_packed_ref_cache(struct packed_ref_store *refs)
 285{
 286        if (refs->cache &&
 287            !stat_validity_check(&refs->cache->validity, refs->path))
 288                clear_packed_ref_cache(refs);
 289}
 290
 291/*
 292 * Get the packed_ref_cache for the specified packed_ref_store,
 293 * creating and populating it if it hasn't been read before or if the
 294 * file has been changed (according to its `validity` field) since it
 295 * was last read. On the other hand, if we hold the lock, then assume
 296 * that the file hasn't been changed out from under us, so skip the
 297 * extra `stat()` call in `stat_validity_check()`.
 298 */
 299static struct packed_ref_cache *get_packed_ref_cache(struct packed_ref_store *refs)
 300{
 301        if (!is_lock_file_locked(&refs->lock))
 302                validate_packed_ref_cache(refs);
 303
 304        if (!refs->cache)
 305                refs->cache = read_packed_refs(refs);
 306
 307        return refs->cache;
 308}
 309
 310static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)
 311{
 312        return get_ref_dir(packed_ref_cache->cache->root);
 313}
 314
 315static struct ref_dir *get_packed_refs(struct packed_ref_store *refs)
 316{
 317        return get_packed_ref_dir(get_packed_ref_cache(refs));
 318}
 319
 320/*
 321 * Return the ref_entry for the given refname from the packed
 322 * references.  If it does not exist, return NULL.
 323 */
 324static struct ref_entry *get_packed_ref(struct packed_ref_store *refs,
 325                                        const char *refname)
 326{
 327        return find_ref_entry(get_packed_refs(refs), refname);
 328}
 329
 330static int packed_read_raw_ref(struct ref_store *ref_store,
 331                               const char *refname, unsigned char *sha1,
 332                               struct strbuf *referent, unsigned int *type)
 333{
 334        struct packed_ref_store *refs =
 335                packed_downcast(ref_store, REF_STORE_READ, "read_raw_ref");
 336
 337        struct ref_entry *entry;
 338
 339        *type = 0;
 340
 341        entry = get_packed_ref(refs, refname);
 342        if (!entry) {
 343                errno = ENOENT;
 344                return -1;
 345        }
 346
 347        hashcpy(sha1, entry->u.value.oid.hash);
 348        *type = REF_ISPACKED;
 349        return 0;
 350}
 351
 352static int packed_peel_ref(struct ref_store *ref_store,
 353                           const char *refname, unsigned char *sha1)
 354{
 355        struct packed_ref_store *refs =
 356                packed_downcast(ref_store, REF_STORE_READ | REF_STORE_ODB,
 357                                "peel_ref");
 358        struct ref_entry *r = get_packed_ref(refs, refname);
 359
 360        if (!r || peel_entry(r, 0))
 361                return -1;
 362
 363        hashcpy(sha1, r->u.value.peeled.hash);
 364        return 0;
 365}
 366
 367struct packed_ref_iterator {
 368        struct ref_iterator base;
 369
 370        struct packed_ref_cache *cache;
 371        struct ref_iterator *iter0;
 372        unsigned int flags;
 373};
 374
 375static int packed_ref_iterator_advance(struct ref_iterator *ref_iterator)
 376{
 377        struct packed_ref_iterator *iter =
 378                (struct packed_ref_iterator *)ref_iterator;
 379        int ok;
 380
 381        while ((ok = ref_iterator_advance(iter->iter0)) == ITER_OK) {
 382                if (iter->flags & DO_FOR_EACH_PER_WORKTREE_ONLY &&
 383                    ref_type(iter->iter0->refname) != REF_TYPE_PER_WORKTREE)
 384                        continue;
 385
 386                if (!(iter->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&
 387                    !ref_resolves_to_object(iter->iter0->refname,
 388                                            iter->iter0->oid,
 389                                            iter->iter0->flags))
 390                        continue;
 391
 392                iter->base.refname = iter->iter0->refname;
 393                iter->base.oid = iter->iter0->oid;
 394                iter->base.flags = iter->iter0->flags;
 395                return ITER_OK;
 396        }
 397
 398        iter->iter0 = NULL;
 399        if (ref_iterator_abort(ref_iterator) != ITER_DONE)
 400                ok = ITER_ERROR;
 401
 402        return ok;
 403}
 404
 405static int packed_ref_iterator_peel(struct ref_iterator *ref_iterator,
 406                                   struct object_id *peeled)
 407{
 408        struct packed_ref_iterator *iter =
 409                (struct packed_ref_iterator *)ref_iterator;
 410
 411        return ref_iterator_peel(iter->iter0, peeled);
 412}
 413
 414static int packed_ref_iterator_abort(struct ref_iterator *ref_iterator)
 415{
 416        struct packed_ref_iterator *iter =
 417                (struct packed_ref_iterator *)ref_iterator;
 418        int ok = ITER_DONE;
 419
 420        if (iter->iter0)
 421                ok = ref_iterator_abort(iter->iter0);
 422
 423        release_packed_ref_cache(iter->cache);
 424        base_ref_iterator_free(ref_iterator);
 425        return ok;
 426}
 427
 428static struct ref_iterator_vtable packed_ref_iterator_vtable = {
 429        packed_ref_iterator_advance,
 430        packed_ref_iterator_peel,
 431        packed_ref_iterator_abort
 432};
 433
 434static struct ref_iterator *packed_ref_iterator_begin(
 435                struct ref_store *ref_store,
 436                const char *prefix, unsigned int flags)
 437{
 438        struct packed_ref_store *refs;
 439        struct packed_ref_iterator *iter;
 440        struct ref_iterator *ref_iterator;
 441        unsigned int required_flags = REF_STORE_READ;
 442
 443        if (!(flags & DO_FOR_EACH_INCLUDE_BROKEN))
 444                required_flags |= REF_STORE_ODB;
 445        refs = packed_downcast(ref_store, required_flags, "ref_iterator_begin");
 446
 447        iter = xcalloc(1, sizeof(*iter));
 448        ref_iterator = &iter->base;
 449        base_ref_iterator_init(ref_iterator, &packed_ref_iterator_vtable, 1);
 450
 451        /*
 452         * Note that get_packed_ref_cache() internally checks whether
 453         * the packed-ref cache is up to date with what is on disk,
 454         * and re-reads it if not.
 455         */
 456
 457        iter->cache = get_packed_ref_cache(refs);
 458        acquire_packed_ref_cache(iter->cache);
 459        iter->iter0 = cache_ref_iterator_begin(iter->cache->cache, prefix, 0);
 460
 461        iter->flags = flags;
 462
 463        return ref_iterator;
 464}
 465
 466/*
 467 * Write an entry to the packed-refs file for the specified refname.
 468 * If peeled is non-NULL, write it as the entry's peeled value. On
 469 * error, return a nonzero value and leave errno set at the value left
 470 * by the failing call to `fprintf()`.
 471 */
 472static int write_packed_entry(FILE *fh, const char *refname,
 473                              const unsigned char *sha1,
 474                              const unsigned char *peeled)
 475{
 476        if (fprintf(fh, "%s %s\n", sha1_to_hex(sha1), refname) < 0 ||
 477            (peeled && fprintf(fh, "^%s\n", sha1_to_hex(peeled)) < 0))
 478                return -1;
 479
 480        return 0;
 481}
 482
 483int packed_refs_lock(struct ref_store *ref_store, int flags, struct strbuf *err)
 484{
 485        struct packed_ref_store *refs =
 486                packed_downcast(ref_store, REF_STORE_WRITE | REF_STORE_MAIN,
 487                                "packed_refs_lock");
 488        static int timeout_configured = 0;
 489        static int timeout_value = 1000;
 490
 491        if (!timeout_configured) {
 492                git_config_get_int("core.packedrefstimeout", &timeout_value);
 493                timeout_configured = 1;
 494        }
 495
 496        /*
 497         * Note that we close the lockfile immediately because we
 498         * don't write new content to it, but rather to a separate
 499         * tempfile.
 500         */
 501        if (hold_lock_file_for_update_timeout(
 502                            &refs->lock,
 503                            refs->path,
 504                            flags, timeout_value) < 0) {
 505                unable_to_lock_message(refs->path, errno, err);
 506                return -1;
 507        }
 508
 509        if (close_lock_file(&refs->lock)) {
 510                strbuf_addf(err, "unable to close %s: %s", refs->path, strerror(errno));
 511                return -1;
 512        }
 513
 514        /*
 515         * Now that we hold the `packed-refs` lock, make sure that our
 516         * cache matches the current version of the file. Normally
 517         * `get_packed_ref_cache()` does that for us, but that
 518         * function assumes that when the file is locked, any existing
 519         * cache is still valid. We've just locked the file, but it
 520         * might have changed the moment *before* we locked it.
 521         */
 522        validate_packed_ref_cache(refs);
 523
 524        /*
 525         * Now make sure that the packed-refs file as it exists in the
 526         * locked state is loaded into the cache:
 527         */
 528        get_packed_ref_cache(refs);
 529        return 0;
 530}
 531
 532void packed_refs_unlock(struct ref_store *ref_store)
 533{
 534        struct packed_ref_store *refs = packed_downcast(
 535                        ref_store,
 536                        REF_STORE_READ | REF_STORE_WRITE,
 537                        "packed_refs_unlock");
 538
 539        if (!is_lock_file_locked(&refs->lock))
 540                die("BUG: packed_refs_unlock() called when not locked");
 541        rollback_lock_file(&refs->lock);
 542}
 543
 544int packed_refs_is_locked(struct ref_store *ref_store)
 545{
 546        struct packed_ref_store *refs = packed_downcast(
 547                        ref_store,
 548                        REF_STORE_READ | REF_STORE_WRITE,
 549                        "packed_refs_is_locked");
 550
 551        return is_lock_file_locked(&refs->lock);
 552}
 553
 554/*
 555 * The packed-refs header line that we write out.  Perhaps other
 556 * traits will be added later.  The trailing space is required.
 557 */
 558static const char PACKED_REFS_HEADER[] =
 559        "# pack-refs with: peeled fully-peeled \n";
 560
 561static int packed_init_db(struct ref_store *ref_store, struct strbuf *err)
 562{
 563        /* Nothing to do. */
 564        return 0;
 565}
 566
 567/*
 568 * Write the packed-refs from the cache to the packed-refs tempfile,
 569 * incorporating any changes from `updates`. `updates` must be a
 570 * sorted string list whose keys are the refnames and whose util
 571 * values are `struct ref_update *`. On error, rollback the tempfile,
 572 * write an error message to `err`, and return a nonzero value.
 573 *
 574 * The packfile must be locked before calling this function and will
 575 * remain locked when it is done.
 576 */
 577static int write_with_updates(struct packed_ref_store *refs,
 578                              struct string_list *updates,
 579                              struct strbuf *err)
 580{
 581        struct ref_iterator *iter = NULL;
 582        size_t i;
 583        int ok;
 584        FILE *out;
 585        struct strbuf sb = STRBUF_INIT;
 586        char *packed_refs_path;
 587
 588        if (!is_lock_file_locked(&refs->lock))
 589                die("BUG: write_with_updates() called while unlocked");
 590
 591        /*
 592         * If packed-refs is a symlink, we want to overwrite the
 593         * symlinked-to file, not the symlink itself. Also, put the
 594         * staging file next to it:
 595         */
 596        packed_refs_path = get_locked_file_path(&refs->lock);
 597        strbuf_addf(&sb, "%s.new", packed_refs_path);
 598        free(packed_refs_path);
 599        if (create_tempfile(&refs->tempfile, sb.buf) < 0) {
 600                strbuf_addf(err, "unable to create file %s: %s",
 601                            sb.buf, strerror(errno));
 602                strbuf_release(&sb);
 603                return -1;
 604        }
 605        strbuf_release(&sb);
 606
 607        out = fdopen_tempfile(&refs->tempfile, "w");
 608        if (!out) {
 609                strbuf_addf(err, "unable to fdopen packed-refs tempfile: %s",
 610                            strerror(errno));
 611                goto error;
 612        }
 613
 614        if (fprintf(out, "%s", PACKED_REFS_HEADER) < 0)
 615                goto write_error;
 616
 617        /*
 618         * We iterate in parallel through the current list of refs and
 619         * the list of updates, processing an entry from at least one
 620         * of the lists each time through the loop. When the current
 621         * list of refs is exhausted, set iter to NULL. When the list
 622         * of updates is exhausted, leave i set to updates->nr.
 623         */
 624        iter = packed_ref_iterator_begin(&refs->base, "",
 625                                         DO_FOR_EACH_INCLUDE_BROKEN);
 626        if ((ok = ref_iterator_advance(iter)) != ITER_OK)
 627                iter = NULL;
 628
 629        i = 0;
 630
 631        while (iter || i < updates->nr) {
 632                struct ref_update *update = NULL;
 633                int cmp;
 634
 635                if (i >= updates->nr) {
 636                        cmp = -1;
 637                } else {
 638                        update = updates->items[i].util;
 639
 640                        if (!iter)
 641                                cmp = +1;
 642                        else
 643                                cmp = strcmp(iter->refname, update->refname);
 644                }
 645
 646                if (!cmp) {
 647                        /*
 648                         * There is both an old value and an update
 649                         * for this reference. Check the old value if
 650                         * necessary:
 651                         */
 652                        if ((update->flags & REF_HAVE_OLD)) {
 653                                if (is_null_oid(&update->old_oid)) {
 654                                        strbuf_addf(err, "cannot update ref '%s': "
 655                                                    "reference already exists",
 656                                                    update->refname);
 657                                        goto error;
 658                                } else if (oidcmp(&update->old_oid, iter->oid)) {
 659                                        strbuf_addf(err, "cannot update ref '%s': "
 660                                                    "is at %s but expected %s",
 661                                                    update->refname,
 662                                                    oid_to_hex(iter->oid),
 663                                                    oid_to_hex(&update->old_oid));
 664                                        goto error;
 665                                }
 666                        }
 667
 668                        /* Now figure out what to use for the new value: */
 669                        if ((update->flags & REF_HAVE_NEW)) {
 670                                /*
 671                                 * The update takes precedence. Skip
 672                                 * the iterator over the unneeded
 673                                 * value.
 674                                 */
 675                                if ((ok = ref_iterator_advance(iter)) != ITER_OK)
 676                                        iter = NULL;
 677                                cmp = +1;
 678                        } else {
 679                                /*
 680                                 * The update doesn't actually want to
 681                                 * change anything. We're done with it.
 682                                 */
 683                                i++;
 684                                cmp = -1;
 685                        }
 686                } else if (cmp > 0) {
 687                        /*
 688                         * There is no old value but there is an
 689                         * update for this reference. Make sure that
 690                         * the update didn't expect an existing value:
 691                         */
 692                        if ((update->flags & REF_HAVE_OLD) &&
 693                            !is_null_oid(&update->old_oid)) {
 694                                strbuf_addf(err, "cannot update ref '%s': "
 695                                            "reference is missing but expected %s",
 696                                            update->refname,
 697                                            oid_to_hex(&update->old_oid));
 698                                goto error;
 699                        }
 700                }
 701
 702                if (cmp < 0) {
 703                        /* Pass the old reference through. */
 704
 705                        struct object_id peeled;
 706                        int peel_error = ref_iterator_peel(iter, &peeled);
 707
 708                        if (write_packed_entry(out, iter->refname,
 709                                               iter->oid->hash,
 710                                               peel_error ? NULL : peeled.hash))
 711                                goto write_error;
 712
 713                        if ((ok = ref_iterator_advance(iter)) != ITER_OK)
 714                                iter = NULL;
 715                } else if (is_null_oid(&update->new_oid)) {
 716                        /*
 717                         * The update wants to delete the reference,
 718                         * and the reference either didn't exist or we
 719                         * have already skipped it. So we're done with
 720                         * the update (and don't have to write
 721                         * anything).
 722                         */
 723                        i++;
 724                } else {
 725                        struct object_id peeled;
 726                        int peel_error = peel_object(update->new_oid.hash,
 727                                                     peeled.hash);
 728
 729                        if (write_packed_entry(out, update->refname,
 730                                               update->new_oid.hash,
 731                                               peel_error ? NULL : peeled.hash))
 732                                goto write_error;
 733
 734                        i++;
 735                }
 736        }
 737
 738        if (ok != ITER_DONE) {
 739                strbuf_addf(err, "unable to write packed-refs file: "
 740                            "error iterating over old contents");
 741                goto error;
 742        }
 743
 744        if (close_tempfile(&refs->tempfile)) {
 745                strbuf_addf(err, "error closing file %s: %s",
 746                            get_tempfile_path(&refs->tempfile),
 747                            strerror(errno));
 748                strbuf_release(&sb);
 749                return -1;
 750        }
 751
 752        return 0;
 753
 754write_error:
 755        strbuf_addf(err, "error writing to %s: %s",
 756                    get_tempfile_path(&refs->tempfile), strerror(errno));
 757
 758error:
 759        if (iter)
 760                ref_iterator_abort(iter);
 761
 762        delete_tempfile(&refs->tempfile);
 763        return -1;
 764}
 765
 766struct packed_transaction_backend_data {
 767        /* True iff the transaction owns the packed-refs lock. */
 768        int own_lock;
 769
 770        struct string_list updates;
 771};
 772
 773static void packed_transaction_cleanup(struct packed_ref_store *refs,
 774                                       struct ref_transaction *transaction)
 775{
 776        struct packed_transaction_backend_data *data = transaction->backend_data;
 777
 778        if (data) {
 779                string_list_clear(&data->updates, 0);
 780
 781                if (is_tempfile_active(&refs->tempfile))
 782                        delete_tempfile(&refs->tempfile);
 783
 784                if (data->own_lock && is_lock_file_locked(&refs->lock)) {
 785                        packed_refs_unlock(&refs->base);
 786                        data->own_lock = 0;
 787                }
 788
 789                free(data);
 790                transaction->backend_data = NULL;
 791        }
 792
 793        transaction->state = REF_TRANSACTION_CLOSED;
 794}
 795
 796static int packed_transaction_prepare(struct ref_store *ref_store,
 797                                      struct ref_transaction *transaction,
 798                                      struct strbuf *err)
 799{
 800        struct packed_ref_store *refs = packed_downcast(
 801                        ref_store,
 802                        REF_STORE_READ | REF_STORE_WRITE | REF_STORE_ODB,
 803                        "ref_transaction_prepare");
 804        struct packed_transaction_backend_data *data;
 805        size_t i;
 806        int ret = TRANSACTION_GENERIC_ERROR;
 807
 808        /*
 809         * Note that we *don't* skip transactions with zero updates,
 810         * because such a transaction might be executed for the side
 811         * effect of ensuring that all of the references are peeled.
 812         * If the caller wants to optimize away empty transactions, it
 813         * should do so itself.
 814         */
 815
 816        data = xcalloc(1, sizeof(*data));
 817        string_list_init(&data->updates, 0);
 818
 819        transaction->backend_data = data;
 820
 821        /*
 822         * Stick the updates in a string list by refname so that we
 823         * can sort them:
 824         */
 825        for (i = 0; i < transaction->nr; i++) {
 826                struct ref_update *update = transaction->updates[i];
 827                struct string_list_item *item =
 828                        string_list_append(&data->updates, update->refname);
 829
 830                /* Store a pointer to update in item->util: */
 831                item->util = update;
 832        }
 833        string_list_sort(&data->updates);
 834
 835        if (ref_update_reject_duplicates(&data->updates, err))
 836                goto failure;
 837
 838        if (!is_lock_file_locked(&refs->lock)) {
 839                if (packed_refs_lock(ref_store, 0, err))
 840                        goto failure;
 841                data->own_lock = 1;
 842        }
 843
 844        if (write_with_updates(refs, &data->updates, err))
 845                goto failure;
 846
 847        transaction->state = REF_TRANSACTION_PREPARED;
 848        return 0;
 849
 850failure:
 851        packed_transaction_cleanup(refs, transaction);
 852        return ret;
 853}
 854
 855static int packed_transaction_abort(struct ref_store *ref_store,
 856                                    struct ref_transaction *transaction,
 857                                    struct strbuf *err)
 858{
 859        struct packed_ref_store *refs = packed_downcast(
 860                        ref_store,
 861                        REF_STORE_READ | REF_STORE_WRITE | REF_STORE_ODB,
 862                        "ref_transaction_abort");
 863
 864        packed_transaction_cleanup(refs, transaction);
 865        return 0;
 866}
 867
 868static int packed_transaction_finish(struct ref_store *ref_store,
 869                                     struct ref_transaction *transaction,
 870                                     struct strbuf *err)
 871{
 872        struct packed_ref_store *refs = packed_downcast(
 873                        ref_store,
 874                        REF_STORE_READ | REF_STORE_WRITE | REF_STORE_ODB,
 875                        "ref_transaction_finish");
 876        int ret = TRANSACTION_GENERIC_ERROR;
 877        char *packed_refs_path;
 878
 879        packed_refs_path = get_locked_file_path(&refs->lock);
 880        if (rename_tempfile(&refs->tempfile, packed_refs_path)) {
 881                strbuf_addf(err, "error replacing %s: %s",
 882                            refs->path, strerror(errno));
 883                goto cleanup;
 884        }
 885
 886        clear_packed_ref_cache(refs);
 887        ret = 0;
 888
 889cleanup:
 890        free(packed_refs_path);
 891        packed_transaction_cleanup(refs, transaction);
 892        return ret;
 893}
 894
 895static int packed_initial_transaction_commit(struct ref_store *ref_store,
 896                                            struct ref_transaction *transaction,
 897                                            struct strbuf *err)
 898{
 899        return ref_transaction_commit(transaction, err);
 900}
 901
 902static int packed_delete_refs(struct ref_store *ref_store, const char *msg,
 903                             struct string_list *refnames, unsigned int flags)
 904{
 905        struct packed_ref_store *refs =
 906                packed_downcast(ref_store, REF_STORE_WRITE, "delete_refs");
 907        struct strbuf err = STRBUF_INIT;
 908        struct ref_transaction *transaction;
 909        struct string_list_item *item;
 910        int ret;
 911
 912        (void)refs; /* We need the check above, but don't use the variable */
 913
 914        if (!refnames->nr)
 915                return 0;
 916
 917        /*
 918         * Since we don't check the references' old_oids, the
 919         * individual updates can't fail, so we can pack all of the
 920         * updates into a single transaction.
 921         */
 922
 923        transaction = ref_store_transaction_begin(ref_store, &err);
 924        if (!transaction)
 925                return -1;
 926
 927        for_each_string_list_item(item, refnames) {
 928                if (ref_transaction_delete(transaction, item->string, NULL,
 929                                           flags, msg, &err)) {
 930                        warning(_("could not delete reference %s: %s"),
 931                                item->string, err.buf);
 932                        strbuf_reset(&err);
 933                }
 934        }
 935
 936        ret = ref_transaction_commit(transaction, &err);
 937
 938        if (ret) {
 939                if (refnames->nr == 1)
 940                        error(_("could not delete reference %s: %s"),
 941                              refnames->items[0].string, err.buf);
 942                else
 943                        error(_("could not delete references: %s"), err.buf);
 944        }
 945
 946        ref_transaction_free(transaction);
 947        strbuf_release(&err);
 948        return ret;
 949}
 950
 951static int packed_pack_refs(struct ref_store *ref_store, unsigned int flags)
 952{
 953        /*
 954         * Packed refs are already packed. It might be that loose refs
 955         * are packed *into* a packed refs store, but that is done by
 956         * updating the packed references via a transaction.
 957         */
 958        return 0;
 959}
 960
 961static int packed_create_symref(struct ref_store *ref_store,
 962                               const char *refname, const char *target,
 963                               const char *logmsg)
 964{
 965        die("BUG: packed reference store does not support symrefs");
 966}
 967
 968static int packed_rename_ref(struct ref_store *ref_store,
 969                            const char *oldrefname, const char *newrefname,
 970                            const char *logmsg)
 971{
 972        die("BUG: packed reference store does not support renaming references");
 973}
 974
 975static struct ref_iterator *packed_reflog_iterator_begin(struct ref_store *ref_store)
 976{
 977        return empty_ref_iterator_begin();
 978}
 979
 980static int packed_for_each_reflog_ent(struct ref_store *ref_store,
 981                                      const char *refname,
 982                                      each_reflog_ent_fn fn, void *cb_data)
 983{
 984        return 0;
 985}
 986
 987static int packed_for_each_reflog_ent_reverse(struct ref_store *ref_store,
 988                                              const char *refname,
 989                                              each_reflog_ent_fn fn,
 990                                              void *cb_data)
 991{
 992        return 0;
 993}
 994
 995static int packed_reflog_exists(struct ref_store *ref_store,
 996                               const char *refname)
 997{
 998        return 0;
 999}
1000
1001static int packed_create_reflog(struct ref_store *ref_store,
1002                               const char *refname, int force_create,
1003                               struct strbuf *err)
1004{
1005        die("BUG: packed reference store does not support reflogs");
1006}
1007
1008static int packed_delete_reflog(struct ref_store *ref_store,
1009                               const char *refname)
1010{
1011        return 0;
1012}
1013
1014static int packed_reflog_expire(struct ref_store *ref_store,
1015                                const char *refname, const unsigned char *sha1,
1016                                unsigned int flags,
1017                                reflog_expiry_prepare_fn prepare_fn,
1018                                reflog_expiry_should_prune_fn should_prune_fn,
1019                                reflog_expiry_cleanup_fn cleanup_fn,
1020                                void *policy_cb_data)
1021{
1022        return 0;
1023}
1024
1025struct ref_storage_be refs_be_packed = {
1026        NULL,
1027        "packed",
1028        packed_ref_store_create,
1029        packed_init_db,
1030        packed_transaction_prepare,
1031        packed_transaction_finish,
1032        packed_transaction_abort,
1033        packed_initial_transaction_commit,
1034
1035        packed_pack_refs,
1036        packed_peel_ref,
1037        packed_create_symref,
1038        packed_delete_refs,
1039        packed_rename_ref,
1040
1041        packed_ref_iterator_begin,
1042        packed_read_raw_ref,
1043
1044        packed_reflog_iterator_begin,
1045        packed_for_each_reflog_ent,
1046        packed_for_each_reflog_ent_reverse,
1047        packed_reflog_exists,
1048        packed_create_reflog,
1049        packed_delete_reflog,
1050        packed_reflog_expire
1051};