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