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