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