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