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