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