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