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