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