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