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