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