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