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