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