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