get_packed_ref_cache(): assume "packed-refs" won't change while locked
[git/git.git] / refs / files-backend.c
CommitLineData
7bd9bcf3
MH
1#include "../cache.h"
2#include "../refs.h"
3#include "refs-internal.h"
958f9646 4#include "ref-cache.h"
3bc581b9 5#include "../iterator.h"
2880d16f 6#include "../dir-iterator.h"
7bd9bcf3
MH
7#include "../lockfile.h"
8#include "../object.h"
9#include "../dir.h"
10
11struct ref_lock {
12 char *ref_name;
7bd9bcf3
MH
13 struct lock_file *lk;
14 struct object_id old_oid;
15};
16
7bd9bcf3 17/*
a8739244
MH
18 * Return true if refname, which has the specified oid and flags, can
19 * be resolved to an object in the database. If the referred-to object
20 * does not exist, emit a warning and return false.
7bd9bcf3 21 */
a8739244
MH
22static int ref_resolves_to_object(const char *refname,
23 const struct object_id *oid,
24 unsigned int flags)
7bd9bcf3 25{
a8739244 26 if (flags & REF_ISBROKEN)
7bd9bcf3 27 return 0;
a8739244
MH
28 if (!has_sha1_file(oid->hash)) {
29 error("%s does not point to a valid object!", refname);
7bd9bcf3
MH
30 return 0;
31 }
32 return 1;
33}
34
7bd9bcf3 35struct packed_ref_cache {
7c22bc8a 36 struct ref_cache *cache;
7bd9bcf3
MH
37
38 /*
39 * Count of references to the data structure in this instance,
65a0a8e5
MH
40 * including the pointer from files_ref_store::packed if any.
41 * The data will not be freed as long as the reference count
42 * is nonzero.
7bd9bcf3
MH
43 */
44 unsigned int referrers;
45
7bd9bcf3
MH
46 /* The metadata from when this packed-refs cache was read */
47 struct stat_validity validity;
48};
49
50/*
51 * Future: need to be in "struct repository"
52 * when doing a full libification.
53 */
00eebe35
MH
54struct files_ref_store {
55 struct ref_store base;
9e7ec634 56 unsigned int store_flags;
32c597e7 57
f57f37e2
NTND
58 char *gitdir;
59 char *gitcommondir;
33dfb9f3
NTND
60 char *packed_refs_path;
61
7c22bc8a 62 struct ref_cache *loose;
7bd9bcf3 63 struct packed_ref_cache *packed;
55c6bc37
MH
64
65 /*
00d17448
MH
66 * Lock used for the "packed-refs" file. Note that this (and
67 * thus the enclosing `files_ref_store`) must not be freed.
55c6bc37 68 */
00d17448 69 struct lock_file packed_refs_lock;
00eebe35 70};
7bd9bcf3 71
7bd9bcf3
MH
72/*
73 * Increment the reference count of *packed_refs.
74 */
75static void acquire_packed_ref_cache(struct packed_ref_cache *packed_refs)
76{
77 packed_refs->referrers++;
78}
79
80/*
81 * Decrease the reference count of *packed_refs. If it goes to zero,
82 * free *packed_refs and return true; otherwise return false.
83 */
84static int release_packed_ref_cache(struct packed_ref_cache *packed_refs)
85{
86 if (!--packed_refs->referrers) {
7c22bc8a 87 free_ref_cache(packed_refs->cache);
7bd9bcf3
MH
88 stat_validity_clear(&packed_refs->validity);
89 free(packed_refs);
90 return 1;
91 } else {
92 return 0;
93 }
94}
95
65a0a8e5 96static void clear_packed_ref_cache(struct files_ref_store *refs)
7bd9bcf3
MH
97{
98 if (refs->packed) {
99 struct packed_ref_cache *packed_refs = refs->packed;
100
00d17448 101 if (is_lock_file_locked(&refs->packed_refs_lock))
04aea8d4 102 die("BUG: packed-ref cache cleared while locked");
7bd9bcf3
MH
103 refs->packed = NULL;
104 release_packed_ref_cache(packed_refs);
105 }
106}
107
65a0a8e5 108static void clear_loose_ref_cache(struct files_ref_store *refs)
7bd9bcf3
MH
109{
110 if (refs->loose) {
7c22bc8a 111 free_ref_cache(refs->loose);
7bd9bcf3
MH
112 refs->loose = NULL;
113 }
114}
115
a2d5156c
JK
116/*
117 * Create a new submodule ref cache and add it to the internal
118 * set of caches.
119 */
9e7ec634
NTND
120static struct ref_store *files_ref_store_create(const char *gitdir,
121 unsigned int flags)
7bd9bcf3 122{
00eebe35
MH
123 struct files_ref_store *refs = xcalloc(1, sizeof(*refs));
124 struct ref_store *ref_store = (struct ref_store *)refs;
f57f37e2 125 struct strbuf sb = STRBUF_INIT;
7bd9bcf3 126
fbfd0a29 127 base_ref_store_init(ref_store, &refs_be_files);
9e7ec634 128 refs->store_flags = flags;
7bd9bcf3 129
f57f37e2
NTND
130 refs->gitdir = xstrdup(gitdir);
131 get_common_dir_noenv(&sb, gitdir);
132 refs->gitcommondir = strbuf_detach(&sb, NULL);
133 strbuf_addf(&sb, "%s/packed-refs", refs->gitcommondir);
134 refs->packed_refs_path = strbuf_detach(&sb, NULL);
7bd9bcf3 135
00eebe35 136 return ref_store;
a2d5156c 137}
7bd9bcf3 138
32c597e7 139/*
9e7ec634
NTND
140 * Die if refs is not the main ref store. caller is used in any
141 * necessary error messages.
32c597e7
MH
142 */
143static void files_assert_main_repository(struct files_ref_store *refs,
144 const char *caller)
145{
9e7ec634
NTND
146 if (refs->store_flags & REF_STORE_MAIN)
147 return;
148
149 die("BUG: operation %s only allowed for main ref store", caller);
32c597e7
MH
150}
151
a2d5156c 152/*
00eebe35 153 * Downcast ref_store to files_ref_store. Die if ref_store is not a
9e7ec634
NTND
154 * files_ref_store. required_flags is compared with ref_store's
155 * store_flags to ensure the ref_store has all required capabilities.
156 * "caller" is used in any necessary error messages.
a2d5156c 157 */
9e7ec634
NTND
158static struct files_ref_store *files_downcast(struct ref_store *ref_store,
159 unsigned int required_flags,
160 const char *caller)
a2d5156c 161{
32c597e7
MH
162 struct files_ref_store *refs;
163
00eebe35
MH
164 if (ref_store->be != &refs_be_files)
165 die("BUG: ref_store is type \"%s\" not \"files\" in %s",
166 ref_store->be->name, caller);
2eed2780 167
32c597e7
MH
168 refs = (struct files_ref_store *)ref_store;
169
9e7ec634
NTND
170 if ((refs->store_flags & required_flags) != required_flags)
171 die("BUG: operation %s requires abilities 0x%x, but only have 0x%x",
172 caller, required_flags, refs->store_flags);
2eed2780 173
32c597e7 174 return refs;
7bd9bcf3
MH
175}
176
177/* The length of a peeled reference line in packed-refs, including EOL: */
178#define PEELED_LINE_LENGTH 42
179
180/*
181 * The packed-refs header line that we write out. Perhaps other
182 * traits will be added later. The trailing space is required.
183 */
184static const char PACKED_REFS_HEADER[] =
185 "# pack-refs with: peeled fully-peeled \n";
186
187/*
188 * Parse one line from a packed-refs file. Write the SHA1 to sha1.
189 * Return a pointer to the refname within the line (null-terminated),
190 * or NULL if there was a problem.
191 */
4417df8c 192static const char *parse_ref_line(struct strbuf *line, struct object_id *oid)
7bd9bcf3
MH
193{
194 const char *ref;
195
4417df8c 196 if (parse_oid_hex(line->buf, oid, &ref) < 0)
7bd9bcf3 197 return NULL;
4417df8c 198 if (!isspace(*ref++))
7bd9bcf3
MH
199 return NULL;
200
7bd9bcf3
MH
201 if (isspace(*ref))
202 return NULL;
203
204 if (line->buf[line->len - 1] != '\n')
205 return NULL;
206 line->buf[--line->len] = 0;
207
208 return ref;
209}
210
211/*
212 * Read f, which is a packed-refs file, into dir.
213 *
214 * A comment line of the form "# pack-refs with: " may contain zero or
215 * more traits. We interpret the traits as follows:
216 *
217 * No traits:
218 *
219 * Probably no references are peeled. But if the file contains a
220 * peeled value for a reference, we will use it.
221 *
222 * peeled:
223 *
224 * References under "refs/tags/", if they *can* be peeled, *are*
225 * peeled in this file. References outside of "refs/tags/" are
226 * probably not peeled even if they could have been, but if we find
227 * a peeled value for such a reference we will use it.
228 *
229 * fully-peeled:
230 *
231 * All references in the file that can be peeled are peeled.
232 * Inversely (and this is more important), any references in the
233 * file for which no peeled value is recorded is not peelable. This
234 * trait should typically be written alongside "peeled" for
235 * compatibility with older clients, but we do not require it
236 * (i.e., "peeled" is a no-op if "fully-peeled" is set).
237 */
238static void read_packed_refs(FILE *f, struct ref_dir *dir)
239{
240 struct ref_entry *last = NULL;
241 struct strbuf line = STRBUF_INIT;
242 enum { PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;
243
244 while (strbuf_getwholeline(&line, f, '\n') != EOF) {
4417df8c 245 struct object_id oid;
7bd9bcf3
MH
246 const char *refname;
247 const char *traits;
248
249 if (skip_prefix(line.buf, "# pack-refs with:", &traits)) {
250 if (strstr(traits, " fully-peeled "))
251 peeled = PEELED_FULLY;
252 else if (strstr(traits, " peeled "))
253 peeled = PEELED_TAGS;
254 /* perhaps other traits later as well */
255 continue;
256 }
257
4417df8c 258 refname = parse_ref_line(&line, &oid);
7bd9bcf3
MH
259 if (refname) {
260 int flag = REF_ISPACKED;
261
262 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
263 if (!refname_is_safe(refname))
264 die("packed refname is dangerous: %s", refname);
4417df8c 265 oidclr(&oid);
7bd9bcf3
MH
266 flag |= REF_BAD_NAME | REF_ISBROKEN;
267 }
4417df8c 268 last = create_ref_entry(refname, &oid, flag, 0);
7bd9bcf3
MH
269 if (peeled == PEELED_FULLY ||
270 (peeled == PEELED_TAGS && starts_with(refname, "refs/tags/")))
271 last->flag |= REF_KNOWS_PEELED;
a3ade2ba 272 add_ref_entry(dir, last);
7bd9bcf3
MH
273 continue;
274 }
275 if (last &&
276 line.buf[0] == '^' &&
277 line.len == PEELED_LINE_LENGTH &&
278 line.buf[PEELED_LINE_LENGTH - 1] == '\n' &&
4417df8c 279 !get_oid_hex(line.buf + 1, &oid)) {
280 oidcpy(&last->u.value.peeled, &oid);
7bd9bcf3
MH
281 /*
282 * Regardless of what the file header said,
283 * we definitely know the value of *this*
284 * reference:
285 */
286 last->flag |= REF_KNOWS_PEELED;
287 }
288 }
289
290 strbuf_release(&line);
291}
292
33dfb9f3
NTND
293static const char *files_packed_refs_path(struct files_ref_store *refs)
294{
295 return refs->packed_refs_path;
296}
297
802de3da
NTND
298static void files_reflog_path(struct files_ref_store *refs,
299 struct strbuf *sb,
300 const char *refname)
301{
302 if (!refname) {
f57f37e2
NTND
303 /*
304 * FIXME: of course this is wrong in multi worktree
305 * setting. To be fixed real soon.
306 */
307 strbuf_addf(sb, "%s/logs", refs->gitcommondir);
802de3da
NTND
308 return;
309 }
310
f57f37e2
NTND
311 switch (ref_type(refname)) {
312 case REF_TYPE_PER_WORKTREE:
313 case REF_TYPE_PSEUDOREF:
314 strbuf_addf(sb, "%s/logs/%s", refs->gitdir, refname);
315 break;
316 case REF_TYPE_NORMAL:
317 strbuf_addf(sb, "%s/logs/%s", refs->gitcommondir, refname);
318 break;
319 default:
320 die("BUG: unknown ref type %d of ref %s",
321 ref_type(refname), refname);
322 }
802de3da
NTND
323}
324
19e02f4f
NTND
325static void files_ref_path(struct files_ref_store *refs,
326 struct strbuf *sb,
327 const char *refname)
328{
f57f37e2
NTND
329 switch (ref_type(refname)) {
330 case REF_TYPE_PER_WORKTREE:
331 case REF_TYPE_PSEUDOREF:
332 strbuf_addf(sb, "%s/%s", refs->gitdir, refname);
333 break;
334 case REF_TYPE_NORMAL:
335 strbuf_addf(sb, "%s/%s", refs->gitcommondir, refname);
336 break;
337 default:
338 die("BUG: unknown ref type %d of ref %s",
339 ref_type(refname), refname);
340 }
19e02f4f
NTND
341}
342
7bd9bcf3 343/*
65a0a8e5 344 * Get the packed_ref_cache for the specified files_ref_store,
28ed9830
MH
345 * creating and populating it if it hasn't been read before or if the
346 * file has been changed (according to its `validity` field) since it
347 * was last read. On the other hand, if we hold the lock, then assume
348 * that the file hasn't been changed out from under us, so skip the
349 * extra `stat()` call in `stat_validity_check()`.
7bd9bcf3 350 */
65a0a8e5 351static struct packed_ref_cache *get_packed_ref_cache(struct files_ref_store *refs)
7bd9bcf3 352{
33dfb9f3 353 const char *packed_refs_file = files_packed_refs_path(refs);
7bd9bcf3
MH
354
355 if (refs->packed &&
28ed9830 356 !is_lock_file_locked(&refs->packed_refs_lock) &&
7bd9bcf3
MH
357 !stat_validity_check(&refs->packed->validity, packed_refs_file))
358 clear_packed_ref_cache(refs);
359
360 if (!refs->packed) {
361 FILE *f;
362
363 refs->packed = xcalloc(1, sizeof(*refs->packed));
364 acquire_packed_ref_cache(refs->packed);
df308759 365 refs->packed->cache = create_ref_cache(&refs->base, NULL);
7c22bc8a 366 refs->packed->cache->root->flag &= ~REF_INCOMPLETE;
7bd9bcf3
MH
367 f = fopen(packed_refs_file, "r");
368 if (f) {
369 stat_validity_update(&refs->packed->validity, fileno(f));
7c22bc8a 370 read_packed_refs(f, get_ref_dir(refs->packed->cache->root));
7bd9bcf3
MH
371 fclose(f);
372 }
373 }
7bd9bcf3
MH
374 return refs->packed;
375}
376
377static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)
378{
7c22bc8a 379 return get_ref_dir(packed_ref_cache->cache->root);
7bd9bcf3
MH
380}
381
65a0a8e5 382static struct ref_dir *get_packed_refs(struct files_ref_store *refs)
7bd9bcf3
MH
383{
384 return get_packed_ref_dir(get_packed_ref_cache(refs));
385}
386
387/*
388 * Add a reference to the in-memory packed reference cache. This may
389 * only be called while the packed-refs file is locked (see
390 * lock_packed_refs()). To actually write the packed-refs file, call
391 * commit_packed_refs().
392 */
d99825ab 393static void add_packed_ref(struct files_ref_store *refs,
4417df8c 394 const char *refname, const struct object_id *oid)
7bd9bcf3 395{
00eebe35 396 struct packed_ref_cache *packed_ref_cache = get_packed_ref_cache(refs);
7bd9bcf3 397
00d17448 398 if (!is_lock_file_locked(&refs->packed_refs_lock))
04aea8d4 399 die("BUG: packed refs not locked");
a3ade2ba 400 add_ref_entry(get_packed_ref_dir(packed_ref_cache),
4417df8c 401 create_ref_entry(refname, oid, REF_ISPACKED, 1));
7bd9bcf3
MH
402}
403
404/*
405 * Read the loose references from the namespace dirname into dir
406 * (without recursing). dirname must end with '/'. dir must be the
407 * directory entry corresponding to dirname.
408 */
df308759
MH
409static void loose_fill_ref_dir(struct ref_store *ref_store,
410 struct ref_dir *dir, const char *dirname)
7bd9bcf3 411{
df308759
MH
412 struct files_ref_store *refs =
413 files_downcast(ref_store, REF_STORE_READ, "fill_ref_dir");
7bd9bcf3
MH
414 DIR *d;
415 struct dirent *de;
416 int dirnamelen = strlen(dirname);
417 struct strbuf refname;
418 struct strbuf path = STRBUF_INIT;
419 size_t path_baselen;
420
19e02f4f 421 files_ref_path(refs, &path, dirname);
7bd9bcf3
MH
422 path_baselen = path.len;
423
424 d = opendir(path.buf);
425 if (!d) {
426 strbuf_release(&path);
427 return;
428 }
429
430 strbuf_init(&refname, dirnamelen + 257);
431 strbuf_add(&refname, dirname, dirnamelen);
432
433 while ((de = readdir(d)) != NULL) {
4417df8c 434 struct object_id oid;
7bd9bcf3
MH
435 struct stat st;
436 int flag;
437
438 if (de->d_name[0] == '.')
439 continue;
440 if (ends_with(de->d_name, ".lock"))
441 continue;
442 strbuf_addstr(&refname, de->d_name);
443 strbuf_addstr(&path, de->d_name);
444 if (stat(path.buf, &st) < 0) {
445 ; /* silently ignore */
446 } else if (S_ISDIR(st.st_mode)) {
447 strbuf_addch(&refname, '/');
448 add_entry_to_dir(dir,
e00d1a4f 449 create_dir_entry(dir->cache, refname.buf,
7bd9bcf3
MH
450 refname.len, 1));
451 } else {
7d2df051 452 if (!refs_resolve_ref_unsafe(&refs->base,
3c0cb0cb
MH
453 refname.buf,
454 RESOLVE_REF_READING,
4417df8c 455 oid.hash, &flag)) {
456 oidclr(&oid);
7bd9bcf3 457 flag |= REF_ISBROKEN;
4417df8c 458 } else if (is_null_oid(&oid)) {
7bd9bcf3
MH
459 /*
460 * It is so astronomically unlikely
461 * that NULL_SHA1 is the SHA-1 of an
462 * actual object that we consider its
463 * appearance in a loose reference
464 * file to be repo corruption
465 * (probably due to a software bug).
466 */
467 flag |= REF_ISBROKEN;
468 }
469
470 if (check_refname_format(refname.buf,
471 REFNAME_ALLOW_ONELEVEL)) {
472 if (!refname_is_safe(refname.buf))
473 die("loose refname is dangerous: %s", refname.buf);
4417df8c 474 oidclr(&oid);
7bd9bcf3
MH
475 flag |= REF_BAD_NAME | REF_ISBROKEN;
476 }
477 add_entry_to_dir(dir,
4417df8c 478 create_ref_entry(refname.buf, &oid, flag, 0));
7bd9bcf3
MH
479 }
480 strbuf_setlen(&refname, dirnamelen);
481 strbuf_setlen(&path, path_baselen);
482 }
483 strbuf_release(&refname);
484 strbuf_release(&path);
485 closedir(d);
e3bf2989
MH
486
487 /*
488 * Manually add refs/bisect, which, being per-worktree, might
489 * not appear in the directory listing for refs/ in the main
490 * repo.
491 */
492 if (!strcmp(dirname, "refs/")) {
493 int pos = search_ref_dir(dir, "refs/bisect/", 12);
494
495 if (pos < 0) {
496 struct ref_entry *child_entry = create_dir_entry(
497 dir->cache, "refs/bisect/", 12, 1);
498 add_entry_to_dir(dir, child_entry);
499 }
500 }
7bd9bcf3
MH
501}
502
a714b19c 503static struct ref_cache *get_loose_ref_cache(struct files_ref_store *refs)
7bd9bcf3
MH
504{
505 if (!refs->loose) {
506 /*
507 * Mark the top-level directory complete because we
508 * are about to read the only subdirectory that can
509 * hold references:
510 */
df308759 511 refs->loose = create_ref_cache(&refs->base, loose_fill_ref_dir);
7c22bc8a
MH
512
513 /* We're going to fill the top level ourselves: */
514 refs->loose->root->flag &= ~REF_INCOMPLETE;
515
7bd9bcf3 516 /*
7c22bc8a
MH
517 * Add an incomplete entry for "refs/" (to be filled
518 * lazily):
7bd9bcf3 519 */
7c22bc8a 520 add_entry_to_dir(get_ref_dir(refs->loose->root),
e00d1a4f 521 create_dir_entry(refs->loose, "refs/", 5, 1));
7bd9bcf3 522 }
a714b19c 523 return refs->loose;
7bd9bcf3
MH
524}
525
7bd9bcf3
MH
526/*
527 * Return the ref_entry for the given refname from the packed
528 * references. If it does not exist, return NULL.
529 */
f0d21efc
MH
530static struct ref_entry *get_packed_ref(struct files_ref_store *refs,
531 const char *refname)
7bd9bcf3 532{
bc1c696e 533 return find_ref_entry(get_packed_refs(refs), refname);
7bd9bcf3
MH
534}
535
536/*
419c6f4c 537 * A loose ref file doesn't exist; check for a packed ref.
7bd9bcf3 538 */
611118d0
MH
539static int resolve_packed_ref(struct files_ref_store *refs,
540 const char *refname,
541 unsigned char *sha1, unsigned int *flags)
7bd9bcf3
MH
542{
543 struct ref_entry *entry;
544
545 /*
546 * The loose reference file does not exist; check for a packed
547 * reference.
548 */
f0d21efc 549 entry = get_packed_ref(refs, refname);
7bd9bcf3
MH
550 if (entry) {
551 hashcpy(sha1, entry->u.value.oid.hash);
a70a93b7 552 *flags |= REF_ISPACKED;
7bd9bcf3
MH
553 return 0;
554 }
419c6f4c
MH
555 /* refname is not a packed reference. */
556 return -1;
7bd9bcf3
MH
557}
558
e1e33b72
MH
559static int files_read_raw_ref(struct ref_store *ref_store,
560 const char *refname, unsigned char *sha1,
561 struct strbuf *referent, unsigned int *type)
7bd9bcf3 562{
4308651c 563 struct files_ref_store *refs =
9e7ec634 564 files_downcast(ref_store, REF_STORE_READ, "read_raw_ref");
42a38cf7
MH
565 struct strbuf sb_contents = STRBUF_INIT;
566 struct strbuf sb_path = STRBUF_INIT;
7048653a
DT
567 const char *path;
568 const char *buf;
569 struct stat st;
570 int fd;
42a38cf7
MH
571 int ret = -1;
572 int save_errno;
e8c42cb9 573 int remaining_retries = 3;
7bd9bcf3 574
fa96ea1b 575 *type = 0;
42a38cf7 576 strbuf_reset(&sb_path);
34c7ad8f 577
19e02f4f 578 files_ref_path(refs, &sb_path, refname);
34c7ad8f 579
42a38cf7 580 path = sb_path.buf;
7bd9bcf3 581
7048653a
DT
582stat_ref:
583 /*
584 * We might have to loop back here to avoid a race
585 * condition: first we lstat() the file, then we try
586 * to read it as a link or as a file. But if somebody
587 * changes the type of the file (file <-> directory
588 * <-> symlink) between the lstat() and reading, then
589 * we don't want to report that as an error but rather
590 * try again starting with the lstat().
e8c42cb9
JK
591 *
592 * We'll keep a count of the retries, though, just to avoid
593 * any confusing situation sending us into an infinite loop.
7048653a 594 */
7bd9bcf3 595
e8c42cb9
JK
596 if (remaining_retries-- <= 0)
597 goto out;
598
7048653a
DT
599 if (lstat(path, &st) < 0) {
600 if (errno != ENOENT)
42a38cf7 601 goto out;
611118d0 602 if (resolve_packed_ref(refs, refname, sha1, type)) {
7048653a 603 errno = ENOENT;
42a38cf7 604 goto out;
7bd9bcf3 605 }
42a38cf7
MH
606 ret = 0;
607 goto out;
7bd9bcf3 608 }
7bd9bcf3 609
7048653a
DT
610 /* Follow "normalized" - ie "refs/.." symlinks by hand */
611 if (S_ISLNK(st.st_mode)) {
42a38cf7
MH
612 strbuf_reset(&sb_contents);
613 if (strbuf_readlink(&sb_contents, path, 0) < 0) {
7048653a 614 if (errno == ENOENT || errno == EINVAL)
7bd9bcf3
MH
615 /* inconsistent with lstat; retry */
616 goto stat_ref;
617 else
42a38cf7 618 goto out;
7bd9bcf3 619 }
42a38cf7
MH
620 if (starts_with(sb_contents.buf, "refs/") &&
621 !check_refname_format(sb_contents.buf, 0)) {
92b38093 622 strbuf_swap(&sb_contents, referent);
3a0b6b9a 623 *type |= REF_ISSYMREF;
42a38cf7
MH
624 ret = 0;
625 goto out;
7bd9bcf3 626 }
3f7bd767
JK
627 /*
628 * It doesn't look like a refname; fall through to just
629 * treating it like a non-symlink, and reading whatever it
630 * points to.
631 */
7048653a 632 }
7bd9bcf3 633
7048653a
DT
634 /* Is it a directory? */
635 if (S_ISDIR(st.st_mode)) {
e167a567
MH
636 /*
637 * Even though there is a directory where the loose
638 * ref is supposed to be, there could still be a
639 * packed ref:
640 */
611118d0 641 if (resolve_packed_ref(refs, refname, sha1, type)) {
e167a567
MH
642 errno = EISDIR;
643 goto out;
644 }
645 ret = 0;
42a38cf7 646 goto out;
7048653a
DT
647 }
648
649 /*
650 * Anything else, just open it and try to use it as
651 * a ref
652 */
653 fd = open(path, O_RDONLY);
654 if (fd < 0) {
3f7bd767 655 if (errno == ENOENT && !S_ISLNK(st.st_mode))
7048653a
DT
656 /* inconsistent with lstat; retry */
657 goto stat_ref;
658 else
42a38cf7 659 goto out;
7048653a 660 }
42a38cf7
MH
661 strbuf_reset(&sb_contents);
662 if (strbuf_read(&sb_contents, fd, 256) < 0) {
7048653a
DT
663 int save_errno = errno;
664 close(fd);
665 errno = save_errno;
42a38cf7 666 goto out;
7048653a
DT
667 }
668 close(fd);
42a38cf7
MH
669 strbuf_rtrim(&sb_contents);
670 buf = sb_contents.buf;
7048653a
DT
671 if (starts_with(buf, "ref:")) {
672 buf += 4;
7bd9bcf3
MH
673 while (isspace(*buf))
674 buf++;
7048653a 675
92b38093
MH
676 strbuf_reset(referent);
677 strbuf_addstr(referent, buf);
3a0b6b9a 678 *type |= REF_ISSYMREF;
42a38cf7
MH
679 ret = 0;
680 goto out;
7bd9bcf3 681 }
7bd9bcf3 682
7048653a
DT
683 /*
684 * Please note that FETCH_HEAD has additional
685 * data after the sha.
686 */
687 if (get_sha1_hex(buf, sha1) ||
688 (buf[40] != '\0' && !isspace(buf[40]))) {
3a0b6b9a 689 *type |= REF_ISBROKEN;
7048653a 690 errno = EINVAL;
42a38cf7 691 goto out;
7048653a
DT
692 }
693
42a38cf7 694 ret = 0;
7bd9bcf3 695
42a38cf7
MH
696out:
697 save_errno = errno;
7bd9bcf3
MH
698 strbuf_release(&sb_path);
699 strbuf_release(&sb_contents);
42a38cf7 700 errno = save_errno;
7bd9bcf3
MH
701 return ret;
702}
703
8415d247
MH
704static void unlock_ref(struct ref_lock *lock)
705{
706 /* Do not free lock->lk -- atexit() still looks at them */
707 if (lock->lk)
708 rollback_lock_file(lock->lk);
709 free(lock->ref_name);
8415d247
MH
710 free(lock);
711}
712
92b1551b
MH
713/*
714 * Lock refname, without following symrefs, and set *lock_p to point
715 * at a newly-allocated lock object. Fill in lock->old_oid, referent,
716 * and type similarly to read_raw_ref().
717 *
718 * The caller must verify that refname is a "safe" reference name (in
719 * the sense of refname_is_safe()) before calling this function.
720 *
721 * If the reference doesn't already exist, verify that refname doesn't
722 * have a D/F conflict with any existing references. extras and skip
524a9fdb 723 * are passed to refs_verify_refname_available() for this check.
92b1551b
MH
724 *
725 * If mustexist is not set and the reference is not found or is
726 * broken, lock the reference anyway but clear sha1.
727 *
728 * Return 0 on success. On failure, write an error message to err and
729 * return TRANSACTION_NAME_CONFLICT or TRANSACTION_GENERIC_ERROR.
730 *
731 * Implementation note: This function is basically
732 *
733 * lock reference
734 * read_raw_ref()
735 *
736 * but it includes a lot more code to
737 * - Deal with possible races with other processes
524a9fdb 738 * - Avoid calling refs_verify_refname_available() when it can be
92b1551b
MH
739 * avoided, namely if we were successfully able to read the ref
740 * - Generate informative error messages in the case of failure
741 */
f7b0a987
MH
742static int lock_raw_ref(struct files_ref_store *refs,
743 const char *refname, int mustexist,
92b1551b
MH
744 const struct string_list *extras,
745 const struct string_list *skip,
746 struct ref_lock **lock_p,
747 struct strbuf *referent,
748 unsigned int *type,
749 struct strbuf *err)
750{
751 struct ref_lock *lock;
752 struct strbuf ref_file = STRBUF_INIT;
753 int attempts_remaining = 3;
754 int ret = TRANSACTION_GENERIC_ERROR;
755
756 assert(err);
32c597e7 757 files_assert_main_repository(refs, "lock_raw_ref");
f7b0a987 758
92b1551b
MH
759 *type = 0;
760
761 /* First lock the file so it can't change out from under us. */
762
763 *lock_p = lock = xcalloc(1, sizeof(*lock));
764
765 lock->ref_name = xstrdup(refname);
19e02f4f 766 files_ref_path(refs, &ref_file, refname);
92b1551b
MH
767
768retry:
769 switch (safe_create_leading_directories(ref_file.buf)) {
770 case SCLD_OK:
771 break; /* success */
772 case SCLD_EXISTS:
773 /*
774 * Suppose refname is "refs/foo/bar". We just failed
775 * to create the containing directory, "refs/foo",
776 * because there was a non-directory in the way. This
777 * indicates a D/F conflict, probably because of
778 * another reference such as "refs/foo". There is no
779 * reason to expect this error to be transitory.
780 */
7d2df051
NTND
781 if (refs_verify_refname_available(&refs->base, refname,
782 extras, skip, err)) {
92b1551b
MH
783 if (mustexist) {
784 /*
785 * To the user the relevant error is
786 * that the "mustexist" reference is
787 * missing:
788 */
789 strbuf_reset(err);
790 strbuf_addf(err, "unable to resolve reference '%s'",
791 refname);
792 } else {
793 /*
794 * The error message set by
524a9fdb
MH
795 * refs_verify_refname_available() is
796 * OK.
92b1551b
MH
797 */
798 ret = TRANSACTION_NAME_CONFLICT;
799 }
800 } else {
801 /*
802 * The file that is in the way isn't a loose
803 * reference. Report it as a low-level
804 * failure.
805 */
806 strbuf_addf(err, "unable to create lock file %s.lock; "
807 "non-directory in the way",
808 ref_file.buf);
809 }
810 goto error_return;
811 case SCLD_VANISHED:
812 /* Maybe another process was tidying up. Try again. */
813 if (--attempts_remaining > 0)
814 goto retry;
815 /* fall through */
816 default:
817 strbuf_addf(err, "unable to create directory for %s",
818 ref_file.buf);
819 goto error_return;
820 }
821
822 if (!lock->lk)
823 lock->lk = xcalloc(1, sizeof(struct lock_file));
824
825 if (hold_lock_file_for_update(lock->lk, ref_file.buf, LOCK_NO_DEREF) < 0) {
826 if (errno == ENOENT && --attempts_remaining > 0) {
827 /*
828 * Maybe somebody just deleted one of the
829 * directories leading to ref_file. Try
830 * again:
831 */
832 goto retry;
833 } else {
834 unable_to_lock_message(ref_file.buf, errno, err);
835 goto error_return;
836 }
837 }
838
839 /*
840 * Now we hold the lock and can read the reference without
841 * fear that its value will change.
842 */
843
f7b0a987 844 if (files_read_raw_ref(&refs->base, refname,
e1e33b72 845 lock->old_oid.hash, referent, type)) {
92b1551b
MH
846 if (errno == ENOENT) {
847 if (mustexist) {
848 /* Garden variety missing reference. */
849 strbuf_addf(err, "unable to resolve reference '%s'",
850 refname);
851 goto error_return;
852 } else {
853 /*
854 * Reference is missing, but that's OK. We
855 * know that there is not a conflict with
856 * another loose reference because
857 * (supposing that we are trying to lock
858 * reference "refs/foo/bar"):
859 *
860 * - We were successfully able to create
861 * the lockfile refs/foo/bar.lock, so we
862 * know there cannot be a loose reference
863 * named "refs/foo".
864 *
865 * - We got ENOENT and not EISDIR, so we
866 * know that there cannot be a loose
867 * reference named "refs/foo/bar/baz".
868 */
869 }
870 } else if (errno == EISDIR) {
871 /*
872 * There is a directory in the way. It might have
873 * contained references that have been deleted. If
874 * we don't require that the reference already
875 * exists, try to remove the directory so that it
876 * doesn't cause trouble when we want to rename the
877 * lockfile into place later.
878 */
879 if (mustexist) {
880 /* Garden variety missing reference. */
881 strbuf_addf(err, "unable to resolve reference '%s'",
882 refname);
883 goto error_return;
884 } else if (remove_dir_recursively(&ref_file,
885 REMOVE_DIR_EMPTY_ONLY)) {
b05855b5
MH
886 if (refs_verify_refname_available(
887 &refs->base, refname,
888 extras, skip, err)) {
92b1551b
MH
889 /*
890 * The error message set by
891 * verify_refname_available() is OK.
892 */
893 ret = TRANSACTION_NAME_CONFLICT;
894 goto error_return;
895 } else {
896 /*
897 * We can't delete the directory,
898 * but we also don't know of any
899 * references that it should
900 * contain.
901 */
902 strbuf_addf(err, "there is a non-empty directory '%s' "
903 "blocking reference '%s'",
904 ref_file.buf, refname);
905 goto error_return;
906 }
907 }
908 } else if (errno == EINVAL && (*type & REF_ISBROKEN)) {
909 strbuf_addf(err, "unable to resolve reference '%s': "
910 "reference broken", refname);
911 goto error_return;
912 } else {
913 strbuf_addf(err, "unable to resolve reference '%s': %s",
914 refname, strerror(errno));
915 goto error_return;
916 }
917
918 /*
919 * If the ref did not exist and we are creating it,
524a9fdb
MH
920 * make sure there is no existing ref that conflicts
921 * with refname:
92b1551b 922 */
524a9fdb
MH
923 if (refs_verify_refname_available(
924 &refs->base, refname,
925 extras, skip, err))
92b1551b 926 goto error_return;
92b1551b
MH
927 }
928
929 ret = 0;
930 goto out;
931
932error_return:
933 unlock_ref(lock);
934 *lock_p = NULL;
935
936out:
937 strbuf_release(&ref_file);
938 return ret;
939}
940
bd427cf2
MH
941static int files_peel_ref(struct ref_store *ref_store,
942 const char *refname, unsigned char *sha1)
7bd9bcf3 943{
9e7ec634
NTND
944 struct files_ref_store *refs =
945 files_downcast(ref_store, REF_STORE_READ | REF_STORE_ODB,
946 "peel_ref");
7bd9bcf3
MH
947 int flag;
948 unsigned char base[20];
949
4c4de895
MH
950 if (current_ref_iter && current_ref_iter->refname == refname) {
951 struct object_id peeled;
952
953 if (ref_iterator_peel(current_ref_iter, &peeled))
7bd9bcf3 954 return -1;
4c4de895 955 hashcpy(sha1, peeled.hash);
7bd9bcf3
MH
956 return 0;
957 }
958
2f40e954
NTND
959 if (refs_read_ref_full(ref_store, refname,
960 RESOLVE_REF_READING, base, &flag))
7bd9bcf3
MH
961 return -1;
962
963 /*
964 * If the reference is packed, read its ref_entry from the
965 * cache in the hope that we already know its peeled value.
966 * We only try this optimization on packed references because
967 * (a) forcing the filling of the loose reference cache could
968 * be expensive and (b) loose references anyway usually do not
969 * have REF_KNOWS_PEELED.
970 */
971 if (flag & REF_ISPACKED) {
f0d21efc 972 struct ref_entry *r = get_packed_ref(refs, refname);
7bd9bcf3
MH
973 if (r) {
974 if (peel_entry(r, 0))
975 return -1;
976 hashcpy(sha1, r->u.value.peeled.hash);
977 return 0;
978 }
979 }
980
981 return peel_object(base, sha1);
982}
983
3bc581b9
MH
984struct files_ref_iterator {
985 struct ref_iterator base;
986
7bd9bcf3 987 struct packed_ref_cache *packed_ref_cache;
3bc581b9
MH
988 struct ref_iterator *iter0;
989 unsigned int flags;
990};
7bd9bcf3 991
3bc581b9
MH
992static int files_ref_iterator_advance(struct ref_iterator *ref_iterator)
993{
994 struct files_ref_iterator *iter =
995 (struct files_ref_iterator *)ref_iterator;
996 int ok;
7bd9bcf3 997
3bc581b9 998 while ((ok = ref_iterator_advance(iter->iter0)) == ITER_OK) {
0c09ec07
DT
999 if (iter->flags & DO_FOR_EACH_PER_WORKTREE_ONLY &&
1000 ref_type(iter->iter0->refname) != REF_TYPE_PER_WORKTREE)
1001 continue;
1002
3bc581b9
MH
1003 if (!(iter->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&
1004 !ref_resolves_to_object(iter->iter0->refname,
1005 iter->iter0->oid,
1006 iter->iter0->flags))
1007 continue;
1008
1009 iter->base.refname = iter->iter0->refname;
1010 iter->base.oid = iter->iter0->oid;
1011 iter->base.flags = iter->iter0->flags;
1012 return ITER_OK;
7bd9bcf3
MH
1013 }
1014
3bc581b9
MH
1015 iter->iter0 = NULL;
1016 if (ref_iterator_abort(ref_iterator) != ITER_DONE)
1017 ok = ITER_ERROR;
1018
1019 return ok;
7bd9bcf3
MH
1020}
1021
3bc581b9
MH
1022static int files_ref_iterator_peel(struct ref_iterator *ref_iterator,
1023 struct object_id *peeled)
7bd9bcf3 1024{
3bc581b9
MH
1025 struct files_ref_iterator *iter =
1026 (struct files_ref_iterator *)ref_iterator;
93770590 1027
3bc581b9
MH
1028 return ref_iterator_peel(iter->iter0, peeled);
1029}
1030
1031static int files_ref_iterator_abort(struct ref_iterator *ref_iterator)
1032{
1033 struct files_ref_iterator *iter =
1034 (struct files_ref_iterator *)ref_iterator;
1035 int ok = ITER_DONE;
1036
1037 if (iter->iter0)
1038 ok = ref_iterator_abort(iter->iter0);
1039
1040 release_packed_ref_cache(iter->packed_ref_cache);
1041 base_ref_iterator_free(ref_iterator);
1042 return ok;
1043}
1044
1045static struct ref_iterator_vtable files_ref_iterator_vtable = {
1046 files_ref_iterator_advance,
1047 files_ref_iterator_peel,
1048 files_ref_iterator_abort
1049};
1050
1a769003 1051static struct ref_iterator *files_ref_iterator_begin(
37b6f6d5 1052 struct ref_store *ref_store,
3bc581b9
MH
1053 const char *prefix, unsigned int flags)
1054{
9e7ec634 1055 struct files_ref_store *refs;
3bc581b9
MH
1056 struct ref_iterator *loose_iter, *packed_iter;
1057 struct files_ref_iterator *iter;
1058 struct ref_iterator *ref_iterator;
1059
7bd9bcf3
MH
1060 if (ref_paranoia < 0)
1061 ref_paranoia = git_env_bool("GIT_REF_PARANOIA", 0);
1062 if (ref_paranoia)
3bc581b9
MH
1063 flags |= DO_FOR_EACH_INCLUDE_BROKEN;
1064
9e7ec634
NTND
1065 refs = files_downcast(ref_store,
1066 REF_STORE_READ | (ref_paranoia ? 0 : REF_STORE_ODB),
1067 "ref_iterator_begin");
1068
3bc581b9
MH
1069 iter = xcalloc(1, sizeof(*iter));
1070 ref_iterator = &iter->base;
1071 base_ref_iterator_init(ref_iterator, &files_ref_iterator_vtable);
1072
1073 /*
1074 * We must make sure that all loose refs are read before
1075 * accessing the packed-refs file; this avoids a race
1076 * condition if loose refs are migrated to the packed-refs
1077 * file by a simultaneous process, but our in-memory view is
1078 * from before the migration. We ensure this as follows:
059ae35a
MH
1079 * First, we call start the loose refs iteration with its
1080 * `prime_ref` argument set to true. This causes the loose
1081 * references in the subtree to be pre-read into the cache.
1082 * (If they've already been read, that's OK; we only need to
1083 * guarantee that they're read before the packed refs, not
1084 * *how much* before.) After that, we call
1085 * get_packed_ref_cache(), which internally checks whether the
1086 * packed-ref cache is up to date with what is on disk, and
1087 * re-reads it if not.
3bc581b9
MH
1088 */
1089
059ae35a
MH
1090 loose_iter = cache_ref_iterator_begin(get_loose_ref_cache(refs),
1091 prefix, 1);
3bc581b9
MH
1092
1093 iter->packed_ref_cache = get_packed_ref_cache(refs);
1094 acquire_packed_ref_cache(iter->packed_ref_cache);
059ae35a
MH
1095 packed_iter = cache_ref_iterator_begin(iter->packed_ref_cache->cache,
1096 prefix, 0);
3bc581b9
MH
1097
1098 iter->iter0 = overlay_ref_iterator_begin(loose_iter, packed_iter);
1099 iter->flags = flags;
1100
1101 return ref_iterator;
7bd9bcf3
MH
1102}
1103
7bd9bcf3
MH
1104/*
1105 * Verify that the reference locked by lock has the value old_sha1.
1106 * Fail if the reference doesn't exist and mustexist is set. Return 0
1107 * on success. On error, write an error message to err, set errno, and
1108 * return a negative value.
1109 */
2f40e954 1110static int verify_lock(struct ref_store *ref_store, struct ref_lock *lock,
7bd9bcf3
MH
1111 const unsigned char *old_sha1, int mustexist,
1112 struct strbuf *err)
1113{
1114 assert(err);
1115
2f40e954
NTND
1116 if (refs_read_ref_full(ref_store, lock->ref_name,
1117 mustexist ? RESOLVE_REF_READING : 0,
1118 lock->old_oid.hash, NULL)) {
6294dcb4
JK
1119 if (old_sha1) {
1120 int save_errno = errno;
0568c8e9 1121 strbuf_addf(err, "can't verify ref '%s'", lock->ref_name);
6294dcb4
JK
1122 errno = save_errno;
1123 return -1;
1124 } else {
c368dde9 1125 oidclr(&lock->old_oid);
6294dcb4
JK
1126 return 0;
1127 }
7bd9bcf3 1128 }
6294dcb4 1129 if (old_sha1 && hashcmp(lock->old_oid.hash, old_sha1)) {
0568c8e9 1130 strbuf_addf(err, "ref '%s' is at %s but expected %s",
7bd9bcf3 1131 lock->ref_name,
c368dde9 1132 oid_to_hex(&lock->old_oid),
7bd9bcf3
MH
1133 sha1_to_hex(old_sha1));
1134 errno = EBUSY;
1135 return -1;
1136 }
1137 return 0;
1138}
1139
1140static int remove_empty_directories(struct strbuf *path)
1141{
1142 /*
1143 * we want to create a file but there is a directory there;
1144 * if that is an empty directory (or a directory that contains
1145 * only empty directories), remove them.
1146 */
1147 return remove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);
1148}
1149
3b5d3c98
MH
1150static int create_reflock(const char *path, void *cb)
1151{
1152 struct lock_file *lk = cb;
1153
1154 return hold_lock_file_for_update(lk, path, LOCK_NO_DEREF) < 0 ? -1 : 0;
1155}
1156
7bd9bcf3
MH
1157/*
1158 * Locks a ref returning the lock on success and NULL on failure.
1159 * On failure errno is set to something meaningful.
1160 */
7eb27cdf
MH
1161static struct ref_lock *lock_ref_sha1_basic(struct files_ref_store *refs,
1162 const char *refname,
7bd9bcf3
MH
1163 const unsigned char *old_sha1,
1164 const struct string_list *extras,
1165 const struct string_list *skip,
bcb497d0 1166 unsigned int flags, int *type,
7bd9bcf3
MH
1167 struct strbuf *err)
1168{
1169 struct strbuf ref_file = STRBUF_INIT;
7bd9bcf3
MH
1170 struct ref_lock *lock;
1171 int last_errno = 0;
7bd9bcf3 1172 int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
7a418f3a 1173 int resolve_flags = RESOLVE_REF_NO_RECURSE;
7a418f3a 1174 int resolved;
7bd9bcf3 1175
32c597e7 1176 files_assert_main_repository(refs, "lock_ref_sha1_basic");
7bd9bcf3
MH
1177 assert(err);
1178
1179 lock = xcalloc(1, sizeof(struct ref_lock));
1180
1181 if (mustexist)
1182 resolve_flags |= RESOLVE_REF_READING;
2859dcd4 1183 if (flags & REF_DELETING)
7bd9bcf3 1184 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;
7bd9bcf3 1185
19e02f4f 1186 files_ref_path(refs, &ref_file, refname);
2f40e954
NTND
1187 resolved = !!refs_resolve_ref_unsafe(&refs->base,
1188 refname, resolve_flags,
1189 lock->old_oid.hash, type);
7a418f3a 1190 if (!resolved && errno == EISDIR) {
7bd9bcf3
MH
1191 /*
1192 * we are trying to lock foo but we used to
1193 * have foo/bar which now does not exist;
1194 * it is normal for the empty directory 'foo'
1195 * to remain.
1196 */
7a418f3a 1197 if (remove_empty_directories(&ref_file)) {
7bd9bcf3 1198 last_errno = errno;
b05855b5
MH
1199 if (!refs_verify_refname_available(
1200 &refs->base,
1201 refname, extras, skip, err))
7bd9bcf3 1202 strbuf_addf(err, "there are still refs under '%s'",
7a418f3a 1203 refname);
7bd9bcf3
MH
1204 goto error_return;
1205 }
2f40e954
NTND
1206 resolved = !!refs_resolve_ref_unsafe(&refs->base,
1207 refname, resolve_flags,
1208 lock->old_oid.hash, type);
7bd9bcf3 1209 }
7a418f3a 1210 if (!resolved) {
7bd9bcf3
MH
1211 last_errno = errno;
1212 if (last_errno != ENOTDIR ||
b05855b5
MH
1213 !refs_verify_refname_available(&refs->base, refname,
1214 extras, skip, err))
0568c8e9 1215 strbuf_addf(err, "unable to resolve reference '%s': %s",
7a418f3a 1216 refname, strerror(last_errno));
7bd9bcf3
MH
1217
1218 goto error_return;
1219 }
2859dcd4 1220
7bd9bcf3
MH
1221 /*
1222 * If the ref did not exist and we are creating it, make sure
1223 * there is no existing packed ref whose name begins with our
1224 * refname, nor a packed ref whose name is a proper prefix of
1225 * our refname.
1226 */
1227 if (is_null_oid(&lock->old_oid) &&
524a9fdb
MH
1228 refs_verify_refname_available(&refs->base, refname,
1229 extras, skip, err)) {
7bd9bcf3
MH
1230 last_errno = ENOTDIR;
1231 goto error_return;
1232 }
1233
1234 lock->lk = xcalloc(1, sizeof(struct lock_file));
1235
7bd9bcf3 1236 lock->ref_name = xstrdup(refname);
7bd9bcf3 1237
3b5d3c98 1238 if (raceproof_create_file(ref_file.buf, create_reflock, lock->lk)) {
7bd9bcf3 1239 last_errno = errno;
3b5d3c98 1240 unable_to_lock_message(ref_file.buf, errno, err);
7bd9bcf3
MH
1241 goto error_return;
1242 }
1243
2f40e954 1244 if (verify_lock(&refs->base, lock, old_sha1, mustexist, err)) {
7bd9bcf3
MH
1245 last_errno = errno;
1246 goto error_return;
1247 }
1248 goto out;
1249
1250 error_return:
1251 unlock_ref(lock);
1252 lock = NULL;
1253
1254 out:
1255 strbuf_release(&ref_file);
7bd9bcf3
MH
1256 errno = last_errno;
1257 return lock;
1258}
1259
1260/*
1261 * Write an entry to the packed-refs file for the specified refname.
1262 * If peeled is non-NULL, write it as the entry's peeled value.
1263 */
1710fbaf
MH
1264static void write_packed_entry(FILE *fh, const char *refname,
1265 const unsigned char *sha1,
1266 const unsigned char *peeled)
7bd9bcf3
MH
1267{
1268 fprintf_or_die(fh, "%s %s\n", sha1_to_hex(sha1), refname);
1269 if (peeled)
1270 fprintf_or_die(fh, "^%s\n", sha1_to_hex(peeled));
1271}
1272
7bd9bcf3
MH
1273/*
1274 * Lock the packed-refs file for writing. Flags is passed to
1275 * hold_lock_file_for_update(). Return 0 on success. On errors, set
1276 * errno appropriately and return a nonzero value.
1277 */
49c0df6a 1278static int lock_packed_refs(struct files_ref_store *refs, int flags)
7bd9bcf3
MH
1279{
1280 static int timeout_configured = 0;
1281 static int timeout_value = 1000;
7bd9bcf3
MH
1282 struct packed_ref_cache *packed_ref_cache;
1283
32c597e7 1284 files_assert_main_repository(refs, "lock_packed_refs");
49c0df6a 1285
7bd9bcf3
MH
1286 if (!timeout_configured) {
1287 git_config_get_int("core.packedrefstimeout", &timeout_value);
1288 timeout_configured = 1;
1289 }
1290
1291 if (hold_lock_file_for_update_timeout(
00d17448 1292 &refs->packed_refs_lock, files_packed_refs_path(refs),
7bd9bcf3
MH
1293 flags, timeout_value) < 0)
1294 return -1;
1295 /*
28ed9830
MH
1296 * Get the current packed-refs while holding the lock. It is
1297 * important that we call `get_packed_ref_cache()` before
1298 * setting `packed_ref_cache->lock`, because otherwise the
1299 * former will see that the file is locked and assume that the
1300 * cache can't be stale.
7bd9bcf3 1301 */
00eebe35 1302 packed_ref_cache = get_packed_ref_cache(refs);
7bd9bcf3
MH
1303 /* Increment the reference count to prevent it from being freed: */
1304 acquire_packed_ref_cache(packed_ref_cache);
1305 return 0;
1306}
1307
1308/*
1309 * Write the current version of the packed refs cache from memory to
1310 * disk. The packed-refs file must already be locked for writing (see
1311 * lock_packed_refs()). Return zero on success. On errors, set errno
1312 * and return a nonzero value
1313 */
49c0df6a 1314static int commit_packed_refs(struct files_ref_store *refs)
7bd9bcf3
MH
1315{
1316 struct packed_ref_cache *packed_ref_cache =
00eebe35 1317 get_packed_ref_cache(refs);
1710fbaf 1318 int ok, error = 0;
7bd9bcf3
MH
1319 int save_errno = 0;
1320 FILE *out;
1710fbaf 1321 struct ref_iterator *iter;
7bd9bcf3 1322
32c597e7 1323 files_assert_main_repository(refs, "commit_packed_refs");
49c0df6a 1324
00d17448 1325 if (!is_lock_file_locked(&refs->packed_refs_lock))
04aea8d4 1326 die("BUG: packed-refs not locked");
7bd9bcf3 1327
00d17448 1328 out = fdopen_lock_file(&refs->packed_refs_lock, "w");
7bd9bcf3
MH
1329 if (!out)
1330 die_errno("unable to fdopen packed-refs descriptor");
1331
1332 fprintf_or_die(out, "%s", PACKED_REFS_HEADER);
1710fbaf
MH
1333
1334 iter = cache_ref_iterator_begin(packed_ref_cache->cache, NULL, 0);
1335 while ((ok = ref_iterator_advance(iter)) == ITER_OK) {
1336 struct object_id peeled;
1337 int peel_error = ref_iterator_peel(iter, &peeled);
1338
1339 write_packed_entry(out, iter->refname, iter->oid->hash,
1340 peel_error ? NULL : peeled.hash);
1341 }
1342
1343 if (ok != ITER_DONE)
1344 die("error while iterating over references");
7bd9bcf3 1345
00d17448 1346 if (commit_lock_file(&refs->packed_refs_lock)) {
7bd9bcf3
MH
1347 save_errno = errno;
1348 error = -1;
1349 }
7bd9bcf3
MH
1350 release_packed_ref_cache(packed_ref_cache);
1351 errno = save_errno;
1352 return error;
1353}
1354
1355/*
1356 * Rollback the lockfile for the packed-refs file, and discard the
1357 * in-memory packed reference cache. (The packed-refs file will be
1358 * read anew if it is needed again after this function is called.)
1359 */
49c0df6a 1360static void rollback_packed_refs(struct files_ref_store *refs)
7bd9bcf3
MH
1361{
1362 struct packed_ref_cache *packed_ref_cache =
00eebe35 1363 get_packed_ref_cache(refs);
7bd9bcf3 1364
32c597e7 1365 files_assert_main_repository(refs, "rollback_packed_refs");
7bd9bcf3 1366
00d17448 1367 if (!is_lock_file_locked(&refs->packed_refs_lock))
04aea8d4 1368 die("BUG: packed-refs not locked");
00d17448 1369 rollback_lock_file(&refs->packed_refs_lock);
7bd9bcf3 1370 release_packed_ref_cache(packed_ref_cache);
00eebe35 1371 clear_packed_ref_cache(refs);
7bd9bcf3
MH
1372}
1373
1374struct ref_to_prune {
1375 struct ref_to_prune *next;
1376 unsigned char sha1[20];
1377 char name[FLEX_ARRAY];
1378};
1379
a8f0db2d
MH
1380enum {
1381 REMOVE_EMPTY_PARENTS_REF = 0x01,
1382 REMOVE_EMPTY_PARENTS_REFLOG = 0x02
1383};
1384
7bd9bcf3 1385/*
a8f0db2d
MH
1386 * Remove empty parent directories associated with the specified
1387 * reference and/or its reflog, but spare [logs/]refs/ and immediate
1388 * subdirs. flags is a combination of REMOVE_EMPTY_PARENTS_REF and/or
1389 * REMOVE_EMPTY_PARENTS_REFLOG.
7bd9bcf3 1390 */
802de3da
NTND
1391static void try_remove_empty_parents(struct files_ref_store *refs,
1392 const char *refname,
1393 unsigned int flags)
7bd9bcf3 1394{
8bdaecb4 1395 struct strbuf buf = STRBUF_INIT;
e9dcc305 1396 struct strbuf sb = STRBUF_INIT;
7bd9bcf3
MH
1397 char *p, *q;
1398 int i;
8bdaecb4
MH
1399
1400 strbuf_addstr(&buf, refname);
1401 p = buf.buf;
7bd9bcf3
MH
1402 for (i = 0; i < 2; i++) { /* refs/{heads,tags,...}/ */
1403 while (*p && *p != '/')
1404 p++;
1405 /* tolerate duplicate slashes; see check_refname_format() */
1406 while (*p == '/')
1407 p++;
1408 }
8bdaecb4 1409 q = buf.buf + buf.len;
a8f0db2d 1410 while (flags & (REMOVE_EMPTY_PARENTS_REF | REMOVE_EMPTY_PARENTS_REFLOG)) {
7bd9bcf3
MH
1411 while (q > p && *q != '/')
1412 q--;
1413 while (q > p && *(q-1) == '/')
1414 q--;
1415 if (q == p)
1416 break;
8bdaecb4 1417 strbuf_setlen(&buf, q - buf.buf);
e9dcc305
NTND
1418
1419 strbuf_reset(&sb);
19e02f4f 1420 files_ref_path(refs, &sb, buf.buf);
e9dcc305 1421 if ((flags & REMOVE_EMPTY_PARENTS_REF) && rmdir(sb.buf))
a8f0db2d 1422 flags &= ~REMOVE_EMPTY_PARENTS_REF;
e9dcc305
NTND
1423
1424 strbuf_reset(&sb);
802de3da 1425 files_reflog_path(refs, &sb, buf.buf);
e9dcc305 1426 if ((flags & REMOVE_EMPTY_PARENTS_REFLOG) && rmdir(sb.buf))
a8f0db2d 1427 flags &= ~REMOVE_EMPTY_PARENTS_REFLOG;
7bd9bcf3 1428 }
8bdaecb4 1429 strbuf_release(&buf);
e9dcc305 1430 strbuf_release(&sb);
7bd9bcf3
MH
1431}
1432
1433/* make sure nobody touched the ref, and unlink */
2f40e954 1434static void prune_ref(struct files_ref_store *refs, struct ref_to_prune *r)
7bd9bcf3
MH
1435{
1436 struct ref_transaction *transaction;
1437 struct strbuf err = STRBUF_INIT;
1438
1439 if (check_refname_format(r->name, 0))
1440 return;
1441
2f40e954 1442 transaction = ref_store_transaction_begin(&refs->base, &err);
7bd9bcf3
MH
1443 if (!transaction ||
1444 ref_transaction_delete(transaction, r->name, r->sha1,
c52ce248 1445 REF_ISPRUNING | REF_NODEREF, NULL, &err) ||
7bd9bcf3
MH
1446 ref_transaction_commit(transaction, &err)) {
1447 ref_transaction_free(transaction);
1448 error("%s", err.buf);
1449 strbuf_release(&err);
1450 return;
1451 }
1452 ref_transaction_free(transaction);
1453 strbuf_release(&err);
7bd9bcf3
MH
1454}
1455
2f40e954 1456static void prune_refs(struct files_ref_store *refs, struct ref_to_prune *r)
7bd9bcf3
MH
1457{
1458 while (r) {
2f40e954 1459 prune_ref(refs, r);
7bd9bcf3
MH
1460 r = r->next;
1461 }
1462}
1463
531cc4a5
MH
1464/*
1465 * Return true if the specified reference should be packed.
1466 */
1467static int should_pack_ref(const char *refname,
1468 const struct object_id *oid, unsigned int ref_flags,
1469 unsigned int pack_flags)
1470{
1471 /* Do not pack per-worktree refs: */
1472 if (ref_type(refname) != REF_TYPE_NORMAL)
1473 return 0;
1474
1475 /* Do not pack non-tags unless PACK_REFS_ALL is set: */
1476 if (!(pack_flags & PACK_REFS_ALL) && !starts_with(refname, "refs/tags/"))
1477 return 0;
1478
1479 /* Do not pack symbolic refs: */
1480 if (ref_flags & REF_ISSYMREF)
1481 return 0;
1482
1483 /* Do not pack broken refs: */
1484 if (!ref_resolves_to_object(refname, oid, ref_flags))
1485 return 0;
1486
1487 return 1;
1488}
1489
8231527e 1490static int files_pack_refs(struct ref_store *ref_store, unsigned int flags)
7bd9bcf3 1491{
00eebe35 1492 struct files_ref_store *refs =
9e7ec634
NTND
1493 files_downcast(ref_store, REF_STORE_WRITE | REF_STORE_ODB,
1494 "pack_refs");
50c2d855
MH
1495 struct ref_iterator *iter;
1496 struct ref_dir *packed_refs;
1497 int ok;
1498 struct ref_to_prune *refs_to_prune = NULL;
7bd9bcf3 1499
49c0df6a 1500 lock_packed_refs(refs, LOCK_DIE_ON_ERROR);
50c2d855
MH
1501 packed_refs = get_packed_refs(refs);
1502
1503 iter = cache_ref_iterator_begin(get_loose_ref_cache(refs), NULL, 0);
1504 while ((ok = ref_iterator_advance(iter)) == ITER_OK) {
1505 /*
1506 * If the loose reference can be packed, add an entry
1507 * in the packed ref cache. If the reference should be
1508 * pruned, also add it to refs_to_prune.
1509 */
1510 struct ref_entry *packed_entry;
7bd9bcf3 1511
531cc4a5
MH
1512 if (!should_pack_ref(iter->refname, iter->oid, iter->flags,
1513 flags))
50c2d855
MH
1514 continue;
1515
1516 /*
1517 * Create an entry in the packed-refs cache equivalent
1518 * to the one from the loose ref cache, except that
1519 * we don't copy the peeled status, because we want it
1520 * to be re-peeled.
1521 */
1522 packed_entry = find_ref_entry(packed_refs, iter->refname);
1523 if (packed_entry) {
1524 /* Overwrite existing packed entry with info from loose entry */
1525 packed_entry->flag = REF_ISPACKED;
1526 oidcpy(&packed_entry->u.value.oid, iter->oid);
1527 } else {
4417df8c 1528 packed_entry = create_ref_entry(iter->refname, iter->oid,
50c2d855
MH
1529 REF_ISPACKED, 0);
1530 add_ref_entry(packed_refs, packed_entry);
1531 }
1532 oidclr(&packed_entry->u.value.peeled);
1533
1534 /* Schedule the loose reference for pruning if requested. */
1535 if ((flags & PACK_REFS_PRUNE)) {
1536 struct ref_to_prune *n;
1537 FLEX_ALLOC_STR(n, name, iter->refname);
1538 hashcpy(n->sha1, iter->oid->hash);
1539 n->next = refs_to_prune;
1540 refs_to_prune = n;
1541 }
1542 }
1543 if (ok != ITER_DONE)
1544 die("error while iterating over references");
7bd9bcf3 1545
49c0df6a 1546 if (commit_packed_refs(refs))
7bd9bcf3
MH
1547 die_errno("unable to overwrite old ref-pack file");
1548
50c2d855 1549 prune_refs(refs, refs_to_prune);
7bd9bcf3
MH
1550 return 0;
1551}
1552
1553/*
1554 * Rewrite the packed-refs file, omitting any refs listed in
1555 * 'refnames'. On error, leave packed-refs unchanged, write an error
1556 * message to 'err', and return a nonzero value.
1557 *
1558 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.
1559 */
0a95ac5f
MH
1560static int repack_without_refs(struct files_ref_store *refs,
1561 struct string_list *refnames, struct strbuf *err)
7bd9bcf3
MH
1562{
1563 struct ref_dir *packed;
1564 struct string_list_item *refname;
1565 int ret, needs_repacking = 0, removed = 0;
1566
32c597e7 1567 files_assert_main_repository(refs, "repack_without_refs");
7bd9bcf3
MH
1568 assert(err);
1569
1570 /* Look for a packed ref */
1571 for_each_string_list_item(refname, refnames) {
f0d21efc 1572 if (get_packed_ref(refs, refname->string)) {
7bd9bcf3
MH
1573 needs_repacking = 1;
1574 break;
1575 }
1576 }
1577
1578 /* Avoid locking if we have nothing to do */
1579 if (!needs_repacking)
1580 return 0; /* no refname exists in packed refs */
1581
49c0df6a 1582 if (lock_packed_refs(refs, 0)) {
33dfb9f3 1583 unable_to_lock_message(files_packed_refs_path(refs), errno, err);
7bd9bcf3
MH
1584 return -1;
1585 }
00eebe35 1586 packed = get_packed_refs(refs);
7bd9bcf3
MH
1587
1588 /* Remove refnames from the cache */
1589 for_each_string_list_item(refname, refnames)
9fc3b063 1590 if (remove_entry_from_dir(packed, refname->string) != -1)
7bd9bcf3
MH
1591 removed = 1;
1592 if (!removed) {
1593 /*
1594 * All packed entries disappeared while we were
1595 * acquiring the lock.
1596 */
49c0df6a 1597 rollback_packed_refs(refs);
7bd9bcf3
MH
1598 return 0;
1599 }
1600
1601 /* Write what remains */
49c0df6a 1602 ret = commit_packed_refs(refs);
7bd9bcf3
MH
1603 if (ret)
1604 strbuf_addf(err, "unable to overwrite old ref-pack file: %s",
1605 strerror(errno));
1606 return ret;
1607}
1608
64da4199 1609static int files_delete_refs(struct ref_store *ref_store, const char *msg,
a27dcf89 1610 struct string_list *refnames, unsigned int flags)
7bd9bcf3 1611{
0a95ac5f 1612 struct files_ref_store *refs =
9e7ec634 1613 files_downcast(ref_store, REF_STORE_WRITE, "delete_refs");
7bd9bcf3
MH
1614 struct strbuf err = STRBUF_INIT;
1615 int i, result = 0;
1616
1617 if (!refnames->nr)
1618 return 0;
1619
0a95ac5f 1620 result = repack_without_refs(refs, refnames, &err);
7bd9bcf3
MH
1621 if (result) {
1622 /*
1623 * If we failed to rewrite the packed-refs file, then
1624 * it is unsafe to try to remove loose refs, because
1625 * doing so might expose an obsolete packed value for
1626 * a reference that might even point at an object that
1627 * has been garbage collected.
1628 */
1629 if (refnames->nr == 1)
1630 error(_("could not delete reference %s: %s"),
1631 refnames->items[0].string, err.buf);
1632 else
1633 error(_("could not delete references: %s"), err.buf);
1634
1635 goto out;
1636 }
1637
1638 for (i = 0; i < refnames->nr; i++) {
1639 const char *refname = refnames->items[i].string;
1640
64da4199 1641 if (refs_delete_ref(&refs->base, msg, refname, NULL, flags))
7bd9bcf3
MH
1642 result |= error(_("could not remove reference %s"), refname);
1643 }
1644
1645out:
1646 strbuf_release(&err);
1647 return result;
1648}
1649
1650/*
1651 * People using contrib's git-new-workdir have .git/logs/refs ->
1652 * /some/other/path/.git/logs/refs, and that may live on another device.
1653 *
1654 * IOW, to avoid cross device rename errors, the temporary renamed log must
1655 * live into logs/refs.
1656 */
a5c1efd6 1657#define TMP_RENAMED_LOG "refs/.tmp-renamed-log"
7bd9bcf3 1658
e9dcc305
NTND
1659struct rename_cb {
1660 const char *tmp_renamed_log;
1661 int true_errno;
1662};
1663
1664static int rename_tmp_log_callback(const char *path, void *cb_data)
7bd9bcf3 1665{
e9dcc305 1666 struct rename_cb *cb = cb_data;
7bd9bcf3 1667
e9dcc305 1668 if (rename(cb->tmp_renamed_log, path)) {
6a7f3631
MH
1669 /*
1670 * rename(a, b) when b is an existing directory ought
1671 * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.
1672 * Sheesh. Record the true errno for error reporting,
1673 * but report EISDIR to raceproof_create_file() so
1674 * that it knows to retry.
1675 */
e9dcc305 1676 cb->true_errno = errno;
6a7f3631
MH
1677 if (errno == ENOTDIR)
1678 errno = EISDIR;
1679 return -1;
1680 } else {
1681 return 0;
7bd9bcf3 1682 }
6a7f3631 1683}
7bd9bcf3 1684
802de3da 1685static int rename_tmp_log(struct files_ref_store *refs, const char *newrefname)
6a7f3631 1686{
e9dcc305
NTND
1687 struct strbuf path = STRBUF_INIT;
1688 struct strbuf tmp = STRBUF_INIT;
1689 struct rename_cb cb;
1690 int ret;
6a7f3631 1691
802de3da
NTND
1692 files_reflog_path(refs, &path, newrefname);
1693 files_reflog_path(refs, &tmp, TMP_RENAMED_LOG);
e9dcc305
NTND
1694 cb.tmp_renamed_log = tmp.buf;
1695 ret = raceproof_create_file(path.buf, rename_tmp_log_callback, &cb);
6a7f3631
MH
1696 if (ret) {
1697 if (errno == EISDIR)
e9dcc305 1698 error("directory not empty: %s", path.buf);
6a7f3631 1699 else
990c98d2 1700 error("unable to move logfile %s to %s: %s",
e9dcc305
NTND
1701 tmp.buf, path.buf,
1702 strerror(cb.true_errno));
7bd9bcf3 1703 }
6a7f3631 1704
e9dcc305
NTND
1705 strbuf_release(&path);
1706 strbuf_release(&tmp);
7bd9bcf3
MH
1707 return ret;
1708}
1709
7bd9bcf3 1710static int write_ref_to_lockfile(struct ref_lock *lock,
4417df8c 1711 const struct object_id *oid, struct strbuf *err);
f18a7892
MH
1712static int commit_ref_update(struct files_ref_store *refs,
1713 struct ref_lock *lock,
4417df8c 1714 const struct object_id *oid, const char *logmsg,
5d9b2de4 1715 struct strbuf *err);
7bd9bcf3 1716
9b6b40d9
DT
1717static int files_rename_ref(struct ref_store *ref_store,
1718 const char *oldrefname, const char *newrefname,
1719 const char *logmsg)
7bd9bcf3 1720{
9b6b40d9 1721 struct files_ref_store *refs =
9e7ec634 1722 files_downcast(ref_store, REF_STORE_WRITE, "rename_ref");
4417df8c 1723 struct object_id oid, orig_oid;
7bd9bcf3
MH
1724 int flag = 0, logmoved = 0;
1725 struct ref_lock *lock;
1726 struct stat loginfo;
e9dcc305
NTND
1727 struct strbuf sb_oldref = STRBUF_INIT;
1728 struct strbuf sb_newref = STRBUF_INIT;
1729 struct strbuf tmp_renamed_log = STRBUF_INIT;
1730 int log, ret;
7bd9bcf3
MH
1731 struct strbuf err = STRBUF_INIT;
1732
802de3da
NTND
1733 files_reflog_path(refs, &sb_oldref, oldrefname);
1734 files_reflog_path(refs, &sb_newref, newrefname);
1735 files_reflog_path(refs, &tmp_renamed_log, TMP_RENAMED_LOG);
e9dcc305
NTND
1736
1737 log = !lstat(sb_oldref.buf, &loginfo);
0a3f07d6
NTND
1738 if (log && S_ISLNK(loginfo.st_mode)) {
1739 ret = error("reflog for %s is a symlink", oldrefname);
1740 goto out;
1741 }
7bd9bcf3 1742
2f40e954
NTND
1743 if (!refs_resolve_ref_unsafe(&refs->base, oldrefname,
1744 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,
4417df8c 1745 orig_oid.hash, &flag)) {
0a3f07d6
NTND
1746 ret = error("refname %s not found", oldrefname);
1747 goto out;
1748 }
e711b1af 1749
0a3f07d6
NTND
1750 if (flag & REF_ISSYMREF) {
1751 ret = error("refname %s is a symbolic ref, renaming it is not supported",
1752 oldrefname);
1753 goto out;
1754 }
7d2df051 1755 if (!refs_rename_ref_available(&refs->base, oldrefname, newrefname)) {
0a3f07d6
NTND
1756 ret = 1;
1757 goto out;
1758 }
7bd9bcf3 1759
e9dcc305 1760 if (log && rename(sb_oldref.buf, tmp_renamed_log.buf)) {
a5c1efd6 1761 ret = error("unable to move logfile logs/%s to logs/"TMP_RENAMED_LOG": %s",
0a3f07d6
NTND
1762 oldrefname, strerror(errno));
1763 goto out;
1764 }
7bd9bcf3 1765
2f40e954 1766 if (refs_delete_ref(&refs->base, logmsg, oldrefname,
4417df8c 1767 orig_oid.hash, REF_NODEREF)) {
7bd9bcf3
MH
1768 error("unable to delete old %s", oldrefname);
1769 goto rollback;
1770 }
1771
12fd3496 1772 /*
4417df8c 1773 * Since we are doing a shallow lookup, oid is not the
1774 * correct value to pass to delete_ref as old_oid. But that
1775 * doesn't matter, because an old_oid check wouldn't add to
12fd3496
DT
1776 * the safety anyway; we want to delete the reference whatever
1777 * its current value.
1778 */
2f40e954
NTND
1779 if (!refs_read_ref_full(&refs->base, newrefname,
1780 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,
4417df8c 1781 oid.hash, NULL) &&
2f40e954
NTND
1782 refs_delete_ref(&refs->base, NULL, newrefname,
1783 NULL, REF_NODEREF)) {
58364324 1784 if (errno == EISDIR) {
7bd9bcf3
MH
1785 struct strbuf path = STRBUF_INIT;
1786 int result;
1787
19e02f4f 1788 files_ref_path(refs, &path, newrefname);
7bd9bcf3
MH
1789 result = remove_empty_directories(&path);
1790 strbuf_release(&path);
1791
1792 if (result) {
1793 error("Directory not empty: %s", newrefname);
1794 goto rollback;
1795 }
1796 } else {
1797 error("unable to delete existing %s", newrefname);
1798 goto rollback;
1799 }
1800 }
1801
802de3da 1802 if (log && rename_tmp_log(refs, newrefname))
7bd9bcf3
MH
1803 goto rollback;
1804
1805 logmoved = log;
1806
7eb27cdf
MH
1807 lock = lock_ref_sha1_basic(refs, newrefname, NULL, NULL, NULL,
1808 REF_NODEREF, NULL, &err);
7bd9bcf3
MH
1809 if (!lock) {
1810 error("unable to rename '%s' to '%s': %s", oldrefname, newrefname, err.buf);
1811 strbuf_release(&err);
1812 goto rollback;
1813 }
4417df8c 1814 oidcpy(&lock->old_oid, &orig_oid);
7bd9bcf3 1815
4417df8c 1816 if (write_ref_to_lockfile(lock, &orig_oid, &err) ||
1817 commit_ref_update(refs, lock, &orig_oid, logmsg, &err)) {
7bd9bcf3
MH
1818 error("unable to write current sha1 into %s: %s", newrefname, err.buf);
1819 strbuf_release(&err);
1820 goto rollback;
1821 }
1822
0a3f07d6
NTND
1823 ret = 0;
1824 goto out;
7bd9bcf3
MH
1825
1826 rollback:
7eb27cdf
MH
1827 lock = lock_ref_sha1_basic(refs, oldrefname, NULL, NULL, NULL,
1828 REF_NODEREF, NULL, &err);
7bd9bcf3
MH
1829 if (!lock) {
1830 error("unable to lock %s for rollback: %s", oldrefname, err.buf);
1831 strbuf_release(&err);
1832 goto rollbacklog;
1833 }
1834
1835 flag = log_all_ref_updates;
341fb286 1836 log_all_ref_updates = LOG_REFS_NONE;
4417df8c 1837 if (write_ref_to_lockfile(lock, &orig_oid, &err) ||
1838 commit_ref_update(refs, lock, &orig_oid, NULL, &err)) {
7bd9bcf3
MH
1839 error("unable to write current sha1 into %s: %s", oldrefname, err.buf);
1840 strbuf_release(&err);
1841 }
1842 log_all_ref_updates = flag;
1843
1844 rollbacklog:
e9dcc305 1845 if (logmoved && rename(sb_newref.buf, sb_oldref.buf))
7bd9bcf3
MH
1846 error("unable to restore logfile %s from %s: %s",
1847 oldrefname, newrefname, strerror(errno));
1848 if (!logmoved && log &&
e9dcc305 1849 rename(tmp_renamed_log.buf, sb_oldref.buf))
a5c1efd6 1850 error("unable to restore logfile %s from logs/"TMP_RENAMED_LOG": %s",
7bd9bcf3 1851 oldrefname, strerror(errno));
0a3f07d6
NTND
1852 ret = 1;
1853 out:
e9dcc305
NTND
1854 strbuf_release(&sb_newref);
1855 strbuf_release(&sb_oldref);
1856 strbuf_release(&tmp_renamed_log);
1857
0a3f07d6 1858 return ret;
7bd9bcf3
MH
1859}
1860
1861static int close_ref(struct ref_lock *lock)
1862{
1863 if (close_lock_file(lock->lk))
1864 return -1;
1865 return 0;
1866}
1867
1868static int commit_ref(struct ref_lock *lock)
1869{
5387c0d8
MH
1870 char *path = get_locked_file_path(lock->lk);
1871 struct stat st;
1872
1873 if (!lstat(path, &st) && S_ISDIR(st.st_mode)) {
1874 /*
1875 * There is a directory at the path we want to rename
1876 * the lockfile to. Hopefully it is empty; try to
1877 * delete it.
1878 */
1879 size_t len = strlen(path);
1880 struct strbuf sb_path = STRBUF_INIT;
1881
1882 strbuf_attach(&sb_path, path, len, len);
1883
1884 /*
1885 * If this fails, commit_lock_file() will also fail
1886 * and will report the problem.
1887 */
1888 remove_empty_directories(&sb_path);
1889 strbuf_release(&sb_path);
1890 } else {
1891 free(path);
1892 }
1893
7bd9bcf3
MH
1894 if (commit_lock_file(lock->lk))
1895 return -1;
1896 return 0;
1897}
1898
1fb0c809
MH
1899static int open_or_create_logfile(const char *path, void *cb)
1900{
1901 int *fd = cb;
1902
1903 *fd = open(path, O_APPEND | O_WRONLY | O_CREAT, 0666);
1904 return (*fd < 0) ? -1 : 0;
1905}
1906
7bd9bcf3 1907/*
4533e534
MH
1908 * Create a reflog for a ref. If force_create = 0, only create the
1909 * reflog for certain refs (those for which should_autocreate_reflog
1910 * returns non-zero). Otherwise, create it regardless of the reference
1911 * name. If the logfile already existed or was created, return 0 and
1912 * set *logfd to the file descriptor opened for appending to the file.
1913 * If no logfile exists and we decided not to create one, return 0 and
1914 * set *logfd to -1. On failure, fill in *err, set *logfd to -1, and
1915 * return -1.
7bd9bcf3 1916 */
802de3da
NTND
1917static int log_ref_setup(struct files_ref_store *refs,
1918 const char *refname, int force_create,
4533e534 1919 int *logfd, struct strbuf *err)
7bd9bcf3 1920{
802de3da
NTND
1921 struct strbuf logfile_sb = STRBUF_INIT;
1922 char *logfile;
1923
1924 files_reflog_path(refs, &logfile_sb, refname);
1925 logfile = strbuf_detach(&logfile_sb, NULL);
7bd9bcf3 1926
7bd9bcf3 1927 if (force_create || should_autocreate_reflog(refname)) {
4533e534 1928 if (raceproof_create_file(logfile, open_or_create_logfile, logfd)) {
1fb0c809
MH
1929 if (errno == ENOENT)
1930 strbuf_addf(err, "unable to create directory for '%s': "
4533e534 1931 "%s", logfile, strerror(errno));
1fb0c809
MH
1932 else if (errno == EISDIR)
1933 strbuf_addf(err, "there are still logs under '%s'",
4533e534 1934 logfile);
1fb0c809 1935 else
854bda6b 1936 strbuf_addf(err, "unable to append to '%s': %s",
4533e534 1937 logfile, strerror(errno));
7bd9bcf3 1938
4533e534 1939 goto error;
7bd9bcf3 1940 }
854bda6b 1941 } else {
4533e534 1942 *logfd = open(logfile, O_APPEND | O_WRONLY, 0666);
e404f459 1943 if (*logfd < 0) {
854bda6b
MH
1944 if (errno == ENOENT || errno == EISDIR) {
1945 /*
1946 * The logfile doesn't already exist,
1947 * but that is not an error; it only
1948 * means that we won't write log
1949 * entries to it.
1950 */
1951 ;
1952 } else {
1953 strbuf_addf(err, "unable to append to '%s': %s",
4533e534
MH
1954 logfile, strerror(errno));
1955 goto error;
854bda6b 1956 }
7bd9bcf3
MH
1957 }
1958 }
1959
e404f459 1960 if (*logfd >= 0)
4533e534 1961 adjust_shared_perm(logfile);
854bda6b 1962
4533e534 1963 free(logfile);
7bd9bcf3 1964 return 0;
7bd9bcf3 1965
4533e534
MH
1966error:
1967 free(logfile);
1968 return -1;
7bd9bcf3 1969}
7bd9bcf3 1970
e3688bd6
DT
1971static int files_create_reflog(struct ref_store *ref_store,
1972 const char *refname, int force_create,
1973 struct strbuf *err)
7bd9bcf3 1974{
802de3da 1975 struct files_ref_store *refs =
9e7ec634 1976 files_downcast(ref_store, REF_STORE_WRITE, "create_reflog");
e404f459 1977 int fd;
7bd9bcf3 1978
802de3da 1979 if (log_ref_setup(refs, refname, force_create, &fd, err))
4533e534
MH
1980 return -1;
1981
e404f459
MH
1982 if (fd >= 0)
1983 close(fd);
4533e534
MH
1984
1985 return 0;
7bd9bcf3
MH
1986}
1987
4417df8c 1988static int log_ref_write_fd(int fd, const struct object_id *old_oid,
1989 const struct object_id *new_oid,
7bd9bcf3
MH
1990 const char *committer, const char *msg)
1991{
1992 int msglen, written;
1993 unsigned maxlen, len;
1994 char *logrec;
1995
1996 msglen = msg ? strlen(msg) : 0;
1997 maxlen = strlen(committer) + msglen + 100;
1998 logrec = xmalloc(maxlen);
1999 len = xsnprintf(logrec, maxlen, "%s %s %s\n",
4417df8c 2000 oid_to_hex(old_oid),
2001 oid_to_hex(new_oid),
7bd9bcf3
MH
2002 committer);
2003 if (msglen)
2004 len += copy_reflog_msg(logrec + len - 1, msg) - 1;
2005
2006 written = len <= maxlen ? write_in_full(fd, logrec, len) : -1;
2007 free(logrec);
2008 if (written != len)
2009 return -1;
2010
2011 return 0;
2012}
2013
802de3da 2014static int files_log_ref_write(struct files_ref_store *refs,
4417df8c 2015 const char *refname, const struct object_id *old_oid,
2016 const struct object_id *new_oid, const char *msg,
11f8457f 2017 int flags, struct strbuf *err)
7bd9bcf3 2018{
e404f459 2019 int logfd, result;
7bd9bcf3 2020
341fb286
CW
2021 if (log_all_ref_updates == LOG_REFS_UNSET)
2022 log_all_ref_updates = is_bare_repository() ? LOG_REFS_NONE : LOG_REFS_NORMAL;
7bd9bcf3 2023
802de3da
NTND
2024 result = log_ref_setup(refs, refname,
2025 flags & REF_FORCE_CREATE_REFLOG,
4533e534 2026 &logfd, err);
7bd9bcf3
MH
2027
2028 if (result)
2029 return result;
2030
7bd9bcf3
MH
2031 if (logfd < 0)
2032 return 0;
4417df8c 2033 result = log_ref_write_fd(logfd, old_oid, new_oid,
7bd9bcf3
MH
2034 git_committer_info(0), msg);
2035 if (result) {
e9dcc305 2036 struct strbuf sb = STRBUF_INIT;
87b21e05
MH
2037 int save_errno = errno;
2038
802de3da 2039 files_reflog_path(refs, &sb, refname);
87b21e05 2040 strbuf_addf(err, "unable to append to '%s': %s",
e9dcc305
NTND
2041 sb.buf, strerror(save_errno));
2042 strbuf_release(&sb);
7bd9bcf3
MH
2043 close(logfd);
2044 return -1;
2045 }
2046 if (close(logfd)) {
e9dcc305 2047 struct strbuf sb = STRBUF_INIT;
87b21e05
MH
2048 int save_errno = errno;
2049
802de3da 2050 files_reflog_path(refs, &sb, refname);
87b21e05 2051 strbuf_addf(err, "unable to append to '%s': %s",
e9dcc305
NTND
2052 sb.buf, strerror(save_errno));
2053 strbuf_release(&sb);
7bd9bcf3
MH
2054 return -1;
2055 }
2056 return 0;
2057}
2058
7bd9bcf3
MH
2059/*
2060 * Write sha1 into the open lockfile, then close the lockfile. On
2061 * errors, rollback the lockfile, fill in *err and
2062 * return -1.
2063 */
2064static int write_ref_to_lockfile(struct ref_lock *lock,
4417df8c 2065 const struct object_id *oid, struct strbuf *err)
7bd9bcf3
MH
2066{
2067 static char term = '\n';
2068 struct object *o;
2069 int fd;
2070
c251c83d 2071 o = parse_object(oid);
7bd9bcf3
MH
2072 if (!o) {
2073 strbuf_addf(err,
0568c8e9 2074 "trying to write ref '%s' with nonexistent object %s",
4417df8c 2075 lock->ref_name, oid_to_hex(oid));
7bd9bcf3
MH
2076 unlock_ref(lock);
2077 return -1;
2078 }
2079 if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
2080 strbuf_addf(err,
0568c8e9 2081 "trying to write non-commit object %s to branch '%s'",
4417df8c 2082 oid_to_hex(oid), lock->ref_name);
7bd9bcf3
MH
2083 unlock_ref(lock);
2084 return -1;
2085 }
2086 fd = get_lock_file_fd(lock->lk);
4417df8c 2087 if (write_in_full(fd, oid_to_hex(oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||
7bd9bcf3
MH
2088 write_in_full(fd, &term, 1) != 1 ||
2089 close_ref(lock) < 0) {
2090 strbuf_addf(err,
0568c8e9 2091 "couldn't write '%s'", get_lock_file_path(lock->lk));
7bd9bcf3
MH
2092 unlock_ref(lock);
2093 return -1;
2094 }
2095 return 0;
2096}
2097
2098/*
2099 * Commit a change to a loose reference that has already been written
2100 * to the loose reference lockfile. Also update the reflogs if
2101 * necessary, using the specified lockmsg (which can be NULL).
2102 */
f18a7892
MH
2103static int commit_ref_update(struct files_ref_store *refs,
2104 struct ref_lock *lock,
4417df8c 2105 const struct object_id *oid, const char *logmsg,
5d9b2de4 2106 struct strbuf *err)
7bd9bcf3 2107{
32c597e7 2108 files_assert_main_repository(refs, "commit_ref_update");
00eebe35
MH
2109
2110 clear_loose_ref_cache(refs);
802de3da 2111 if (files_log_ref_write(refs, lock->ref_name,
4417df8c 2112 &lock->old_oid, oid,
81b1b6d4 2113 logmsg, 0, err)) {
7bd9bcf3 2114 char *old_msg = strbuf_detach(err, NULL);
0568c8e9 2115 strbuf_addf(err, "cannot update the ref '%s': %s",
7bd9bcf3
MH
2116 lock->ref_name, old_msg);
2117 free(old_msg);
2118 unlock_ref(lock);
2119 return -1;
2120 }
7a418f3a
MH
2121
2122 if (strcmp(lock->ref_name, "HEAD") != 0) {
7bd9bcf3
MH
2123 /*
2124 * Special hack: If a branch is updated directly and HEAD
2125 * points to it (may happen on the remote side of a push
2126 * for example) then logically the HEAD reflog should be
2127 * updated too.
2128 * A generic solution implies reverse symref information,
2129 * but finding all symrefs pointing to the given branch
2130 * would be rather costly for this rare event (the direct
2131 * update of a branch) to be worth it. So let's cheat and
2132 * check with HEAD only which should cover 99% of all usage
2133 * scenarios (even 100% of the default ones).
2134 */
4417df8c 2135 struct object_id head_oid;
7bd9bcf3
MH
2136 int head_flag;
2137 const char *head_ref;
7a418f3a 2138
2f40e954
NTND
2139 head_ref = refs_resolve_ref_unsafe(&refs->base, "HEAD",
2140 RESOLVE_REF_READING,
4417df8c 2141 head_oid.hash, &head_flag);
7bd9bcf3
MH
2142 if (head_ref && (head_flag & REF_ISSYMREF) &&
2143 !strcmp(head_ref, lock->ref_name)) {
2144 struct strbuf log_err = STRBUF_INIT;
802de3da 2145 if (files_log_ref_write(refs, "HEAD",
4417df8c 2146 &lock->old_oid, oid,
802de3da 2147 logmsg, 0, &log_err)) {
7bd9bcf3
MH
2148 error("%s", log_err.buf);
2149 strbuf_release(&log_err);
2150 }
2151 }
2152 }
7a418f3a 2153
7bd9bcf3 2154 if (commit_ref(lock)) {
0568c8e9 2155 strbuf_addf(err, "couldn't set '%s'", lock->ref_name);
7bd9bcf3
MH
2156 unlock_ref(lock);
2157 return -1;
2158 }
2159
2160 unlock_ref(lock);
2161 return 0;
2162}
2163
370e5ad6 2164static int create_ref_symlink(struct ref_lock *lock, const char *target)
7bd9bcf3 2165{
370e5ad6 2166 int ret = -1;
7bd9bcf3 2167#ifndef NO_SYMLINK_HEAD
370e5ad6
JK
2168 char *ref_path = get_locked_file_path(lock->lk);
2169 unlink(ref_path);
2170 ret = symlink(target, ref_path);
2171 free(ref_path);
2172
2173 if (ret)
7bd9bcf3 2174 fprintf(stderr, "no symlink - falling back to symbolic ref\n");
7bd9bcf3 2175#endif
370e5ad6
JK
2176 return ret;
2177}
7bd9bcf3 2178
802de3da
NTND
2179static void update_symref_reflog(struct files_ref_store *refs,
2180 struct ref_lock *lock, const char *refname,
370e5ad6
JK
2181 const char *target, const char *logmsg)
2182{
2183 struct strbuf err = STRBUF_INIT;
4417df8c 2184 struct object_id new_oid;
2f40e954
NTND
2185 if (logmsg &&
2186 !refs_read_ref_full(&refs->base, target,
4417df8c 2187 RESOLVE_REF_READING, new_oid.hash, NULL) &&
2188 files_log_ref_write(refs, refname, &lock->old_oid,
2189 &new_oid, logmsg, 0, &err)) {
7bd9bcf3
MH
2190 error("%s", err.buf);
2191 strbuf_release(&err);
2192 }
370e5ad6 2193}
7bd9bcf3 2194
802de3da
NTND
2195static int create_symref_locked(struct files_ref_store *refs,
2196 struct ref_lock *lock, const char *refname,
370e5ad6
JK
2197 const char *target, const char *logmsg)
2198{
2199 if (prefer_symlink_refs && !create_ref_symlink(lock, target)) {
802de3da 2200 update_symref_reflog(refs, lock, refname, target, logmsg);
370e5ad6
JK
2201 return 0;
2202 }
2203
2204 if (!fdopen_lock_file(lock->lk, "w"))
2205 return error("unable to fdopen %s: %s",
2206 lock->lk->tempfile.filename.buf, strerror(errno));
2207
802de3da 2208 update_symref_reflog(refs, lock, refname, target, logmsg);
396da8f7 2209
370e5ad6
JK
2210 /* no error check; commit_ref will check ferror */
2211 fprintf(lock->lk->tempfile.fp, "ref: %s\n", target);
2212 if (commit_ref(lock) < 0)
2213 return error("unable to write symref for %s: %s", refname,
2214 strerror(errno));
7bd9bcf3
MH
2215 return 0;
2216}
2217
284689ba
MH
2218static int files_create_symref(struct ref_store *ref_store,
2219 const char *refname, const char *target,
2220 const char *logmsg)
370e5ad6 2221{
7eb27cdf 2222 struct files_ref_store *refs =
9e7ec634 2223 files_downcast(ref_store, REF_STORE_WRITE, "create_symref");
370e5ad6
JK
2224 struct strbuf err = STRBUF_INIT;
2225 struct ref_lock *lock;
2226 int ret;
2227
7eb27cdf
MH
2228 lock = lock_ref_sha1_basic(refs, refname, NULL,
2229 NULL, NULL, REF_NODEREF, NULL,
370e5ad6
JK
2230 &err);
2231 if (!lock) {
2232 error("%s", err.buf);
2233 strbuf_release(&err);
2234 return -1;
2235 }
2236
802de3da 2237 ret = create_symref_locked(refs, lock, refname, target, logmsg);
370e5ad6
JK
2238 unlock_ref(lock);
2239 return ret;
2240}
2241
e3688bd6
DT
2242static int files_reflog_exists(struct ref_store *ref_store,
2243 const char *refname)
7bd9bcf3 2244{
802de3da 2245 struct files_ref_store *refs =
9e7ec634 2246 files_downcast(ref_store, REF_STORE_READ, "reflog_exists");
e9dcc305 2247 struct strbuf sb = STRBUF_INIT;
7bd9bcf3 2248 struct stat st;
e9dcc305 2249 int ret;
7bd9bcf3 2250
802de3da 2251 files_reflog_path(refs, &sb, refname);
e9dcc305
NTND
2252 ret = !lstat(sb.buf, &st) && S_ISREG(st.st_mode);
2253 strbuf_release(&sb);
2254 return ret;
7bd9bcf3
MH
2255}
2256
e3688bd6
DT
2257static int files_delete_reflog(struct ref_store *ref_store,
2258 const char *refname)
7bd9bcf3 2259{
802de3da 2260 struct files_ref_store *refs =
9e7ec634 2261 files_downcast(ref_store, REF_STORE_WRITE, "delete_reflog");
e9dcc305
NTND
2262 struct strbuf sb = STRBUF_INIT;
2263 int ret;
2264
802de3da 2265 files_reflog_path(refs, &sb, refname);
e9dcc305
NTND
2266 ret = remove_path(sb.buf);
2267 strbuf_release(&sb);
2268 return ret;
7bd9bcf3
MH
2269}
2270
2271static int show_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn, void *cb_data)
2272{
9461d272 2273 struct object_id ooid, noid;
7bd9bcf3 2274 char *email_end, *message;
dddbad72 2275 timestamp_t timestamp;
7bd9bcf3 2276 int tz;
43bc3b6c 2277 const char *p = sb->buf;
7bd9bcf3
MH
2278
2279 /* old SP new SP name <email> SP time TAB msg LF */
43bc3b6c 2280 if (!sb->len || sb->buf[sb->len - 1] != '\n' ||
2281 parse_oid_hex(p, &ooid, &p) || *p++ != ' ' ||
2282 parse_oid_hex(p, &noid, &p) || *p++ != ' ' ||
2283 !(email_end = strchr(p, '>')) ||
7bd9bcf3 2284 email_end[1] != ' ' ||
1aeb7e75 2285 !(timestamp = parse_timestamp(email_end + 2, &message, 10)) ||
7bd9bcf3
MH
2286 !message || message[0] != ' ' ||
2287 (message[1] != '+' && message[1] != '-') ||
2288 !isdigit(message[2]) || !isdigit(message[3]) ||
2289 !isdigit(message[4]) || !isdigit(message[5]))
2290 return 0; /* corrupt? */
2291 email_end[1] = '\0';
2292 tz = strtol(message + 1, NULL, 10);
2293 if (message[6] != '\t')
2294 message += 6;
2295 else
2296 message += 7;
43bc3b6c 2297 return fn(&ooid, &noid, p, timestamp, tz, message, cb_data);
7bd9bcf3
MH
2298}
2299
2300static char *find_beginning_of_line(char *bob, char *scan)
2301{
2302 while (bob < scan && *(--scan) != '\n')
2303 ; /* keep scanning backwards */
2304 /*
2305 * Return either beginning of the buffer, or LF at the end of
2306 * the previous line.
2307 */
2308 return scan;
2309}
2310
e3688bd6
DT
2311static int files_for_each_reflog_ent_reverse(struct ref_store *ref_store,
2312 const char *refname,
2313 each_reflog_ent_fn fn,
2314 void *cb_data)
7bd9bcf3 2315{
802de3da 2316 struct files_ref_store *refs =
9e7ec634
NTND
2317 files_downcast(ref_store, REF_STORE_READ,
2318 "for_each_reflog_ent_reverse");
7bd9bcf3
MH
2319 struct strbuf sb = STRBUF_INIT;
2320 FILE *logfp;
2321 long pos;
2322 int ret = 0, at_tail = 1;
2323
802de3da 2324 files_reflog_path(refs, &sb, refname);
e9dcc305
NTND
2325 logfp = fopen(sb.buf, "r");
2326 strbuf_release(&sb);
7bd9bcf3
MH
2327 if (!logfp)
2328 return -1;
2329
2330 /* Jump to the end */
2331 if (fseek(logfp, 0, SEEK_END) < 0)
be686f03
RS
2332 ret = error("cannot seek back reflog for %s: %s",
2333 refname, strerror(errno));
7bd9bcf3
MH
2334 pos = ftell(logfp);
2335 while (!ret && 0 < pos) {
2336 int cnt;
2337 size_t nread;
2338 char buf[BUFSIZ];
2339 char *endp, *scanp;
2340
2341 /* Fill next block from the end */
2342 cnt = (sizeof(buf) < pos) ? sizeof(buf) : pos;
be686f03
RS
2343 if (fseek(logfp, pos - cnt, SEEK_SET)) {
2344 ret = error("cannot seek back reflog for %s: %s",
2345 refname, strerror(errno));
2346 break;
2347 }
7bd9bcf3 2348 nread = fread(buf, cnt, 1, logfp);
be686f03
RS
2349 if (nread != 1) {
2350 ret = error("cannot read %d bytes from reflog for %s: %s",
2351 cnt, refname, strerror(errno));
2352 break;
2353 }
7bd9bcf3
MH
2354 pos -= cnt;
2355
2356 scanp = endp = buf + cnt;
2357 if (at_tail && scanp[-1] == '\n')
2358 /* Looking at the final LF at the end of the file */
2359 scanp--;
2360 at_tail = 0;
2361
2362 while (buf < scanp) {
2363 /*
2364 * terminating LF of the previous line, or the beginning
2365 * of the buffer.
2366 */
2367 char *bp;
2368
2369 bp = find_beginning_of_line(buf, scanp);
2370
2371 if (*bp == '\n') {
2372 /*
2373 * The newline is the end of the previous line,
2374 * so we know we have complete line starting
2375 * at (bp + 1). Prefix it onto any prior data
2376 * we collected for the line and process it.
2377 */
2378 strbuf_splice(&sb, 0, 0, bp + 1, endp - (bp + 1));
2379 scanp = bp;
2380 endp = bp + 1;
2381 ret = show_one_reflog_ent(&sb, fn, cb_data);
2382 strbuf_reset(&sb);
2383 if (ret)
2384 break;
2385 } else if (!pos) {
2386 /*
2387 * We are at the start of the buffer, and the
2388 * start of the file; there is no previous
2389 * line, and we have everything for this one.
2390 * Process it, and we can end the loop.
2391 */
2392 strbuf_splice(&sb, 0, 0, buf, endp - buf);
2393 ret = show_one_reflog_ent(&sb, fn, cb_data);
2394 strbuf_reset(&sb);
2395 break;
2396 }
2397
2398 if (bp == buf) {
2399 /*
2400 * We are at the start of the buffer, and there
2401 * is more file to read backwards. Which means
2402 * we are in the middle of a line. Note that we
2403 * may get here even if *bp was a newline; that
2404 * just means we are at the exact end of the
2405 * previous line, rather than some spot in the
2406 * middle.
2407 *
2408 * Save away what we have to be combined with
2409 * the data from the next read.
2410 */
2411 strbuf_splice(&sb, 0, 0, buf, endp - buf);
2412 break;
2413 }
2414 }
2415
2416 }
2417 if (!ret && sb.len)
2418 die("BUG: reverse reflog parser had leftover data");
2419
2420 fclose(logfp);
2421 strbuf_release(&sb);
2422 return ret;
2423}
2424
e3688bd6
DT
2425static int files_for_each_reflog_ent(struct ref_store *ref_store,
2426 const char *refname,
2427 each_reflog_ent_fn fn, void *cb_data)
7bd9bcf3 2428{
802de3da 2429 struct files_ref_store *refs =
9e7ec634
NTND
2430 files_downcast(ref_store, REF_STORE_READ,
2431 "for_each_reflog_ent");
7bd9bcf3
MH
2432 FILE *logfp;
2433 struct strbuf sb = STRBUF_INIT;
2434 int ret = 0;
2435
802de3da 2436 files_reflog_path(refs, &sb, refname);
e9dcc305
NTND
2437 logfp = fopen(sb.buf, "r");
2438 strbuf_release(&sb);
7bd9bcf3
MH
2439 if (!logfp)
2440 return -1;
2441
2442 while (!ret && !strbuf_getwholeline(&sb, logfp, '\n'))
2443 ret = show_one_reflog_ent(&sb, fn, cb_data);
2444 fclose(logfp);
2445 strbuf_release(&sb);
2446 return ret;
2447}
7bd9bcf3 2448
2880d16f
MH
2449struct files_reflog_iterator {
2450 struct ref_iterator base;
7bd9bcf3 2451
2f40e954 2452 struct ref_store *ref_store;
2880d16f
MH
2453 struct dir_iterator *dir_iterator;
2454 struct object_id oid;
2455};
7bd9bcf3 2456
2880d16f
MH
2457static int files_reflog_iterator_advance(struct ref_iterator *ref_iterator)
2458{
2459 struct files_reflog_iterator *iter =
2460 (struct files_reflog_iterator *)ref_iterator;
2461 struct dir_iterator *diter = iter->dir_iterator;
2462 int ok;
2463
2464 while ((ok = dir_iterator_advance(diter)) == ITER_OK) {
2465 int flags;
2466
2467 if (!S_ISREG(diter->st.st_mode))
7bd9bcf3 2468 continue;
2880d16f
MH
2469 if (diter->basename[0] == '.')
2470 continue;
2471 if (ends_with(diter->basename, ".lock"))
7bd9bcf3 2472 continue;
7bd9bcf3 2473
2f40e954
NTND
2474 if (refs_read_ref_full(iter->ref_store,
2475 diter->relative_path, 0,
2476 iter->oid.hash, &flags)) {
2880d16f
MH
2477 error("bad ref for %s", diter->path.buf);
2478 continue;
7bd9bcf3 2479 }
2880d16f
MH
2480
2481 iter->base.refname = diter->relative_path;
2482 iter->base.oid = &iter->oid;
2483 iter->base.flags = flags;
2484 return ITER_OK;
7bd9bcf3 2485 }
2880d16f
MH
2486
2487 iter->dir_iterator = NULL;
2488 if (ref_iterator_abort(ref_iterator) == ITER_ERROR)
2489 ok = ITER_ERROR;
2490 return ok;
2491}
2492
2493static int files_reflog_iterator_peel(struct ref_iterator *ref_iterator,
2494 struct object_id *peeled)
2495{
2496 die("BUG: ref_iterator_peel() called for reflog_iterator");
2497}
2498
2499static int files_reflog_iterator_abort(struct ref_iterator *ref_iterator)
2500{
2501 struct files_reflog_iterator *iter =
2502 (struct files_reflog_iterator *)ref_iterator;
2503 int ok = ITER_DONE;
2504
2505 if (iter->dir_iterator)
2506 ok = dir_iterator_abort(iter->dir_iterator);
2507
2508 base_ref_iterator_free(ref_iterator);
2509 return ok;
2510}
2511
2512static struct ref_iterator_vtable files_reflog_iterator_vtable = {
2513 files_reflog_iterator_advance,
2514 files_reflog_iterator_peel,
2515 files_reflog_iterator_abort
2516};
2517
e3688bd6 2518static struct ref_iterator *files_reflog_iterator_begin(struct ref_store *ref_store)
2880d16f 2519{
802de3da 2520 struct files_ref_store *refs =
9e7ec634
NTND
2521 files_downcast(ref_store, REF_STORE_READ,
2522 "reflog_iterator_begin");
2880d16f
MH
2523 struct files_reflog_iterator *iter = xcalloc(1, sizeof(*iter));
2524 struct ref_iterator *ref_iterator = &iter->base;
e9dcc305 2525 struct strbuf sb = STRBUF_INIT;
2880d16f
MH
2526
2527 base_ref_iterator_init(ref_iterator, &files_reflog_iterator_vtable);
802de3da 2528 files_reflog_path(refs, &sb, NULL);
e9dcc305 2529 iter->dir_iterator = dir_iterator_begin(sb.buf);
2f40e954 2530 iter->ref_store = ref_store;
e9dcc305 2531 strbuf_release(&sb);
2880d16f 2532 return ref_iterator;
7bd9bcf3
MH
2533}
2534
165056b2 2535/*
92b1551b
MH
2536 * If update is a direct update of head_ref (the reference pointed to
2537 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.
2538 */
2539static int split_head_update(struct ref_update *update,
2540 struct ref_transaction *transaction,
2541 const char *head_ref,
2542 struct string_list *affected_refnames,
2543 struct strbuf *err)
2544{
2545 struct string_list_item *item;
2546 struct ref_update *new_update;
2547
2548 if ((update->flags & REF_LOG_ONLY) ||
2549 (update->flags & REF_ISPRUNING) ||
2550 (update->flags & REF_UPDATE_VIA_HEAD))
2551 return 0;
2552
2553 if (strcmp(update->refname, head_ref))
2554 return 0;
2555
2556 /*
2557 * First make sure that HEAD is not already in the
2558 * transaction. This insertion is O(N) in the transaction
2559 * size, but it happens at most once per transaction.
2560 */
2561 item = string_list_insert(affected_refnames, "HEAD");
2562 if (item->util) {
2563 /* An entry already existed */
2564 strbuf_addf(err,
2565 "multiple updates for 'HEAD' (including one "
2566 "via its referent '%s') are not allowed",
2567 update->refname);
2568 return TRANSACTION_NAME_CONFLICT;
2569 }
2570
2571 new_update = ref_transaction_add_update(
2572 transaction, "HEAD",
2573 update->flags | REF_LOG_ONLY | REF_NODEREF,
98491298 2574 update->new_oid.hash, update->old_oid.hash,
92b1551b
MH
2575 update->msg);
2576
2577 item->util = new_update;
2578
2579 return 0;
2580}
2581
2582/*
2583 * update is for a symref that points at referent and doesn't have
2584 * REF_NODEREF set. Split it into two updates:
2585 * - The original update, but with REF_LOG_ONLY and REF_NODEREF set
2586 * - A new, separate update for the referent reference
2587 * Note that the new update will itself be subject to splitting when
2588 * the iteration gets to it.
2589 */
fcc42ea0
MH
2590static int split_symref_update(struct files_ref_store *refs,
2591 struct ref_update *update,
92b1551b
MH
2592 const char *referent,
2593 struct ref_transaction *transaction,
2594 struct string_list *affected_refnames,
2595 struct strbuf *err)
2596{
2597 struct string_list_item *item;
2598 struct ref_update *new_update;
2599 unsigned int new_flags;
2600
2601 /*
2602 * First make sure that referent is not already in the
2603 * transaction. This insertion is O(N) in the transaction
2604 * size, but it happens at most once per symref in a
2605 * transaction.
2606 */
2607 item = string_list_insert(affected_refnames, referent);
2608 if (item->util) {
2609 /* An entry already existed */
2610 strbuf_addf(err,
2611 "multiple updates for '%s' (including one "
2612 "via symref '%s') are not allowed",
2613 referent, update->refname);
2614 return TRANSACTION_NAME_CONFLICT;
2615 }
2616
2617 new_flags = update->flags;
2618 if (!strcmp(update->refname, "HEAD")) {
2619 /*
2620 * Record that the new update came via HEAD, so that
2621 * when we process it, split_head_update() doesn't try
2622 * to add another reflog update for HEAD. Note that
2623 * this bit will be propagated if the new_update
2624 * itself needs to be split.
2625 */
2626 new_flags |= REF_UPDATE_VIA_HEAD;
2627 }
2628
2629 new_update = ref_transaction_add_update(
2630 transaction, referent, new_flags,
98491298 2631 update->new_oid.hash, update->old_oid.hash,
92b1551b
MH
2632 update->msg);
2633
6e30b2f6
MH
2634 new_update->parent_update = update;
2635
2636 /*
2637 * Change the symbolic ref update to log only. Also, it
2638 * doesn't need to check its old SHA-1 value, as that will be
2639 * done when new_update is processed.
2640 */
92b1551b 2641 update->flags |= REF_LOG_ONLY | REF_NODEREF;
6e30b2f6 2642 update->flags &= ~REF_HAVE_OLD;
92b1551b
MH
2643
2644 item->util = new_update;
2645
2646 return 0;
2647}
2648
6e30b2f6
MH
2649/*
2650 * Return the refname under which update was originally requested.
2651 */
2652static const char *original_update_refname(struct ref_update *update)
2653{
2654 while (update->parent_update)
2655 update = update->parent_update;
2656
2657 return update->refname;
2658}
2659
e3f51039
MH
2660/*
2661 * Check whether the REF_HAVE_OLD and old_oid values stored in update
2662 * are consistent with oid, which is the reference's current value. If
2663 * everything is OK, return 0; otherwise, write an error message to
2664 * err and return -1.
2665 */
2666static int check_old_oid(struct ref_update *update, struct object_id *oid,
2667 struct strbuf *err)
2668{
2669 if (!(update->flags & REF_HAVE_OLD) ||
98491298 2670 !oidcmp(oid, &update->old_oid))
e3f51039
MH
2671 return 0;
2672
98491298 2673 if (is_null_oid(&update->old_oid))
e3f51039
MH
2674 strbuf_addf(err, "cannot lock ref '%s': "
2675 "reference already exists",
2676 original_update_refname(update));
2677 else if (is_null_oid(oid))
2678 strbuf_addf(err, "cannot lock ref '%s': "
2679 "reference is missing but expected %s",
2680 original_update_refname(update),
98491298 2681 oid_to_hex(&update->old_oid));
e3f51039
MH
2682 else
2683 strbuf_addf(err, "cannot lock ref '%s': "
2684 "is at %s but expected %s",
2685 original_update_refname(update),
2686 oid_to_hex(oid),
98491298 2687 oid_to_hex(&update->old_oid));
e3f51039
MH
2688
2689 return -1;
2690}
2691
92b1551b
MH
2692/*
2693 * Prepare for carrying out update:
2694 * - Lock the reference referred to by update.
2695 * - Read the reference under lock.
2696 * - Check that its old SHA-1 value (if specified) is correct, and in
2697 * any case record it in update->lock->old_oid for later use when
2698 * writing the reflog.
2699 * - If it is a symref update without REF_NODEREF, split it up into a
2700 * REF_LOG_ONLY update of the symref and add a separate update for
2701 * the referent to transaction.
2702 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY
2703 * update of HEAD.
165056b2 2704 */
b3bbbc5c
MH
2705static int lock_ref_for_update(struct files_ref_store *refs,
2706 struct ref_update *update,
165056b2 2707 struct ref_transaction *transaction,
92b1551b 2708 const char *head_ref,
165056b2
MH
2709 struct string_list *affected_refnames,
2710 struct strbuf *err)
2711{
92b1551b
MH
2712 struct strbuf referent = STRBUF_INIT;
2713 int mustexist = (update->flags & REF_HAVE_OLD) &&
98491298 2714 !is_null_oid(&update->old_oid);
165056b2 2715 int ret;
92b1551b 2716 struct ref_lock *lock;
165056b2 2717
32c597e7 2718 files_assert_main_repository(refs, "lock_ref_for_update");
b3bbbc5c 2719
98491298 2720 if ((update->flags & REF_HAVE_NEW) && is_null_oid(&update->new_oid))
165056b2 2721 update->flags |= REF_DELETING;
92b1551b
MH
2722
2723 if (head_ref) {
2724 ret = split_head_update(update, transaction, head_ref,
2725 affected_refnames, err);
2726 if (ret)
2727 return ret;
2728 }
2729
f7b0a987 2730 ret = lock_raw_ref(refs, update->refname, mustexist,
92b1551b 2731 affected_refnames, NULL,
7d618264 2732 &lock, &referent,
92b1551b 2733 &update->type, err);
92b1551b 2734 if (ret) {
165056b2
MH
2735 char *reason;
2736
165056b2
MH
2737 reason = strbuf_detach(err, NULL);
2738 strbuf_addf(err, "cannot lock ref '%s': %s",
e3f51039 2739 original_update_refname(update), reason);
165056b2
MH
2740 free(reason);
2741 return ret;
2742 }
92b1551b 2743
7d618264 2744 update->backend_data = lock;
92b1551b 2745
8169d0d0 2746 if (update->type & REF_ISSYMREF) {
6e30b2f6
MH
2747 if (update->flags & REF_NODEREF) {
2748 /*
2749 * We won't be reading the referent as part of
2750 * the transaction, so we have to read it here
2751 * to record and possibly check old_sha1:
2752 */
2f40e954
NTND
2753 if (refs_read_ref_full(&refs->base,
2754 referent.buf, 0,
2755 lock->old_oid.hash, NULL)) {
6e30b2f6
MH
2756 if (update->flags & REF_HAVE_OLD) {
2757 strbuf_addf(err, "cannot lock ref '%s': "
e3f51039
MH
2758 "error reading reference",
2759 original_update_refname(update));
2760 return -1;
6e30b2f6 2761 }
e3f51039 2762 } else if (check_old_oid(update, &lock->old_oid, err)) {
8169d0d0 2763 return TRANSACTION_GENERIC_ERROR;
8169d0d0 2764 }
6e30b2f6
MH
2765 } else {
2766 /*
2767 * Create a new update for the reference this
2768 * symref is pointing at. Also, we will record
2769 * and verify old_sha1 for this update as part
2770 * of processing the split-off update, so we
2771 * don't have to do it here.
2772 */
fcc42ea0
MH
2773 ret = split_symref_update(refs, update,
2774 referent.buf, transaction,
92b1551b
MH
2775 affected_refnames, err);
2776 if (ret)
2777 return ret;
2778 }
6e30b2f6
MH
2779 } else {
2780 struct ref_update *parent_update;
8169d0d0 2781
e3f51039
MH
2782 if (check_old_oid(update, &lock->old_oid, err))
2783 return TRANSACTION_GENERIC_ERROR;
2784
6e30b2f6
MH
2785 /*
2786 * If this update is happening indirectly because of a
2787 * symref update, record the old SHA-1 in the parent
2788 * update:
2789 */
2790 for (parent_update = update->parent_update;
2791 parent_update;
2792 parent_update = parent_update->parent_update) {
7d618264
DT
2793 struct ref_lock *parent_lock = parent_update->backend_data;
2794 oidcpy(&parent_lock->old_oid, &lock->old_oid);
6e30b2f6 2795 }
92b1551b
MH
2796 }
2797
165056b2
MH
2798 if ((update->flags & REF_HAVE_NEW) &&
2799 !(update->flags & REF_DELETING) &&
2800 !(update->flags & REF_LOG_ONLY)) {
92b1551b 2801 if (!(update->type & REF_ISSYMREF) &&
98491298 2802 !oidcmp(&lock->old_oid, &update->new_oid)) {
165056b2
MH
2803 /*
2804 * The reference already has the desired
2805 * value, so we don't need to write it.
2806 */
4417df8c 2807 } else if (write_ref_to_lockfile(lock, &update->new_oid,
165056b2
MH
2808 err)) {
2809 char *write_err = strbuf_detach(err, NULL);
2810
2811 /*
2812 * The lock was freed upon failure of
2813 * write_ref_to_lockfile():
2814 */
7d618264 2815 update->backend_data = NULL;
165056b2 2816 strbuf_addf(err,
e3f51039 2817 "cannot update ref '%s': %s",
165056b2
MH
2818 update->refname, write_err);
2819 free(write_err);
2820 return TRANSACTION_GENERIC_ERROR;
2821 } else {
2822 update->flags |= REF_NEEDS_COMMIT;
2823 }
2824 }
2825 if (!(update->flags & REF_NEEDS_COMMIT)) {
2826 /*
2827 * We didn't call write_ref_to_lockfile(), so
2828 * the lockfile is still open. Close it to
2829 * free up the file descriptor:
2830 */
92b1551b 2831 if (close_ref(lock)) {
165056b2
MH
2832 strbuf_addf(err, "couldn't close '%s.lock'",
2833 update->refname);
2834 return TRANSACTION_GENERIC_ERROR;
2835 }
2836 }
2837 return 0;
2838}
2839
c0ca9357
MH
2840/*
2841 * Unlock any references in `transaction` that are still locked, and
2842 * mark the transaction closed.
2843 */
2844static void files_transaction_cleanup(struct ref_transaction *transaction)
2845{
2846 size_t i;
2847
2848 for (i = 0; i < transaction->nr; i++) {
2849 struct ref_update *update = transaction->updates[i];
2850 struct ref_lock *lock = update->backend_data;
2851
2852 if (lock) {
2853 unlock_ref(lock);
2854 update->backend_data = NULL;
2855 }
2856 }
2857
2858 transaction->state = REF_TRANSACTION_CLOSED;
2859}
2860
30173b88
MH
2861static int files_transaction_prepare(struct ref_store *ref_store,
2862 struct ref_transaction *transaction,
2863 struct strbuf *err)
7bd9bcf3 2864{
00eebe35 2865 struct files_ref_store *refs =
9e7ec634 2866 files_downcast(ref_store, REF_STORE_WRITE,
30173b88 2867 "ref_transaction_prepare");
43a2dfde
MH
2868 size_t i;
2869 int ret = 0;
7bd9bcf3 2870 struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
92b1551b
MH
2871 char *head_ref = NULL;
2872 int head_type;
2873 struct object_id head_oid;
7bd9bcf3
MH
2874
2875 assert(err);
2876
c0ca9357
MH
2877 if (!transaction->nr)
2878 goto cleanup;
7bd9bcf3 2879
92b1551b
MH
2880 /*
2881 * Fail if a refname appears more than once in the
2882 * transaction. (If we end up splitting up any updates using
2883 * split_symref_update() or split_head_update(), those
2884 * functions will check that the new updates don't have the
2885 * same refname as any existing ones.)
2886 */
2887 for (i = 0; i < transaction->nr; i++) {
2888 struct ref_update *update = transaction->updates[i];
2889 struct string_list_item *item =
2890 string_list_append(&affected_refnames, update->refname);
2891
2892 /*
2893 * We store a pointer to update in item->util, but at
2894 * the moment we never use the value of this field
2895 * except to check whether it is non-NULL.
2896 */
2897 item->util = update;
2898 }
7bd9bcf3
MH
2899 string_list_sort(&affected_refnames);
2900 if (ref_update_reject_duplicates(&affected_refnames, err)) {
2901 ret = TRANSACTION_GENERIC_ERROR;
2902 goto cleanup;
2903 }
2904
92b1551b
MH
2905 /*
2906 * Special hack: If a branch is updated directly and HEAD
2907 * points to it (may happen on the remote side of a push
2908 * for example) then logically the HEAD reflog should be
2909 * updated too.
2910 *
2911 * A generic solution would require reverse symref lookups,
2912 * but finding all symrefs pointing to a given branch would be
2913 * rather costly for this rare event (the direct update of a
2914 * branch) to be worth it. So let's cheat and check with HEAD
2915 * only, which should cover 99% of all usage scenarios (even
2916 * 100% of the default ones).
2917 *
2918 * So if HEAD is a symbolic reference, then record the name of
2919 * the reference that it points to. If we see an update of
2920 * head_ref within the transaction, then split_head_update()
2921 * arranges for the reflog of HEAD to be updated, too.
2922 */
2f40e954
NTND
2923 head_ref = refs_resolve_refdup(ref_store, "HEAD",
2924 RESOLVE_REF_NO_RECURSE,
2925 head_oid.hash, &head_type);
92b1551b
MH
2926
2927 if (head_ref && !(head_type & REF_ISSYMREF)) {
2928 free(head_ref);
2929 head_ref = NULL;
2930 }
2931
7bd9bcf3
MH
2932 /*
2933 * Acquire all locks, verify old values if provided, check
2934 * that new values are valid, and write new values to the
2935 * lockfiles, ready to be activated. Only keep one lockfile
2936 * open at a time to avoid running out of file descriptors.
30173b88
MH
2937 * Note that lock_ref_for_update() might append more updates
2938 * to the transaction.
7bd9bcf3 2939 */
efe47281
MH
2940 for (i = 0; i < transaction->nr; i++) {
2941 struct ref_update *update = transaction->updates[i];
7bd9bcf3 2942
b3bbbc5c
MH
2943 ret = lock_ref_for_update(refs, update, transaction,
2944 head_ref, &affected_refnames, err);
165056b2 2945 if (ret)
30173b88
MH
2946 break;
2947 }
2948
2949cleanup:
2950 free(head_ref);
2951 string_list_clear(&affected_refnames, 0);
2952
2953 if (ret)
2954 files_transaction_cleanup(transaction);
2955 else
2956 transaction->state = REF_TRANSACTION_PREPARED;
2957
2958 return ret;
2959}
2960
2961static int files_transaction_finish(struct ref_store *ref_store,
2962 struct ref_transaction *transaction,
2963 struct strbuf *err)
2964{
2965 struct files_ref_store *refs =
2966 files_downcast(ref_store, 0, "ref_transaction_finish");
2967 size_t i;
2968 int ret = 0;
2969 struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;
2970 struct string_list_item *ref_to_delete;
2971 struct strbuf sb = STRBUF_INIT;
2972
2973 assert(err);
2974
2975 if (!transaction->nr) {
2976 transaction->state = REF_TRANSACTION_CLOSED;
2977 return 0;
7bd9bcf3 2978 }
7bd9bcf3 2979
7bd9bcf3 2980 /* Perform updates first so live commits remain referenced */
efe47281
MH
2981 for (i = 0; i < transaction->nr; i++) {
2982 struct ref_update *update = transaction->updates[i];
7d618264 2983 struct ref_lock *lock = update->backend_data;
7bd9bcf3 2984
d99aa884
DT
2985 if (update->flags & REF_NEEDS_COMMIT ||
2986 update->flags & REF_LOG_ONLY) {
802de3da
NTND
2987 if (files_log_ref_write(refs,
2988 lock->ref_name,
4417df8c 2989 &lock->old_oid,
2990 &update->new_oid,
81b1b6d4
MH
2991 update->msg, update->flags,
2992 err)) {
92b1551b
MH
2993 char *old_msg = strbuf_detach(err, NULL);
2994
2995 strbuf_addf(err, "cannot update the ref '%s': %s",
2996 lock->ref_name, old_msg);
2997 free(old_msg);
2998 unlock_ref(lock);
7d618264 2999 update->backend_data = NULL;
7bd9bcf3
MH
3000 ret = TRANSACTION_GENERIC_ERROR;
3001 goto cleanup;
7bd9bcf3
MH
3002 }
3003 }
7bd9bcf3 3004 if (update->flags & REF_NEEDS_COMMIT) {
00eebe35 3005 clear_loose_ref_cache(refs);
92b1551b
MH
3006 if (commit_ref(lock)) {
3007 strbuf_addf(err, "couldn't set '%s'", lock->ref_name);
3008 unlock_ref(lock);
7d618264 3009 update->backend_data = NULL;
7bd9bcf3
MH
3010 ret = TRANSACTION_GENERIC_ERROR;
3011 goto cleanup;
7bd9bcf3
MH
3012 }
3013 }
3014 }
7bd9bcf3 3015 /* Perform deletes now that updates are safely completed */
efe47281
MH
3016 for (i = 0; i < transaction->nr; i++) {
3017 struct ref_update *update = transaction->updates[i];
7d618264 3018 struct ref_lock *lock = update->backend_data;
7bd9bcf3 3019
d99aa884
DT
3020 if (update->flags & REF_DELETING &&
3021 !(update->flags & REF_LOG_ONLY)) {
ce0af24d
MH
3022 if (!(update->type & REF_ISPACKED) ||
3023 update->type & REF_ISSYMREF) {
3024 /* It is a loose reference. */
e9dcc305 3025 strbuf_reset(&sb);
19e02f4f 3026 files_ref_path(refs, &sb, lock->ref_name);
e9dcc305 3027 if (unlink_or_msg(sb.buf, err)) {
ce0af24d
MH
3028 ret = TRANSACTION_GENERIC_ERROR;
3029 goto cleanup;
3030 }
44639777 3031 update->flags |= REF_DELETED_LOOSE;
7bd9bcf3
MH
3032 }
3033
3034 if (!(update->flags & REF_ISPRUNING))
3035 string_list_append(&refs_to_delete,
7d618264 3036 lock->ref_name);
7bd9bcf3
MH
3037 }
3038 }
3039
0a95ac5f 3040 if (repack_without_refs(refs, &refs_to_delete, err)) {
7bd9bcf3
MH
3041 ret = TRANSACTION_GENERIC_ERROR;
3042 goto cleanup;
3043 }
44639777
MH
3044
3045 /* Delete the reflogs of any references that were deleted: */
3046 for_each_string_list_item(ref_to_delete, &refs_to_delete) {
e9dcc305 3047 strbuf_reset(&sb);
802de3da 3048 files_reflog_path(refs, &sb, ref_to_delete->string);
e9dcc305 3049 if (!unlink_or_warn(sb.buf))
802de3da 3050 try_remove_empty_parents(refs, ref_to_delete->string,
44639777
MH
3051 REMOVE_EMPTY_PARENTS_REFLOG);
3052 }
3053
00eebe35 3054 clear_loose_ref_cache(refs);
7bd9bcf3
MH
3055
3056cleanup:
c0ca9357 3057 files_transaction_cleanup(transaction);
7bd9bcf3 3058
44639777
MH
3059 for (i = 0; i < transaction->nr; i++) {
3060 struct ref_update *update = transaction->updates[i];
44639777
MH
3061
3062 if (update->flags & REF_DELETED_LOOSE) {
3063 /*
3064 * The loose reference was deleted. Delete any
3065 * empty parent directories. (Note that this
3066 * can only work because we have already
3067 * removed the lockfile.)
3068 */
802de3da 3069 try_remove_empty_parents(refs, update->refname,
44639777
MH
3070 REMOVE_EMPTY_PARENTS_REF);
3071 }
3072 }
3073
30173b88 3074 strbuf_release(&sb);
7bd9bcf3 3075 string_list_clear(&refs_to_delete, 0);
7bd9bcf3
MH
3076 return ret;
3077}
3078
30173b88
MH
3079static int files_transaction_abort(struct ref_store *ref_store,
3080 struct ref_transaction *transaction,
3081 struct strbuf *err)
3082{
3083 files_transaction_cleanup(transaction);
3084 return 0;
3085}
3086
7bd9bcf3
MH
3087static int ref_present(const char *refname,
3088 const struct object_id *oid, int flags, void *cb_data)
3089{
3090 struct string_list *affected_refnames = cb_data;
3091
3092 return string_list_has_string(affected_refnames, refname);
3093}
3094
fc681463
DT
3095static int files_initial_transaction_commit(struct ref_store *ref_store,
3096 struct ref_transaction *transaction,
3097 struct strbuf *err)
7bd9bcf3 3098{
d99825ab 3099 struct files_ref_store *refs =
9e7ec634
NTND
3100 files_downcast(ref_store, REF_STORE_WRITE,
3101 "initial_ref_transaction_commit");
43a2dfde
MH
3102 size_t i;
3103 int ret = 0;
7bd9bcf3
MH
3104 struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
3105
3106 assert(err);
3107
3108 if (transaction->state != REF_TRANSACTION_OPEN)
3109 die("BUG: commit called for transaction that is not open");
3110
3111 /* Fail if a refname appears more than once in the transaction: */
efe47281
MH
3112 for (i = 0; i < transaction->nr; i++)
3113 string_list_append(&affected_refnames,
3114 transaction->updates[i]->refname);
7bd9bcf3
MH
3115 string_list_sort(&affected_refnames);
3116 if (ref_update_reject_duplicates(&affected_refnames, err)) {
3117 ret = TRANSACTION_GENERIC_ERROR;
3118 goto cleanup;
3119 }
3120
3121 /*
3122 * It's really undefined to call this function in an active
3123 * repository or when there are existing references: we are
3124 * only locking and changing packed-refs, so (1) any
3125 * simultaneous processes might try to change a reference at
3126 * the same time we do, and (2) any existing loose versions of
3127 * the references that we are setting would have precedence
3128 * over our values. But some remote helpers create the remote
3129 * "HEAD" and "master" branches before calling this function,
3130 * so here we really only check that none of the references
3131 * that we are creating already exists.
3132 */
2f40e954
NTND
3133 if (refs_for_each_rawref(&refs->base, ref_present,
3134 &affected_refnames))
7bd9bcf3
MH
3135 die("BUG: initial ref transaction called with existing refs");
3136
efe47281
MH
3137 for (i = 0; i < transaction->nr; i++) {
3138 struct ref_update *update = transaction->updates[i];
7bd9bcf3
MH
3139
3140 if ((update->flags & REF_HAVE_OLD) &&
98491298 3141 !is_null_oid(&update->old_oid))
7bd9bcf3 3142 die("BUG: initial ref transaction with old_sha1 set");
7d2df051
NTND
3143 if (refs_verify_refname_available(&refs->base, update->refname,
3144 &affected_refnames, NULL,
3145 err)) {
7bd9bcf3
MH
3146 ret = TRANSACTION_NAME_CONFLICT;
3147 goto cleanup;
3148 }
3149 }
3150
49c0df6a 3151 if (lock_packed_refs(refs, 0)) {
7bd9bcf3
MH
3152 strbuf_addf(err, "unable to lock packed-refs file: %s",
3153 strerror(errno));
3154 ret = TRANSACTION_GENERIC_ERROR;
3155 goto cleanup;
3156 }
3157
efe47281
MH
3158 for (i = 0; i < transaction->nr; i++) {
3159 struct ref_update *update = transaction->updates[i];
7bd9bcf3
MH
3160
3161 if ((update->flags & REF_HAVE_NEW) &&
98491298 3162 !is_null_oid(&update->new_oid))
3163 add_packed_ref(refs, update->refname,
4417df8c 3164 &update->new_oid);
7bd9bcf3
MH
3165 }
3166
49c0df6a 3167 if (commit_packed_refs(refs)) {
7bd9bcf3
MH
3168 strbuf_addf(err, "unable to commit packed-refs file: %s",
3169 strerror(errno));
3170 ret = TRANSACTION_GENERIC_ERROR;
3171 goto cleanup;
3172 }
3173
3174cleanup:
3175 transaction->state = REF_TRANSACTION_CLOSED;
3176 string_list_clear(&affected_refnames, 0);
3177 return ret;
3178}
3179
3180struct expire_reflog_cb {
3181 unsigned int flags;
3182 reflog_expiry_should_prune_fn *should_prune_fn;
3183 void *policy_cb;
3184 FILE *newlog;
9461d272 3185 struct object_id last_kept_oid;
7bd9bcf3
MH
3186};
3187
9461d272 3188static int expire_reflog_ent(struct object_id *ooid, struct object_id *noid,
dddbad72 3189 const char *email, timestamp_t timestamp, int tz,
7bd9bcf3
MH
3190 const char *message, void *cb_data)
3191{
3192 struct expire_reflog_cb *cb = cb_data;
3193 struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;
3194
3195 if (cb->flags & EXPIRE_REFLOGS_REWRITE)
9461d272 3196 ooid = &cb->last_kept_oid;
7bd9bcf3 3197
4322478a 3198 if ((*cb->should_prune_fn)(ooid, noid, email, timestamp, tz,
7bd9bcf3
MH
3199 message, policy_cb)) {
3200 if (!cb->newlog)
3201 printf("would prune %s", message);
3202 else if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
3203 printf("prune %s", message);
3204 } else {
3205 if (cb->newlog) {
cb71f8bd 3206 fprintf(cb->newlog, "%s %s %s %"PRItime" %+05d\t%s",
9461d272 3207 oid_to_hex(ooid), oid_to_hex(noid),
7bd9bcf3 3208 email, timestamp, tz, message);
9461d272 3209 oidcpy(&cb->last_kept_oid, noid);
7bd9bcf3
MH
3210 }
3211 if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
3212 printf("keep %s", message);
3213 }
3214 return 0;
3215}
3216
e3688bd6
DT
3217static int files_reflog_expire(struct ref_store *ref_store,
3218 const char *refname, const unsigned char *sha1,
3219 unsigned int flags,
3220 reflog_expiry_prepare_fn prepare_fn,
3221 reflog_expiry_should_prune_fn should_prune_fn,
3222 reflog_expiry_cleanup_fn cleanup_fn,
3223 void *policy_cb_data)
7bd9bcf3 3224{
7eb27cdf 3225 struct files_ref_store *refs =
9e7ec634 3226 files_downcast(ref_store, REF_STORE_WRITE, "reflog_expire");
7bd9bcf3
MH
3227 static struct lock_file reflog_lock;
3228 struct expire_reflog_cb cb;
3229 struct ref_lock *lock;
802de3da 3230 struct strbuf log_file_sb = STRBUF_INIT;
7bd9bcf3
MH
3231 char *log_file;
3232 int status = 0;
3233 int type;
3234 struct strbuf err = STRBUF_INIT;
4322478a 3235 struct object_id oid;
7bd9bcf3
MH
3236
3237 memset(&cb, 0, sizeof(cb));
3238 cb.flags = flags;
3239 cb.policy_cb = policy_cb_data;
3240 cb.should_prune_fn = should_prune_fn;
3241
3242 /*
3243 * The reflog file is locked by holding the lock on the
3244 * reference itself, plus we might need to update the
3245 * reference if --updateref was specified:
3246 */
7eb27cdf
MH
3247 lock = lock_ref_sha1_basic(refs, refname, sha1,
3248 NULL, NULL, REF_NODEREF,
41d796ed 3249 &type, &err);
7bd9bcf3
MH
3250 if (!lock) {
3251 error("cannot lock ref '%s': %s", refname, err.buf);
3252 strbuf_release(&err);
3253 return -1;
3254 }
2f40e954 3255 if (!refs_reflog_exists(ref_store, refname)) {
7bd9bcf3
MH
3256 unlock_ref(lock);
3257 return 0;
3258 }
3259
802de3da
NTND
3260 files_reflog_path(refs, &log_file_sb, refname);
3261 log_file = strbuf_detach(&log_file_sb, NULL);
7bd9bcf3
MH
3262 if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
3263 /*
3264 * Even though holding $GIT_DIR/logs/$reflog.lock has
3265 * no locking implications, we use the lock_file
3266 * machinery here anyway because it does a lot of the
3267 * work we need, including cleaning up if the program
3268 * exits unexpectedly.
3269 */
3270 if (hold_lock_file_for_update(&reflog_lock, log_file, 0) < 0) {
3271 struct strbuf err = STRBUF_INIT;
3272 unable_to_lock_message(log_file, errno, &err);
3273 error("%s", err.buf);
3274 strbuf_release(&err);
3275 goto failure;
3276 }
3277 cb.newlog = fdopen_lock_file(&reflog_lock, "w");
3278 if (!cb.newlog) {
3279 error("cannot fdopen %s (%s)",
3280 get_lock_file_path(&reflog_lock), strerror(errno));
3281 goto failure;
3282 }
3283 }
3284
4322478a 3285 hashcpy(oid.hash, sha1);
3286
3287 (*prepare_fn)(refname, &oid, cb.policy_cb);
2f40e954 3288 refs_for_each_reflog_ent(ref_store, refname, expire_reflog_ent, &cb);
7bd9bcf3
MH
3289 (*cleanup_fn)(cb.policy_cb);
3290
3291 if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
3292 /*
3293 * It doesn't make sense to adjust a reference pointed
3294 * to by a symbolic ref based on expiring entries in
3295 * the symbolic reference's reflog. Nor can we update
3296 * a reference if there are no remaining reflog
3297 * entries.
3298 */
3299 int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&
3300 !(type & REF_ISSYMREF) &&
9461d272 3301 !is_null_oid(&cb.last_kept_oid);
7bd9bcf3
MH
3302
3303 if (close_lock_file(&reflog_lock)) {
3304 status |= error("couldn't write %s: %s", log_file,
3305 strerror(errno));
3306 } else if (update &&
3307 (write_in_full(get_lock_file_fd(lock->lk),
9461d272 3308 oid_to_hex(&cb.last_kept_oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||
7bd9bcf3
MH
3309 write_str_in_full(get_lock_file_fd(lock->lk), "\n") != 1 ||
3310 close_ref(lock) < 0)) {
3311 status |= error("couldn't write %s",
3312 get_lock_file_path(lock->lk));
3313 rollback_lock_file(&reflog_lock);
3314 } else if (commit_lock_file(&reflog_lock)) {
e0048d3e 3315 status |= error("unable to write reflog '%s' (%s)",
7bd9bcf3
MH
3316 log_file, strerror(errno));
3317 } else if (update && commit_ref(lock)) {
3318 status |= error("couldn't set %s", lock->ref_name);
3319 }
3320 }
3321 free(log_file);
3322 unlock_ref(lock);
3323 return status;
3324
3325 failure:
3326 rollback_lock_file(&reflog_lock);
3327 free(log_file);
3328 unlock_ref(lock);
3329 return -1;
3330}
3dce444f 3331
6fb5acfd
DT
3332static int files_init_db(struct ref_store *ref_store, struct strbuf *err)
3333{
19e02f4f 3334 struct files_ref_store *refs =
9e7ec634 3335 files_downcast(ref_store, REF_STORE_WRITE, "init_db");
e9dcc305
NTND
3336 struct strbuf sb = STRBUF_INIT;
3337
6fb5acfd
DT
3338 /*
3339 * Create .git/refs/{heads,tags}
3340 */
19e02f4f 3341 files_ref_path(refs, &sb, "refs/heads");
e9dcc305
NTND
3342 safe_create_dir(sb.buf, 1);
3343
3344 strbuf_reset(&sb);
19e02f4f 3345 files_ref_path(refs, &sb, "refs/tags");
e9dcc305
NTND
3346 safe_create_dir(sb.buf, 1);
3347
3348 strbuf_release(&sb);
6fb5acfd
DT
3349 return 0;
3350}
3351
3dce444f
RS
3352struct ref_storage_be refs_be_files = {
3353 NULL,
00eebe35 3354 "files",
127b42a1 3355 files_ref_store_create,
6fb5acfd 3356 files_init_db,
30173b88
MH
3357 files_transaction_prepare,
3358 files_transaction_finish,
3359 files_transaction_abort,
fc681463 3360 files_initial_transaction_commit,
e1e33b72 3361
8231527e 3362 files_pack_refs,
bd427cf2 3363 files_peel_ref,
284689ba 3364 files_create_symref,
a27dcf89 3365 files_delete_refs,
9b6b40d9 3366 files_rename_ref,
8231527e 3367
1a769003 3368 files_ref_iterator_begin,
62665823 3369 files_read_raw_ref,
e3688bd6
DT
3370
3371 files_reflog_iterator_begin,
3372 files_for_each_reflog_ent,
3373 files_for_each_reflog_ent_reverse,
3374 files_reflog_exists,
3375 files_create_reflog,
3376 files_delete_reflog,
3377 files_reflog_expire
3dce444f 3378};