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