]> git.ipfire.org Git - thirdparty/git.git/blob - refs/packed-backend.c
Merge branch 'tz/lib-gpg-prereq-fix'
[thirdparty/git.git] / refs / packed-backend.c
1 #include "../cache.h"
2 #include "../alloc.h"
3 #include "../config.h"
4 #include "../gettext.h"
5 #include "../hash.h"
6 #include "../hex.h"
7 #include "../refs.h"
8 #include "refs-internal.h"
9 #include "packed-backend.h"
10 #include "../iterator.h"
11 #include "../lockfile.h"
12 #include "../chdir-notify.h"
13 #include "../wrapper.h"
14 #include "../write-or-die.h"
15
16 enum mmap_strategy {
17 /*
18 * Don't use mmap() at all for reading `packed-refs`.
19 */
20 MMAP_NONE,
21
22 /*
23 * Can use mmap() for reading `packed-refs`, but the file must
24 * not remain mmapped. This is the usual option on Windows,
25 * where you cannot rename a new version of a file onto a file
26 * that is currently mmapped.
27 */
28 MMAP_TEMPORARY,
29
30 /*
31 * It is OK to leave the `packed-refs` file mmapped while
32 * arbitrary other code is running.
33 */
34 MMAP_OK
35 };
36
37 #if defined(NO_MMAP)
38 static enum mmap_strategy mmap_strategy = MMAP_NONE;
39 #elif defined(MMAP_PREVENTS_DELETE)
40 static enum mmap_strategy mmap_strategy = MMAP_TEMPORARY;
41 #else
42 static enum mmap_strategy mmap_strategy = MMAP_OK;
43 #endif
44
45 struct packed_ref_store;
46
47 /*
48 * A `snapshot` represents one snapshot of a `packed-refs` file.
49 *
50 * Normally, this will be a mmapped view of the contents of the
51 * `packed-refs` file at the time the snapshot was created. However,
52 * if the `packed-refs` file was not sorted, this might point at heap
53 * memory holding the contents of the `packed-refs` file with its
54 * records sorted by refname.
55 *
56 * `snapshot` instances are reference counted (via
57 * `acquire_snapshot()` and `release_snapshot()`). This is to prevent
58 * an instance from disappearing while an iterator is still iterating
59 * over it. Instances are garbage collected when their `referrers`
60 * count goes to zero.
61 *
62 * The most recent `snapshot`, if available, is referenced by the
63 * `packed_ref_store`. Its freshness is checked whenever
64 * `get_snapshot()` is called; if the existing snapshot is obsolete, a
65 * new snapshot is taken.
66 */
67 struct snapshot {
68 /*
69 * A back-pointer to the packed_ref_store with which this
70 * snapshot is associated:
71 */
72 struct packed_ref_store *refs;
73
74 /* Is the `packed-refs` file currently mmapped? */
75 int mmapped;
76
77 /*
78 * The contents of the `packed-refs` file:
79 *
80 * - buf -- a pointer to the start of the memory
81 * - start -- a pointer to the first byte of actual references
82 * (i.e., after the header line, if one is present)
83 * - eof -- a pointer just past the end of the reference
84 * contents
85 *
86 * If the `packed-refs` file was already sorted, `buf` points
87 * at the mmapped contents of the file. If not, it points at
88 * heap-allocated memory containing the contents, sorted. If
89 * there were no contents (e.g., because the file didn't
90 * exist), `buf`, `start`, and `eof` are all NULL.
91 */
92 char *buf, *start, *eof;
93
94 /*
95 * What is the peeled state of the `packed-refs` file that
96 * this snapshot represents? (This is usually determined from
97 * the file's header.)
98 */
99 enum { PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled;
100
101 /*
102 * Count of references to this instance, including the pointer
103 * from `packed_ref_store::snapshot`, if any. The instance
104 * will not be freed as long as the reference count is
105 * nonzero.
106 */
107 unsigned int referrers;
108
109 /*
110 * The metadata of the `packed-refs` file from which this
111 * snapshot was created, used to tell if the file has been
112 * replaced since we read it.
113 */
114 struct stat_validity validity;
115 };
116
117 /*
118 * A `ref_store` representing references stored in a `packed-refs`
119 * file. It implements the `ref_store` interface, though it has some
120 * limitations:
121 *
122 * - It cannot store symbolic references.
123 *
124 * - It cannot store reflogs.
125 *
126 * - It does not support reference renaming (though it could).
127 *
128 * On the other hand, it can be locked outside of a reference
129 * transaction. In that case, it remains locked even after the
130 * transaction is done and the new `packed-refs` file is activated.
131 */
132 struct packed_ref_store {
133 struct ref_store base;
134
135 unsigned int store_flags;
136
137 /* The path of the "packed-refs" file: */
138 char *path;
139
140 /*
141 * A snapshot of the values read from the `packed-refs` file,
142 * if it might still be current; otherwise, NULL.
143 */
144 struct snapshot *snapshot;
145
146 /*
147 * Lock used for the "packed-refs" file. Note that this (and
148 * thus the enclosing `packed_ref_store`) must not be freed.
149 */
150 struct lock_file lock;
151
152 /*
153 * Temporary file used when rewriting new contents to the
154 * "packed-refs" file. Note that this (and thus the enclosing
155 * `packed_ref_store`) must not be freed.
156 */
157 struct tempfile *tempfile;
158 };
159
160 /*
161 * Increment the reference count of `*snapshot`.
162 */
163 static void acquire_snapshot(struct snapshot *snapshot)
164 {
165 snapshot->referrers++;
166 }
167
168 /*
169 * If the buffer in `snapshot` is active, then either munmap the
170 * memory and close the file, or free the memory. Then set the buffer
171 * pointers to NULL.
172 */
173 static void clear_snapshot_buffer(struct snapshot *snapshot)
174 {
175 if (snapshot->mmapped) {
176 if (munmap(snapshot->buf, snapshot->eof - snapshot->buf))
177 die_errno("error ummapping packed-refs file %s",
178 snapshot->refs->path);
179 snapshot->mmapped = 0;
180 } else {
181 free(snapshot->buf);
182 }
183 snapshot->buf = snapshot->start = snapshot->eof = NULL;
184 }
185
186 /*
187 * Decrease the reference count of `*snapshot`. If it goes to zero,
188 * free `*snapshot` and return true; otherwise return false.
189 */
190 static int release_snapshot(struct snapshot *snapshot)
191 {
192 if (!--snapshot->referrers) {
193 stat_validity_clear(&snapshot->validity);
194 clear_snapshot_buffer(snapshot);
195 free(snapshot);
196 return 1;
197 } else {
198 return 0;
199 }
200 }
201
202 struct ref_store *packed_ref_store_create(struct repository *repo,
203 const char *gitdir,
204 unsigned int store_flags)
205 {
206 struct packed_ref_store *refs = xcalloc(1, sizeof(*refs));
207 struct ref_store *ref_store = (struct ref_store *)refs;
208 struct strbuf sb = STRBUF_INIT;
209
210 base_ref_store_init(ref_store, repo, gitdir, &refs_be_packed);
211 refs->store_flags = store_flags;
212
213 strbuf_addf(&sb, "%s/packed-refs", gitdir);
214 refs->path = strbuf_detach(&sb, NULL);
215 chdir_notify_reparent("packed-refs", &refs->path);
216 return ref_store;
217 }
218
219 /*
220 * Downcast `ref_store` to `packed_ref_store`. Die if `ref_store` is
221 * not a `packed_ref_store`. Also die if `packed_ref_store` doesn't
222 * support at least the flags specified in `required_flags`. `caller`
223 * is used in any necessary error messages.
224 */
225 static struct packed_ref_store *packed_downcast(struct ref_store *ref_store,
226 unsigned int required_flags,
227 const char *caller)
228 {
229 struct packed_ref_store *refs;
230
231 if (ref_store->be != &refs_be_packed)
232 BUG("ref_store is type \"%s\" not \"packed\" in %s",
233 ref_store->be->name, caller);
234
235 refs = (struct packed_ref_store *)ref_store;
236
237 if ((refs->store_flags & required_flags) != required_flags)
238 BUG("unallowed operation (%s), requires %x, has %x\n",
239 caller, required_flags, refs->store_flags);
240
241 return refs;
242 }
243
244 static void clear_snapshot(struct packed_ref_store *refs)
245 {
246 if (refs->snapshot) {
247 struct snapshot *snapshot = refs->snapshot;
248
249 refs->snapshot = NULL;
250 release_snapshot(snapshot);
251 }
252 }
253
254 static NORETURN void die_unterminated_line(const char *path,
255 const char *p, size_t len)
256 {
257 if (len < 80)
258 die("unterminated line in %s: %.*s", path, (int)len, p);
259 else
260 die("unterminated line in %s: %.75s...", path, p);
261 }
262
263 static NORETURN void die_invalid_line(const char *path,
264 const char *p, size_t len)
265 {
266 const char *eol = memchr(p, '\n', len);
267
268 if (!eol)
269 die_unterminated_line(path, p, len);
270 else if (eol - p < 80)
271 die("unexpected line in %s: %.*s", path, (int)(eol - p), p);
272 else
273 die("unexpected line in %s: %.75s...", path, p);
274
275 }
276
277 struct snapshot_record {
278 const char *start;
279 size_t len;
280 };
281
282 static int cmp_packed_ref_records(const void *v1, const void *v2)
283 {
284 const struct snapshot_record *e1 = v1, *e2 = v2;
285 const char *r1 = e1->start + the_hash_algo->hexsz + 1;
286 const char *r2 = e2->start + the_hash_algo->hexsz + 1;
287
288 while (1) {
289 if (*r1 == '\n')
290 return *r2 == '\n' ? 0 : -1;
291 if (*r1 != *r2) {
292 if (*r2 == '\n')
293 return 1;
294 else
295 return (unsigned char)*r1 < (unsigned char)*r2 ? -1 : +1;
296 }
297 r1++;
298 r2++;
299 }
300 }
301
302 /*
303 * Compare a snapshot record at `rec` to the specified NUL-terminated
304 * refname.
305 */
306 static int cmp_record_to_refname(const char *rec, const char *refname)
307 {
308 const char *r1 = rec + the_hash_algo->hexsz + 1;
309 const char *r2 = refname;
310
311 while (1) {
312 if (*r1 == '\n')
313 return *r2 ? -1 : 0;
314 if (!*r2)
315 return 1;
316 if (*r1 != *r2)
317 return (unsigned char)*r1 < (unsigned char)*r2 ? -1 : +1;
318 r1++;
319 r2++;
320 }
321 }
322
323 /*
324 * `snapshot->buf` is not known to be sorted. Check whether it is, and
325 * if not, sort it into new memory and munmap/free the old storage.
326 */
327 static void sort_snapshot(struct snapshot *snapshot)
328 {
329 struct snapshot_record *records = NULL;
330 size_t alloc = 0, nr = 0;
331 int sorted = 1;
332 const char *pos, *eof, *eol;
333 size_t len, i;
334 char *new_buffer, *dst;
335
336 pos = snapshot->start;
337 eof = snapshot->eof;
338
339 if (pos == eof)
340 return;
341
342 len = eof - pos;
343
344 /*
345 * Initialize records based on a crude estimate of the number
346 * of references in the file (we'll grow it below if needed):
347 */
348 ALLOC_GROW(records, len / 80 + 20, alloc);
349
350 while (pos < eof) {
351 eol = memchr(pos, '\n', eof - pos);
352 if (!eol)
353 /* The safety check should prevent this. */
354 BUG("unterminated line found in packed-refs");
355 if (eol - pos < the_hash_algo->hexsz + 2)
356 die_invalid_line(snapshot->refs->path,
357 pos, eof - pos);
358 eol++;
359 if (eol < eof && *eol == '^') {
360 /*
361 * Keep any peeled line together with its
362 * reference:
363 */
364 const char *peeled_start = eol;
365
366 eol = memchr(peeled_start, '\n', eof - peeled_start);
367 if (!eol)
368 /* The safety check should prevent this. */
369 BUG("unterminated peeled line found in packed-refs");
370 eol++;
371 }
372
373 ALLOC_GROW(records, nr + 1, alloc);
374 records[nr].start = pos;
375 records[nr].len = eol - pos;
376 nr++;
377
378 if (sorted &&
379 nr > 1 &&
380 cmp_packed_ref_records(&records[nr - 2],
381 &records[nr - 1]) >= 0)
382 sorted = 0;
383
384 pos = eol;
385 }
386
387 if (sorted)
388 goto cleanup;
389
390 /* We need to sort the memory. First we sort the records array: */
391 QSORT(records, nr, cmp_packed_ref_records);
392
393 /*
394 * Allocate a new chunk of memory, and copy the old memory to
395 * the new in the order indicated by `records` (not bothering
396 * with the header line):
397 */
398 new_buffer = xmalloc(len);
399 for (dst = new_buffer, i = 0; i < nr; i++) {
400 memcpy(dst, records[i].start, records[i].len);
401 dst += records[i].len;
402 }
403
404 /*
405 * Now munmap the old buffer and use the sorted buffer in its
406 * place:
407 */
408 clear_snapshot_buffer(snapshot);
409 snapshot->buf = snapshot->start = new_buffer;
410 snapshot->eof = new_buffer + len;
411
412 cleanup:
413 free(records);
414 }
415
416 /*
417 * Return a pointer to the start of the record that contains the
418 * character `*p` (which must be within the buffer). If no other
419 * record start is found, return `buf`.
420 */
421 static const char *find_start_of_record(const char *buf, const char *p)
422 {
423 while (p > buf && (p[-1] != '\n' || p[0] == '^'))
424 p--;
425 return p;
426 }
427
428 /*
429 * Return a pointer to the start of the record following the record
430 * that contains `*p`. If none is found before `end`, return `end`.
431 */
432 static const char *find_end_of_record(const char *p, const char *end)
433 {
434 while (++p < end && (p[-1] != '\n' || p[0] == '^'))
435 ;
436 return p;
437 }
438
439 /*
440 * We want to be able to compare mmapped reference records quickly,
441 * without totally parsing them. We can do so because the records are
442 * LF-terminated, and the refname should start exactly (GIT_SHA1_HEXSZ
443 * + 1) bytes past the beginning of the record.
444 *
445 * But what if the `packed-refs` file contains garbage? We're willing
446 * to tolerate not detecting the problem, as long as we don't produce
447 * totally garbled output (we can't afford to check the integrity of
448 * the whole file during every Git invocation). But we do want to be
449 * sure that we never read past the end of the buffer in memory and
450 * perform an illegal memory access.
451 *
452 * Guarantee that minimum level of safety by verifying that the last
453 * record in the file is LF-terminated, and that it has at least
454 * (GIT_SHA1_HEXSZ + 1) characters before the LF. Die if either of
455 * these checks fails.
456 */
457 static void verify_buffer_safe(struct snapshot *snapshot)
458 {
459 const char *start = snapshot->start;
460 const char *eof = snapshot->eof;
461 const char *last_line;
462
463 if (start == eof)
464 return;
465
466 last_line = find_start_of_record(start, eof - 1);
467 if (*(eof - 1) != '\n' || eof - last_line < the_hash_algo->hexsz + 2)
468 die_invalid_line(snapshot->refs->path,
469 last_line, eof - last_line);
470 }
471
472 #define SMALL_FILE_SIZE (32*1024)
473
474 /*
475 * Depending on `mmap_strategy`, either mmap or read the contents of
476 * the `packed-refs` file into the snapshot. Return 1 if the file
477 * existed and was read, or 0 if the file was absent or empty. Die on
478 * errors.
479 */
480 static int load_contents(struct snapshot *snapshot)
481 {
482 int fd;
483 struct stat st;
484 size_t size;
485 ssize_t bytes_read;
486
487 fd = open(snapshot->refs->path, O_RDONLY);
488 if (fd < 0) {
489 if (errno == ENOENT) {
490 /*
491 * This is OK; it just means that no
492 * "packed-refs" file has been written yet,
493 * which is equivalent to it being empty,
494 * which is its state when initialized with
495 * zeros.
496 */
497 return 0;
498 } else {
499 die_errno("couldn't read %s", snapshot->refs->path);
500 }
501 }
502
503 stat_validity_update(&snapshot->validity, fd);
504
505 if (fstat(fd, &st) < 0)
506 die_errno("couldn't stat %s", snapshot->refs->path);
507 size = xsize_t(st.st_size);
508
509 if (!size) {
510 close(fd);
511 return 0;
512 } else if (mmap_strategy == MMAP_NONE || size <= SMALL_FILE_SIZE) {
513 snapshot->buf = xmalloc(size);
514 bytes_read = read_in_full(fd, snapshot->buf, size);
515 if (bytes_read < 0 || bytes_read != size)
516 die_errno("couldn't read %s", snapshot->refs->path);
517 snapshot->mmapped = 0;
518 } else {
519 snapshot->buf = xmmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
520 snapshot->mmapped = 1;
521 }
522 close(fd);
523
524 snapshot->start = snapshot->buf;
525 snapshot->eof = snapshot->buf + size;
526
527 return 1;
528 }
529
530 /*
531 * Find the place in `snapshot->buf` where the start of the record for
532 * `refname` starts. If `mustexist` is true and the reference doesn't
533 * exist, then return NULL. If `mustexist` is false and the reference
534 * doesn't exist, then return the point where that reference would be
535 * inserted, or `snapshot->eof` (which might be NULL) if it would be
536 * inserted at the end of the file. In the latter mode, `refname`
537 * doesn't have to be a proper reference name; for example, one could
538 * search for "refs/replace/" to find the start of any replace
539 * references.
540 *
541 * The record is sought using a binary search, so `snapshot->buf` must
542 * be sorted.
543 */
544 static const char *find_reference_location(struct snapshot *snapshot,
545 const char *refname, int mustexist)
546 {
547 /*
548 * This is not *quite* a garden-variety binary search, because
549 * the data we're searching is made up of records, and we
550 * always need to find the beginning of a record to do a
551 * comparison. A "record" here is one line for the reference
552 * itself and zero or one peel lines that start with '^'. Our
553 * loop invariant is described in the next two comments.
554 */
555
556 /*
557 * A pointer to the character at the start of a record whose
558 * preceding records all have reference names that come
559 * *before* `refname`.
560 */
561 const char *lo = snapshot->start;
562
563 /*
564 * A pointer to a the first character of a record whose
565 * reference name comes *after* `refname`.
566 */
567 const char *hi = snapshot->eof;
568
569 while (lo != hi) {
570 const char *mid, *rec;
571 int cmp;
572
573 mid = lo + (hi - lo) / 2;
574 rec = find_start_of_record(lo, mid);
575 cmp = cmp_record_to_refname(rec, refname);
576 if (cmp < 0) {
577 lo = find_end_of_record(mid, hi);
578 } else if (cmp > 0) {
579 hi = rec;
580 } else {
581 return rec;
582 }
583 }
584
585 if (mustexist)
586 return NULL;
587 else
588 return lo;
589 }
590
591 /*
592 * Create a newly-allocated `snapshot` of the `packed-refs` file in
593 * its current state and return it. The return value will already have
594 * its reference count incremented.
595 *
596 * A comment line of the form "# pack-refs with: " may contain zero or
597 * more traits. We interpret the traits as follows:
598 *
599 * Neither `peeled` nor `fully-peeled`:
600 *
601 * Probably no references are peeled. But if the file contains a
602 * peeled value for a reference, we will use it.
603 *
604 * `peeled`:
605 *
606 * References under "refs/tags/", if they *can* be peeled, *are*
607 * peeled in this file. References outside of "refs/tags/" are
608 * probably not peeled even if they could have been, but if we find
609 * a peeled value for such a reference we will use it.
610 *
611 * `fully-peeled`:
612 *
613 * All references in the file that can be peeled are peeled.
614 * Inversely (and this is more important), any references in the
615 * file for which no peeled value is recorded is not peelable. This
616 * trait should typically be written alongside "peeled" for
617 * compatibility with older clients, but we do not require it
618 * (i.e., "peeled" is a no-op if "fully-peeled" is set).
619 *
620 * `sorted`:
621 *
622 * The references in this file are known to be sorted by refname.
623 */
624 static struct snapshot *create_snapshot(struct packed_ref_store *refs)
625 {
626 struct snapshot *snapshot = xcalloc(1, sizeof(*snapshot));
627 int sorted = 0;
628
629 snapshot->refs = refs;
630 acquire_snapshot(snapshot);
631 snapshot->peeled = PEELED_NONE;
632
633 if (!load_contents(snapshot))
634 return snapshot;
635
636 /* If the file has a header line, process it: */
637 if (snapshot->buf < snapshot->eof && *snapshot->buf == '#') {
638 char *tmp, *p, *eol;
639 struct string_list traits = STRING_LIST_INIT_NODUP;
640
641 eol = memchr(snapshot->buf, '\n',
642 snapshot->eof - snapshot->buf);
643 if (!eol)
644 die_unterminated_line(refs->path,
645 snapshot->buf,
646 snapshot->eof - snapshot->buf);
647
648 tmp = xmemdupz(snapshot->buf, eol - snapshot->buf);
649
650 if (!skip_prefix(tmp, "# pack-refs with:", (const char **)&p))
651 die_invalid_line(refs->path,
652 snapshot->buf,
653 snapshot->eof - snapshot->buf);
654
655 string_list_split_in_place(&traits, p, " ", -1);
656
657 if (unsorted_string_list_has_string(&traits, "fully-peeled"))
658 snapshot->peeled = PEELED_FULLY;
659 else if (unsorted_string_list_has_string(&traits, "peeled"))
660 snapshot->peeled = PEELED_TAGS;
661
662 sorted = unsorted_string_list_has_string(&traits, "sorted");
663
664 /* perhaps other traits later as well */
665
666 /* The "+ 1" is for the LF character. */
667 snapshot->start = eol + 1;
668
669 string_list_clear(&traits, 0);
670 free(tmp);
671 }
672
673 verify_buffer_safe(snapshot);
674
675 if (!sorted) {
676 sort_snapshot(snapshot);
677
678 /*
679 * Reordering the records might have moved a short one
680 * to the end of the buffer, so verify the buffer's
681 * safety again:
682 */
683 verify_buffer_safe(snapshot);
684 }
685
686 if (mmap_strategy != MMAP_OK && snapshot->mmapped) {
687 /*
688 * We don't want to leave the file mmapped, so we are
689 * forced to make a copy now:
690 */
691 size_t size = snapshot->eof - snapshot->start;
692 char *buf_copy = xmalloc(size);
693
694 memcpy(buf_copy, snapshot->start, size);
695 clear_snapshot_buffer(snapshot);
696 snapshot->buf = snapshot->start = buf_copy;
697 snapshot->eof = buf_copy + size;
698 }
699
700 return snapshot;
701 }
702
703 /*
704 * Check that `refs->snapshot` (if present) still reflects the
705 * contents of the `packed-refs` file. If not, clear the snapshot.
706 */
707 static void validate_snapshot(struct packed_ref_store *refs)
708 {
709 if (refs->snapshot &&
710 !stat_validity_check(&refs->snapshot->validity, refs->path))
711 clear_snapshot(refs);
712 }
713
714 /*
715 * Get the `snapshot` for the specified packed_ref_store, creating and
716 * populating it if it hasn't been read before or if the file has been
717 * changed (according to its `validity` field) since it was last read.
718 * On the other hand, if we hold the lock, then assume that the file
719 * hasn't been changed out from under us, so skip the extra `stat()`
720 * call in `stat_validity_check()`. This function does *not* increase
721 * the snapshot's reference count on behalf of the caller.
722 */
723 static struct snapshot *get_snapshot(struct packed_ref_store *refs)
724 {
725 if (!is_lock_file_locked(&refs->lock))
726 validate_snapshot(refs);
727
728 if (!refs->snapshot)
729 refs->snapshot = create_snapshot(refs);
730
731 return refs->snapshot;
732 }
733
734 static int packed_read_raw_ref(struct ref_store *ref_store, const char *refname,
735 struct object_id *oid, struct strbuf *referent UNUSED,
736 unsigned int *type, int *failure_errno)
737 {
738 struct packed_ref_store *refs =
739 packed_downcast(ref_store, REF_STORE_READ, "read_raw_ref");
740 struct snapshot *snapshot = get_snapshot(refs);
741 const char *rec;
742
743 *type = 0;
744
745 rec = find_reference_location(snapshot, refname, 1);
746
747 if (!rec) {
748 /* refname is not a packed reference. */
749 *failure_errno = ENOENT;
750 return -1;
751 }
752
753 if (get_oid_hex(rec, oid))
754 die_invalid_line(refs->path, rec, snapshot->eof - rec);
755
756 *type = REF_ISPACKED;
757 return 0;
758 }
759
760 /*
761 * This value is set in `base.flags` if the peeled value of the
762 * current reference is known. In that case, `peeled` contains the
763 * correct peeled value for the reference, which might be `null_oid`
764 * if the reference is not a tag or if it is broken.
765 */
766 #define REF_KNOWS_PEELED 0x40
767
768 /*
769 * An iterator over a snapshot of a `packed-refs` file.
770 */
771 struct packed_ref_iterator {
772 struct ref_iterator base;
773
774 struct snapshot *snapshot;
775
776 /* The current position in the snapshot's buffer: */
777 const char *pos;
778
779 /* The end of the part of the buffer that will be iterated over: */
780 const char *eof;
781
782 /* Scratch space for current values: */
783 struct object_id oid, peeled;
784 struct strbuf refname_buf;
785
786 struct repository *repo;
787 unsigned int flags;
788 };
789
790 /*
791 * Move the iterator to the next record in the snapshot, without
792 * respect for whether the record is actually required by the current
793 * iteration. Adjust the fields in `iter` and return `ITER_OK` or
794 * `ITER_DONE`. This function does not free the iterator in the case
795 * of `ITER_DONE`.
796 */
797 static int next_record(struct packed_ref_iterator *iter)
798 {
799 const char *p = iter->pos, *eol;
800
801 strbuf_reset(&iter->refname_buf);
802
803 if (iter->pos == iter->eof)
804 return ITER_DONE;
805
806 iter->base.flags = REF_ISPACKED;
807
808 if (iter->eof - p < the_hash_algo->hexsz + 2 ||
809 parse_oid_hex(p, &iter->oid, &p) ||
810 !isspace(*p++))
811 die_invalid_line(iter->snapshot->refs->path,
812 iter->pos, iter->eof - iter->pos);
813
814 eol = memchr(p, '\n', iter->eof - p);
815 if (!eol)
816 die_unterminated_line(iter->snapshot->refs->path,
817 iter->pos, iter->eof - iter->pos);
818
819 strbuf_add(&iter->refname_buf, p, eol - p);
820 iter->base.refname = iter->refname_buf.buf;
821
822 if (check_refname_format(iter->base.refname, REFNAME_ALLOW_ONELEVEL)) {
823 if (!refname_is_safe(iter->base.refname))
824 die("packed refname is dangerous: %s",
825 iter->base.refname);
826 oidclr(&iter->oid);
827 iter->base.flags |= REF_BAD_NAME | REF_ISBROKEN;
828 }
829 if (iter->snapshot->peeled == PEELED_FULLY ||
830 (iter->snapshot->peeled == PEELED_TAGS &&
831 starts_with(iter->base.refname, "refs/tags/")))
832 iter->base.flags |= REF_KNOWS_PEELED;
833
834 iter->pos = eol + 1;
835
836 if (iter->pos < iter->eof && *iter->pos == '^') {
837 p = iter->pos + 1;
838 if (iter->eof - p < the_hash_algo->hexsz + 1 ||
839 parse_oid_hex(p, &iter->peeled, &p) ||
840 *p++ != '\n')
841 die_invalid_line(iter->snapshot->refs->path,
842 iter->pos, iter->eof - iter->pos);
843 iter->pos = p;
844
845 /*
846 * Regardless of what the file header said, we
847 * definitely know the value of *this* reference. But
848 * we suppress it if the reference is broken:
849 */
850 if ((iter->base.flags & REF_ISBROKEN)) {
851 oidclr(&iter->peeled);
852 iter->base.flags &= ~REF_KNOWS_PEELED;
853 } else {
854 iter->base.flags |= REF_KNOWS_PEELED;
855 }
856 } else {
857 oidclr(&iter->peeled);
858 }
859
860 return ITER_OK;
861 }
862
863 static int packed_ref_iterator_advance(struct ref_iterator *ref_iterator)
864 {
865 struct packed_ref_iterator *iter =
866 (struct packed_ref_iterator *)ref_iterator;
867 int ok;
868
869 while ((ok = next_record(iter)) == ITER_OK) {
870 if (iter->flags & DO_FOR_EACH_PER_WORKTREE_ONLY &&
871 !is_per_worktree_ref(iter->base.refname))
872 continue;
873
874 if (!(iter->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&
875 !ref_resolves_to_object(iter->base.refname, iter->repo,
876 &iter->oid, iter->flags))
877 continue;
878
879 return ITER_OK;
880 }
881
882 if (ref_iterator_abort(ref_iterator) != ITER_DONE)
883 ok = ITER_ERROR;
884
885 return ok;
886 }
887
888 static int packed_ref_iterator_peel(struct ref_iterator *ref_iterator,
889 struct object_id *peeled)
890 {
891 struct packed_ref_iterator *iter =
892 (struct packed_ref_iterator *)ref_iterator;
893
894 if (iter->repo != the_repository)
895 BUG("peeling for non-the_repository is not supported");
896
897 if ((iter->base.flags & REF_KNOWS_PEELED)) {
898 oidcpy(peeled, &iter->peeled);
899 return is_null_oid(&iter->peeled) ? -1 : 0;
900 } else if ((iter->base.flags & (REF_ISBROKEN | REF_ISSYMREF))) {
901 return -1;
902 } else {
903 return peel_object(&iter->oid, peeled) ? -1 : 0;
904 }
905 }
906
907 static int packed_ref_iterator_abort(struct ref_iterator *ref_iterator)
908 {
909 struct packed_ref_iterator *iter =
910 (struct packed_ref_iterator *)ref_iterator;
911 int ok = ITER_DONE;
912
913 strbuf_release(&iter->refname_buf);
914 release_snapshot(iter->snapshot);
915 base_ref_iterator_free(ref_iterator);
916 return ok;
917 }
918
919 static struct ref_iterator_vtable packed_ref_iterator_vtable = {
920 .advance = packed_ref_iterator_advance,
921 .peel = packed_ref_iterator_peel,
922 .abort = packed_ref_iterator_abort
923 };
924
925 static struct ref_iterator *packed_ref_iterator_begin(
926 struct ref_store *ref_store,
927 const char *prefix, unsigned int flags)
928 {
929 struct packed_ref_store *refs;
930 struct snapshot *snapshot;
931 const char *start;
932 struct packed_ref_iterator *iter;
933 struct ref_iterator *ref_iterator;
934 unsigned int required_flags = REF_STORE_READ;
935
936 if (!(flags & DO_FOR_EACH_INCLUDE_BROKEN))
937 required_flags |= REF_STORE_ODB;
938 refs = packed_downcast(ref_store, required_flags, "ref_iterator_begin");
939
940 /*
941 * Note that `get_snapshot()` internally checks whether the
942 * snapshot is up to date with what is on disk, and re-reads
943 * it if not.
944 */
945 snapshot = get_snapshot(refs);
946
947 if (prefix && *prefix)
948 start = find_reference_location(snapshot, prefix, 0);
949 else
950 start = snapshot->start;
951
952 if (start == snapshot->eof)
953 return empty_ref_iterator_begin();
954
955 CALLOC_ARRAY(iter, 1);
956 ref_iterator = &iter->base;
957 base_ref_iterator_init(ref_iterator, &packed_ref_iterator_vtable, 1);
958
959 iter->snapshot = snapshot;
960 acquire_snapshot(snapshot);
961
962 iter->pos = start;
963 iter->eof = snapshot->eof;
964 strbuf_init(&iter->refname_buf, 0);
965
966 iter->base.oid = &iter->oid;
967
968 iter->repo = ref_store->repo;
969 iter->flags = flags;
970
971 if (prefix && *prefix)
972 /* Stop iteration after we've gone *past* prefix: */
973 ref_iterator = prefix_ref_iterator_begin(ref_iterator, prefix, 0);
974
975 return ref_iterator;
976 }
977
978 /*
979 * Write an entry to the packed-refs file for the specified refname.
980 * If peeled is non-NULL, write it as the entry's peeled value. On
981 * error, return a nonzero value and leave errno set at the value left
982 * by the failing call to `fprintf()`.
983 */
984 static int write_packed_entry(FILE *fh, const char *refname,
985 const struct object_id *oid,
986 const struct object_id *peeled)
987 {
988 if (fprintf(fh, "%s %s\n", oid_to_hex(oid), refname) < 0 ||
989 (peeled && fprintf(fh, "^%s\n", oid_to_hex(peeled)) < 0))
990 return -1;
991
992 return 0;
993 }
994
995 int packed_refs_lock(struct ref_store *ref_store, int flags, struct strbuf *err)
996 {
997 struct packed_ref_store *refs =
998 packed_downcast(ref_store, REF_STORE_WRITE | REF_STORE_MAIN,
999 "packed_refs_lock");
1000 static int timeout_configured = 0;
1001 static int timeout_value = 1000;
1002
1003 if (!timeout_configured) {
1004 git_config_get_int("core.packedrefstimeout", &timeout_value);
1005 timeout_configured = 1;
1006 }
1007
1008 /*
1009 * Note that we close the lockfile immediately because we
1010 * don't write new content to it, but rather to a separate
1011 * tempfile.
1012 */
1013 if (hold_lock_file_for_update_timeout(
1014 &refs->lock,
1015 refs->path,
1016 flags, timeout_value) < 0) {
1017 unable_to_lock_message(refs->path, errno, err);
1018 return -1;
1019 }
1020
1021 if (close_lock_file_gently(&refs->lock)) {
1022 strbuf_addf(err, "unable to close %s: %s", refs->path, strerror(errno));
1023 rollback_lock_file(&refs->lock);
1024 return -1;
1025 }
1026
1027 /*
1028 * There is a stat-validity problem might cause `update-ref -d`
1029 * lost the newly commit of a ref, because a new `packed-refs`
1030 * file might has the same on-disk file attributes such as
1031 * timestamp, file size and inode value, but has a changed
1032 * ref value.
1033 *
1034 * This could happen with a very small chance when
1035 * `update-ref -d` is called and at the same time another
1036 * `pack-refs --all` process is running.
1037 *
1038 * Now that we hold the `packed-refs` lock, it is important
1039 * to make sure we could read the latest version of
1040 * `packed-refs` file no matter we have just mmap it or not.
1041 * So what need to do is clear the snapshot if we hold it
1042 * already.
1043 */
1044 clear_snapshot(refs);
1045
1046 /*
1047 * Now make sure that the packed-refs file as it exists in the
1048 * locked state is loaded into the snapshot:
1049 */
1050 get_snapshot(refs);
1051 return 0;
1052 }
1053
1054 void packed_refs_unlock(struct ref_store *ref_store)
1055 {
1056 struct packed_ref_store *refs = packed_downcast(
1057 ref_store,
1058 REF_STORE_READ | REF_STORE_WRITE,
1059 "packed_refs_unlock");
1060
1061 if (!is_lock_file_locked(&refs->lock))
1062 BUG("packed_refs_unlock() called when not locked");
1063 rollback_lock_file(&refs->lock);
1064 }
1065
1066 int packed_refs_is_locked(struct ref_store *ref_store)
1067 {
1068 struct packed_ref_store *refs = packed_downcast(
1069 ref_store,
1070 REF_STORE_READ | REF_STORE_WRITE,
1071 "packed_refs_is_locked");
1072
1073 return is_lock_file_locked(&refs->lock);
1074 }
1075
1076 /*
1077 * The packed-refs header line that we write out. Perhaps other traits
1078 * will be added later.
1079 *
1080 * Note that earlier versions of Git used to parse these traits by
1081 * looking for " trait " in the line. For this reason, the space after
1082 * the colon and the trailing space are required.
1083 */
1084 static const char PACKED_REFS_HEADER[] =
1085 "# pack-refs with: peeled fully-peeled sorted \n";
1086
1087 static int packed_init_db(struct ref_store *ref_store UNUSED,
1088 struct strbuf *err UNUSED)
1089 {
1090 /* Nothing to do. */
1091 return 0;
1092 }
1093
1094 /*
1095 * Write the packed refs from the current snapshot to the packed-refs
1096 * tempfile, incorporating any changes from `updates`. `updates` must
1097 * be a sorted string list whose keys are the refnames and whose util
1098 * values are `struct ref_update *`. On error, rollback the tempfile,
1099 * write an error message to `err`, and return a nonzero value.
1100 *
1101 * The packfile must be locked before calling this function and will
1102 * remain locked when it is done.
1103 */
1104 static int write_with_updates(struct packed_ref_store *refs,
1105 struct string_list *updates,
1106 struct strbuf *err)
1107 {
1108 struct ref_iterator *iter = NULL;
1109 size_t i;
1110 int ok;
1111 FILE *out;
1112 struct strbuf sb = STRBUF_INIT;
1113 char *packed_refs_path;
1114
1115 if (!is_lock_file_locked(&refs->lock))
1116 BUG("write_with_updates() called while unlocked");
1117
1118 /*
1119 * If packed-refs is a symlink, we want to overwrite the
1120 * symlinked-to file, not the symlink itself. Also, put the
1121 * staging file next to it:
1122 */
1123 packed_refs_path = get_locked_file_path(&refs->lock);
1124 strbuf_addf(&sb, "%s.new", packed_refs_path);
1125 free(packed_refs_path);
1126 refs->tempfile = create_tempfile(sb.buf);
1127 if (!refs->tempfile) {
1128 strbuf_addf(err, "unable to create file %s: %s",
1129 sb.buf, strerror(errno));
1130 strbuf_release(&sb);
1131 return -1;
1132 }
1133 strbuf_release(&sb);
1134
1135 out = fdopen_tempfile(refs->tempfile, "w");
1136 if (!out) {
1137 strbuf_addf(err, "unable to fdopen packed-refs tempfile: %s",
1138 strerror(errno));
1139 goto error;
1140 }
1141
1142 if (fprintf(out, "%s", PACKED_REFS_HEADER) < 0)
1143 goto write_error;
1144
1145 /*
1146 * We iterate in parallel through the current list of refs and
1147 * the list of updates, processing an entry from at least one
1148 * of the lists each time through the loop. When the current
1149 * list of refs is exhausted, set iter to NULL. When the list
1150 * of updates is exhausted, leave i set to updates->nr.
1151 */
1152 iter = packed_ref_iterator_begin(&refs->base, "",
1153 DO_FOR_EACH_INCLUDE_BROKEN);
1154 if ((ok = ref_iterator_advance(iter)) != ITER_OK)
1155 iter = NULL;
1156
1157 i = 0;
1158
1159 while (iter || i < updates->nr) {
1160 struct ref_update *update = NULL;
1161 int cmp;
1162
1163 if (i >= updates->nr) {
1164 cmp = -1;
1165 } else {
1166 update = updates->items[i].util;
1167
1168 if (!iter)
1169 cmp = +1;
1170 else
1171 cmp = strcmp(iter->refname, update->refname);
1172 }
1173
1174 if (!cmp) {
1175 /*
1176 * There is both an old value and an update
1177 * for this reference. Check the old value if
1178 * necessary:
1179 */
1180 if ((update->flags & REF_HAVE_OLD)) {
1181 if (is_null_oid(&update->old_oid)) {
1182 strbuf_addf(err, "cannot update ref '%s': "
1183 "reference already exists",
1184 update->refname);
1185 goto error;
1186 } else if (!oideq(&update->old_oid, iter->oid)) {
1187 strbuf_addf(err, "cannot update ref '%s': "
1188 "is at %s but expected %s",
1189 update->refname,
1190 oid_to_hex(iter->oid),
1191 oid_to_hex(&update->old_oid));
1192 goto error;
1193 }
1194 }
1195
1196 /* Now figure out what to use for the new value: */
1197 if ((update->flags & REF_HAVE_NEW)) {
1198 /*
1199 * The update takes precedence. Skip
1200 * the iterator over the unneeded
1201 * value.
1202 */
1203 if ((ok = ref_iterator_advance(iter)) != ITER_OK)
1204 iter = NULL;
1205 cmp = +1;
1206 } else {
1207 /*
1208 * The update doesn't actually want to
1209 * change anything. We're done with it.
1210 */
1211 i++;
1212 cmp = -1;
1213 }
1214 } else if (cmp > 0) {
1215 /*
1216 * There is no old value but there is an
1217 * update for this reference. Make sure that
1218 * the update didn't expect an existing value:
1219 */
1220 if ((update->flags & REF_HAVE_OLD) &&
1221 !is_null_oid(&update->old_oid)) {
1222 strbuf_addf(err, "cannot update ref '%s': "
1223 "reference is missing but expected %s",
1224 update->refname,
1225 oid_to_hex(&update->old_oid));
1226 goto error;
1227 }
1228 }
1229
1230 if (cmp < 0) {
1231 /* Pass the old reference through. */
1232
1233 struct object_id peeled;
1234 int peel_error = ref_iterator_peel(iter, &peeled);
1235
1236 if (write_packed_entry(out, iter->refname,
1237 iter->oid,
1238 peel_error ? NULL : &peeled))
1239 goto write_error;
1240
1241 if ((ok = ref_iterator_advance(iter)) != ITER_OK)
1242 iter = NULL;
1243 } else if (is_null_oid(&update->new_oid)) {
1244 /*
1245 * The update wants to delete the reference,
1246 * and the reference either didn't exist or we
1247 * have already skipped it. So we're done with
1248 * the update (and don't have to write
1249 * anything).
1250 */
1251 i++;
1252 } else {
1253 struct object_id peeled;
1254 int peel_error = peel_object(&update->new_oid,
1255 &peeled);
1256
1257 if (write_packed_entry(out, update->refname,
1258 &update->new_oid,
1259 peel_error ? NULL : &peeled))
1260 goto write_error;
1261
1262 i++;
1263 }
1264 }
1265
1266 if (ok != ITER_DONE) {
1267 strbuf_addstr(err, "unable to write packed-refs file: "
1268 "error iterating over old contents");
1269 goto error;
1270 }
1271
1272 if (fflush(out) ||
1273 fsync_component(FSYNC_COMPONENT_REFERENCE, get_tempfile_fd(refs->tempfile)) ||
1274 close_tempfile_gently(refs->tempfile)) {
1275 strbuf_addf(err, "error closing file %s: %s",
1276 get_tempfile_path(refs->tempfile),
1277 strerror(errno));
1278 strbuf_release(&sb);
1279 delete_tempfile(&refs->tempfile);
1280 return -1;
1281 }
1282
1283 return 0;
1284
1285 write_error:
1286 strbuf_addf(err, "error writing to %s: %s",
1287 get_tempfile_path(refs->tempfile), strerror(errno));
1288
1289 error:
1290 if (iter)
1291 ref_iterator_abort(iter);
1292
1293 delete_tempfile(&refs->tempfile);
1294 return -1;
1295 }
1296
1297 int is_packed_transaction_needed(struct ref_store *ref_store,
1298 struct ref_transaction *transaction)
1299 {
1300 struct packed_ref_store *refs = packed_downcast(
1301 ref_store,
1302 REF_STORE_READ,
1303 "is_packed_transaction_needed");
1304 struct strbuf referent = STRBUF_INIT;
1305 size_t i;
1306 int ret;
1307
1308 if (!is_lock_file_locked(&refs->lock))
1309 BUG("is_packed_transaction_needed() called while unlocked");
1310
1311 /*
1312 * We're only going to bother returning false for the common,
1313 * trivial case that references are only being deleted, their
1314 * old values are not being checked, and the old `packed-refs`
1315 * file doesn't contain any of those reference(s). This gives
1316 * false positives for some other cases that could
1317 * theoretically be optimized away:
1318 *
1319 * 1. It could be that the old value is being verified without
1320 * setting a new value. In this case, we could verify the
1321 * old value here and skip the update if it agrees. If it
1322 * disagrees, we could either let the update go through
1323 * (the actual commit would re-detect and report the
1324 * problem), or come up with a way of reporting such an
1325 * error to *our* caller.
1326 *
1327 * 2. It could be that a new value is being set, but that it
1328 * is identical to the current packed value of the
1329 * reference.
1330 *
1331 * Neither of these cases will come up in the current code,
1332 * because the only caller of this function passes to it a
1333 * transaction that only includes `delete` updates with no
1334 * `old_id`. Even if that ever changes, false positives only
1335 * cause an optimization to be missed; they do not affect
1336 * correctness.
1337 */
1338
1339 /*
1340 * Start with the cheap checks that don't require old
1341 * reference values to be read:
1342 */
1343 for (i = 0; i < transaction->nr; i++) {
1344 struct ref_update *update = transaction->updates[i];
1345
1346 if (update->flags & REF_HAVE_OLD)
1347 /* Have to check the old value -> needed. */
1348 return 1;
1349
1350 if ((update->flags & REF_HAVE_NEW) && !is_null_oid(&update->new_oid))
1351 /* Have to set a new value -> needed. */
1352 return 1;
1353 }
1354
1355 /*
1356 * The transaction isn't checking any old values nor is it
1357 * setting any nonzero new values, so it still might be able
1358 * to be skipped. Now do the more expensive check: the update
1359 * is needed if any of the updates is a delete, and the old
1360 * `packed-refs` file contains a value for that reference.
1361 */
1362 ret = 0;
1363 for (i = 0; i < transaction->nr; i++) {
1364 struct ref_update *update = transaction->updates[i];
1365 int failure_errno;
1366 unsigned int type;
1367 struct object_id oid;
1368
1369 if (!(update->flags & REF_HAVE_NEW))
1370 /*
1371 * This reference isn't being deleted -> not
1372 * needed.
1373 */
1374 continue;
1375
1376 if (!refs_read_raw_ref(ref_store, update->refname, &oid,
1377 &referent, &type, &failure_errno) ||
1378 failure_errno != ENOENT) {
1379 /*
1380 * We have to actually delete that reference
1381 * -> this transaction is needed.
1382 */
1383 ret = 1;
1384 break;
1385 }
1386 }
1387
1388 strbuf_release(&referent);
1389 return ret;
1390 }
1391
1392 struct packed_transaction_backend_data {
1393 /* True iff the transaction owns the packed-refs lock. */
1394 int own_lock;
1395
1396 struct string_list updates;
1397 };
1398
1399 static void packed_transaction_cleanup(struct packed_ref_store *refs,
1400 struct ref_transaction *transaction)
1401 {
1402 struct packed_transaction_backend_data *data = transaction->backend_data;
1403
1404 if (data) {
1405 string_list_clear(&data->updates, 0);
1406
1407 if (is_tempfile_active(refs->tempfile))
1408 delete_tempfile(&refs->tempfile);
1409
1410 if (data->own_lock && is_lock_file_locked(&refs->lock)) {
1411 packed_refs_unlock(&refs->base);
1412 data->own_lock = 0;
1413 }
1414
1415 free(data);
1416 transaction->backend_data = NULL;
1417 }
1418
1419 transaction->state = REF_TRANSACTION_CLOSED;
1420 }
1421
1422 static int packed_transaction_prepare(struct ref_store *ref_store,
1423 struct ref_transaction *transaction,
1424 struct strbuf *err)
1425 {
1426 struct packed_ref_store *refs = packed_downcast(
1427 ref_store,
1428 REF_STORE_READ | REF_STORE_WRITE | REF_STORE_ODB,
1429 "ref_transaction_prepare");
1430 struct packed_transaction_backend_data *data;
1431 size_t i;
1432 int ret = TRANSACTION_GENERIC_ERROR;
1433
1434 /*
1435 * Note that we *don't* skip transactions with zero updates,
1436 * because such a transaction might be executed for the side
1437 * effect of ensuring that all of the references are peeled or
1438 * ensuring that the `packed-refs` file is sorted. If the
1439 * caller wants to optimize away empty transactions, it should
1440 * do so itself.
1441 */
1442
1443 CALLOC_ARRAY(data, 1);
1444 string_list_init_nodup(&data->updates);
1445
1446 transaction->backend_data = data;
1447
1448 /*
1449 * Stick the updates in a string list by refname so that we
1450 * can sort them:
1451 */
1452 for (i = 0; i < transaction->nr; i++) {
1453 struct ref_update *update = transaction->updates[i];
1454 struct string_list_item *item =
1455 string_list_append(&data->updates, update->refname);
1456
1457 /* Store a pointer to update in item->util: */
1458 item->util = update;
1459 }
1460 string_list_sort(&data->updates);
1461
1462 if (ref_update_reject_duplicates(&data->updates, err))
1463 goto failure;
1464
1465 if (!is_lock_file_locked(&refs->lock)) {
1466 if (packed_refs_lock(ref_store, 0, err))
1467 goto failure;
1468 data->own_lock = 1;
1469 }
1470
1471 if (write_with_updates(refs, &data->updates, err))
1472 goto failure;
1473
1474 transaction->state = REF_TRANSACTION_PREPARED;
1475 return 0;
1476
1477 failure:
1478 packed_transaction_cleanup(refs, transaction);
1479 return ret;
1480 }
1481
1482 static int packed_transaction_abort(struct ref_store *ref_store,
1483 struct ref_transaction *transaction,
1484 struct strbuf *err UNUSED)
1485 {
1486 struct packed_ref_store *refs = packed_downcast(
1487 ref_store,
1488 REF_STORE_READ | REF_STORE_WRITE | REF_STORE_ODB,
1489 "ref_transaction_abort");
1490
1491 packed_transaction_cleanup(refs, transaction);
1492 return 0;
1493 }
1494
1495 static int packed_transaction_finish(struct ref_store *ref_store,
1496 struct ref_transaction *transaction,
1497 struct strbuf *err)
1498 {
1499 struct packed_ref_store *refs = packed_downcast(
1500 ref_store,
1501 REF_STORE_READ | REF_STORE_WRITE | REF_STORE_ODB,
1502 "ref_transaction_finish");
1503 int ret = TRANSACTION_GENERIC_ERROR;
1504 char *packed_refs_path;
1505
1506 clear_snapshot(refs);
1507
1508 packed_refs_path = get_locked_file_path(&refs->lock);
1509 if (rename_tempfile(&refs->tempfile, packed_refs_path)) {
1510 strbuf_addf(err, "error replacing %s: %s",
1511 refs->path, strerror(errno));
1512 goto cleanup;
1513 }
1514
1515 ret = 0;
1516
1517 cleanup:
1518 free(packed_refs_path);
1519 packed_transaction_cleanup(refs, transaction);
1520 return ret;
1521 }
1522
1523 static int packed_initial_transaction_commit(struct ref_store *ref_store UNUSED,
1524 struct ref_transaction *transaction,
1525 struct strbuf *err)
1526 {
1527 return ref_transaction_commit(transaction, err);
1528 }
1529
1530 static int packed_delete_refs(struct ref_store *ref_store, const char *msg,
1531 struct string_list *refnames, unsigned int flags)
1532 {
1533 struct packed_ref_store *refs =
1534 packed_downcast(ref_store, REF_STORE_WRITE, "delete_refs");
1535 struct strbuf err = STRBUF_INIT;
1536 struct ref_transaction *transaction;
1537 struct string_list_item *item;
1538 int ret;
1539
1540 (void)refs; /* We need the check above, but don't use the variable */
1541
1542 if (!refnames->nr)
1543 return 0;
1544
1545 /*
1546 * Since we don't check the references' old_oids, the
1547 * individual updates can't fail, so we can pack all of the
1548 * updates into a single transaction.
1549 */
1550
1551 transaction = ref_store_transaction_begin(ref_store, &err);
1552 if (!transaction)
1553 return -1;
1554
1555 for_each_string_list_item(item, refnames) {
1556 if (ref_transaction_delete(transaction, item->string, NULL,
1557 flags, msg, &err)) {
1558 warning(_("could not delete reference %s: %s"),
1559 item->string, err.buf);
1560 strbuf_reset(&err);
1561 }
1562 }
1563
1564 ret = ref_transaction_commit(transaction, &err);
1565
1566 if (ret) {
1567 if (refnames->nr == 1)
1568 error(_("could not delete reference %s: %s"),
1569 refnames->items[0].string, err.buf);
1570 else
1571 error(_("could not delete references: %s"), err.buf);
1572 }
1573
1574 ref_transaction_free(transaction);
1575 strbuf_release(&err);
1576 return ret;
1577 }
1578
1579 static int packed_pack_refs(struct ref_store *ref_store UNUSED,
1580 struct pack_refs_opts *pack_opts UNUSED)
1581 {
1582 /*
1583 * Packed refs are already packed. It might be that loose refs
1584 * are packed *into* a packed refs store, but that is done by
1585 * updating the packed references via a transaction.
1586 */
1587 return 0;
1588 }
1589
1590 static struct ref_iterator *packed_reflog_iterator_begin(struct ref_store *ref_store UNUSED)
1591 {
1592 return empty_ref_iterator_begin();
1593 }
1594
1595 struct ref_storage_be refs_be_packed = {
1596 .next = NULL,
1597 .name = "packed",
1598 .init = packed_ref_store_create,
1599 .init_db = packed_init_db,
1600 .transaction_prepare = packed_transaction_prepare,
1601 .transaction_finish = packed_transaction_finish,
1602 .transaction_abort = packed_transaction_abort,
1603 .initial_transaction_commit = packed_initial_transaction_commit,
1604
1605 .pack_refs = packed_pack_refs,
1606 .create_symref = NULL,
1607 .delete_refs = packed_delete_refs,
1608 .rename_ref = NULL,
1609 .copy_ref = NULL,
1610
1611 .iterator_begin = packed_ref_iterator_begin,
1612 .read_raw_ref = packed_read_raw_ref,
1613 .read_symbolic_ref = NULL,
1614
1615 .reflog_iterator_begin = packed_reflog_iterator_begin,
1616 .for_each_reflog_ent = NULL,
1617 .for_each_reflog_ent_reverse = NULL,
1618 .reflog_exists = NULL,
1619 .create_reflog = NULL,
1620 .delete_reflog = NULL,
1621 .reflog_expire = NULL,
1622 };