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