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