Raw
1 #define DISABLE_SIGN_COMPARE_WARNINGS
2
3 #include "../git-compat-util.h"
4 #include "../abspath.h"
5 #include "../config.h"
6 #include "../copy.h"
7 #include "../environment.h"
8 #include "../gettext.h"
9 #include "../hash.h"
10 #include "../hex.h"
11 #include "../fsck.h"
12 #include "../refs.h"
13 #include "../repo-settings.h"
14 #include "refs-internal.h"
15 #include "ref-cache.h"
16 #include "packed-backend.h"
17 #include "../ident.h"
18 #include "../iterator.h"
19 #include "../dir-iterator.h"
20 #include "../lockfile.h"
21 #include "../path.h"
22 #include "../dir.h"
23 #include "../chdir-notify.h"
24 #include "../setup.h"
25 #include "../worktree.h"
26 #include "../wrapper.h"
27 #include "../write-or-die.h"
28 #include "../revision.h"
29 #include <wildmatch.h>
30
31 /* So that we can drop `USE_THE_REPOSITORY_VARIABLE`. */
32 extern int ignore_case;
33
34 /*
35 * This backend uses the following flags in `ref_update::flags` for
36 * internal bookkeeping purposes. Their numerical values must not
37 * conflict with REF_NO_DEREF, REF_FORCE_CREATE_REFLOG, REF_HAVE_NEW,
38 * or REF_HAVE_OLD, which are also stored in `ref_update::flags`.
39 */
40
41 /*
42 * Used as a flag in ref_update::flags when a loose ref is being
43 * pruned. This flag must only be used when REF_NO_DEREF is set.
44 */
45 #define REF_IS_PRUNING (1 << 4)
46
47 /*
48 * Flag passed to lock_ref_sha1_basic() telling it to tolerate broken
49 * refs (i.e., because the reference is about to be deleted anyway).
50 */
51 #define REF_DELETING (1 << 5)
52
53 /*
54 * Used as a flag in ref_update::flags when the lockfile needs to be
55 * committed.
56 */
57 #define REF_NEEDS_COMMIT (1 << 6)
58
59 /*
60 * Used as a flag in ref_update::flags when the ref_update was via an
61 * update to HEAD.
62 */
63 #define REF_UPDATE_VIA_HEAD (1 << 8)
64
65 /*
66 * Used as a flag in ref_update::flags when a reference has been
67 * deleted and the ref's parent directories may need cleanup.
68 */
69 #define REF_DELETED_RMDIR (1 << 9)
70
71 /*
72 * Used to indicate that the reflog-only update has been created via
73 * `split_head_update()`.
74 */
75 #define REF_LOG_VIA_SPLIT (1 << 14)
76
77 struct ref_lock {
78 char *ref_name;
79 struct lock_file lk;
80 struct object_id old_oid;
81 unsigned int count; /* track users of the lock (ref update + reflog updates) */
82 };
83
84 struct files_ref_store {
85 struct ref_store base;
86 unsigned int store_flags;
87
88 char *gitcommondir;
89 struct ref_cache *loose;
90 struct ref_store *packed_ref_store;
91
92 /*
93 * Options used when writing references. These are parsed from the
94 * config lazily on first use via `files_ref_store_write_options()` so
95 * that we don't have to access the configuration when initializing the
96 * ref store. Do not access these fields directly, but use the accessor
97 * instead.
98 */
99 struct files_ref_store_write_options {
100 enum log_refs_config log_all_ref_updates;
101 int prefer_symlink_refs;
102 bool initialized;
103 } write_opts_lazy_loaded;
104 };
105
106 static void clear_loose_ref_cache(struct files_ref_store *refs)
107 {
108 if (refs->loose) {
109 free_ref_cache(refs->loose);
110 refs->loose = NULL;
111 }
112 }
113
114 static void files_ref_store_reparent(const char *name UNUSED,
115 const char *old_cwd,
116 const char *new_cwd,
117 void *payload)
118 {
119 struct files_ref_store *refs = payload;
120 char *tmp;
121
122 tmp = reparent_relative_path(old_cwd, new_cwd, refs->base.gitdir);
123 free(refs->base.gitdir);
124 refs->base.gitdir = tmp;
125
126 tmp = reparent_relative_path(old_cwd, new_cwd, refs->gitcommondir);
127 free(refs->gitcommondir);
128 refs->gitcommondir = tmp;
129 }
130
131 static int files_ref_store_config(const char *var, const char *value,
132 const struct config_context *ctx UNUSED,
133 void *payload)
134 {
135 struct files_ref_store_write_options *opts = payload;
136
137 if (!strcmp(var, "core.prefersymlinkrefs")) {
138 opts->prefer_symlink_refs = git_config_bool(var, value);
139 } else if (!strcmp(var, "core.logallrefupdates")) {
140 opts->log_all_ref_updates = refs_parse_log_all_ref_updates_config(value);
141 }
142
143 return 0;
144 }
145
146 static const struct files_ref_store_write_options *files_ref_store_write_options(struct files_ref_store *refs)
147 {
148 struct files_ref_store_write_options *opts = &refs->write_opts_lazy_loaded;
149
150 if (opts->initialized)
151 return opts;
152
153 opts->log_all_ref_updates = LOG_REFS_UNSET;
154 repo_config(refs->base.repo, files_ref_store_config, opts);
155
156 opts->initialized = true;
157 return opts;
158 }
159
160 /*
161 * Create a new submodule ref cache and add it to the internal
162 * set of caches.
163 */
164 static struct ref_store *files_ref_store_init(struct repository *repo,
165 const char *payload,
166 const char *gitdir,
167 const struct ref_store_init_options *opts)
168 {
169 struct files_ref_store *refs = xcalloc(1, sizeof(*refs));
170 struct ref_store *ref_store = (struct ref_store *)refs;
171 struct strbuf ref_common_dir = STRBUF_INIT;
172 struct strbuf refdir = STRBUF_INIT;
173 bool is_worktree;
174
175 refs_compute_filesystem_location(gitdir, payload, &is_worktree, &refdir,
176 &ref_common_dir);
177
178 base_ref_store_init(ref_store, repo, refdir.buf, &refs_be_files);
179
180 refs->gitcommondir = strbuf_detach(&ref_common_dir, NULL);
181 refs->packed_ref_store =
182 packed_ref_store_init(repo, NULL, refs->gitcommondir, opts);
183 refs->store_flags = opts->access_flags;
184
185 chdir_notify_register(NULL, files_ref_store_reparent, refs);
186
187 strbuf_release(&refdir);
188
189 return ref_store;
190 }
191
192 /*
193 * Die if refs is not the main ref store. caller is used in any
194 * necessary error messages.
195 */
196 static void files_assert_main_repository(struct files_ref_store *refs,
197 const char *caller)
198 {
199 if (refs->store_flags & REF_STORE_MAIN)
200 return;
201
202 BUG("operation %s only allowed for main ref store", caller);
203 }
204
205 /*
206 * Downcast ref_store to files_ref_store. Die if ref_store is not a
207 * files_ref_store. required_flags is compared with ref_store's
208 * store_flags to ensure the ref_store has all required capabilities.
209 * "caller" is used in any necessary error messages.
210 */
211 static struct files_ref_store *files_downcast(struct ref_store *ref_store,
212 unsigned int required_flags,
213 const char *caller)
214 {
215 struct files_ref_store *refs;
216
217 if (ref_store->be != &refs_be_files)
218 BUG("ref_store is type \"%s\" not \"files\" in %s",
219 ref_store->be->name, caller);
220
221 refs = (struct files_ref_store *)ref_store;
222
223 if ((refs->store_flags & required_flags) != required_flags)
224 BUG("operation %s requires abilities 0x%x, but only have 0x%x",
225 caller, required_flags, refs->store_flags);
226
227 return refs;
228 }
229
230 static void files_ref_store_release(struct ref_store *ref_store)
231 {
232 struct files_ref_store *refs = files_downcast(ref_store, 0, "release");
233 free_ref_cache(refs->loose);
234 free(refs->gitcommondir);
235 ref_store_release(refs->packed_ref_store);
236 free(refs->packed_ref_store);
237 chdir_notify_unregister(NULL, files_ref_store_reparent, refs);
238 }
239
240 static void files_reflog_path(struct files_ref_store *refs,
241 struct strbuf *sb,
242 const char *refname)
243 {
244 const char *bare_refname;
245 const char *wtname;
246 int wtname_len;
247 enum ref_worktree_type wt_type = parse_worktree_ref(
248 refname, &wtname, &wtname_len, &bare_refname);
249
250 switch (wt_type) {
251 case REF_WORKTREE_CURRENT:
252 strbuf_addf(sb, "%s/logs/%s", refs->base.gitdir, refname);
253 break;
254 case REF_WORKTREE_SHARED:
255 case REF_WORKTREE_MAIN:
256 strbuf_addf(sb, "%s/logs/%s", refs->gitcommondir, bare_refname);
257 break;
258 case REF_WORKTREE_OTHER:
259 strbuf_addf(sb, "%s/worktrees/%.*s/logs/%s", refs->gitcommondir,
260 wtname_len, wtname, bare_refname);
261 break;
262 default:
263 BUG("unknown ref type %d of ref %s", wt_type, refname);
264 }
265 }
266
267 static void files_ref_path(struct files_ref_store *refs,
268 struct strbuf *sb,
269 const char *refname)
270 {
271 const char *bare_refname;
272 const char *wtname;
273 int wtname_len;
274 enum ref_worktree_type wt_type = parse_worktree_ref(
275 refname, &wtname, &wtname_len, &bare_refname);
276 switch (wt_type) {
277 case REF_WORKTREE_CURRENT:
278 strbuf_addf(sb, "%s/%s", refs->base.gitdir, refname);
279 break;
280 case REF_WORKTREE_OTHER:
281 strbuf_addf(sb, "%s/worktrees/%.*s/%s", refs->gitcommondir,
282 wtname_len, wtname, bare_refname);
283 break;
284 case REF_WORKTREE_SHARED:
285 case REF_WORKTREE_MAIN:
286 strbuf_addf(sb, "%s/%s", refs->gitcommondir, bare_refname);
287 break;
288 default:
289 BUG("unknown ref type %d of ref %s", wt_type, refname);
290 }
291 }
292
293 /*
294 * Manually add refs/bisect, refs/rewritten and refs/worktree, which, being
295 * per-worktree, might not appear in the directory listing for
296 * refs/ in the main repo.
297 */
298 static void add_per_worktree_entries_to_dir(struct ref_dir *dir, const char *dirname)
299 {
300 const char *prefixes[] = { "refs/bisect/", "refs/worktree/", "refs/rewritten/" };
301 int ip;
302
303 if (strcmp(dirname, "refs/"))
304 return;
305
306 for (ip = 0; ip < ARRAY_SIZE(prefixes); ip++) {
307 const char *prefix = prefixes[ip];
308 int prefix_len = strlen(prefix);
309 struct ref_entry *child_entry;
310 int pos;
311
312 pos = search_ref_dir(dir, prefix, prefix_len);
313 if (pos >= 0)
314 continue;
315 child_entry = create_dir_entry(dir->cache, prefix, prefix_len);
316 add_entry_to_dir(dir, child_entry);
317 }
318 }
319
320 static void loose_fill_ref_dir_regular_file(struct files_ref_store *refs,
321 const char *refname,
322 struct ref_dir *dir)
323 {
324 struct object_id oid;
325 int flag;
326 const char *referent = refs_resolve_ref_unsafe(&refs->base,
327 refname,
328 RESOLVE_REF_READING,
329 &oid, &flag);
330
331 if (!referent) {
332 oidclr(&oid, refs->base.repo->hash_algo);
333 flag |= REF_ISBROKEN;
334 } else if (is_null_oid(&oid)) {
335 /*
336 * It is so astronomically unlikely
337 * that null_oid is the OID of an
338 * actual object that we consider its
339 * appearance in a loose reference
340 * file to be repo corruption
341 * (probably due to a software bug).
342 */
343 flag |= REF_ISBROKEN;
344 }
345
346 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
347 if (!refname_is_safe(refname))
348 die("loose refname is dangerous: %s", refname);
349 oidclr(&oid, refs->base.repo->hash_algo);
350 flag |= REF_BAD_NAME | REF_ISBROKEN;
351 }
352
353 if (!(flag & REF_ISSYMREF))
354 referent = NULL;
355
356 add_entry_to_dir(dir, create_ref_entry(refname, referent, &oid, flag));
357 }
358
359 /*
360 * Read the loose references from the namespace dirname into dir
361 * (without recursing). dirname must end with '/'. dir must be the
362 * directory entry corresponding to dirname.
363 */
364 static void loose_fill_ref_dir(struct ref_store *ref_store,
365 struct ref_dir *dir, const char *dirname)
366 {
367 struct files_ref_store *refs =
368 files_downcast(ref_store, REF_STORE_READ, "fill_ref_dir");
369 DIR *d;
370 struct dirent *de;
371 int dirnamelen = strlen(dirname);
372 struct strbuf refname;
373 struct strbuf path = STRBUF_INIT;
374
375 files_ref_path(refs, &path, dirname);
376
377 d = opendir(path.buf);
378 if (!d) {
379 strbuf_release(&path);
380 return;
381 }
382
383 strbuf_init(&refname, dirnamelen + 257);
384 strbuf_add(&refname, dirname, dirnamelen);
385
386 while ((de = readdir(d)) != NULL) {
387 unsigned char dtype;
388
389 if (de->d_name[0] == '.')
390 continue;
391 if (ends_with(de->d_name, ".lock"))
392 continue;
393 strbuf_addstr(&refname, de->d_name);
394
395 dtype = get_dtype(de, &path, 1);
396 if (dtype == DT_DIR) {
397 strbuf_addch(&refname, '/');
398 add_entry_to_dir(dir,
399 create_dir_entry(dir->cache, refname.buf,
400 refname.len));
401 } else if (dtype == DT_REG) {
402 loose_fill_ref_dir_regular_file(refs, refname.buf, dir);
403 }
404 strbuf_setlen(&refname, dirnamelen);
405 }
406 strbuf_release(&refname);
407 strbuf_release(&path);
408 closedir(d);
409
410 add_per_worktree_entries_to_dir(dir, dirname);
411 }
412
413 static int for_each_root_ref(struct files_ref_store *refs,
414 int (*cb)(const char *refname, void *cb_data),
415 void *cb_data)
416 {
417 struct strbuf path = STRBUF_INIT, refname = STRBUF_INIT;
418 struct dirent *de;
419 int ret;
420 DIR *d;
421
422 files_ref_path(refs, &path, "");
423
424 d = opendir(path.buf);
425 if (!d) {
426 strbuf_release(&path);
427 return -1;
428 }
429
430 while ((de = readdir(d)) != NULL) {
431 unsigned char dtype;
432
433 if (de->d_name[0] == '.')
434 continue;
435 if (ends_with(de->d_name, ".lock"))
436 continue;
437
438 strbuf_reset(&refname);
439 strbuf_addstr(&refname, de->d_name);
440
441 dtype = get_dtype(de, &path, 1);
442 if (dtype == DT_REG && is_root_ref(de->d_name)) {
443 ret = cb(refname.buf, cb_data);
444 if (ret)
445 goto done;
446 }
447 }
448
449 ret = 0;
450
451 done:
452 strbuf_release(&refname);
453 strbuf_release(&path);
454 closedir(d);
455 return ret;
456 }
457
458 struct fill_root_ref_data {
459 struct files_ref_store *refs;
460 struct ref_dir *dir;
461 };
462
463 static int fill_root_ref(const char *refname, void *cb_data)
464 {
465 struct fill_root_ref_data *data = cb_data;
466 loose_fill_ref_dir_regular_file(data->refs, refname, data->dir);
467 return 0;
468 }
469
470 /*
471 * Add root refs to the ref dir by parsing the directory for any files which
472 * follow the root ref syntax.
473 */
474 static void add_root_refs(struct files_ref_store *refs,
475 struct ref_dir *dir)
476 {
477 struct fill_root_ref_data data = {
478 .refs = refs,
479 .dir = dir,
480 };
481
482 for_each_root_ref(refs, fill_root_ref, &data);
483 }
484
485 static struct ref_cache *get_loose_ref_cache(struct files_ref_store *refs,
486 unsigned int flags)
487 {
488 if (!refs->loose) {
489 struct ref_dir *dir;
490
491 /*
492 * Mark the top-level directory complete because we
493 * are about to read the only subdirectory that can
494 * hold references:
495 */
496 refs->loose = create_ref_cache(&refs->base, loose_fill_ref_dir);
497
498 /* We're going to fill the top level ourselves: */
499 refs->loose->root->flag &= ~REF_INCOMPLETE;
500
501 dir = get_ref_dir(refs->loose->root);
502
503 if (flags & REFS_FOR_EACH_INCLUDE_ROOT_REFS)
504 add_root_refs(refs, dir);
505
506 /*
507 * Add an incomplete entry for "refs/" (to be filled
508 * lazily):
509 */
510 add_entry_to_dir(dir, create_dir_entry(refs->loose, "refs/", 5));
511 }
512 return refs->loose;
513 }
514
515 static int read_ref_internal(struct ref_store *ref_store, const char *refname,
516 struct object_id *oid, struct strbuf *referent,
517 unsigned int *type, int *failure_errno, int skip_packed_refs)
518 {
519 struct files_ref_store *refs =
520 files_downcast(ref_store, REF_STORE_READ, "read_raw_ref");
521 struct strbuf sb_contents = STRBUF_INIT;
522 struct strbuf sb_path = STRBUF_INIT;
523 const char *path;
524 const char *buf;
525 struct stat st;
526 int fd;
527 int ret = -1;
528 int remaining_retries = 3;
529 int myerr = 0;
530
531 *type = 0;
532 strbuf_reset(&sb_path);
533
534 files_ref_path(refs, &sb_path, refname);
535
536 path = sb_path.buf;
537
538 stat_ref:
539 /*
540 * We might have to loop back here to avoid a race
541 * condition: first we lstat() the file, then we try
542 * to read it as a link or as a file. But if somebody
543 * changes the type of the file (file <-> directory
544 * <-> symlink) between the lstat() and reading, then
545 * we don't want to report that as an error but rather
546 * try again starting with the lstat().
547 *
548 * We'll keep a count of the retries, though, just to avoid
549 * any confusing situation sending us into an infinite loop.
550 */
551
552 if (remaining_retries-- <= 0)
553 goto out;
554
555 if (lstat(path, &st) < 0) {
556 int ignore_errno;
557 myerr = errno;
558 if (myerr != ENOENT || skip_packed_refs)
559 goto out;
560 if (refs_read_raw_ref(refs->packed_ref_store, refname, oid,
561 referent, type, &ignore_errno)) {
562 myerr = ENOENT;
563 goto out;
564 }
565 ret = 0;
566 goto out;
567 }
568
569 /* Follow "normalized" - ie "refs/.." symlinks by hand */
570 if (S_ISLNK(st.st_mode)) {
571 strbuf_reset(&sb_contents);
572 if (strbuf_readlink(&sb_contents, path, st.st_size) < 0) {
573 myerr = errno;
574 if (myerr == ENOENT || myerr == EINVAL)
575 /* inconsistent with lstat; retry */
576 goto stat_ref;
577 else
578 goto out;
579 }
580 if (starts_with(sb_contents.buf, "refs/") &&
581 !check_refname_format(sb_contents.buf, 0)) {
582 strbuf_swap(&sb_contents, referent);
583 *type |= REF_ISSYMREF;
584 ret = 0;
585 goto out;
586 }
587 /*
588 * It doesn't look like a refname; fall through to just
589 * treating it like a non-symlink, and reading whatever it
590 * points to.
591 */
592 }
593
594 /* Is it a directory? */
595 if (S_ISDIR(st.st_mode)) {
596 int ignore_errno;
597 /*
598 * Even though there is a directory where the loose
599 * ref is supposed to be, there could still be a
600 * packed ref:
601 */
602 if (skip_packed_refs ||
603 refs_read_raw_ref(refs->packed_ref_store, refname, oid,
604 referent, type, &ignore_errno)) {
605 myerr = EISDIR;
606 goto out;
607 }
608 ret = 0;
609 goto out;
610 }
611
612 /*
613 * Anything else, just open it and try to use it as
614 * a ref
615 */
616 fd = open(path, O_RDONLY);
617 if (fd < 0) {
618 myerr = errno;
619 if (myerr == ENOENT && !S_ISLNK(st.st_mode))
620 /* inconsistent with lstat; retry */
621 goto stat_ref;
622 else
623 goto out;
624 }
625 strbuf_reset(&sb_contents);
626 if (strbuf_read(&sb_contents, fd, 256) < 0) {
627 myerr = errno;
628 close(fd);
629 goto out;
630 }
631 close(fd);
632 strbuf_rtrim(&sb_contents);
633 buf = sb_contents.buf;
634
635 ret = parse_loose_ref_contents(ref_store->repo->hash_algo, buf,
636 oid, referent, type, NULL, &myerr);
637
638 out:
639 if (ret && !myerr)
640 BUG("returning non-zero %d, should have set myerr!", ret);
641 *failure_errno = myerr;
642
643 strbuf_release(&sb_path);
644 strbuf_release(&sb_contents);
645 errno = 0;
646 return ret;
647 }
648
649 static int files_read_raw_ref(struct ref_store *ref_store, const char *refname,
650 struct object_id *oid, struct strbuf *referent,
651 unsigned int *type, int *failure_errno)
652 {
653 return read_ref_internal(ref_store, refname, oid, referent, type, failure_errno, 0);
654 }
655
656 static int files_read_symbolic_ref(struct ref_store *ref_store, const char *refname,
657 struct strbuf *referent)
658 {
659 struct object_id oid;
660 int failure_errno, ret;
661 unsigned int type;
662
663 ret = read_ref_internal(ref_store, refname, &oid, referent, &type, &failure_errno, 1);
664 if (!ret && !(type & REF_ISSYMREF))
665 return NOT_A_SYMREF;
666 return ret;
667 }
668
669 int parse_loose_ref_contents(const struct git_hash_algo *algop,
670 const char *buf, struct object_id *oid,
671 struct strbuf *referent, unsigned int *type,
672 const char **trailing, int *failure_errno)
673 {
674 const char *p;
675 if (skip_prefix(buf, "ref:", &buf)) {
676 while (isspace(*buf))
677 buf++;
678
679 strbuf_reset(referent);
680 strbuf_addstr(referent, buf);
681 *type |= REF_ISSYMREF;
682 return 0;
683 }
684
685 /*
686 * FETCH_HEAD has additional data after the sha.
687 */
688 if (parse_oid_hex_algop(buf, oid, &p, algop) ||
689 (*p != '\0' && !isspace(*p))) {
690 *type |= REF_ISBROKEN;
691 *failure_errno = EINVAL;
692 return -1;
693 }
694
695 if (trailing)
696 *trailing = p;
697
698 return 0;
699 }
700
701 static void unlock_ref(struct ref_lock *lock)
702 {
703 lock->count--;
704 if (!lock->count) {
705 rollback_lock_file(&lock->lk);
706 free(lock->ref_name);
707 free(lock);
708 }
709 }
710
711 /*
712 * Check if the transaction has another update with a case-insensitive refname
713 * match.
714 *
715 * If the update is part of the transaction, we only check up to that index.
716 * Further updates are expected to call this function to match previous indices.
717 */
718 static bool transaction_has_case_conflicting_update(struct ref_transaction *transaction,
719 struct ref_update *update)
720 {
721 for (size_t i = 0; i < transaction->nr; i++) {
722 if (transaction->updates[i] == update)
723 break;
724
725 if (!strcasecmp(transaction->updates[i]->refname, update->refname))
726 return true;
727 }
728 return false;
729 }
730
731 /*
732 * Lock refname, without following symrefs, and set *lock_p to point
733 * at a newly-allocated lock object. Fill in lock->old_oid, referent,
734 * and type similarly to read_raw_ref().
735 *
736 * The caller must verify that refname is a "safe" reference name (in
737 * the sense of refname_is_safe()) before calling this function.
738 *
739 * If the reference doesn't already exist, verify that refname doesn't
740 * have a D/F conflict with any existing references. extras and skip
741 * are passed to refs_verify_refname_available() for this check.
742 *
743 * If mustexist is not set and the reference is not found or is
744 * broken, lock the reference anyway but clear old_oid.
745 *
746 * Return 0 on success. On failure, write an error message to err and
747 * return REF_TRANSACTION_ERROR_NAME_CONFLICT or REF_TRANSACTION_ERROR_GENERIC.
748 *
749 * Implementation note: This function is basically
750 *
751 * lock reference
752 * read_raw_ref()
753 *
754 * but it includes a lot more code to
755 * - Deal with possible races with other processes
756 * - Avoid calling refs_verify_refname_available() when it can be
757 * avoided, namely if we were successfully able to read the ref
758 * - Generate informative error messages in the case of failure
759 */
760 static enum ref_transaction_error lock_raw_ref(struct files_ref_store *refs,
761 struct ref_transaction *transaction,
762 size_t update_idx,
763 int mustexist,
764 struct string_list *refnames_to_check,
765 struct ref_lock **lock_p,
766 struct strbuf *referent,
767 struct strbuf *err)
768 {
769 enum ref_transaction_error ret = REF_TRANSACTION_ERROR_GENERIC;
770 struct ref_update *update = transaction->updates[update_idx];
771 const struct string_list *extras = &transaction->refnames;
772 const char *refname = update->refname;
773 unsigned int *type = &update->type;
774 struct ref_lock *lock;
775 struct strbuf ref_file = STRBUF_INIT;
776 int attempts_remaining = 3;
777 int failure_errno;
778
779 assert(err);
780 files_assert_main_repository(refs, "lock_raw_ref");
781
782 *type = 0;
783
784 /* First lock the file so it can't change out from under us. */
785
786 *lock_p = CALLOC_ARRAY(lock, 1);
787
788 lock->ref_name = xstrdup(refname);
789 lock->count = 1;
790 files_ref_path(refs, &ref_file, refname);
791
792 retry:
793 switch (safe_create_leading_directories(refs->base.repo, ref_file.buf)) {
794 case SCLD_OK:
795 break; /* success */
796 case SCLD_EXISTS:
797 /*
798 * Suppose refname is "refs/foo/bar". We just failed
799 * to create the containing directory, "refs/foo",
800 * because there was a non-directory in the way. This
801 * indicates a D/F conflict, probably because of
802 * another reference such as "refs/foo". There is no
803 * reason to expect this error to be transitory.
804 */
805 if (refs_verify_refname_available(&refs->base, refname,
806 extras, NULL, 0, err)) {
807 if (mustexist) {
808 /*
809 * To the user the relevant error is
810 * that the "mustexist" reference is
811 * missing:
812 */
813 strbuf_reset(err);
814 strbuf_addf(err, "unable to resolve reference '%s'",
815 refname);
816 ret = REF_TRANSACTION_ERROR_NONEXISTENT_REF;
817 } else {
818 /*
819 * The error message set by
820 * refs_verify_refname_available() is
821 * OK.
822 */
823 ret = REF_TRANSACTION_ERROR_NAME_CONFLICT;
824 }
825 } else {
826 /*
827 * The file that is in the way isn't a loose
828 * reference. Report it as a low-level
829 * failure.
830 */
831 strbuf_addf(err, "unable to create lock file %s.lock; "
832 "non-directory in the way",
833 ref_file.buf);
834 }
835 goto error_return;
836 case SCLD_VANISHED:
837 /* Maybe another process was tidying up. Try again. */
838 if (--attempts_remaining > 0)
839 goto retry;
840 /* fall through */
841 default:
842 strbuf_addf(err, "unable to create directory for %s",
843 ref_file.buf);
844 goto error_return;
845 }
846
847 if (repo_hold_lock_file_for_update_timeout(refs->base.repo,
848 &lock->lk, ref_file.buf, LOCK_NO_DEREF,
849 get_files_ref_lock_timeout_ms(transaction->ref_store->repo)) < 0) {
850 int myerr = errno;
851 errno = 0;
852 if (myerr == ENOENT && --attempts_remaining > 0) {
853 /*
854 * Maybe somebody just deleted one of the
855 * directories leading to ref_file. Try
856 * again:
857 */
858 goto retry;
859 } else {
860 unable_to_lock_message(ref_file.buf, myerr, err);
861 if (myerr == EEXIST) {
862 if (repo_ignore_case(refs->base.repo) &&
863 transaction_has_case_conflicting_update(transaction, update)) {
864 /*
865 * In case-insensitive filesystems, ensure that conflicts within a
866 * given transaction are handled. Pre-existing refs on a
867 * case-insensitive system will be overridden without any issue.
868 */
869 ret = REF_TRANSACTION_ERROR_CASE_CONFLICT;
870 } else {
871 /*
872 * Pre-existing case-conflicting reference locks should also be
873 * specially categorized to avoid failing all batched updates.
874 */
875 ret = REF_TRANSACTION_ERROR_CREATE_EXISTS;
876 }
877 }
878
879 goto error_return;
880 }
881 }
882
883 /*
884 * Now we hold the lock and can read the reference without
885 * fear that its value will change.
886 */
887
888 if (files_read_raw_ref(&refs->base, refname, &lock->old_oid, referent,
889 type, &failure_errno)) {
890 struct string_list_item *item;
891
892 if (failure_errno == ENOENT) {
893 if (mustexist) {
894 /* Garden variety missing reference. */
895 strbuf_addf(err, "unable to resolve reference '%s'",
896 refname);
897 ret = REF_TRANSACTION_ERROR_NONEXISTENT_REF;
898 goto error_return;
899 } else {
900 /*
901 * Reference is missing, but that's OK. We
902 * know that there is not a conflict with
903 * another loose reference because
904 * (supposing that we are trying to lock
905 * reference "refs/foo/bar"):
906 *
907 * - We were successfully able to create
908 * the lockfile refs/foo/bar.lock, so we
909 * know there cannot be a loose reference
910 * named "refs/foo".
911 *
912 * - We got ENOENT and not EISDIR, so we
913 * know that there cannot be a loose
914 * reference named "refs/foo/bar/baz".
915 */
916 }
917 } else if (failure_errno == EISDIR) {
918 /*
919 * There is a directory in the way. It might have
920 * contained references that have been deleted. If
921 * we don't require that the reference already
922 * exists, try to remove the directory so that it
923 * doesn't cause trouble when we want to rename the
924 * lockfile into place later.
925 */
926 if (mustexist) {
927 /* Garden variety missing reference. */
928 strbuf_addf(err, "unable to resolve reference '%s'",
929 refname);
930 ret = REF_TRANSACTION_ERROR_NONEXISTENT_REF;
931 goto error_return;
932 } else if (remove_dir_recursively(&ref_file,
933 REMOVE_DIR_EMPTY_ONLY)) {
934 ret = REF_TRANSACTION_ERROR_NAME_CONFLICT;
935 if (refs_verify_refname_available(
936 &refs->base, refname,
937 extras, NULL, 0, err)) {
938 /*
939 * The error message set by
940 * verify_refname_available() is OK.
941 */
942 goto error_return;
943 } else {
944 /*
945 * Directory conflicts can occur if there
946 * is an existing lock file in the directory
947 * or if the filesystem is case-insensitive
948 * and the directory contains a valid reference
949 * but conflicts with the update.
950 */
951 strbuf_addf(err, "there is a non-empty directory '%s' "
952 "blocking reference '%s'",
953 ref_file.buf, refname);
954 goto error_return;
955 }
956 }
957 } else if (failure_errno == EINVAL && (*type & REF_ISBROKEN)) {
958 strbuf_addf(err, "unable to resolve reference '%s': "
959 "reference broken", refname);
960 goto error_return;
961 } else {
962 strbuf_addf(err, "unable to resolve reference '%s': %s",
963 refname, strerror(failure_errno));
964 goto error_return;
965 }
966
967 /*
968 * If the ref did not exist and we are creating it, we have to
969 * make sure there is no existing packed ref that conflicts
970 * with refname. This check is deferred so that we can batch it.
971 *
972 * For case-insensitive filesystems, we should also check for F/D
973 * conflicts between 'foo' and 'Foo/bar'. So let's lowercase
974 * the refname.
975 */
976 if (repo_ignore_case(refs->base.repo)) {
977 struct strbuf lower = STRBUF_INIT;
978
979 strbuf_addstr(&lower, refname);
980 strbuf_tolower(&lower);
981
982 item = string_list_append_nodup(refnames_to_check,
983 strbuf_detach(&lower, NULL));
984 } else {
985 item = string_list_append(refnames_to_check, refname);
986 }
987
988 item->util = xmalloc(sizeof(update_idx));
989 memcpy(item->util, &update_idx, sizeof(update_idx));
990 }
991
992 ret = 0;
993 goto out;
994
995 error_return:
996 unlock_ref(lock);
997 *lock_p = NULL;
998
999 out:
1000 strbuf_release(&ref_file);
1001 return ret;
1002 }
1003
1004 struct files_ref_iterator {
1005 struct ref_iterator base;
1006
1007 struct ref_iterator *iter0;
1008 struct repository *repo;
1009 unsigned int flags;
1010 };
1011
1012 static int files_ref_iterator_advance(struct ref_iterator *ref_iterator)
1013 {
1014 struct files_ref_iterator *iter =
1015 (struct files_ref_iterator *)ref_iterator;
1016 int ok;
1017
1018 while ((ok = ref_iterator_advance(iter->iter0)) == ITER_OK) {
1019 if (iter->flags & REFS_FOR_EACH_PER_WORKTREE_ONLY &&
1020 parse_worktree_ref(iter->iter0->ref.name, NULL, NULL,
1021 NULL) != REF_WORKTREE_CURRENT)
1022 continue;
1023
1024 if ((iter->flags & REFS_FOR_EACH_OMIT_DANGLING_SYMREFS) &&
1025 (iter->iter0->ref.flags & REF_ISSYMREF) &&
1026 (iter->iter0->ref.flags & REF_ISBROKEN))
1027 continue;
1028
1029 if (!(iter->flags & REFS_FOR_EACH_INCLUDE_BROKEN) &&
1030 !ref_resolves_to_object(iter->iter0->ref.name,
1031 iter->repo,
1032 iter->iter0->ref.oid,
1033 iter->iter0->ref.flags))
1034 continue;
1035
1036 iter->base.ref = iter->iter0->ref;
1037
1038 return ITER_OK;
1039 }
1040
1041 return ok;
1042 }
1043
1044 static int files_ref_iterator_seek(struct ref_iterator *ref_iterator,
1045 const char *refname, unsigned int flags)
1046 {
1047 struct files_ref_iterator *iter =
1048 (struct files_ref_iterator *)ref_iterator;
1049 return ref_iterator_seek(iter->iter0, refname, flags);
1050 }
1051
1052 static void files_ref_iterator_release(struct ref_iterator *ref_iterator)
1053 {
1054 struct files_ref_iterator *iter =
1055 (struct files_ref_iterator *)ref_iterator;
1056 ref_iterator_free(iter->iter0);
1057 }
1058
1059 static struct ref_iterator_vtable files_ref_iterator_vtable = {
1060 .advance = files_ref_iterator_advance,
1061 .seek = files_ref_iterator_seek,
1062 .release = files_ref_iterator_release,
1063 };
1064
1065 static struct ref_iterator *files_ref_iterator_begin(
1066 struct ref_store *ref_store,
1067 const char *prefix, const char **exclude_patterns,
1068 unsigned int flags)
1069 {
1070 struct files_ref_store *refs;
1071 struct ref_iterator *loose_iter, *packed_iter, *overlay_iter;
1072 struct files_ref_iterator *iter;
1073 struct ref_iterator *ref_iterator;
1074 unsigned int required_flags = REF_STORE_READ;
1075
1076 if (!(flags & REFS_FOR_EACH_INCLUDE_BROKEN))
1077 required_flags |= REF_STORE_ODB;
1078
1079 refs = files_downcast(ref_store, required_flags, "ref_iterator_begin");
1080
1081 /*
1082 * We must make sure that all loose refs are read before
1083 * accessing the packed-refs file; this avoids a race
1084 * condition if loose refs are migrated to the packed-refs
1085 * file by a simultaneous process, but our in-memory view is
1086 * from before the migration. We ensure this as follows:
1087 * First, we call start the loose refs iteration with its
1088 * `prime_ref` argument set to true. This causes the loose
1089 * references in the subtree to be pre-read into the cache.
1090 * (If they've already been read, that's OK; we only need to
1091 * guarantee that they're read before the packed refs, not
1092 * *how much* before.) After that, we call
1093 * packed_ref_iterator_begin(), which internally checks
1094 * whether the packed-ref cache is up to date with what is on
1095 * disk, and re-reads it if not.
1096 */
1097
1098 loose_iter = cache_ref_iterator_begin(get_loose_ref_cache(refs, flags),
1099 prefix, ref_store->repo, 1);
1100
1101 /*
1102 * The packed-refs file might contain broken references, for
1103 * example an old version of a reference that points at an
1104 * object that has since been garbage-collected. This is OK as
1105 * long as there is a corresponding loose reference that
1106 * overrides it, and we don't want to emit an error message in
1107 * this case. So ask the packed_ref_store for all of its
1108 * references, and (if needed) do our own check for broken
1109 * ones in files_ref_iterator_advance(), after we have merged
1110 * the packed and loose references.
1111 */
1112 packed_iter = refs_ref_iterator_begin(
1113 refs->packed_ref_store, prefix, exclude_patterns, 0,
1114 REFS_FOR_EACH_INCLUDE_BROKEN);
1115
1116 overlay_iter = overlay_ref_iterator_begin(loose_iter, packed_iter);
1117
1118 CALLOC_ARRAY(iter, 1);
1119 ref_iterator = &iter->base;
1120 base_ref_iterator_init(ref_iterator, &files_ref_iterator_vtable);
1121 iter->iter0 = overlay_iter;
1122 iter->repo = ref_store->repo;
1123 iter->flags = flags;
1124
1125 return ref_iterator;
1126 }
1127
1128 /*
1129 * Callback function for raceproof_create_file(). This function is
1130 * expected to do something that makes dirname(path) permanent despite
1131 * the fact that other processes might be cleaning up empty
1132 * directories at the same time. Usually it will create a file named
1133 * path, but alternatively it could create another file in that
1134 * directory, or even chdir() into that directory. The function should
1135 * return 0 if the action was completed successfully. On error, it
1136 * should return a nonzero result and set errno.
1137 * raceproof_create_file() treats two errno values specially:
1138 *
1139 * - ENOENT -- dirname(path) does not exist. In this case,
1140 * raceproof_create_file() tries creating dirname(path)
1141 * (and any parent directories, if necessary) and calls
1142 * the function again.
1143 *
1144 * - EISDIR -- the file already exists and is a directory. In this
1145 * case, raceproof_create_file() removes the directory if
1146 * it is empty (and recursively any empty directories that
1147 * it contains) and calls the function again.
1148 *
1149 * Any other errno causes raceproof_create_file() to fail with the
1150 * callback's return value and errno.
1151 *
1152 * Obviously, this function should be OK with being called again if it
1153 * fails with ENOENT or EISDIR. In other scenarios it will not be
1154 * called again.
1155 */
1156 typedef int create_file_fn(const char *path, void *cb);
1157
1158 /*
1159 * Create a file in dirname(path) by calling fn, creating leading
1160 * directories if necessary. Retry a few times in case we are racing
1161 * with another process that is trying to clean up the directory that
1162 * contains path. See the documentation for create_file_fn for more
1163 * details.
1164 *
1165 * Return the value and set the errno that resulted from the most
1166 * recent call of fn. fn is always called at least once, and will be
1167 * called more than once if it returns ENOENT or EISDIR.
1168 */
1169 static int raceproof_create_file(struct files_ref_store *refs,
1170 const char *path, create_file_fn fn, void *cb)
1171 {
1172 /*
1173 * The number of times we will try to remove empty directories
1174 * in the way of path. This is only 1 because if another
1175 * process is racily creating directories that conflict with
1176 * us, we don't want to fight against them.
1177 */
1178 int remove_directories_remaining = 1;
1179
1180 /*
1181 * The number of times that we will try to create the
1182 * directories containing path. We are willing to attempt this
1183 * more than once, because another process could be trying to
1184 * clean up empty directories at the same time as we are
1185 * trying to create them.
1186 */
1187 int create_directories_remaining = 3;
1188
1189 /* A scratch copy of path, filled lazily if we need it: */
1190 struct strbuf path_copy = STRBUF_INIT;
1191
1192 int ret, save_errno;
1193
1194 /* Sanity check: */
1195 assert(*path);
1196
1197 retry_fn:
1198 ret = fn(path, cb);
1199 save_errno = errno;
1200 if (!ret)
1201 goto out;
1202
1203 if (errno == EISDIR && remove_directories_remaining-- > 0) {
1204 /*
1205 * A directory is in the way. Maybe it is empty; try
1206 * to remove it:
1207 */
1208 if (!path_copy.len)
1209 strbuf_addstr(&path_copy, path);
1210
1211 if (!remove_dir_recursively(&path_copy, REMOVE_DIR_EMPTY_ONLY))
1212 goto retry_fn;
1213 } else if (errno == ENOENT && create_directories_remaining-- > 0) {
1214 /*
1215 * Maybe the containing directory didn't exist, or
1216 * maybe it was just deleted by a process that is
1217 * racing with us to clean up empty directories. Try
1218 * to create it:
1219 */
1220 enum scld_error scld_result;
1221
1222 if (!path_copy.len)
1223 strbuf_addstr(&path_copy, path);
1224
1225 do {
1226 scld_result = safe_create_leading_directories(refs->base.repo, path_copy.buf);
1227 if (scld_result == SCLD_OK)
1228 goto retry_fn;
1229 } while (scld_result == SCLD_VANISHED && create_directories_remaining-- > 0);
1230 }
1231
1232 out:
1233 strbuf_release(&path_copy);
1234 errno = save_errno;
1235 return ret;
1236 }
1237
1238 static int remove_empty_directories(struct strbuf *path)
1239 {
1240 /*
1241 * we want to create a file but there is a directory there;
1242 * if that is an empty directory (or a directory that contains
1243 * only empty directories), remove them.
1244 */
1245 return remove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);
1246 }
1247
1248 struct create_reflock_cb {
1249 struct lock_file *lk;
1250 struct repository *repo;
1251 };
1252
1253 static int create_reflock(const char *path, void *cb)
1254 {
1255 struct create_reflock_cb *data = cb;
1256 return repo_hold_lock_file_for_update_timeout(
1257 data->repo, data->lk, path, LOCK_NO_DEREF,
1258 get_files_ref_lock_timeout_ms(data->repo)) < 0 ? -1 : 0;
1259 }
1260
1261 /*
1262 * Locks a ref returning the lock on success and NULL on failure.
1263 */
1264 static struct ref_lock *lock_ref_oid_basic(struct files_ref_store *refs,
1265 const char *refname,
1266 struct strbuf *err)
1267 {
1268 struct strbuf ref_file = STRBUF_INIT;
1269 struct ref_lock *lock;
1270 struct create_reflock_cb cb_data;
1271
1272 files_assert_main_repository(refs, "lock_ref_oid_basic");
1273 assert(err);
1274
1275 CALLOC_ARRAY(lock, 1);
1276
1277 files_ref_path(refs, &ref_file, refname);
1278
1279 /*
1280 * If the ref did not exist and we are creating it, make sure
1281 * there is no existing packed ref whose name begins with our
1282 * refname, nor a packed ref whose name is a proper prefix of
1283 * our refname.
1284 */
1285 if (is_null_oid(&lock->old_oid) &&
1286 refs_verify_refname_available(refs->packed_ref_store, refname,
1287 NULL, NULL, 0, err))
1288 goto error_return;
1289
1290 lock->ref_name = xstrdup(refname);
1291 lock->count = 1;
1292 cb_data.lk = &lock->lk;
1293 cb_data.repo = refs->base.repo;
1294
1295 if (raceproof_create_file(refs, ref_file.buf, create_reflock, &cb_data)) {
1296 unable_to_lock_message(ref_file.buf, errno, err);
1297 goto error_return;
1298 }
1299
1300 if (!refs_resolve_ref_unsafe(&refs->base, lock->ref_name, 0,
1301 &lock->old_oid, NULL))
1302 oidclr(&lock->old_oid, refs->base.repo->hash_algo);
1303 goto out;
1304
1305 error_return:
1306 unlock_ref(lock);
1307 lock = NULL;
1308
1309 out:
1310 strbuf_release(&ref_file);
1311 return lock;
1312 }
1313
1314 struct ref_to_prune {
1315 struct ref_to_prune *next;
1316 struct object_id oid;
1317 char name[FLEX_ARRAY];
1318 };
1319
1320 enum {
1321 REMOVE_EMPTY_PARENTS_REF = 0x01,
1322 REMOVE_EMPTY_PARENTS_REFLOG = 0x02
1323 };
1324
1325 /*
1326 * Remove empty parent directories associated with the specified
1327 * reference and/or its reflog, but spare [logs/]refs/ and immediate
1328 * subdirs. flags is a combination of REMOVE_EMPTY_PARENTS_REF and/or
1329 * REMOVE_EMPTY_PARENTS_REFLOG.
1330 */
1331 static void try_remove_empty_parents(struct files_ref_store *refs,
1332 const char *refname,
1333 unsigned int flags)
1334 {
1335 struct strbuf buf = STRBUF_INIT;
1336 struct strbuf sb = STRBUF_INIT;
1337 char *p, *q;
1338 int i;
1339
1340 strbuf_addstr(&buf, refname);
1341 p = buf.buf;
1342 for (i = 0; i < 2; i++) { /* refs/{heads,tags,...}/ */
1343 while (*p && *p != '/')
1344 p++;
1345 /* tolerate duplicate slashes; see check_refname_format() */
1346 while (*p == '/')
1347 p++;
1348 }
1349 q = buf.buf + buf.len;
1350 while (flags & (REMOVE_EMPTY_PARENTS_REF | REMOVE_EMPTY_PARENTS_REFLOG)) {
1351 while (q > p && *q != '/')
1352 q--;
1353 while (q > p && *(q-1) == '/')
1354 q--;
1355 if (q == p)
1356 break;
1357 strbuf_setlen(&buf, q - buf.buf);
1358
1359 strbuf_reset(&sb);
1360 files_ref_path(refs, &sb, buf.buf);
1361 if ((flags & REMOVE_EMPTY_PARENTS_REF) && rmdir(sb.buf))
1362 flags &= ~REMOVE_EMPTY_PARENTS_REF;
1363
1364 strbuf_reset(&sb);
1365 files_reflog_path(refs, &sb, buf.buf);
1366 if ((flags & REMOVE_EMPTY_PARENTS_REFLOG) && rmdir(sb.buf))
1367 flags &= ~REMOVE_EMPTY_PARENTS_REFLOG;
1368 }
1369 strbuf_release(&buf);
1370 strbuf_release(&sb);
1371 }
1372
1373 /* make sure nobody touched the ref, and unlink */
1374 static void prune_ref(struct files_ref_store *refs, struct ref_to_prune *r)
1375 {
1376 struct ref_transaction *transaction;
1377 struct strbuf err = STRBUF_INIT;
1378 int ret = -1;
1379
1380 if (check_refname_format(r->name, 0))
1381 return;
1382
1383 transaction = ref_store_transaction_begin(&refs->base, 0, &err);
1384 if (!transaction)
1385 goto cleanup;
1386 ref_transaction_add_update(
1387 transaction, r->name,
1388 REF_NO_DEREF | REF_HAVE_NEW | REF_HAVE_OLD | REF_IS_PRUNING,
1389 null_oid(refs->base.repo->hash_algo), &r->oid, NULL, NULL, NULL,
1390 NULL, NULL);
1391 if (ref_transaction_commit(transaction, &err))
1392 goto cleanup;
1393
1394 ret = 0;
1395
1396 cleanup:
1397 if (ret)
1398 error("%s", err.buf);
1399 strbuf_release(&err);
1400 ref_transaction_free(transaction);
1401 return;
1402 }
1403
1404 /*
1405 * Prune the loose versions of the references in the linked list
1406 * `*refs_to_prune`, freeing the entries in the list as we go.
1407 */
1408 static void prune_refs(struct files_ref_store *refs, struct ref_to_prune **refs_to_prune)
1409 {
1410 while (*refs_to_prune) {
1411 struct ref_to_prune *r = *refs_to_prune;
1412 *refs_to_prune = r->next;
1413 prune_ref(refs, r);
1414 free(r);
1415 }
1416 }
1417
1418 /*
1419 * Return true if the specified reference should be packed.
1420 */
1421 static int should_pack_ref(struct files_ref_store *refs,
1422 const struct reference *ref,
1423 struct refs_optimize_opts *opts)
1424 {
1425 struct string_list_item *item;
1426
1427 /* Do not pack per-worktree refs: */
1428 if (parse_worktree_ref(ref->name, NULL, NULL, NULL) !=
1429 REF_WORKTREE_SHARED)
1430 return 0;
1431
1432 /* Do not pack symbolic refs: */
1433 if (ref->flags & REF_ISSYMREF)
1434 return 0;
1435
1436 /* Do not pack broken refs: */
1437 if (!ref_resolves_to_object(ref->name, refs->base.repo, ref->oid, ref->flags))
1438 return 0;
1439
1440 if (ref_excluded(opts->exclusions, ref->name))
1441 return 0;
1442
1443 for_each_string_list_item(item, opts->includes)
1444 if (!wildmatch(item->string, ref->name, 0))
1445 return 1;
1446
1447 return 0;
1448 }
1449
1450 static int should_pack_refs(struct files_ref_store *refs,
1451 struct refs_optimize_opts *opts)
1452 {
1453 struct ref_iterator *iter;
1454 size_t packed_size;
1455 size_t refcount = 0;
1456 size_t limit;
1457 int ret;
1458
1459 if (!(opts->flags & REFS_OPTIMIZE_AUTO))
1460 return 1;
1461
1462 ret = packed_refs_size(refs->packed_ref_store, &packed_size);
1463 if (ret < 0)
1464 die("cannot determine packed-refs size");
1465
1466 /*
1467 * Packing loose references into the packed-refs file scales with the
1468 * number of references we're about to write. We thus decide whether we
1469 * repack refs by weighing the current size of the packed-refs file
1470 * against the number of loose references. This is done such that we do
1471 * not repack too often on repositories with a huge number of
1472 * references, where we can expect a lot of churn in the number of
1473 * references.
1474 *
1475 * As a heuristic, we repack if the number of loose references in the
1476 * repository exceeds `log2(nr_packed_refs) * 5`, where we estimate
1477 * `nr_packed_refs = packed_size / 100`, which scales as following:
1478 *
1479 * - 1kB ~ 10 packed refs: 16 refs
1480 * - 10kB ~ 100 packed refs: 33 refs
1481 * - 100kB ~ 1k packed refs: 49 refs
1482 * - 1MB ~ 10k packed refs: 66 refs
1483 * - 10MB ~ 100k packed refs: 82 refs
1484 * - 100MB ~ 1m packed refs: 99 refs
1485 *
1486 * We thus allow roughly 16 additional loose refs per factor of ten of
1487 * packed refs. This heuristic may be tweaked in the future, but should
1488 * serve as a sufficiently good first iteration.
1489 */
1490 limit = log2u(packed_size / 100) * 5;
1491 if (limit < 16)
1492 limit = 16;
1493
1494 iter = cache_ref_iterator_begin(get_loose_ref_cache(refs, 0), NULL,
1495 refs->base.repo, 0);
1496 while ((ret = ref_iterator_advance(iter)) == ITER_OK) {
1497 if (should_pack_ref(refs, &iter->ref, opts))
1498 refcount++;
1499 if (refcount >= limit) {
1500 ref_iterator_free(iter);
1501 return 1;
1502 }
1503 }
1504
1505 if (ret != ITER_DONE)
1506 die("error while iterating over references");
1507
1508 ref_iterator_free(iter);
1509 return 0;
1510 }
1511
1512 static int files_optimize(struct ref_store *ref_store,
1513 struct refs_optimize_opts *opts)
1514 {
1515 struct files_ref_store *refs =
1516 files_downcast(ref_store, REF_STORE_WRITE | REF_STORE_ODB,
1517 "pack_refs");
1518 struct ref_iterator *iter;
1519 int ok;
1520 struct ref_to_prune *refs_to_prune = NULL;
1521 struct strbuf err = STRBUF_INIT;
1522 struct ref_transaction *transaction;
1523
1524 if (!should_pack_refs(refs, opts))
1525 return 0;
1526
1527 transaction = ref_store_transaction_begin(refs->packed_ref_store,
1528 0, &err);
1529 if (!transaction)
1530 return -1;
1531
1532 packed_refs_lock(refs->packed_ref_store, LOCK_DIE_ON_ERROR, &err);
1533
1534 iter = cache_ref_iterator_begin(get_loose_ref_cache(refs, 0), NULL,
1535 refs->base.repo, 0);
1536 while ((ok = ref_iterator_advance(iter)) == ITER_OK) {
1537 /*
1538 * If the loose reference can be packed, add an entry
1539 * in the packed ref cache. If the reference should be
1540 * pruned, also add it to refs_to_prune.
1541 */
1542 if (!should_pack_ref(refs, &iter->ref, opts))
1543 continue;
1544
1545 /*
1546 * Add a reference creation for this reference to the
1547 * packed-refs transaction:
1548 */
1549 if (ref_transaction_update(transaction, iter->ref.name,
1550 iter->ref.oid, NULL, NULL, NULL,
1551 REF_NO_DEREF, NULL, &err))
1552 die("failure preparing to create packed reference %s: %s",
1553 iter->ref.name, err.buf);
1554
1555 /* Schedule the loose reference for pruning if requested. */
1556 if ((opts->flags & REFS_OPTIMIZE_PRUNE)) {
1557 struct ref_to_prune *n;
1558 FLEX_ALLOC_STR(n, name, iter->ref.name);
1559 oidcpy(&n->oid, iter->ref.oid);
1560 n->next = refs_to_prune;
1561 refs_to_prune = n;
1562 }
1563 }
1564 if (ok != ITER_DONE)
1565 die("error while iterating over references");
1566
1567 if (ref_transaction_commit(transaction, &err))
1568 die("unable to write new packed-refs: %s", err.buf);
1569
1570 ref_transaction_free(transaction);
1571
1572 packed_refs_unlock(refs->packed_ref_store);
1573
1574 prune_refs(refs, &refs_to_prune);
1575 ref_iterator_free(iter);
1576 strbuf_release(&err);
1577 return 0;
1578 }
1579
1580 static int files_optimize_required(struct ref_store *ref_store,
1581 struct refs_optimize_opts *opts,
1582 bool *required)
1583 {
1584 struct files_ref_store *refs = files_downcast(ref_store, REF_STORE_READ,
1585 "optimize_required");
1586 *required = should_pack_refs(refs, opts);
1587 return 0;
1588 }
1589
1590 /*
1591 * People using contrib's git-new-workdir have .git/logs/refs ->
1592 * /some/other/path/.git/logs/refs, and that may live on another device.
1593 *
1594 * IOW, to avoid cross device rename errors, the temporary renamed log must
1595 * live into logs/refs.
1596 */
1597 #define TMP_RENAMED_LOG "refs/.tmp-renamed-log"
1598
1599 struct rename_cb {
1600 const char *tmp_renamed_log;
1601 int true_errno;
1602 };
1603
1604 static int rename_tmp_log_callback(const char *path, void *cb_data)
1605 {
1606 struct rename_cb *cb = cb_data;
1607
1608 if (rename(cb->tmp_renamed_log, path)) {
1609 /*
1610 * rename(a, b) when b is an existing directory ought
1611 * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.
1612 * Sheesh. Record the true errno for error reporting,
1613 * but report EISDIR to raceproof_create_file() so
1614 * that it knows to retry.
1615 */
1616 cb->true_errno = errno;
1617 if (errno == ENOTDIR)
1618 errno = EISDIR;
1619 return -1;
1620 } else {
1621 return 0;
1622 }
1623 }
1624
1625 static int rename_tmp_log(struct files_ref_store *refs, const char *newrefname)
1626 {
1627 struct strbuf path = STRBUF_INIT;
1628 struct strbuf tmp = STRBUF_INIT;
1629 struct rename_cb cb;
1630 int ret;
1631
1632 files_reflog_path(refs, &path, newrefname);
1633 files_reflog_path(refs, &tmp, TMP_RENAMED_LOG);
1634 cb.tmp_renamed_log = tmp.buf;
1635 ret = raceproof_create_file(refs, path.buf, rename_tmp_log_callback, &cb);
1636 if (ret) {
1637 if (errno == EISDIR)
1638 error("directory not empty: %s", path.buf);
1639 else
1640 error("unable to move logfile %s to %s: %s",
1641 tmp.buf, path.buf,
1642 strerror(cb.true_errno));
1643 }
1644
1645 strbuf_release(&path);
1646 strbuf_release(&tmp);
1647 return ret;
1648 }
1649
1650 static enum ref_transaction_error write_ref_to_lockfile(struct files_ref_store *refs,
1651 struct ref_lock *lock,
1652 const struct object_id *oid,
1653 struct strbuf *err);
1654 static int commit_ref_update(struct files_ref_store *refs,
1655 struct ref_lock *lock,
1656 const struct object_id *oid, const char *logmsg,
1657 int flags,
1658 struct strbuf *err);
1659
1660 /*
1661 * Emit a better error message than lockfile.c's
1662 * unable_to_lock_message() would in case there is a D/F conflict with
1663 * another existing reference. If there would be a conflict, emit an error
1664 * message and return false; otherwise, return true.
1665 *
1666 * Note that this function is not safe against all races with other
1667 * processes, and that's not its job. We'll emit a more verbose error on D/f
1668 * conflicts if we get past it into lock_ref_oid_basic().
1669 */
1670 static int refs_rename_ref_available(struct ref_store *refs,
1671 const char *old_refname,
1672 const char *new_refname)
1673 {
1674 struct string_list skip = STRING_LIST_INIT_NODUP;
1675 struct strbuf err = STRBUF_INIT;
1676 int ok;
1677
1678 string_list_insert(&skip, old_refname);
1679 ok = !refs_verify_refname_available(refs, new_refname,
1680 NULL, &skip, 0, &err);
1681 if (!ok)
1682 error("%s", err.buf);
1683
1684 string_list_clear(&skip, 0);
1685 strbuf_release(&err);
1686 return ok;
1687 }
1688
1689 static int files_copy_or_rename_ref(struct ref_store *ref_store,
1690 const char *oldrefname, const char *newrefname,
1691 const char *logmsg, int copy)
1692 {
1693 struct files_ref_store *refs =
1694 files_downcast(ref_store, REF_STORE_WRITE, "rename_ref");
1695 struct object_id orig_oid;
1696 int flag = 0, logmoved = 0;
1697 struct ref_lock *lock;
1698 struct stat loginfo;
1699 struct strbuf sb_oldref = STRBUF_INIT;
1700 struct strbuf sb_newref = STRBUF_INIT;
1701 struct strbuf tmp_renamed_log = STRBUF_INIT;
1702 int log, ret;
1703 struct strbuf err = STRBUF_INIT;
1704
1705 files_reflog_path(refs, &sb_oldref, oldrefname);
1706 files_reflog_path(refs, &sb_newref, newrefname);
1707 files_reflog_path(refs, &tmp_renamed_log, TMP_RENAMED_LOG);
1708
1709 log = !lstat(sb_oldref.buf, &loginfo);
1710 if (log && S_ISLNK(loginfo.st_mode)) {
1711 ret = error("reflog for %s is a symlink", oldrefname);
1712 goto out;
1713 }
1714
1715 if (!refs_resolve_ref_unsafe(&refs->base, oldrefname,
1716 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,
1717 &orig_oid, &flag)) {
1718 ret = error("refname %s not found", oldrefname);
1719 goto out;
1720 }
1721
1722 if (flag & REF_ISSYMREF) {
1723 if (copy)
1724 ret = error("refname %s is a symbolic ref, copying it is not supported",
1725 oldrefname);
1726 else
1727 ret = error("refname %s is a symbolic ref, renaming it is not supported",
1728 oldrefname);
1729 goto out;
1730 }
1731 if (!refs_rename_ref_available(&refs->base, oldrefname, newrefname)) {
1732 ret = 1;
1733 goto out;
1734 }
1735
1736 if (!copy && log && rename(sb_oldref.buf, tmp_renamed_log.buf)) {
1737 ret = error("unable to move logfile logs/%s to logs/"TMP_RENAMED_LOG": %s",
1738 oldrefname, strerror(errno));
1739 goto out;
1740 }
1741
1742 if (copy && log && copy_file(refs->base.repo, tmp_renamed_log.buf, sb_oldref.buf, 0644)) {
1743 ret = error("unable to copy logfile logs/%s to logs/"TMP_RENAMED_LOG": %s",
1744 oldrefname, strerror(errno));
1745 goto out;
1746 }
1747
1748 if (!copy && refs_delete_ref(&refs->base, logmsg, oldrefname,
1749 &orig_oid, REF_NO_DEREF)) {
1750 error("unable to delete old %s", oldrefname);
1751 goto rollback;
1752 }
1753
1754 /*
1755 * Since we are doing a shallow lookup, oid is not the
1756 * correct value to pass to delete_ref as old_oid. But that
1757 * doesn't matter, because an old_oid check wouldn't add to
1758 * the safety anyway; we want to delete the reference whatever
1759 * its current value.
1760 */
1761 if (!copy && refs_resolve_ref_unsafe(&refs->base, newrefname,
1762 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,
1763 NULL, NULL) &&
1764 refs_delete_ref(&refs->base, NULL, newrefname,
1765 NULL, REF_NO_DEREF)) {
1766 if (errno == EISDIR) {
1767 struct strbuf path = STRBUF_INIT;
1768 int result;
1769
1770 files_ref_path(refs, &path, newrefname);
1771 result = remove_empty_directories(&path);
1772 strbuf_release(&path);
1773
1774 if (result) {
1775 error("Directory not empty: %s", newrefname);
1776 goto rollback;
1777 }
1778 } else {
1779 error("unable to delete existing %s", newrefname);
1780 goto rollback;
1781 }
1782 }
1783
1784 if (log && rename_tmp_log(refs, newrefname))
1785 goto rollback;
1786
1787 logmoved = log;
1788
1789 lock = lock_ref_oid_basic(refs, newrefname, &err);
1790 if (!lock) {
1791 if (copy)
1792 error("unable to copy '%s' to '%s': %s", oldrefname, newrefname, err.buf);
1793 else
1794 error("unable to rename '%s' to '%s': %s", oldrefname, newrefname, err.buf);
1795 strbuf_release(&err);
1796 goto rollback;
1797 }
1798 oidcpy(&lock->old_oid, &orig_oid);
1799
1800 if (write_ref_to_lockfile(refs, lock, &orig_oid, &err) ||
1801 commit_ref_update(refs, lock, &orig_oid, logmsg, 0, &err)) {
1802 error("unable to write current sha1 into %s: %s", newrefname, err.buf);
1803 strbuf_release(&err);
1804 goto rollback;
1805 }
1806
1807 ret = 0;
1808 goto out;
1809
1810 rollback:
1811 lock = lock_ref_oid_basic(refs, oldrefname, &err);
1812 if (!lock) {
1813 error("unable to lock %s for rollback: %s", oldrefname, err.buf);
1814 strbuf_release(&err);
1815 goto rollbacklog;
1816 }
1817
1818 if (write_ref_to_lockfile(refs, lock, &orig_oid, &err) ||
1819 commit_ref_update(refs, lock, &orig_oid, NULL, REF_SKIP_CREATE_REFLOG, &err)) {
1820 error("unable to write current sha1 into %s: %s", oldrefname, err.buf);
1821 strbuf_release(&err);
1822 }
1823
1824 rollbacklog:
1825 if (logmoved && rename(sb_newref.buf, sb_oldref.buf))
1826 error("unable to restore logfile %s from %s: %s",
1827 oldrefname, newrefname, strerror(errno));
1828 if (!logmoved && log &&
1829 rename(tmp_renamed_log.buf, sb_oldref.buf))
1830 error("unable to restore logfile %s from logs/"TMP_RENAMED_LOG": %s",
1831 oldrefname, strerror(errno));
1832 ret = 1;
1833 out:
1834 strbuf_release(&sb_newref);
1835 strbuf_release(&sb_oldref);
1836 strbuf_release(&tmp_renamed_log);
1837
1838 return ret;
1839 }
1840
1841 static int files_rename_ref(struct ref_store *ref_store,
1842 const char *oldrefname, const char *newrefname,
1843 const char *logmsg)
1844 {
1845 return files_copy_or_rename_ref(ref_store, oldrefname,
1846 newrefname, logmsg, 0);
1847 }
1848
1849 static int files_copy_ref(struct ref_store *ref_store,
1850 const char *oldrefname, const char *newrefname,
1851 const char *logmsg)
1852 {
1853 return files_copy_or_rename_ref(ref_store, oldrefname,
1854 newrefname, logmsg, 1);
1855 }
1856
1857 static int close_ref_gently(struct ref_lock *lock)
1858 {
1859 if (close_lock_file_gently(&lock->lk))
1860 return -1;
1861 return 0;
1862 }
1863
1864 static int commit_ref(struct ref_lock *lock)
1865 {
1866 char *path = get_locked_file_path(&lock->lk);
1867 struct stat st;
1868
1869 if (!lstat(path, &st) && S_ISDIR(st.st_mode)) {
1870 /*
1871 * There is a directory at the path we want to rename
1872 * the lockfile to. Hopefully it is empty; try to
1873 * delete it.
1874 */
1875 size_t len = strlen(path);
1876 struct strbuf sb_path = STRBUF_INIT;
1877
1878 strbuf_attach(&sb_path, path, len, len + 1);
1879
1880 /*
1881 * If this fails, commit_lock_file() will also fail
1882 * and will report the problem.
1883 */
1884 remove_empty_directories(&sb_path);
1885 strbuf_release(&sb_path);
1886 } else {
1887 free(path);
1888 }
1889
1890 if (commit_lock_file(&lock->lk))
1891 return -1;
1892 return 0;
1893 }
1894
1895 static int open_or_create_logfile(const char *path, void *cb)
1896 {
1897 int *fd = cb;
1898
1899 *fd = open(path, O_APPEND | O_WRONLY | O_CREAT, 0666);
1900 return (*fd < 0) ? -1 : 0;
1901 }
1902
1903 /*
1904 * Create a reflog for a ref. If force_create = 0, only create the
1905 * reflog for certain refs (those for which should_autocreate_reflog
1906 * returns non-zero). Otherwise, create it regardless of the reference
1907 * name. If the logfile already existed or was created, return 0 and
1908 * set *logfd to the file descriptor opened for appending to the file.
1909 * If no logfile exists and we decided not to create one, return 0 and
1910 * set *logfd to -1. On failure, fill in *err, set *logfd to -1, and
1911 * return -1.
1912 */
1913 static int log_ref_setup(struct files_ref_store *refs,
1914 const char *refname, int force_create,
1915 int *logfd, struct strbuf *err)
1916 {
1917 enum log_refs_config log_refs_cfg = files_ref_store_write_options(refs)->log_all_ref_updates;
1918 struct strbuf logfile_sb = STRBUF_INIT;
1919 char *logfile;
1920
1921 if (log_refs_cfg == LOG_REFS_UNSET)
1922 log_refs_cfg = is_bare_repository(refs->base.repo) ? LOG_REFS_NONE : LOG_REFS_NORMAL;
1923
1924 files_reflog_path(refs, &logfile_sb, refname);
1925 logfile = strbuf_detach(&logfile_sb, NULL);
1926
1927 if (force_create || should_autocreate_reflog(log_refs_cfg, refname)) {
1928 if (raceproof_create_file(refs, logfile, open_or_create_logfile, logfd)) {
1929 if (errno == ENOENT)
1930 strbuf_addf(err, "unable to create directory for '%s': "
1931 "%s", logfile, strerror(errno));
1932 else if (errno == EISDIR)
1933 strbuf_addf(err, "there are still logs under '%s'",
1934 logfile);
1935 else
1936 strbuf_addf(err, "unable to append to '%s': %s",
1937 logfile, strerror(errno));
1938
1939 goto error;
1940 }
1941 } else {
1942 *logfd = open(logfile, O_APPEND | O_WRONLY);
1943 if (*logfd < 0) {
1944 if (errno == ENOENT || errno == EISDIR) {
1945 /*
1946 * The logfile doesn't already exist,
1947 * but that is not an error; it only
1948 * means that we won't write log
1949 * entries to it.
1950 */
1951 ;
1952 } else {
1953 strbuf_addf(err, "unable to append to '%s': %s",
1954 logfile, strerror(errno));
1955 goto error;
1956 }
1957 }
1958 }
1959
1960 if (*logfd >= 0)
1961 adjust_shared_perm(refs->base.repo, logfile);
1962
1963 free(logfile);
1964 return 0;
1965
1966 error:
1967 free(logfile);
1968 return -1;
1969 }
1970
1971 static int files_create_reflog(struct ref_store *ref_store, const char *refname,
1972 struct strbuf *err)
1973 {
1974 struct files_ref_store *refs =
1975 files_downcast(ref_store, REF_STORE_WRITE, "create_reflog");
1976 int fd;
1977
1978 if (log_ref_setup(refs, refname, 1, &fd, err))
1979 return -1;
1980
1981 if (fd >= 0)
1982 close(fd);
1983
1984 return 0;
1985 }
1986
1987 static int log_ref_write_fd(int fd, const struct object_id *old_oid,
1988 const struct object_id *new_oid,
1989 const char *committer, const char *msg)
1990 {
1991 struct strbuf sb = STRBUF_INIT;
1992 int ret = 0;
1993
1994 if (!committer)
1995 committer = git_committer_info(0);
1996
1997 strbuf_addf(&sb, "%s %s %s", oid_to_hex(old_oid), oid_to_hex(new_oid), committer);
1998 if (msg && *msg) {
1999 strbuf_addch(&sb, '\t');
2000 strbuf_addstr(&sb, msg);
2001 }
2002 strbuf_addch(&sb, '\n');
2003 if (write_in_full(fd, sb.buf, sb.len) < 0)
2004 ret = -1;
2005 strbuf_release(&sb);
2006 return ret;
2007 }
2008
2009 static int files_log_ref_write(struct files_ref_store *refs,
2010 const char *refname,
2011 const struct object_id *old_oid,
2012 const struct object_id *new_oid,
2013 const char *committer_info, const char *msg,
2014 int flags, struct strbuf *err)
2015 {
2016 int logfd, result;
2017
2018 if (flags & REF_SKIP_CREATE_REFLOG)
2019 return 0;
2020
2021 result = log_ref_setup(refs, refname,
2022 flags & REF_FORCE_CREATE_REFLOG,
2023 &logfd, err);
2024
2025 if (result)
2026 return result;
2027
2028 if (logfd < 0)
2029 return 0;
2030 result = log_ref_write_fd(logfd, old_oid, new_oid, committer_info, msg);
2031 if (result) {
2032 struct strbuf sb = STRBUF_INIT;
2033 int save_errno = errno;
2034
2035 files_reflog_path(refs, &sb, refname);
2036 strbuf_addf(err, "unable to append to '%s': %s",
2037 sb.buf, strerror(save_errno));
2038 strbuf_release(&sb);
2039 close(logfd);
2040 return -1;
2041 }
2042 if (close(logfd)) {
2043 struct strbuf sb = STRBUF_INIT;
2044 int save_errno = errno;
2045
2046 files_reflog_path(refs, &sb, refname);
2047 strbuf_addf(err, "unable to append to '%s': %s",
2048 sb.buf, strerror(save_errno));
2049 strbuf_release(&sb);
2050 return -1;
2051 }
2052 return 0;
2053 }
2054
2055 /*
2056 * Write oid into the open lockfile, then close the lockfile. On
2057 * errors, rollback the lockfile, fill in *err and return -1.
2058 */
2059 static enum ref_transaction_error write_ref_to_lockfile(struct files_ref_store *refs,
2060 struct ref_lock *lock,
2061 const struct object_id *oid,
2062 struct strbuf *err)
2063 {
2064 static char term = '\n';
2065 int fd;
2066
2067 fd = get_lock_file_fd(&lock->lk);
2068 if (write_in_full(fd, oid_to_hex(oid), refs->base.repo->hash_algo->hexsz) < 0 ||
2069 write_in_full(fd, &term, 1) < 0 ||
2070 fsync_component(FSYNC_COMPONENT_REFERENCE, get_lock_file_fd(&lock->lk)) < 0 ||
2071 close_ref_gently(lock) < 0) {
2072 strbuf_addf(err,
2073 "couldn't write '%s'", get_lock_file_path(&lock->lk));
2074 unlock_ref(lock);
2075 return REF_TRANSACTION_ERROR_GENERIC;
2076 }
2077 return 0;
2078 }
2079
2080 /*
2081 * Commit a change to a loose reference that has already been written
2082 * to the loose reference lockfile. Also update the reflogs if
2083 * necessary, using the specified lockmsg (which can be NULL).
2084 */
2085 static int commit_ref_update(struct files_ref_store *refs,
2086 struct ref_lock *lock,
2087 const struct object_id *oid, const char *logmsg,
2088 int flags,
2089 struct strbuf *err)
2090 {
2091 files_assert_main_repository(refs, "commit_ref_update");
2092
2093 clear_loose_ref_cache(refs);
2094 if (files_log_ref_write(refs, lock->ref_name, &lock->old_oid, oid, NULL,
2095 logmsg, flags, err)) {
2096 char *old_msg = strbuf_detach(err, NULL);
2097 strbuf_addf(err, "cannot update the ref '%s': %s",
2098 lock->ref_name, old_msg);
2099 free(old_msg);
2100 unlock_ref(lock);
2101 return -1;
2102 }
2103
2104 if (strcmp(lock->ref_name, "HEAD") != 0) {
2105 /*
2106 * Special hack: If a branch is updated directly and HEAD
2107 * points to it (may happen on the remote side of a push
2108 * for example) then logically the HEAD reflog should be
2109 * updated too.
2110 * A generic solution implies reverse symref information,
2111 * but finding all symrefs pointing to the given branch
2112 * would be rather costly for this rare event (the direct
2113 * update of a branch) to be worth it. So let's cheat and
2114 * check with HEAD only which should cover 99% of all usage
2115 * scenarios (even 100% of the default ones).
2116 */
2117 int head_flag;
2118 const char *head_ref;
2119
2120 head_ref = refs_resolve_ref_unsafe(&refs->base, "HEAD",
2121 RESOLVE_REF_READING,
2122 NULL, &head_flag);
2123 if (head_ref && (head_flag & REF_ISSYMREF) &&
2124 !strcmp(head_ref, lock->ref_name)) {
2125 struct strbuf log_err = STRBUF_INIT;
2126 if (files_log_ref_write(refs, "HEAD", &lock->old_oid,
2127 oid, NULL, logmsg, flags,
2128 &log_err)) {
2129 error("%s", log_err.buf);
2130 strbuf_release(&log_err);
2131 }
2132 }
2133 }
2134
2135 if (commit_ref(lock)) {
2136 strbuf_addf(err, "couldn't set '%s'", lock->ref_name);
2137 unlock_ref(lock);
2138 return -1;
2139 }
2140
2141 unlock_ref(lock);
2142 return 0;
2143 }
2144
2145 #if defined(NO_SYMLINK_HEAD) || defined(WITH_BREAKING_CHANGES)
2146 #define create_ref_symlink(a, b) (-1)
2147 #else
2148 static int create_ref_symlink(struct ref_lock *lock, const char *target)
2149 {
2150 static int warn_once = 1;
2151 char *ref_path;
2152 int ret = -1;
2153
2154 ref_path = get_locked_file_path(&lock->lk);
2155 unlink(ref_path);
2156 ret = symlink(target, ref_path);
2157 free(ref_path);
2158
2159 if (ret)
2160 fprintf(stderr, "no symlink - falling back to symbolic ref\n");
2161
2162 if (warn_once)
2163 warning(_("'core.preferSymlinkRefs=true' is nominated for removal.\n"
2164 "hint: The use of symbolic links for symbolic refs is deprecated\n"
2165 "hint: and will be removed in Git 3.0. The configuration that\n"
2166 "hint: tells Git to use them is thus going away. You can unset\n"
2167 "hint: it with:\n"
2168 "hint:\n"
2169 "hint:\tgit config unset core.preferSymlinkRefs\n"
2170 "hint:\n"
2171 "hint: Git will then use the textual symref format instead."));
2172 warn_once = 0;
2173
2174 return ret;
2175 }
2176 #endif
2177
2178 static int create_symref_lock(struct ref_lock *lock, const char *target,
2179 struct strbuf *err)
2180 {
2181 if (!fdopen_lock_file(&lock->lk, "w")) {
2182 strbuf_addf(err, "unable to fdopen %s: %s",
2183 get_lock_file_path(&lock->lk), strerror(errno));
2184 return -1;
2185 }
2186
2187 if (fprintf(get_lock_file_fp(&lock->lk), "ref: %s\n", target) < 0) {
2188 strbuf_addf(err, "unable to write to %s: %s",
2189 get_lock_file_path(&lock->lk), strerror(errno));
2190 return -1;
2191 }
2192
2193 return 0;
2194 }
2195
2196 static int files_reflog_exists(struct ref_store *ref_store,
2197 const char *refname)
2198 {
2199 struct files_ref_store *refs =
2200 files_downcast(ref_store, REF_STORE_READ, "reflog_exists");
2201 struct strbuf sb = STRBUF_INIT;
2202 struct stat st;
2203 int ret;
2204
2205 files_reflog_path(refs, &sb, refname);
2206 ret = !lstat(sb.buf, &st) && S_ISREG(st.st_mode);
2207 strbuf_release(&sb);
2208 return ret;
2209 }
2210
2211 static int files_delete_reflog(struct ref_store *ref_store,
2212 const char *refname)
2213 {
2214 struct files_ref_store *refs =
2215 files_downcast(ref_store, REF_STORE_WRITE, "delete_reflog");
2216 struct strbuf sb = STRBUF_INIT;
2217 int ret;
2218
2219 files_reflog_path(refs, &sb, refname);
2220 ret = remove_path(sb.buf);
2221 strbuf_release(&sb);
2222 return ret;
2223 }
2224
2225 static int show_one_reflog_ent(struct files_ref_store *refs,
2226 const char *refname,
2227 struct strbuf *sb,
2228 each_reflog_ent_fn fn, void *cb_data)
2229 {
2230 struct object_id ooid, noid;
2231 char *email_end, *message;
2232 timestamp_t timestamp;
2233 int tz;
2234 char *p = sb->buf;
2235
2236 /* old SP new SP name <email> SP time TAB msg LF */
2237 if (!sb->len || sb->buf[sb->len - 1] != '\n' ||
2238 parse_oid_hex_algop(p, &ooid, &p, refs->base.repo->hash_algo) || *p++ != ' ' ||
2239 parse_oid_hex_algop(p, &noid, &p, refs->base.repo->hash_algo) || *p++ != ' ' ||
2240 !(email_end = strchr(p, '>')) ||
2241 email_end[1] != ' ' ||
2242 !(timestamp = parse_timestamp(email_end + 2, &message, 10)) ||
2243 !message || message[0] != ' ' ||
2244 (message[1] != '+' && message[1] != '-') ||
2245 !isdigit(message[2]) || !isdigit(message[3]) ||
2246 !isdigit(message[4]) || !isdigit(message[5]))
2247 return 0; /* corrupt? */
2248 email_end[1] = '\0';
2249 tz = strtol(message + 1, NULL, 10);
2250 if (message[6] != '\t')
2251 message += 6;
2252 else
2253 message += 7;
2254 return fn(refname, &ooid, &noid, p, timestamp, tz, message, cb_data);
2255 }
2256
2257 static char *find_beginning_of_line(char *bob, char *scan)
2258 {
2259 while (bob < scan && *(--scan) != '\n')
2260 ; /* keep scanning backwards */
2261 /*
2262 * Return either beginning of the buffer, or LF at the end of
2263 * the previous line.
2264 */
2265 return scan;
2266 }
2267
2268 static int files_for_each_reflog_ent_reverse(struct ref_store *ref_store,
2269 const char *refname,
2270 each_reflog_ent_fn fn,
2271 void *cb_data)
2272 {
2273 struct files_ref_store *refs =
2274 files_downcast(ref_store, REF_STORE_READ,
2275 "for_each_reflog_ent_reverse");
2276 struct strbuf sb = STRBUF_INIT;
2277 FILE *logfp;
2278 long pos;
2279 int ret = 0, at_tail = 1;
2280
2281 files_reflog_path(refs, &sb, refname);
2282 logfp = fopen(sb.buf, "r");
2283 strbuf_release(&sb);
2284 if (!logfp)
2285 return -1;
2286
2287 /* Jump to the end */
2288 if (fseek(logfp, 0, SEEK_END) < 0)
2289 ret = error("cannot seek back reflog for %s: %s",
2290 refname, strerror(errno));
2291 pos = ftell(logfp);
2292 while (!ret && 0 < pos) {
2293 int cnt;
2294 size_t nread;
2295 char buf[BUFSIZ];
2296 char *endp, *scanp;
2297
2298 /* Fill next block from the end */
2299 cnt = (sizeof(buf) < pos) ? sizeof(buf) : pos;
2300 if (fseek(logfp, pos - cnt, SEEK_SET)) {
2301 ret = error("cannot seek back reflog for %s: %s",
2302 refname, strerror(errno));
2303 break;
2304 }
2305 nread = fread(buf, cnt, 1, logfp);
2306 if (nread != 1) {
2307 ret = error("cannot read %d bytes from reflog for %s: %s",
2308 cnt, refname, strerror(errno));
2309 break;
2310 }
2311 pos -= cnt;
2312
2313 scanp = endp = buf + cnt;
2314 if (at_tail && scanp[-1] == '\n')
2315 /* Looking at the final LF at the end of the file */
2316 scanp--;
2317 at_tail = 0;
2318
2319 while (buf < scanp) {
2320 /*
2321 * terminating LF of the previous line, or the beginning
2322 * of the buffer.
2323 */
2324 char *bp;
2325
2326 bp = find_beginning_of_line(buf, scanp);
2327
2328 if (*bp == '\n') {
2329 /*
2330 * The newline is the end of the previous line,
2331 * so we know we have complete line starting
2332 * at (bp + 1). Prefix it onto any prior data
2333 * we collected for the line and process it.
2334 */
2335 strbuf_splice(&sb, 0, 0, bp + 1, endp - (bp + 1));
2336 scanp = bp;
2337 endp = bp + 1;
2338 ret = show_one_reflog_ent(refs, refname, &sb, fn, cb_data);
2339 strbuf_reset(&sb);
2340 if (ret)
2341 break;
2342 } else if (!pos) {
2343 /*
2344 * We are at the start of the buffer, and the
2345 * start of the file; there is no previous
2346 * line, and we have everything for this one.
2347 * Process it, and we can end the loop.
2348 */
2349 strbuf_splice(&sb, 0, 0, buf, endp - buf);
2350 ret = show_one_reflog_ent(refs, refname, &sb, fn, cb_data);
2351 strbuf_reset(&sb);
2352 break;
2353 }
2354
2355 if (bp == buf) {
2356 /*
2357 * We are at the start of the buffer, and there
2358 * is more file to read backwards. Which means
2359 * we are in the middle of a line. Note that we
2360 * may get here even if *bp was a newline; that
2361 * just means we are at the exact end of the
2362 * previous line, rather than some spot in the
2363 * middle.
2364 *
2365 * Save away what we have to be combined with
2366 * the data from the next read.
2367 */
2368 strbuf_splice(&sb, 0, 0, buf, endp - buf);
2369 break;
2370 }
2371 }
2372
2373 }
2374 if (!ret && sb.len)
2375 BUG("reverse reflog parser had leftover data");
2376
2377 fclose(logfp);
2378 strbuf_release(&sb);
2379 return ret;
2380 }
2381
2382 static int files_for_each_reflog_ent(struct ref_store *ref_store,
2383 const char *refname,
2384 each_reflog_ent_fn fn, void *cb_data)
2385 {
2386 struct files_ref_store *refs =
2387 files_downcast(ref_store, REF_STORE_READ,
2388 "for_each_reflog_ent");
2389 FILE *logfp;
2390 struct strbuf sb = STRBUF_INIT;
2391 int ret = 0;
2392
2393 files_reflog_path(refs, &sb, refname);
2394 logfp = fopen(sb.buf, "r");
2395 strbuf_release(&sb);
2396 if (!logfp)
2397 return -1;
2398
2399 while (!ret && !strbuf_getwholeline(&sb, logfp, '\n'))
2400 ret = show_one_reflog_ent(refs, refname, &sb, fn, cb_data);
2401 fclose(logfp);
2402 strbuf_release(&sb);
2403 return ret;
2404 }
2405
2406 struct files_reflog_iterator {
2407 struct ref_iterator base;
2408 struct ref_store *ref_store;
2409 struct dir_iterator *dir_iterator;
2410 };
2411
2412 static int files_reflog_iterator_advance(struct ref_iterator *ref_iterator)
2413 {
2414 struct files_reflog_iterator *iter =
2415 (struct files_reflog_iterator *)ref_iterator;
2416 struct dir_iterator *diter = iter->dir_iterator;
2417 int ok;
2418
2419 while ((ok = dir_iterator_advance(diter)) == ITER_OK) {
2420 if (!S_ISREG(diter->st.st_mode))
2421 continue;
2422 if (check_refname_format(diter->basename,
2423 REFNAME_ALLOW_ONELEVEL))
2424 continue;
2425
2426 iter->base.ref.name = diter->relative_path;
2427 return ITER_OK;
2428 }
2429
2430 return ok;
2431 }
2432
2433 static int files_reflog_iterator_seek(struct ref_iterator *ref_iterator UNUSED,
2434 const char *refname UNUSED,
2435 unsigned int flags UNUSED)
2436 {
2437 BUG("ref_iterator_seek() called for reflog_iterator");
2438 }
2439
2440 static void files_reflog_iterator_release(struct ref_iterator *ref_iterator)
2441 {
2442 struct files_reflog_iterator *iter =
2443 (struct files_reflog_iterator *)ref_iterator;
2444 dir_iterator_free(iter->dir_iterator);
2445 }
2446
2447 static struct ref_iterator_vtable files_reflog_iterator_vtable = {
2448 .advance = files_reflog_iterator_advance,
2449 .seek = files_reflog_iterator_seek,
2450 .release = files_reflog_iterator_release,
2451 };
2452
2453 static struct ref_iterator *reflog_iterator_begin(struct ref_store *ref_store,
2454 const char *gitdir)
2455 {
2456 struct dir_iterator *diter;
2457 struct files_reflog_iterator *iter;
2458 struct ref_iterator *ref_iterator;
2459 struct strbuf sb = STRBUF_INIT;
2460
2461 strbuf_addf(&sb, "%s/logs", gitdir);
2462
2463 diter = dir_iterator_begin(sb.buf, DIR_ITERATOR_SORTED);
2464 if (!diter) {
2465 strbuf_release(&sb);
2466 return empty_ref_iterator_begin();
2467 }
2468
2469 CALLOC_ARRAY(iter, 1);
2470 ref_iterator = &iter->base;
2471
2472 base_ref_iterator_init(ref_iterator, &files_reflog_iterator_vtable);
2473 iter->dir_iterator = diter;
2474 iter->ref_store = ref_store;
2475 strbuf_release(&sb);
2476
2477 return ref_iterator;
2478 }
2479
2480 static struct ref_iterator *files_reflog_iterator_begin(struct ref_store *ref_store)
2481 {
2482 struct files_ref_store *refs =
2483 files_downcast(ref_store, REF_STORE_READ,
2484 "reflog_iterator_begin");
2485
2486 if (!strcmp(refs->base.gitdir, refs->gitcommondir)) {
2487 return reflog_iterator_begin(ref_store, refs->gitcommondir);
2488 } else {
2489 return merge_ref_iterator_begin(
2490 reflog_iterator_begin(ref_store, refs->base.gitdir),
2491 reflog_iterator_begin(ref_store, refs->gitcommondir),
2492 ref_iterator_select, refs);
2493 }
2494 }
2495
2496 /*
2497 * If update is a direct update of head_ref (the reference pointed to
2498 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.
2499 */
2500 static enum ref_transaction_error split_head_update(struct ref_update *update,
2501 struct ref_transaction *transaction,
2502 const char *head_ref,
2503 struct strbuf *err)
2504 {
2505 struct ref_update *new_update;
2506
2507 if ((update->flags & REF_LOG_ONLY) ||
2508 (update->flags & REF_SKIP_CREATE_REFLOG) ||
2509 (update->flags & REF_IS_PRUNING) ||
2510 (update->flags & REF_UPDATE_VIA_HEAD))
2511 return 0;
2512
2513 if (strcmp(update->refname, head_ref))
2514 return 0;
2515
2516 /*
2517 * First make sure that HEAD is not already in the
2518 * transaction. This check is O(lg N) in the transaction
2519 * size, but it happens at most once per transaction.
2520 */
2521 if (string_list_has_string(&transaction->refnames, "HEAD")) {
2522 /* An entry already existed */
2523 strbuf_addf(err,
2524 "multiple updates for 'HEAD' (including one "
2525 "via its referent '%s') are not allowed",
2526 update->refname);
2527 return REF_TRANSACTION_ERROR_NAME_CONFLICT;
2528 }
2529
2530 new_update = ref_transaction_add_update(
2531 transaction, "HEAD",
2532 update->flags | REF_LOG_ONLY | REF_NO_DEREF | REF_LOG_VIA_SPLIT,
2533 &update->new_oid, &update->old_oid, &update->peeled,
2534 NULL, NULL, update->committer_info, update->msg);
2535 new_update->parent_update = update;
2536
2537 /*
2538 * Add "HEAD". This insertion is O(N) in the transaction
2539 * size, but it happens at most once per transaction.
2540 * Add new_update->refname instead of a literal "HEAD".
2541 */
2542 if (strcmp(new_update->refname, "HEAD"))
2543 BUG("%s unexpectedly not 'HEAD'", new_update->refname);
2544
2545 return 0;
2546 }
2547
2548 /*
2549 * update is for a symref that points at referent and doesn't have
2550 * REF_NO_DEREF set. Split it into two updates:
2551 * - The original update, but with REF_LOG_ONLY and REF_NO_DEREF set
2552 * - A new, separate update for the referent reference
2553 * Note that the new update will itself be subject to splitting when
2554 * the iteration gets to it.
2555 */
2556 static enum ref_transaction_error split_symref_update(struct ref_update *update,
2557 const char *referent,
2558 struct ref_transaction *transaction,
2559 struct strbuf *err)
2560 {
2561 struct ref_update *new_update;
2562 unsigned int new_flags;
2563
2564 /*
2565 * First make sure that referent is not already in the
2566 * transaction. This check is O(lg N) in the transaction
2567 * size, but it happens at most once per symref in a
2568 * transaction.
2569 */
2570 if (string_list_has_string(&transaction->refnames, referent)) {
2571 /* An entry already exists */
2572 strbuf_addf(err,
2573 "multiple updates for '%s' (including one "
2574 "via symref '%s') are not allowed",
2575 referent, update->refname);
2576 return REF_TRANSACTION_ERROR_NAME_CONFLICT;
2577 }
2578
2579 new_flags = update->flags;
2580 if (!strcmp(update->refname, "HEAD")) {
2581 /*
2582 * Record that the new update came via HEAD, so that
2583 * when we process it, split_head_update() doesn't try
2584 * to add another reflog update for HEAD. Note that
2585 * this bit will be propagated if the new_update
2586 * itself needs to be split.
2587 */
2588 new_flags |= REF_UPDATE_VIA_HEAD;
2589 }
2590
2591 new_update = ref_transaction_add_update(
2592 transaction, referent, new_flags,
2593 update->new_target ? NULL : &update->new_oid,
2594 update->old_target ? NULL : &update->old_oid,
2595 &update->peeled, update->new_target, update->old_target,
2596 NULL, update->msg);
2597
2598 new_update->parent_update = update;
2599
2600 /*
2601 * Change the symbolic ref update to log only. Also, it
2602 * doesn't need to check its old OID value, as that will be
2603 * done when new_update is processed.
2604 */
2605 update->flags |= REF_LOG_ONLY | REF_NO_DEREF;
2606
2607 return 0;
2608 }
2609
2610 /*
2611 * Check whether the REF_HAVE_OLD and old_oid values stored in update
2612 * are consistent with oid, which is the reference's current value. If
2613 * everything is OK, return 0; otherwise, write an error message to
2614 * err and return -1.
2615 */
2616 static enum ref_transaction_error check_old_oid(struct ref_update *update,
2617 struct object_id *oid,
2618 struct strbuf *referent,
2619 struct strbuf *err)
2620 {
2621 if (update->flags & REF_LOG_ONLY ||
2622 !(update->flags & REF_HAVE_OLD))
2623 return 0;
2624
2625 if (oideq(oid, &update->old_oid)) {
2626 /*
2627 * Normally matching the expected old oid is enough. Either we
2628 * found the ref at the expected state, or we are creating and
2629 * expect the null oid (and likewise found nothing).
2630 *
2631 * But there is one exception for the null oid: if we found a
2632 * symref pointing to nothing we'll also get the null oid. In
2633 * regular recursive mode, that's good (we'll write to what the
2634 * symref points to, which doesn't exist). But in no-deref
2635 * mode, it means we'll clobber the symref, even though the
2636 * caller asked for this to be a creation event. So flag
2637 * that case to preserve the dangling symref.
2638 */
2639 if ((update->flags & REF_NO_DEREF) && referent->len &&
2640 is_null_oid(oid)) {
2641 strbuf_addf(err, "cannot lock ref '%s': "
2642 "dangling symref already exists",
2643 ref_update_original_update_refname(update));
2644 return REF_TRANSACTION_ERROR_CREATE_EXISTS;
2645 }
2646 return 0;
2647 }
2648
2649 if (is_null_oid(&update->old_oid)) {
2650 strbuf_addf(err, "cannot lock ref '%s': "
2651 "reference already exists",
2652 ref_update_original_update_refname(update));
2653 return REF_TRANSACTION_ERROR_CREATE_EXISTS;
2654 } else if (is_null_oid(oid)) {
2655 strbuf_addf(err, "cannot lock ref '%s': "
2656 "reference is missing but expected %s",
2657 ref_update_original_update_refname(update),
2658 oid_to_hex(&update->old_oid));
2659 return REF_TRANSACTION_ERROR_NONEXISTENT_REF;
2660 }
2661
2662 strbuf_addf(err, "cannot lock ref '%s': is at %s but expected %s",
2663 ref_update_original_update_refname(update), oid_to_hex(oid),
2664 oid_to_hex(&update->old_oid));
2665
2666 return REF_TRANSACTION_ERROR_INCORRECT_OLD_VALUE;
2667 }
2668
2669 struct files_transaction_backend_data {
2670 struct ref_transaction *packed_transaction;
2671 int packed_refs_locked;
2672 struct strmap ref_locks;
2673 };
2674
2675 /*
2676 * Prepare for carrying out update:
2677 * - Lock the reference referred to by update.
2678 * - Read the reference under lock.
2679 * - Check that its old OID value (if specified) is correct, and in
2680 * any case record it in update->lock->old_oid for later use when
2681 * writing the reflog.
2682 * - If it is a symref update without REF_NO_DEREF, split it up into a
2683 * REF_LOG_ONLY update of the symref and add a separate update for
2684 * the referent to transaction.
2685 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY
2686 * update of HEAD.
2687 */
2688 static enum ref_transaction_error lock_ref_for_update(struct files_ref_store *refs,
2689 struct ref_update *update,
2690 size_t update_idx,
2691 struct ref_transaction *transaction,
2692 const char *head_ref,
2693 struct string_list *refnames_to_check,
2694 struct strbuf *err)
2695 {
2696 struct strbuf referent = STRBUF_INIT;
2697 int mustexist = ref_update_expects_existing_old_ref(update);
2698 struct files_transaction_backend_data *backend_data;
2699 enum ref_transaction_error ret = 0;
2700 struct ref_lock *lock;
2701
2702 files_assert_main_repository(refs, "lock_ref_for_update");
2703
2704 backend_data = transaction->backend_data;
2705
2706 if ((update->flags & REF_HAVE_NEW) && ref_update_has_null_new_value(update))
2707 update->flags |= REF_DELETING;
2708
2709 if (head_ref) {
2710 ret = split_head_update(update, transaction, head_ref, err);
2711 if (ret)
2712 goto out;
2713 }
2714
2715 lock = strmap_get(&backend_data->ref_locks, update->refname);
2716 if (lock) {
2717 lock->count++;
2718 } else {
2719 ret = lock_raw_ref(refs, transaction, update_idx, mustexist,
2720 refnames_to_check, &lock, &referent, err);
2721 if (ret) {
2722 char *reason;
2723
2724 reason = strbuf_detach(err, NULL);
2725 strbuf_addf(err, "cannot lock ref '%s': %s",
2726 ref_update_original_update_refname(update), reason);
2727 free(reason);
2728 goto out;
2729 }
2730
2731 strmap_put(&backend_data->ref_locks, update->refname, lock);
2732 }
2733
2734 update->backend_data = lock;
2735
2736 if (update->flags & REF_LOG_VIA_SPLIT) {
2737 struct ref_lock *parent_lock;
2738
2739 if (!update->parent_update)
2740 BUG("split update without a parent");
2741
2742 parent_lock = update->parent_update->backend_data;
2743
2744 /*
2745 * Check that "HEAD" didn't racily change since we have looked
2746 * it up. If it did we must refuse to write the reflog entry.
2747 *
2748 * Note that this does not catch all races: if "HEAD" was
2749 * racily changed to point to one of the refs part of the
2750 * transaction then we would miss writing the split reflog
2751 * entry for "HEAD".
2752 */
2753 if (!(update->type & REF_ISSYMREF) ||
2754 strcmp(update->parent_update->refname, referent.buf)) {
2755 strbuf_addstr(err, "HEAD has been racily updated");
2756 ret = REF_TRANSACTION_ERROR_GENERIC;
2757 goto out;
2758 }
2759
2760 if (update->flags & REF_HAVE_OLD) {
2761 oidcpy(&lock->old_oid, &update->old_oid);
2762 } else {
2763 oidcpy(&lock->old_oid, &parent_lock->old_oid);
2764 }
2765 } else if (update->type & REF_ISSYMREF) {
2766 if (update->flags & REF_NO_DEREF) {
2767 /*
2768 * We won't be reading the referent as part of
2769 * the transaction, so we have to read it here
2770 * to record and possibly check old_oid:
2771 */
2772 if (!refs_resolve_ref_unsafe(&refs->base,
2773 referent.buf, 0,
2774 &lock->old_oid, NULL)) {
2775 if (update->flags & REF_HAVE_OLD) {
2776 strbuf_addf(err, "cannot lock ref '%s': "
2777 "error reading reference",
2778 ref_update_original_update_refname(update));
2779 ret = REF_TRANSACTION_ERROR_GENERIC;
2780 goto out;
2781 }
2782 }
2783
2784 if (update->old_target)
2785 ret = ref_update_check_old_target(referent.buf, update, err);
2786 else
2787 ret = check_old_oid(update, &lock->old_oid,
2788 &referent, err);
2789 if (ret)
2790 goto out;
2791 } else {
2792 /*
2793 * Create a new update for the reference this
2794 * symref is pointing at. Also, we will record
2795 * and verify old_oid for this update as part
2796 * of processing the split-off update, so we
2797 * don't have to do it here.
2798 */
2799 ret = split_symref_update(update, referent.buf,
2800 transaction, err);
2801 if (ret)
2802 goto out;
2803 }
2804 } else {
2805 struct ref_update *parent_update;
2806
2807 /*
2808 * Even if the ref is a regular ref, if `old_target` is set, we
2809 * fail with an error.
2810 */
2811 if (update->old_target) {
2812 strbuf_addf(err, _("cannot lock ref '%s': "
2813 "expected symref with target '%s': "
2814 "but is a regular ref"),
2815 ref_update_original_update_refname(update),
2816 update->old_target);
2817 ret = REF_TRANSACTION_ERROR_EXPECTED_SYMREF;
2818 goto out;
2819 } else {
2820 ret = check_old_oid(update, &lock->old_oid,
2821 &referent, err);
2822 if (ret) {
2823 goto out;
2824 }
2825 }
2826
2827 /*
2828 * If this update is happening indirectly because of a
2829 * symref update, record the old OID in the parent
2830 * update:
2831 */
2832 for (parent_update = update->parent_update;
2833 parent_update;
2834 parent_update = parent_update->parent_update) {
2835 struct ref_lock *parent_lock = parent_update->backend_data;
2836 oidcpy(&parent_lock->old_oid, &lock->old_oid);
2837 }
2838 }
2839
2840 if (update->new_target && !(update->flags & REF_LOG_ONLY)) {
2841 if (create_symref_lock(lock, update->new_target, err)) {
2842 ret = REF_TRANSACTION_ERROR_GENERIC;
2843 goto out;
2844 }
2845
2846 if (close_ref_gently(lock)) {
2847 strbuf_addf(err, "couldn't close '%s.lock'",
2848 update->refname);
2849 ret = REF_TRANSACTION_ERROR_GENERIC;
2850 goto out;
2851 }
2852
2853 /*
2854 * Once we have created the symref lock, the commit
2855 * phase of the transaction only needs to commit the lock.
2856 */
2857 update->flags |= REF_NEEDS_COMMIT;
2858 } else if ((update->flags & REF_HAVE_NEW) &&
2859 !(update->flags & REF_DELETING) &&
2860 !(update->flags & REF_LOG_ONLY)) {
2861 if (!(update->type & REF_ISSYMREF) &&
2862 oideq(&lock->old_oid, &update->new_oid)) {
2863 /*
2864 * The reference already has the desired
2865 * value, so we don't need to write it.
2866 */
2867 } else {
2868 ret = write_ref_to_lockfile(
2869 refs, lock, &update->new_oid,
2870 err);
2871 if (ret) {
2872 char *write_err = strbuf_detach(err, NULL);
2873
2874 /*
2875 * The lock was freed upon failure of
2876 * write_ref_to_lockfile():
2877 */
2878 update->backend_data = NULL;
2879 strbuf_addf(err,
2880 "cannot update ref '%s': %s",
2881 update->refname, write_err);
2882 free(write_err);
2883 goto out;
2884 } else {
2885 update->flags |= REF_NEEDS_COMMIT;
2886 }
2887 }
2888 }
2889 if (!(update->flags & REF_NEEDS_COMMIT)) {
2890 /*
2891 * We didn't call write_ref_to_lockfile(), so
2892 * the lockfile is still open. Close it to
2893 * free up the file descriptor:
2894 */
2895 if (close_ref_gently(lock)) {
2896 strbuf_addf(err, "couldn't close '%s.lock'",
2897 update->refname);
2898 ret = REF_TRANSACTION_ERROR_GENERIC;
2899 goto out;
2900 }
2901 }
2902
2903 out:
2904 strbuf_release(&referent);
2905 return ret;
2906 }
2907
2908 /*
2909 * Unlock any references in `transaction` that are still locked, and
2910 * mark the transaction closed.
2911 */
2912 static void files_transaction_cleanup(struct files_ref_store *refs,
2913 struct ref_transaction *transaction)
2914 {
2915 size_t i;
2916 struct files_transaction_backend_data *backend_data =
2917 transaction->backend_data;
2918 struct strbuf err = STRBUF_INIT;
2919
2920 for (i = 0; i < transaction->nr; i++) {
2921 struct ref_update *update = transaction->updates[i];
2922 struct ref_lock *lock = update->backend_data;
2923
2924 if (lock) {
2925 unlock_ref(lock);
2926 try_remove_empty_parents(refs, update->refname,
2927 REMOVE_EMPTY_PARENTS_REF);
2928 update->backend_data = NULL;
2929 }
2930 }
2931
2932 if (backend_data) {
2933 if (backend_data->packed_transaction &&
2934 ref_transaction_abort(backend_data->packed_transaction, &err)) {
2935 error("error aborting transaction: %s", err.buf);
2936 strbuf_release(&err);
2937 }
2938
2939 if (backend_data->packed_refs_locked)
2940 packed_refs_unlock(refs->packed_ref_store);
2941
2942 strmap_clear(&backend_data->ref_locks, 0);
2943
2944 free(backend_data);
2945 }
2946
2947 transaction->state = REF_TRANSACTION_CLOSED;
2948 }
2949
2950 static int files_transaction_prepare(struct ref_store *ref_store,
2951 struct ref_transaction *transaction,
2952 struct strbuf *err)
2953 {
2954 struct files_ref_store *refs =
2955 files_downcast(ref_store, REF_STORE_WRITE,
2956 "ref_transaction_prepare");
2957 size_t i;
2958 int ret = 0;
2959 struct string_list refnames_to_check = STRING_LIST_INIT_DUP;
2960 char *head_ref = NULL;
2961 int head_type;
2962 struct files_transaction_backend_data *backend_data;
2963 struct ref_transaction *packed_transaction = NULL;
2964
2965 assert(err);
2966
2967 if (transaction->flags & REF_TRANSACTION_FLAG_INITIAL)
2968 goto cleanup;
2969 if (!transaction->nr)
2970 goto cleanup;
2971
2972 CALLOC_ARRAY(backend_data, 1);
2973 strmap_init(&backend_data->ref_locks);
2974 transaction->backend_data = backend_data;
2975
2976 /*
2977 * Fail if any of the updates use REF_IS_PRUNING without REF_NO_DEREF.
2978 */
2979 for (i = 0; i < transaction->nr; i++) {
2980 struct ref_update *update = transaction->updates[i];
2981
2982 if ((update->flags & REF_IS_PRUNING) &&
2983 !(update->flags & REF_NO_DEREF))
2984 BUG("REF_IS_PRUNING set without REF_NO_DEREF");
2985 }
2986
2987 /*
2988 * Special hack: If a branch is updated directly and HEAD
2989 * points to it (may happen on the remote side of a push
2990 * for example) then logically the HEAD reflog should be
2991 * updated too.
2992 *
2993 * A generic solution would require reverse symref lookups,
2994 * but finding all symrefs pointing to a given branch would be
2995 * rather costly for this rare event (the direct update of a
2996 * branch) to be worth it. So let's cheat and check with HEAD
2997 * only, which should cover 99% of all usage scenarios (even
2998 * 100% of the default ones).
2999 *
3000 * So if HEAD is a symbolic reference, then record the name of
3001 * the reference that it points to. If we see an update of
3002 * head_ref within the transaction, then split_head_update()
3003 * arranges for the reflog of HEAD to be updated, too.
3004 */
3005 head_ref = refs_resolve_refdup(ref_store, "HEAD",
3006 RESOLVE_REF_NO_RECURSE,
3007 NULL, &head_type);
3008
3009 if (head_ref && !(head_type & REF_ISSYMREF)) {
3010 FREE_AND_NULL(head_ref);
3011 }
3012
3013 /*
3014 * Acquire all locks, verify old values if provided, check
3015 * that new values are valid, and write new values to the
3016 * lockfiles, ready to be activated. Only keep one lockfile
3017 * open at a time to avoid running out of file descriptors.
3018 * Note that lock_ref_for_update() might append more updates
3019 * to the transaction.
3020 */
3021 for (i = 0; i < transaction->nr; i++) {
3022 struct ref_update *update = transaction->updates[i];
3023
3024 ret = lock_ref_for_update(refs, update, i, transaction,
3025 head_ref, &refnames_to_check,
3026 err);
3027 if (ret) {
3028 if (ref_transaction_maybe_set_rejected(transaction, i,
3029 ret, err)) {
3030 ret = 0;
3031 continue;
3032 }
3033 goto cleanup;
3034 }
3035
3036 if (update->flags & REF_DELETING &&
3037 !(update->flags & REF_LOG_ONLY) &&
3038 !(update->flags & REF_IS_PRUNING)) {
3039 /*
3040 * This reference has to be deleted from
3041 * packed-refs if it exists there.
3042 */
3043 if (!packed_transaction) {
3044 packed_transaction = ref_store_transaction_begin(
3045 refs->packed_ref_store,
3046 transaction->flags, err);
3047 if (!packed_transaction) {
3048 ret = REF_TRANSACTION_ERROR_GENERIC;
3049 goto cleanup;
3050 }
3051
3052 backend_data->packed_transaction =
3053 packed_transaction;
3054 }
3055
3056 ref_transaction_add_update(
3057 packed_transaction, update->refname,
3058 REF_HAVE_NEW | REF_NO_DEREF,
3059 &update->new_oid, NULL, NULL,
3060 NULL, NULL, NULL, NULL);
3061 }
3062 }
3063
3064 /*
3065 * Verify that none of the loose reference that we're about to write
3066 * conflict with any existing packed references. Ideally, we'd do this
3067 * check after the packed-refs are locked so that the file cannot
3068 * change underneath our feet. But introducing such a lock now would
3069 * probably do more harm than good as users rely on there not being a
3070 * global lock with the "files" backend.
3071 *
3072 * Another alternative would be to do the check after the (optional)
3073 * lock, but that would extend the time we spend in the globally-locked
3074 * state.
3075 *
3076 * So instead, we accept the race for now.
3077 */
3078 if (refs_verify_refnames_available(refs->packed_ref_store, &refnames_to_check,
3079 &transaction->refnames, NULL, transaction,
3080 0, err)) {
3081 ret = REF_TRANSACTION_ERROR_NAME_CONFLICT;
3082 goto cleanup;
3083 }
3084
3085 if (packed_transaction) {
3086 if (packed_refs_lock(refs->packed_ref_store, 0, err)) {
3087 ret = REF_TRANSACTION_ERROR_GENERIC;
3088 goto cleanup;
3089 }
3090 backend_data->packed_refs_locked = 1;
3091
3092 if (is_packed_transaction_needed(refs->packed_ref_store,
3093 packed_transaction)) {
3094 ret = ref_transaction_prepare(packed_transaction, err);
3095 /*
3096 * A failure during the prepare step will abort
3097 * itself, but not free. Do that now, and disconnect
3098 * from the files_transaction so it does not try to
3099 * abort us when we hit the cleanup code below.
3100 */
3101 if (ret) {
3102 ref_transaction_free(packed_transaction);
3103 backend_data->packed_transaction = NULL;
3104 }
3105 } else {
3106 /*
3107 * We can skip rewriting the `packed-refs`
3108 * file. But we do need to leave it locked, so
3109 * that somebody else doesn't pack a reference
3110 * that we are trying to delete.
3111 *
3112 * We need to disconnect our transaction from
3113 * backend_data, since the abort (whether successful or
3114 * not) will free it.
3115 */
3116 backend_data->packed_transaction = NULL;
3117 if (ref_transaction_abort(packed_transaction, err)) {
3118 ret = REF_TRANSACTION_ERROR_GENERIC;
3119 goto cleanup;
3120 }
3121 }
3122 }
3123
3124 cleanup:
3125 free(head_ref);
3126 string_list_clear(&refnames_to_check, 1);
3127
3128 if (ret)
3129 files_transaction_cleanup(refs, transaction);
3130 else
3131 transaction->state = REF_TRANSACTION_PREPARED;
3132
3133 return ret;
3134 }
3135
3136 static int parse_and_write_reflog(struct files_ref_store *refs,
3137 struct ref_update *update,
3138 struct ref_lock *lock,
3139 struct strbuf *err)
3140 {
3141 struct object_id *old_oid = &lock->old_oid;
3142
3143 if (update->flags & REF_LOG_USE_PROVIDED_OIDS) {
3144 if (!(update->flags & REF_HAVE_OLD) ||
3145 !(update->flags & REF_HAVE_NEW) ||
3146 !(update->flags & REF_LOG_ONLY)) {
3147 strbuf_addf(err, _("trying to write reflog for '%s' "
3148 "with incomplete values"), update->refname);
3149 return REF_TRANSACTION_ERROR_GENERIC;
3150 }
3151
3152 old_oid = &update->old_oid;
3153 }
3154
3155 if (update->new_target) {
3156 /*
3157 * We want to get the resolved OID for the target, to ensure
3158 * that the correct value is added to the reflog.
3159 */
3160 if (!refs_resolve_ref_unsafe(&refs->base, update->new_target,
3161 RESOLVE_REF_READING,
3162 &update->new_oid, NULL)) {
3163 /*
3164 * TODO: currently we skip creating reflogs for dangling
3165 * symref updates. It would be nice to capture this as
3166 * zero oid updates however.
3167 */
3168 return 0;
3169 }
3170 }
3171
3172 if (files_log_ref_write(refs, lock->ref_name, old_oid,
3173 &update->new_oid, update->committer_info,
3174 update->msg, update->flags, err)) {
3175 char *old_msg = strbuf_detach(err, NULL);
3176
3177 strbuf_addf(err, "cannot update the ref '%s': %s",
3178 lock->ref_name, old_msg);
3179 free(old_msg);
3180 unlock_ref(lock);
3181 update->backend_data = NULL;
3182 return -1;
3183 }
3184
3185 return 0;
3186 }
3187
3188 static int ref_present(const struct reference *ref, void *cb_data)
3189 {
3190 struct string_list *affected_refnames = cb_data;
3191
3192 return string_list_has_string(affected_refnames, ref->name);
3193 }
3194
3195 static int files_transaction_finish_initial(struct files_ref_store *refs,
3196 struct ref_transaction *transaction,
3197 struct strbuf *err)
3198 {
3199 struct refs_for_each_ref_options opts = {
3200 .flags = REFS_FOR_EACH_INCLUDE_BROKEN,
3201 };
3202 size_t i;
3203 int ret = 0;
3204 struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
3205 struct string_list refnames_to_check = STRING_LIST_INIT_NODUP;
3206 struct ref_transaction *packed_transaction = NULL;
3207 struct ref_transaction *loose_transaction = NULL;
3208
3209 assert(err);
3210
3211 if (transaction->state != REF_TRANSACTION_PREPARED)
3212 BUG("commit called for transaction that is not prepared");
3213
3214 /*
3215 * It's really undefined to call this function in an active
3216 * repository or when there are existing references: we are
3217 * only locking and changing packed-refs, so (1) any
3218 * simultaneous processes might try to change a reference at
3219 * the same time we do, and (2) any existing loose versions of
3220 * the references that we are setting would have precedence
3221 * over our values. But some remote helpers create the remote
3222 * "HEAD" and "master" branches before calling this function,
3223 * so here we really only check that none of the references
3224 * that we are creating already exists.
3225 */
3226 if (refs_for_each_ref_ext(&refs->base, ref_present,
3227 &transaction->refnames, &opts))
3228 BUG("initial ref transaction called with existing refs");
3229
3230 packed_transaction = ref_store_transaction_begin(refs->packed_ref_store,
3231 transaction->flags, err);
3232 if (!packed_transaction) {
3233 ret = REF_TRANSACTION_ERROR_GENERIC;
3234 goto cleanup;
3235 }
3236
3237 for (i = 0; i < transaction->nr; i++) {
3238 struct ref_update *update = transaction->updates[i];
3239
3240 if (!(update->flags & REF_LOG_ONLY) &&
3241 (update->flags & REF_HAVE_OLD) &&
3242 !is_null_oid(&update->old_oid))
3243 BUG("initial ref transaction with old_sha1 set");
3244
3245 string_list_append(&refnames_to_check, update->refname);
3246
3247 /*
3248 * packed-refs don't support symbolic refs, root refs and reflogs,
3249 * so we have to queue these references via the loose transaction.
3250 */
3251 if (update->new_target ||
3252 is_root_ref(update->refname) ||
3253 (update->flags & REF_LOG_ONLY)) {
3254 if (!loose_transaction) {
3255 loose_transaction = ref_store_transaction_begin(&refs->base, 0, err);
3256 if (!loose_transaction) {
3257 ret = REF_TRANSACTION_ERROR_GENERIC;
3258 goto cleanup;
3259 }
3260 }
3261
3262 if (update->flags & REF_LOG_ONLY)
3263 ref_transaction_add_update(loose_transaction, update->refname,
3264 update->flags, &update->new_oid,
3265 &update->old_oid, &update->peeled,
3266 NULL, NULL,
3267 update->committer_info, update->msg);
3268 else
3269 ref_transaction_add_update(loose_transaction, update->refname,
3270 update->flags & ~REF_HAVE_OLD,
3271 update->new_target ? NULL : &update->new_oid, NULL,
3272 &update->peeled, update->new_target,
3273 NULL, update->committer_info,
3274 NULL);
3275 } else {
3276 ref_transaction_add_update(packed_transaction, update->refname,
3277 update->flags & ~REF_HAVE_OLD,
3278 &update->new_oid, &update->old_oid,
3279 &update->peeled, NULL, NULL,
3280 update->committer_info, NULL);
3281 }
3282 }
3283
3284 if (packed_refs_lock(refs->packed_ref_store, 0, err)) {
3285 ret = REF_TRANSACTION_ERROR_GENERIC;
3286 goto cleanup;
3287 }
3288
3289 if (refs_verify_refnames_available(&refs->base, &refnames_to_check,
3290 &affected_refnames, NULL, transaction,
3291 1, err)) {
3292 packed_refs_unlock(refs->packed_ref_store);
3293 ret = REF_TRANSACTION_ERROR_NAME_CONFLICT;
3294 goto cleanup;
3295 }
3296
3297 if (ref_transaction_commit(packed_transaction, err)) {
3298 ret = REF_TRANSACTION_ERROR_GENERIC;
3299 goto cleanup;
3300 }
3301 packed_refs_unlock(refs->packed_ref_store);
3302
3303 if (loose_transaction) {
3304 if (ref_transaction_prepare(loose_transaction, err) ||
3305 ref_transaction_commit(loose_transaction, err)) {
3306 ret = REF_TRANSACTION_ERROR_GENERIC;
3307 goto cleanup;
3308 }
3309 }
3310
3311 cleanup:
3312 if (loose_transaction)
3313 ref_transaction_free(loose_transaction);
3314 if (packed_transaction)
3315 ref_transaction_free(packed_transaction);
3316 transaction->state = REF_TRANSACTION_CLOSED;
3317 string_list_clear(&affected_refnames, 0);
3318 string_list_clear(&refnames_to_check, 0);
3319 return ret;
3320 }
3321
3322 static int files_transaction_finish(struct ref_store *ref_store,
3323 struct ref_transaction *transaction,
3324 struct strbuf *err)
3325 {
3326 struct files_ref_store *refs =
3327 files_downcast(ref_store, 0, "ref_transaction_finish");
3328 const struct files_ref_store_write_options *write_opts = files_ref_store_write_options(refs);
3329 size_t i;
3330 int ret = 0;
3331 struct strbuf sb = STRBUF_INIT;
3332 struct files_transaction_backend_data *backend_data;
3333 struct ref_transaction *packed_transaction;
3334
3335
3336 assert(err);
3337
3338 if (transaction->flags & REF_TRANSACTION_FLAG_INITIAL)
3339 return files_transaction_finish_initial(refs, transaction, err);
3340 if (!transaction->nr) {
3341 transaction->state = REF_TRANSACTION_CLOSED;
3342 return 0;
3343 }
3344
3345 backend_data = transaction->backend_data;
3346 packed_transaction = backend_data->packed_transaction;
3347
3348 /* Perform updates first so live commits remain referenced */
3349 for (i = 0; i < transaction->nr; i++) {
3350 struct ref_update *update = transaction->updates[i];
3351 struct ref_lock *lock = update->backend_data;
3352
3353 if (update->rejection_err)
3354 continue;
3355
3356 if (update->flags & REF_NEEDS_COMMIT ||
3357 update->flags & REF_LOG_ONLY) {
3358 if (parse_and_write_reflog(refs, update, lock, err)) {
3359 ret = REF_TRANSACTION_ERROR_GENERIC;
3360 goto cleanup;
3361 }
3362 }
3363
3364 /*
3365 * We try creating a symlink, if that succeeds we continue to the
3366 * next update. If not, we try and create a regular symref.
3367 */
3368 if (update->new_target && write_opts->prefer_symlink_refs)
3369 /*
3370 * By using the `NOT_CONSTANT()` trick, we can avoid
3371 * errors by `clang`'s `-Wunreachable` logic that would
3372 * report that the `continue` statement is not reachable
3373 * when `NO_SYMLINK_HEAD` is `#define`d.
3374 */
3375 if (NOT_CONSTANT(!create_ref_symlink(lock, update->new_target)))
3376 continue;
3377
3378 if (update->flags & REF_NEEDS_COMMIT) {
3379 clear_loose_ref_cache(refs);
3380 if (commit_ref(lock)) {
3381 strbuf_addf(err, "couldn't set '%s'", lock->ref_name);
3382 unlock_ref(lock);
3383 update->backend_data = NULL;
3384 ret = REF_TRANSACTION_ERROR_GENERIC;
3385 goto cleanup;
3386 }
3387 }
3388 }
3389
3390 /*
3391 * Now that updates are safely completed, we can perform
3392 * deletes. First delete the reflogs of any references that
3393 * will be deleted, since (in the unexpected event of an
3394 * error) leaving a reference without a reflog is less bad
3395 * than leaving a reflog without a reference (the latter is a
3396 * mildly invalid repository state):
3397 */
3398 for (i = 0; i < transaction->nr; i++) {
3399 struct ref_update *update = transaction->updates[i];
3400
3401 if (update->rejection_err)
3402 continue;
3403
3404 if (update->flags & REF_DELETING &&
3405 !(update->flags & REF_LOG_ONLY) &&
3406 !(update->flags & REF_IS_PRUNING)) {
3407 strbuf_reset(&sb);
3408 files_reflog_path(refs, &sb, update->refname);
3409 if (!unlink_or_warn(sb.buf))
3410 try_remove_empty_parents(refs, update->refname,
3411 REMOVE_EMPTY_PARENTS_REFLOG);
3412 }
3413 }
3414
3415 /*
3416 * Perform deletes now that updates are safely completed.
3417 *
3418 * First delete any packed versions of the references, while
3419 * retaining the packed-refs lock:
3420 */
3421 if (packed_transaction) {
3422 ret = ref_transaction_commit(packed_transaction, err);
3423 ref_transaction_free(packed_transaction);
3424 packed_transaction = NULL;
3425 backend_data->packed_transaction = NULL;
3426 if (ret)
3427 goto cleanup;
3428 }
3429
3430 /* Now delete the loose versions of the references: */
3431 for (i = 0; i < transaction->nr; i++) {
3432 struct ref_update *update = transaction->updates[i];
3433 struct ref_lock *lock = update->backend_data;
3434
3435 if (update->rejection_err)
3436 continue;
3437
3438 if (update->flags & REF_DELETING &&
3439 !(update->flags & REF_LOG_ONLY)) {
3440 update->flags |= REF_DELETED_RMDIR;
3441 if (!(update->type & REF_ISPACKED) ||
3442 update->type & REF_ISSYMREF) {
3443 /* It is a loose reference. */
3444 strbuf_reset(&sb);
3445 files_ref_path(refs, &sb, lock->ref_name);
3446 if (unlink_or_msg(sb.buf, err)) {
3447 ret = REF_TRANSACTION_ERROR_GENERIC;
3448 goto cleanup;
3449 }
3450 }
3451 }
3452 }
3453
3454 clear_loose_ref_cache(refs);
3455
3456 cleanup:
3457 files_transaction_cleanup(refs, transaction);
3458
3459 for (i = 0; i < transaction->nr; i++) {
3460 struct ref_update *update = transaction->updates[i];
3461
3462 if (update->flags & REF_DELETED_RMDIR) {
3463 /*
3464 * The reference was deleted. Delete any
3465 * empty parent directories. (Note that this
3466 * can only work because we have already
3467 * removed the lockfile.)
3468 */
3469 try_remove_empty_parents(refs, update->refname,
3470 REMOVE_EMPTY_PARENTS_REF);
3471 }
3472 }
3473
3474 strbuf_release(&sb);
3475 return ret;
3476 }
3477
3478 static int files_transaction_abort(struct ref_store *ref_store,
3479 struct ref_transaction *transaction,
3480 struct strbuf *err UNUSED)
3481 {
3482 struct files_ref_store *refs =
3483 files_downcast(ref_store, 0, "ref_transaction_abort");
3484
3485 files_transaction_cleanup(refs, transaction);
3486 return 0;
3487 }
3488
3489 struct expire_reflog_cb {
3490 reflog_expiry_should_prune_fn *should_prune_fn;
3491 void *policy_cb;
3492 FILE *newlog;
3493 struct object_id last_kept_oid;
3494 unsigned int rewrite:1,
3495 dry_run:1;
3496 };
3497
3498 static int expire_reflog_ent(const char *refname UNUSED,
3499 struct object_id *ooid, struct object_id *noid,
3500 const char *email, timestamp_t timestamp, int tz,
3501 const char *message, void *cb_data)
3502 {
3503 struct expire_reflog_cb *cb = cb_data;
3504 reflog_expiry_should_prune_fn *fn = cb->should_prune_fn;
3505
3506 if (cb->rewrite)
3507 ooid = &cb->last_kept_oid;
3508
3509 if (fn(ooid, noid, email, timestamp, tz, message, cb->policy_cb))
3510 return 0;
3511
3512 if (cb->dry_run)
3513 return 0; /* --dry-run */
3514
3515 fprintf(cb->newlog, "%s %s %s %"PRItime" %+05d\t%s", oid_to_hex(ooid),
3516 oid_to_hex(noid), email, timestamp, tz, message);
3517 oidcpy(&cb->last_kept_oid, noid);
3518
3519 return 0;
3520 }
3521
3522 static int files_reflog_expire(struct ref_store *ref_store,
3523 const char *refname,
3524 unsigned int expire_flags,
3525 reflog_expiry_prepare_fn prepare_fn,
3526 reflog_expiry_should_prune_fn should_prune_fn,
3527 reflog_expiry_cleanup_fn cleanup_fn,
3528 void *policy_cb_data)
3529 {
3530 struct files_ref_store *refs =
3531 files_downcast(ref_store, REF_STORE_WRITE, "reflog_expire");
3532 struct lock_file reflog_lock = LOCK_INIT;
3533 struct expire_reflog_cb cb;
3534 struct ref_lock *lock;
3535 struct strbuf log_file_sb = STRBUF_INIT;
3536 char *log_file;
3537 int status = 0;
3538 struct strbuf err = STRBUF_INIT;
3539 const struct object_id *oid;
3540
3541 memset(&cb, 0, sizeof(cb));
3542 cb.rewrite = !!(expire_flags & EXPIRE_REFLOGS_REWRITE);
3543 cb.dry_run = !!(expire_flags & EXPIRE_REFLOGS_DRY_RUN);
3544 cb.policy_cb = policy_cb_data;
3545 cb.should_prune_fn = should_prune_fn;
3546
3547 /*
3548 * The reflog file is locked by holding the lock on the
3549 * reference itself, plus we might need to update the
3550 * reference if --updateref was specified:
3551 */
3552 lock = lock_ref_oid_basic(refs, refname, &err);
3553 if (!lock) {
3554 error("cannot lock ref '%s': %s", refname, err.buf);
3555 strbuf_release(&err);
3556 return -1;
3557 }
3558 oid = &lock->old_oid;
3559
3560 /*
3561 * When refs are deleted, their reflog is deleted before the
3562 * ref itself is deleted. This is because there is no separate
3563 * lock for reflog; instead we take a lock on the ref with
3564 * lock_ref_oid_basic().
3565 *
3566 * If a race happens and the reflog doesn't exist after we've
3567 * acquired the lock that's OK. We've got nothing more to do;
3568 * We were asked to delete the reflog, but someone else
3569 * deleted it! The caller doesn't care that we deleted it,
3570 * just that it is deleted. So we can return successfully.
3571 */
3572 if (!refs_reflog_exists(ref_store, refname)) {
3573 unlock_ref(lock);
3574 return 0;
3575 }
3576
3577 files_reflog_path(refs, &log_file_sb, refname);
3578 log_file = strbuf_detach(&log_file_sb, NULL);
3579 if (!cb.dry_run) {
3580 /*
3581 * Even though holding $GIT_DIR/logs/$reflog.lock has
3582 * no locking implications, we use the lock_file
3583 * machinery here anyway because it does a lot of the
3584 * work we need, including cleaning up if the program
3585 * exits unexpectedly.
3586 */
3587 if (repo_hold_lock_file_for_update(ref_store->repo,
3588 &reflog_lock, log_file,
3589 0) < 0) {
3590 struct strbuf err = STRBUF_INIT;
3591 unable_to_lock_message(log_file, errno, &err);
3592 error("%s", err.buf);
3593 strbuf_release(&err);
3594 goto failure;
3595 }
3596 cb.newlog = fdopen_lock_file(&reflog_lock, "w");
3597 if (!cb.newlog) {
3598 error("cannot fdopen %s (%s)",
3599 get_lock_file_path(&reflog_lock), strerror(errno));
3600 goto failure;
3601 }
3602 }
3603
3604 (*prepare_fn)(refname, oid, cb.policy_cb);
3605 refs_for_each_reflog_ent(ref_store, refname, expire_reflog_ent, &cb);
3606 (*cleanup_fn)(cb.policy_cb);
3607
3608 if (!cb.dry_run) {
3609 /*
3610 * It doesn't make sense to adjust a reference pointed
3611 * to by a symbolic ref based on expiring entries in
3612 * the symbolic reference's reflog. Nor can we update
3613 * a reference if there are no remaining reflog
3614 * entries.
3615 */
3616 int update = 0;
3617
3618 if ((expire_flags & EXPIRE_REFLOGS_UPDATE_REF) &&
3619 !is_null_oid(&cb.last_kept_oid)) {
3620 int type;
3621 const char *ref;
3622
3623 ref = refs_resolve_ref_unsafe(&refs->base, refname,
3624 RESOLVE_REF_NO_RECURSE,
3625 NULL, &type);
3626 update = !!(ref && !(type & REF_ISSYMREF));
3627 }
3628
3629 if (close_lock_file_gently(&reflog_lock)) {
3630 status |= error("couldn't write %s: %s", log_file,
3631 strerror(errno));
3632 rollback_lock_file(&reflog_lock);
3633 } else if (update &&
3634 (write_in_full(get_lock_file_fd(&lock->lk),
3635 oid_to_hex(&cb.last_kept_oid), refs->base.repo->hash_algo->hexsz) < 0 ||
3636 write_str_in_full(get_lock_file_fd(&lock->lk), "\n") < 0 ||
3637 close_ref_gently(lock) < 0)) {
3638 status |= error("couldn't write %s",
3639 get_lock_file_path(&lock->lk));
3640 rollback_lock_file(&reflog_lock);
3641 } else if (commit_lock_file(&reflog_lock)) {
3642 status |= error("unable to write reflog '%s' (%s)",
3643 log_file, strerror(errno));
3644 } else if (update && commit_ref(lock)) {
3645 status |= error("couldn't set %s", lock->ref_name);
3646 }
3647 }
3648 free(log_file);
3649 unlock_ref(lock);
3650 return status;
3651
3652 failure:
3653 rollback_lock_file(&reflog_lock);
3654 free(log_file);
3655 unlock_ref(lock);
3656 return -1;
3657 }
3658
3659 static int files_ref_store_create_on_disk(struct ref_store *ref_store,
3660 int flags,
3661 struct strbuf *err UNUSED)
3662 {
3663 struct files_ref_store *refs =
3664 files_downcast(ref_store, REF_STORE_WRITE, "create");
3665 struct strbuf sb = STRBUF_INIT;
3666
3667 /*
3668 * We need to create a "refs" dir in any case so that older versions of
3669 * Git can tell that this is a repository. This serves two main purposes:
3670 *
3671 * - Clients will know to stop walking the parent-directory chain when
3672 * detecting the Git repository. Otherwise they may end up detecting
3673 * a Git repository in a parent directory instead.
3674 *
3675 * - Instead of failing to detect a repository with unknown reference
3676 * format altogether, old clients will print an error saying that
3677 * they do not understand the reference format extension.
3678 */
3679 strbuf_addf(&sb, "%s/refs", ref_store->gitdir);
3680 safe_create_dir(refs->base.repo, sb.buf, 1);
3681 adjust_shared_perm(refs->base.repo, sb.buf);
3682
3683 /*
3684 * There is no need to create directories for common refs when creating
3685 * a worktree ref store.
3686 */
3687 if (!(flags & REF_STORE_CREATE_ON_DISK_IS_WORKTREE)) {
3688 /*
3689 * Create .git/refs/{heads,tags}
3690 */
3691 strbuf_reset(&sb);
3692 files_ref_path(refs, &sb, "refs/heads");
3693 safe_create_dir(refs->base.repo, sb.buf, 1);
3694
3695 strbuf_reset(&sb);
3696 files_ref_path(refs, &sb, "refs/tags");
3697 safe_create_dir(refs->base.repo, sb.buf, 1);
3698 }
3699
3700 strbuf_release(&sb);
3701 return 0;
3702 }
3703
3704 struct remove_one_root_ref_data {
3705 const char *gitdir;
3706 struct strbuf *err;
3707 };
3708
3709 static int remove_one_root_ref(const char *refname,
3710 void *cb_data)
3711 {
3712 struct remove_one_root_ref_data *data = cb_data;
3713 struct strbuf buf = STRBUF_INIT;
3714 int ret = 0;
3715
3716 strbuf_addf(&buf, "%s/%s", data->gitdir, refname);
3717
3718 ret = unlink(buf.buf);
3719 if (ret < 0)
3720 strbuf_addf(data->err, "could not delete %s: %s\n",
3721 refname, strerror(errno));
3722
3723 strbuf_release(&buf);
3724 return ret;
3725 }
3726
3727 static int files_ref_store_remove_on_disk(struct ref_store *ref_store,
3728 struct strbuf *err)
3729 {
3730 struct files_ref_store *refs =
3731 files_downcast(ref_store, REF_STORE_WRITE, "remove");
3732 struct remove_one_root_ref_data data = {
3733 .gitdir = refs->base.gitdir,
3734 .err = err,
3735 };
3736 struct strbuf sb = STRBUF_INIT;
3737 int ret = 0;
3738
3739 strbuf_addf(&sb, "%s/refs", refs->base.gitdir);
3740 if (remove_dir_recursively(&sb, 0) < 0) {
3741 strbuf_addf(err, "could not delete refs: %s",
3742 strerror(errno));
3743 ret = -1;
3744 }
3745 strbuf_reset(&sb);
3746
3747 strbuf_addf(&sb, "%s/logs", refs->base.gitdir);
3748 if (remove_dir_recursively(&sb, 0) < 0) {
3749 strbuf_addf(err, "could not delete logs: %s",
3750 strerror(errno));
3751 ret = -1;
3752 }
3753 strbuf_reset(&sb);
3754
3755 if (for_each_root_ref(refs, remove_one_root_ref, &data) < 0)
3756 ret = -1;
3757
3758 /*
3759 * Directly access the cleanup functions for packed-refs as the generic function
3760 * would try to clear stubs which isn't required for the files backend.
3761 */
3762 if (refs->packed_ref_store->be->remove_on_disk(refs->packed_ref_store, err) < 0)
3763 ret = -1;
3764
3765 strbuf_release(&sb);
3766 return ret;
3767 }
3768
3769 /*
3770 * For refs and reflogs, they share a unified interface when scanning
3771 * the whole directory. This function is used as the callback for each
3772 * regular file or symlink in the directory.
3773 */
3774 typedef int (*files_fsck_refs_fn)(struct ref_store *ref_store,
3775 struct fsck_options *o,
3776 const char *refname,
3777 const char *path,
3778 int mode);
3779
3780 static int files_fsck_symref_target(struct ref_store *ref_store,
3781 struct fsck_options *o,
3782 struct fsck_ref_report *report,
3783 const char *refname,
3784 struct strbuf *referent,
3785 unsigned int symbolic_link)
3786 {
3787 char orig_last_byte;
3788 size_t orig_len;
3789 int ret = 0;
3790
3791 orig_len = referent->len;
3792 orig_last_byte = referent->buf[orig_len - 1];
3793
3794 if (!symbolic_link) {
3795 strbuf_rtrim(referent);
3796
3797 if (referent->len == orig_len ||
3798 (referent->len < orig_len && orig_last_byte != '\n')) {
3799 ret |= fsck_report_ref(o, report,
3800 FSCK_MSG_REF_MISSING_NEWLINE,
3801 "misses LF at the end");
3802 }
3803
3804 if (referent->len != orig_len && referent->len != orig_len - 1) {
3805 ret |= fsck_report_ref(o, report,
3806 FSCK_MSG_TRAILING_REF_CONTENT,
3807 "has trailing whitespaces or newlines");
3808 }
3809 }
3810
3811 ret |= refs_fsck_symref(ref_store, o, report, refname, referent->buf);
3812
3813 return ret ? -1 : 0;
3814 }
3815
3816 static int files_fsck_refs_content(struct ref_store *ref_store,
3817 struct fsck_options *o,
3818 const char *target_name,
3819 const char *path,
3820 int mode)
3821 {
3822 struct strbuf ref_content = STRBUF_INIT;
3823 struct strbuf abs_gitdir = STRBUF_INIT;
3824 struct strbuf referent = STRBUF_INIT;
3825 struct fsck_ref_report report = { 0 };
3826 const char *trailing = NULL;
3827 unsigned int type = 0;
3828 int failure_errno = 0;
3829 struct object_id oid;
3830 int ret = 0;
3831
3832 report.path = target_name;
3833
3834 if (S_ISLNK(mode)) {
3835 const char *relative_referent_path = NULL;
3836
3837 ret = fsck_report_ref(o, &report,
3838 FSCK_MSG_SYMLINK_REF,
3839 "use deprecated symbolic link for symref");
3840
3841 strbuf_add_absolute_path(&abs_gitdir, ref_store->repo->gitdir);
3842 strbuf_normalize_path(&abs_gitdir);
3843 if (!is_dir_sep(abs_gitdir.buf[abs_gitdir.len - 1]))
3844 strbuf_addch(&abs_gitdir, '/');
3845
3846 strbuf_add_real_path(&ref_content, path);
3847 skip_prefix(ref_content.buf, abs_gitdir.buf,
3848 &relative_referent_path);
3849
3850 if (relative_referent_path)
3851 strbuf_addstr(&referent, relative_referent_path);
3852 else
3853 strbuf_addbuf(&referent, &ref_content);
3854
3855 ret |= files_fsck_symref_target(ref_store, o, &report,
3856 target_name, &referent, 1);
3857 goto cleanup;
3858 }
3859
3860 if (strbuf_read_file(&ref_content, path, 0) < 0) {
3861 /*
3862 * Ref file could be removed by another concurrent process. We should
3863 * ignore this error and continue to the next ref.
3864 */
3865 if (errno == ENOENT)
3866 goto cleanup;
3867
3868 ret = error_errno(_("cannot read ref file '%s'"), path);
3869 goto cleanup;
3870 }
3871
3872 if (parse_loose_ref_contents(ref_store->repo->hash_algo,
3873 ref_content.buf, &oid, &referent,
3874 &type, &trailing, &failure_errno)) {
3875 strbuf_rtrim(&ref_content);
3876 ret = fsck_report_ref(o, &report,
3877 FSCK_MSG_BAD_REF_CONTENT,
3878 "%s", ref_content.buf);
3879 goto cleanup;
3880 }
3881
3882 if (!(type & REF_ISSYMREF)) {
3883 if (!*trailing) {
3884 ret = fsck_report_ref(o, &report,
3885 FSCK_MSG_REF_MISSING_NEWLINE,
3886 "misses LF at the end");
3887 goto cleanup;
3888 }
3889 if (*trailing != '\n' || *(trailing + 1)) {
3890 ret = fsck_report_ref(o, &report,
3891 FSCK_MSG_TRAILING_REF_CONTENT,
3892 "has trailing garbage: '%s'", trailing);
3893 goto cleanup;
3894 }
3895
3896 ret = refs_fsck_ref(ref_store, o, &report, target_name, &oid);
3897 } else {
3898 ret = files_fsck_symref_target(ref_store, o, &report,
3899 target_name, &referent, 0);
3900 goto cleanup;
3901 }
3902
3903 cleanup:
3904 strbuf_release(&ref_content);
3905 strbuf_release(&referent);
3906 strbuf_release(&abs_gitdir);
3907 return ret;
3908 }
3909
3910 static int files_fsck_refs_name(struct ref_store *ref_store UNUSED,
3911 struct fsck_options *o,
3912 const char *refname,
3913 const char *path UNUSED,
3914 int mode UNUSED)
3915 {
3916 struct strbuf sb = STRBUF_INIT;
3917 int ret = 0;
3918
3919 if (is_root_ref(refname))
3920 goto cleanup;
3921
3922 if (check_refname_format(refname, 0)) {
3923 struct fsck_ref_report report = { 0 };
3924
3925 report.path = refname;
3926 ret = fsck_report_ref(o, &report,
3927 FSCK_MSG_BAD_REF_NAME,
3928 "invalid refname format");
3929 }
3930
3931 cleanup:
3932 strbuf_release(&sb);
3933 return ret;
3934 }
3935
3936 static const files_fsck_refs_fn fsck_refs_fn[]= {
3937 files_fsck_refs_name,
3938 files_fsck_refs_content,
3939 NULL,
3940 };
3941
3942 static int files_fsck_ref(struct ref_store *ref_store,
3943 struct fsck_options *o,
3944 const char *refname,
3945 const char *path,
3946 int mode)
3947 {
3948 int ret = 0;
3949
3950 if (o->verbose)
3951 fprintf_ln(stderr, "Checking %s", refname);
3952
3953 if (!S_ISREG(mode) && !S_ISLNK(mode)) {
3954 struct fsck_ref_report report = { .path = refname };
3955
3956 if (fsck_report_ref(o, &report,
3957 FSCK_MSG_BAD_REF_FILETYPE,
3958 "unexpected file type"))
3959 ret = -1;
3960 goto out;
3961 }
3962
3963 for (size_t i = 0; fsck_refs_fn[i]; i++)
3964 if (fsck_refs_fn[i](ref_store, o, refname, path, mode))
3965 ret = -1;
3966
3967 out:
3968 return ret;
3969 }
3970
3971 static int files_fsck_refs_dir(struct ref_store *ref_store,
3972 struct fsck_options *o,
3973 struct worktree *wt)
3974 {
3975 struct strbuf refname = STRBUF_INIT;
3976 struct strbuf sb = STRBUF_INIT;
3977 struct dir_iterator *iter;
3978 const char *filename;
3979 int iter_status;
3980 int ret = 0;
3981
3982 strbuf_addf(&sb, "%s/refs", ref_store->gitdir);
3983
3984 iter = dir_iterator_begin(sb.buf, 0);
3985 if (!iter) {
3986 if (errno == ENOENT && !is_main_worktree(wt))
3987 goto out;
3988
3989 ret = error_errno(_("cannot open directory %s"), sb.buf);
3990 goto out;
3991 }
3992
3993 while ((iter_status = dir_iterator_advance(iter)) == ITER_OK) {
3994 if (S_ISDIR(iter->st.st_mode))
3995 continue;
3996
3997 strbuf_reset(&refname);
3998 if (!is_main_worktree(wt))
3999 strbuf_addf(&refname, "worktrees/%s/", wt->id);
4000 strbuf_addf(&refname, "refs/%s", iter->relative_path);
4001
4002 filename = basename((char *) iter->path.buf);
4003
4004 /*
4005 * Ignore the files ending with ".lock" as they may be lock files.
4006 * However, do not skip invalid refnames with '.lock' suffix.
4007 */
4008 if (filename[0] != '.' && ends_with(filename, ".lock"))
4009 continue;
4010
4011 if (files_fsck_ref(ref_store, o, refname.buf,
4012 iter->path.buf, iter->st.st_mode) < 0)
4013 ret = -1;
4014 }
4015
4016 if (iter_status != ITER_DONE)
4017 ret = error(_("failed to iterate over '%s'"), sb.buf);
4018
4019 out:
4020 dir_iterator_free(iter);
4021 strbuf_release(&sb);
4022 strbuf_release(&refname);
4023 return ret;
4024 }
4025
4026 struct files_fsck_root_ref_data {
4027 struct files_ref_store *refs;
4028 struct fsck_options *o;
4029 struct worktree *wt;
4030 struct strbuf refname;
4031 struct strbuf path;
4032 };
4033
4034 static int files_fsck_root_ref(const char *refname, void *cb_data)
4035 {
4036 struct files_fsck_root_ref_data *data = cb_data;
4037 struct stat st;
4038
4039 strbuf_reset(&data->refname);
4040 if (!is_main_worktree(data->wt))
4041 strbuf_addf(&data->refname, "worktrees/%s/", data->wt->id);
4042 strbuf_addstr(&data->refname, refname);
4043
4044 strbuf_reset(&data->path);
4045 strbuf_addf(&data->path, "%s/%s", data->refs->gitcommondir, data->refname.buf);
4046
4047 if (stat(data->path.buf, &st)) {
4048 if (errno == ENOENT)
4049 return 0;
4050 return error_errno("failed to read ref: '%s'", data->path.buf);
4051 }
4052
4053 return files_fsck_ref(&data->refs->base, data->o, data->refname.buf,
4054 data->path.buf, st.st_mode);
4055 }
4056
4057 static int files_fsck(struct ref_store *ref_store,
4058 struct fsck_options *o,
4059 struct worktree *wt)
4060 {
4061 struct files_ref_store *refs =
4062 files_downcast(ref_store, REF_STORE_READ, "fsck");
4063 struct files_fsck_root_ref_data data = {
4064 .refs = refs,
4065 .o = o,
4066 .wt = wt,
4067 .refname = STRBUF_INIT,
4068 .path = STRBUF_INIT,
4069 };
4070 int ret = 0;
4071
4072 if (files_fsck_refs_dir(ref_store, o, wt) < 0)
4073 ret = -1;
4074
4075 if (for_each_root_ref(refs, files_fsck_root_ref, &data) < 0)
4076 ret = -1;
4077
4078 if (refs->packed_ref_store->be->fsck(refs->packed_ref_store, o, wt) < 0)
4079 ret = -1;
4080
4081 strbuf_release(&data.refname);
4082 strbuf_release(&data.path);
4083 return ret;
4084 }
4085
4086 struct ref_storage_be refs_be_files = {
4087 .name = "files",
4088 .init = files_ref_store_init,
4089 .release = files_ref_store_release,
4090 .create_on_disk = files_ref_store_create_on_disk,
4091 .remove_on_disk = files_ref_store_remove_on_disk,
4092
4093 .transaction_prepare = files_transaction_prepare,
4094 .transaction_finish = files_transaction_finish,
4095 .transaction_abort = files_transaction_abort,
4096
4097 .optimize = files_optimize,
4098 .optimize_required = files_optimize_required,
4099 .rename_ref = files_rename_ref,
4100 .copy_ref = files_copy_ref,
4101
4102 .iterator_begin = files_ref_iterator_begin,
4103 .read_raw_ref = files_read_raw_ref,
4104 .read_symbolic_ref = files_read_symbolic_ref,
4105
4106 .reflog_iterator_begin = files_reflog_iterator_begin,
4107 .for_each_reflog_ent = files_for_each_reflog_ent,
4108 .for_each_reflog_ent_reverse = files_for_each_reflog_ent_reverse,
4109 .reflog_exists = files_reflog_exists,
4110 .create_reflog = files_create_reflog,
4111 .delete_reflog = files_delete_reflog,
4112 .reflog_expire = files_reflog_expire,
4113
4114 .fsck = files_fsck,
4115 };