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