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