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