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