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