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