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