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