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