interplane.Get Omega
Read in your language

git

[Ported from github.com/git/git] Sync with Git 2.56.1

Brought by drakestapleton

branch master Branches Tags History

git / refs / files-backend.c

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