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