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