refs_ref_iterator_begin(): new function
[git/git.git] / refs / files-backend.c
CommitLineData
7bd9bcf3
MH
1#include "../cache.h"
2#include "../refs.h"
3#include "refs-internal.h"
3bc581b9 4#include "../iterator.h"
2880d16f 5#include "../dir-iterator.h"
7bd9bcf3
MH
6#include "../lockfile.h"
7#include "../object.h"
8#include "../dir.h"
9
10struct ref_lock {
11 char *ref_name;
7bd9bcf3
MH
12 struct lock_file *lk;
13 struct object_id old_oid;
14};
15
16struct ref_entry;
17
18/*
19 * Information used (along with the information in ref_entry) to
20 * describe a single cached reference. This data structure only
21 * occurs embedded in a union in struct ref_entry, and only when
22 * (ref_entry->flag & REF_DIR) is zero.
23 */
24struct ref_value {
25 /*
26 * The name of the object to which this reference resolves
27 * (which may be a tag object). If REF_ISBROKEN, this is
28 * null. If REF_ISSYMREF, then this is the name of the object
29 * referred to by the last reference in the symlink chain.
30 */
31 struct object_id oid;
32
33 /*
34 * If REF_KNOWS_PEELED, then this field holds the peeled value
35 * of this reference, or null if the reference is known not to
36 * be peelable. See the documentation for peel_ref() for an
37 * exact definition of "peelable".
38 */
39 struct object_id peeled;
40};
41
65a0a8e5 42struct files_ref_store;
7bd9bcf3
MH
43
44/*
45 * Information used (along with the information in ref_entry) to
46 * describe a level in the hierarchy of references. This data
47 * structure only occurs embedded in a union in struct ref_entry, and
48 * only when (ref_entry.flag & REF_DIR) is set. In that case,
49 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references
50 * in the directory have already been read:
51 *
52 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose
53 * or packed references, already read.
54 *
55 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose
56 * references that hasn't been read yet (nor has any of its
57 * subdirectories).
58 *
59 * Entries within a directory are stored within a growable array of
60 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i <
61 * sorted are sorted by their component name in strcmp() order and the
62 * remaining entries are unsorted.
63 *
64 * Loose references are read lazily, one directory at a time. When a
65 * directory of loose references is read, then all of the references
66 * in that directory are stored, and REF_INCOMPLETE stubs are created
67 * for any subdirectories, but the subdirectories themselves are not
68 * read. The reading is triggered by get_ref_dir().
69 */
70struct ref_dir {
71 int nr, alloc;
72
73 /*
74 * Entries with index 0 <= i < sorted are sorted by name. New
75 * entries are appended to the list unsorted, and are sorted
76 * only when required; thus we avoid the need to sort the list
77 * after the addition of every reference.
78 */
79 int sorted;
80
65a0a8e5
MH
81 /* A pointer to the files_ref_store that contains this ref_dir. */
82 struct files_ref_store *ref_store;
7bd9bcf3
MH
83
84 struct ref_entry **entries;
85};
86
87/*
88 * Bit values for ref_entry::flag. REF_ISSYMREF=0x01,
89 * REF_ISPACKED=0x02, REF_ISBROKEN=0x04 and REF_BAD_NAME=0x08 are
90 * public values; see refs.h.
91 */
92
93/*
94 * The field ref_entry->u.value.peeled of this value entry contains
95 * the correct peeled value for the reference, which might be
96 * null_sha1 if the reference is not a tag or if it is broken.
97 */
98#define REF_KNOWS_PEELED 0x10
99
100/* ref_entry represents a directory of references */
101#define REF_DIR 0x20
102
103/*
104 * Entry has not yet been read from disk (used only for REF_DIR
105 * entries representing loose references)
106 */
107#define REF_INCOMPLETE 0x40
108
109/*
110 * A ref_entry represents either a reference or a "subdirectory" of
111 * references.
112 *
113 * Each directory in the reference namespace is represented by a
114 * ref_entry with (flags & REF_DIR) set and containing a subdir member
115 * that holds the entries in that directory that have been read so
116 * far. If (flags & REF_INCOMPLETE) is set, then the directory and
117 * its subdirectories haven't been read yet. REF_INCOMPLETE is only
118 * used for loose reference directories.
119 *
120 * References are represented by a ref_entry with (flags & REF_DIR)
121 * unset and a value member that describes the reference's value. The
122 * flag member is at the ref_entry level, but it is also needed to
123 * interpret the contents of the value field (in other words, a
124 * ref_value object is not very much use without the enclosing
125 * ref_entry).
126 *
127 * Reference names cannot end with slash and directories' names are
128 * always stored with a trailing slash (except for the top-level
129 * directory, which is always denoted by ""). This has two nice
130 * consequences: (1) when the entries in each subdir are sorted
131 * lexicographically by name (as they usually are), the references in
132 * a whole tree can be generated in lexicographic order by traversing
133 * the tree in left-to-right, depth-first order; (2) the names of
134 * references and subdirectories cannot conflict, and therefore the
135 * presence of an empty subdirectory does not block the creation of a
136 * similarly-named reference. (The fact that reference names with the
137 * same leading components can conflict *with each other* is a
138 * separate issue that is regulated by verify_refname_available().)
139 *
140 * Please note that the name field contains the fully-qualified
141 * reference (or subdirectory) name. Space could be saved by only
142 * storing the relative names. But that would require the full names
143 * to be generated on the fly when iterating in do_for_each_ref(), and
144 * would break callback functions, who have always been able to assume
145 * that the name strings that they are passed will not be freed during
146 * the iteration.
147 */
148struct ref_entry {
149 unsigned char flag; /* ISSYMREF? ISPACKED? */
150 union {
151 struct ref_value value; /* if not (flags&REF_DIR) */
152 struct ref_dir subdir; /* if (flags&REF_DIR) */
153 } u;
154 /*
155 * The full name of the reference (e.g., "refs/heads/master")
156 * or the full name of the directory with a trailing slash
157 * (e.g., "refs/heads/"):
158 */
159 char name[FLEX_ARRAY];
160};
161
162static void read_loose_refs(const char *dirname, struct ref_dir *dir);
163static int search_ref_dir(struct ref_dir *dir, const char *refname, size_t len);
65a0a8e5 164static struct ref_entry *create_dir_entry(struct files_ref_store *ref_store,
7bd9bcf3
MH
165 const char *dirname, size_t len,
166 int incomplete);
167static void add_entry_to_dir(struct ref_dir *dir, struct ref_entry *entry);
802de3da
NTND
168static int files_log_ref_write(struct files_ref_store *refs,
169 const char *refname, const unsigned char *old_sha1,
11f8457f
NTND
170 const unsigned char *new_sha1, const char *msg,
171 int flags, struct strbuf *err);
7bd9bcf3
MH
172
173static struct ref_dir *get_ref_dir(struct ref_entry *entry)
174{
175 struct ref_dir *dir;
176 assert(entry->flag & REF_DIR);
177 dir = &entry->u.subdir;
178 if (entry->flag & REF_INCOMPLETE) {
179 read_loose_refs(entry->name, dir);
180
181 /*
182 * Manually add refs/bisect, which, being
183 * per-worktree, might not appear in the directory
184 * listing for refs/ in the main repo.
185 */
186 if (!strcmp(entry->name, "refs/")) {
187 int pos = search_ref_dir(dir, "refs/bisect/", 12);
188 if (pos < 0) {
189 struct ref_entry *child_entry;
65a0a8e5 190 child_entry = create_dir_entry(dir->ref_store,
7bd9bcf3
MH
191 "refs/bisect/",
192 12, 1);
193 add_entry_to_dir(dir, child_entry);
7bd9bcf3
MH
194 }
195 }
196 entry->flag &= ~REF_INCOMPLETE;
197 }
198 return dir;
199}
200
201static struct ref_entry *create_ref_entry(const char *refname,
202 const unsigned char *sha1, int flag,
203 int check_name)
204{
7bd9bcf3
MH
205 struct ref_entry *ref;
206
207 if (check_name &&
208 check_refname_format(refname, REFNAME_ALLOW_ONELEVEL))
209 die("Reference has invalid format: '%s'", refname);
96ffc06f 210 FLEX_ALLOC_STR(ref, name, refname);
7bd9bcf3
MH
211 hashcpy(ref->u.value.oid.hash, sha1);
212 oidclr(&ref->u.value.peeled);
7bd9bcf3
MH
213 ref->flag = flag;
214 return ref;
215}
216
217static void clear_ref_dir(struct ref_dir *dir);
218
219static void free_ref_entry(struct ref_entry *entry)
220{
221 if (entry->flag & REF_DIR) {
222 /*
223 * Do not use get_ref_dir() here, as that might
224 * trigger the reading of loose refs.
225 */
226 clear_ref_dir(&entry->u.subdir);
227 }
228 free(entry);
229}
230
231/*
232 * Add a ref_entry to the end of dir (unsorted). Entry is always
233 * stored directly in dir; no recursion into subdirectories is
234 * done.
235 */
236static void add_entry_to_dir(struct ref_dir *dir, struct ref_entry *entry)
237{
238 ALLOC_GROW(dir->entries, dir->nr + 1, dir->alloc);
239 dir->entries[dir->nr++] = entry;
240 /* optimize for the case that entries are added in order */
241 if (dir->nr == 1 ||
242 (dir->nr == dir->sorted + 1 &&
243 strcmp(dir->entries[dir->nr - 2]->name,
244 dir->entries[dir->nr - 1]->name) < 0))
245 dir->sorted = dir->nr;
246}
247
248/*
249 * Clear and free all entries in dir, recursively.
250 */
251static void clear_ref_dir(struct ref_dir *dir)
252{
253 int i;
254 for (i = 0; i < dir->nr; i++)
255 free_ref_entry(dir->entries[i]);
256 free(dir->entries);
257 dir->sorted = dir->nr = dir->alloc = 0;
258 dir->entries = NULL;
259}
260
261/*
262 * Create a struct ref_entry object for the specified dirname.
263 * dirname is the name of the directory with a trailing slash (e.g.,
264 * "refs/heads/") or "" for the top-level directory.
265 */
65a0a8e5 266static struct ref_entry *create_dir_entry(struct files_ref_store *ref_store,
7bd9bcf3
MH
267 const char *dirname, size_t len,
268 int incomplete)
269{
270 struct ref_entry *direntry;
96ffc06f 271 FLEX_ALLOC_MEM(direntry, name, dirname, len);
65a0a8e5 272 direntry->u.subdir.ref_store = ref_store;
7bd9bcf3
MH
273 direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE : 0);
274 return direntry;
275}
276
277static int ref_entry_cmp(const void *a, const void *b)
278{
279 struct ref_entry *one = *(struct ref_entry **)a;
280 struct ref_entry *two = *(struct ref_entry **)b;
281 return strcmp(one->name, two->name);
282}
283
284static void sort_ref_dir(struct ref_dir *dir);
285
286struct string_slice {
287 size_t len;
288 const char *str;
289};
290
291static int ref_entry_cmp_sslice(const void *key_, const void *ent_)
292{
293 const struct string_slice *key = key_;
294 const struct ref_entry *ent = *(const struct ref_entry * const *)ent_;
295 int cmp = strncmp(key->str, ent->name, key->len);
296 if (cmp)
297 return cmp;
298 return '\0' - (unsigned char)ent->name[key->len];
299}
300
301/*
302 * Return the index of the entry with the given refname from the
303 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if
304 * no such entry is found. dir must already be complete.
305 */
306static int search_ref_dir(struct ref_dir *dir, const char *refname, size_t len)
307{
308 struct ref_entry **r;
309 struct string_slice key;
310
311 if (refname == NULL || !dir->nr)
312 return -1;
313
314 sort_ref_dir(dir);
315 key.len = len;
316 key.str = refname;
317 r = bsearch(&key, dir->entries, dir->nr, sizeof(*dir->entries),
318 ref_entry_cmp_sslice);
319
320 if (r == NULL)
321 return -1;
322
323 return r - dir->entries;
324}
325
326/*
327 * Search for a directory entry directly within dir (without
328 * recursing). Sort dir if necessary. subdirname must be a directory
329 * name (i.e., end in '/'). If mkdir is set, then create the
330 * directory if it is missing; otherwise, return NULL if the desired
331 * directory cannot be found. dir must already be complete.
332 */
333static struct ref_dir *search_for_subdir(struct ref_dir *dir,
334 const char *subdirname, size_t len,
335 int mkdir)
336{
337 int entry_index = search_ref_dir(dir, subdirname, len);
338 struct ref_entry *entry;
339 if (entry_index == -1) {
340 if (!mkdir)
341 return NULL;
342 /*
343 * Since dir is complete, the absence of a subdir
344 * means that the subdir really doesn't exist;
345 * therefore, create an empty record for it but mark
346 * the record complete.
347 */
65a0a8e5 348 entry = create_dir_entry(dir->ref_store, subdirname, len, 0);
7bd9bcf3
MH
349 add_entry_to_dir(dir, entry);
350 } else {
351 entry = dir->entries[entry_index];
352 }
353 return get_ref_dir(entry);
354}
355
356/*
357 * If refname is a reference name, find the ref_dir within the dir
358 * tree that should hold refname. If refname is a directory name
359 * (i.e., ends in '/'), then return that ref_dir itself. dir must
360 * represent the top-level directory and must already be complete.
361 * Sort ref_dirs and recurse into subdirectories as necessary. If
362 * mkdir is set, then create any missing directories; otherwise,
363 * return NULL if the desired directory cannot be found.
364 */
365static struct ref_dir *find_containing_dir(struct ref_dir *dir,
366 const char *refname, int mkdir)
367{
368 const char *slash;
369 for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) {
370 size_t dirnamelen = slash - refname + 1;
371 struct ref_dir *subdir;
372 subdir = search_for_subdir(dir, refname, dirnamelen, mkdir);
373 if (!subdir) {
374 dir = NULL;
375 break;
376 }
377 dir = subdir;
378 }
379
380 return dir;
381}
382
383/*
384 * Find the value entry with the given name in dir, sorting ref_dirs
385 * and recursing into subdirectories as necessary. If the name is not
386 * found or it corresponds to a directory entry, return NULL.
387 */
388static struct ref_entry *find_ref(struct ref_dir *dir, const char *refname)
389{
390 int entry_index;
391 struct ref_entry *entry;
392 dir = find_containing_dir(dir, refname, 0);
393 if (!dir)
394 return NULL;
395 entry_index = search_ref_dir(dir, refname, strlen(refname));
396 if (entry_index == -1)
397 return NULL;
398 entry = dir->entries[entry_index];
399 return (entry->flag & REF_DIR) ? NULL : entry;
400}
401
402/*
403 * Remove the entry with the given name from dir, recursing into
404 * subdirectories as necessary. If refname is the name of a directory
405 * (i.e., ends with '/'), then remove the directory and its contents.
406 * If the removal was successful, return the number of entries
407 * remaining in the directory entry that contained the deleted entry.
408 * If the name was not found, return -1. Please note that this
409 * function only deletes the entry from the cache; it does not delete
410 * it from the filesystem or ensure that other cache entries (which
411 * might be symbolic references to the removed entry) are updated.
412 * Nor does it remove any containing dir entries that might be made
413 * empty by the removal. dir must represent the top-level directory
414 * and must already be complete.
415 */
416static int remove_entry(struct ref_dir *dir, const char *refname)
417{
418 int refname_len = strlen(refname);
419 int entry_index;
420 struct ref_entry *entry;
421 int is_dir = refname[refname_len - 1] == '/';
422 if (is_dir) {
423 /*
424 * refname represents a reference directory. Remove
425 * the trailing slash; otherwise we will get the
426 * directory *representing* refname rather than the
427 * one *containing* it.
428 */
429 char *dirname = xmemdupz(refname, refname_len - 1);
430 dir = find_containing_dir(dir, dirname, 0);
431 free(dirname);
432 } else {
433 dir = find_containing_dir(dir, refname, 0);
434 }
435 if (!dir)
436 return -1;
437 entry_index = search_ref_dir(dir, refname, refname_len);
438 if (entry_index == -1)
439 return -1;
440 entry = dir->entries[entry_index];
441
442 memmove(&dir->entries[entry_index],
443 &dir->entries[entry_index + 1],
444 (dir->nr - entry_index - 1) * sizeof(*dir->entries)
445 );
446 dir->nr--;
447 if (dir->sorted > entry_index)
448 dir->sorted--;
449 free_ref_entry(entry);
450 return dir->nr;
451}
452
453/*
454 * Add a ref_entry to the ref_dir (unsorted), recursing into
455 * subdirectories as necessary. dir must represent the top-level
456 * directory. Return 0 on success.
457 */
458static int add_ref(struct ref_dir *dir, struct ref_entry *ref)
459{
460 dir = find_containing_dir(dir, ref->name, 1);
461 if (!dir)
462 return -1;
463 add_entry_to_dir(dir, ref);
464 return 0;
465}
466
467/*
468 * Emit a warning and return true iff ref1 and ref2 have the same name
469 * and the same sha1. Die if they have the same name but different
470 * sha1s.
471 */
472static int is_dup_ref(const struct ref_entry *ref1, const struct ref_entry *ref2)
473{
474 if (strcmp(ref1->name, ref2->name))
475 return 0;
476
477 /* Duplicate name; make sure that they don't conflict: */
478
479 if ((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR))
480 /* This is impossible by construction */
481 die("Reference directory conflict: %s", ref1->name);
482
483 if (oidcmp(&ref1->u.value.oid, &ref2->u.value.oid))
484 die("Duplicated ref, and SHA1s don't match: %s", ref1->name);
485
486 warning("Duplicated ref: %s", ref1->name);
487 return 1;
488}
489
490/*
491 * Sort the entries in dir non-recursively (if they are not already
492 * sorted) and remove any duplicate entries.
493 */
494static void sort_ref_dir(struct ref_dir *dir)
495{
496 int i, j;
497 struct ref_entry *last = NULL;
498
499 /*
500 * This check also prevents passing a zero-length array to qsort(),
501 * which is a problem on some platforms.
502 */
503 if (dir->sorted == dir->nr)
504 return;
505
9ed0d8d6 506 QSORT(dir->entries, dir->nr, ref_entry_cmp);
7bd9bcf3
MH
507
508 /* Remove any duplicates: */
509 for (i = 0, j = 0; j < dir->nr; j++) {
510 struct ref_entry *entry = dir->entries[j];
511 if (last && is_dup_ref(last, entry))
512 free_ref_entry(entry);
513 else
514 last = dir->entries[i++] = entry;
515 }
516 dir->sorted = dir->nr = i;
517}
518
7bd9bcf3 519/*
a8739244
MH
520 * Return true if refname, which has the specified oid and flags, can
521 * be resolved to an object in the database. If the referred-to object
522 * does not exist, emit a warning and return false.
7bd9bcf3 523 */
a8739244
MH
524static int ref_resolves_to_object(const char *refname,
525 const struct object_id *oid,
526 unsigned int flags)
7bd9bcf3 527{
a8739244 528 if (flags & REF_ISBROKEN)
7bd9bcf3 529 return 0;
a8739244
MH
530 if (!has_sha1_file(oid->hash)) {
531 error("%s does not point to a valid object!", refname);
7bd9bcf3
MH
532 return 0;
533 }
534 return 1;
535}
536
537/*
a8739244
MH
538 * Return true if the reference described by entry can be resolved to
539 * an object in the database; otherwise, emit a warning and return
540 * false.
7bd9bcf3 541 */
a8739244 542static int entry_resolves_to_object(struct ref_entry *entry)
7bd9bcf3 543{
a8739244
MH
544 return ref_resolves_to_object(entry->name,
545 &entry->u.value.oid, entry->flag);
7bd9bcf3
MH
546}
547
7bd9bcf3
MH
548typedef int each_ref_entry_fn(struct ref_entry *entry, void *cb_data);
549
7bd9bcf3
MH
550/*
551 * Call fn for each reference in dir that has index in the range
552 * offset <= index < dir->nr. Recurse into subdirectories that are in
553 * that index range, sorting them before iterating. This function
554 * does not sort dir itself; it should be sorted beforehand. fn is
555 * called for all references, including broken ones.
556 */
557static int do_for_each_entry_in_dir(struct ref_dir *dir, int offset,
558 each_ref_entry_fn fn, void *cb_data)
559{
560 int i;
561 assert(dir->sorted == dir->nr);
562 for (i = offset; i < dir->nr; i++) {
563 struct ref_entry *entry = dir->entries[i];
564 int retval;
565 if (entry->flag & REF_DIR) {
566 struct ref_dir *subdir = get_ref_dir(entry);
567 sort_ref_dir(subdir);
568 retval = do_for_each_entry_in_dir(subdir, 0, fn, cb_data);
569 } else {
570 retval = fn(entry, cb_data);
571 }
572 if (retval)
573 return retval;
574 }
575 return 0;
576}
577
7bd9bcf3
MH
578/*
579 * Load all of the refs from the dir into our in-memory cache. The hard work
580 * of loading loose refs is done by get_ref_dir(), so we just need to recurse
581 * through all of the sub-directories. We do not even need to care about
582 * sorting, as traversal order does not matter to us.
583 */
584static void prime_ref_dir(struct ref_dir *dir)
585{
586 int i;
587 for (i = 0; i < dir->nr; i++) {
588 struct ref_entry *entry = dir->entries[i];
589 if (entry->flag & REF_DIR)
590 prime_ref_dir(get_ref_dir(entry));
591 }
592}
593
3bc581b9
MH
594/*
595 * A level in the reference hierarchy that is currently being iterated
596 * through.
597 */
598struct cache_ref_iterator_level {
599 /*
600 * The ref_dir being iterated over at this level. The ref_dir
601 * is sorted before being stored here.
602 */
603 struct ref_dir *dir;
604
605 /*
606 * The index of the current entry within dir (which might
607 * itself be a directory). If index == -1, then the iteration
608 * hasn't yet begun. If index == dir->nr, then the iteration
609 * through this level is over.
610 */
611 int index;
612};
613
614/*
615 * Represent an iteration through a ref_dir in the memory cache. The
616 * iteration recurses through subdirectories.
617 */
618struct cache_ref_iterator {
619 struct ref_iterator base;
620
621 /*
622 * The number of levels currently on the stack. This is always
623 * at least 1, because when it becomes zero the iteration is
624 * ended and this struct is freed.
625 */
626 size_t levels_nr;
627
628 /* The number of levels that have been allocated on the stack */
629 size_t levels_alloc;
630
631 /*
632 * A stack of levels. levels[0] is the uppermost level that is
633 * being iterated over in this iteration. (This is not
634 * necessary the top level in the references hierarchy. If we
635 * are iterating through a subtree, then levels[0] will hold
636 * the ref_dir for that subtree, and subsequent levels will go
637 * on from there.)
638 */
639 struct cache_ref_iterator_level *levels;
640};
641
642static int cache_ref_iterator_advance(struct ref_iterator *ref_iterator)
643{
644 struct cache_ref_iterator *iter =
645 (struct cache_ref_iterator *)ref_iterator;
646
647 while (1) {
648 struct cache_ref_iterator_level *level =
649 &iter->levels[iter->levels_nr - 1];
650 struct ref_dir *dir = level->dir;
651 struct ref_entry *entry;
652
653 if (level->index == -1)
654 sort_ref_dir(dir);
655
656 if (++level->index == level->dir->nr) {
657 /* This level is exhausted; pop up a level */
658 if (--iter->levels_nr == 0)
659 return ref_iterator_abort(ref_iterator);
660
661 continue;
662 }
663
664 entry = dir->entries[level->index];
665
666 if (entry->flag & REF_DIR) {
667 /* push down a level */
668 ALLOC_GROW(iter->levels, iter->levels_nr + 1,
669 iter->levels_alloc);
670
671 level = &iter->levels[iter->levels_nr++];
672 level->dir = get_ref_dir(entry);
673 level->index = -1;
674 } else {
675 iter->base.refname = entry->name;
676 iter->base.oid = &entry->u.value.oid;
677 iter->base.flags = entry->flag;
678 return ITER_OK;
679 }
680 }
681}
682
683static enum peel_status peel_entry(struct ref_entry *entry, int repeel);
684
685static int cache_ref_iterator_peel(struct ref_iterator *ref_iterator,
686 struct object_id *peeled)
687{
688 struct cache_ref_iterator *iter =
689 (struct cache_ref_iterator *)ref_iterator;
690 struct cache_ref_iterator_level *level;
691 struct ref_entry *entry;
692
693 level = &iter->levels[iter->levels_nr - 1];
694
695 if (level->index == -1)
696 die("BUG: peel called before advance for cache iterator");
697
698 entry = level->dir->entries[level->index];
699
700 if (peel_entry(entry, 0))
701 return -1;
8694769f 702 oidcpy(peeled, &entry->u.value.peeled);
3bc581b9
MH
703 return 0;
704}
705
706static int cache_ref_iterator_abort(struct ref_iterator *ref_iterator)
707{
708 struct cache_ref_iterator *iter =
709 (struct cache_ref_iterator *)ref_iterator;
710
711 free(iter->levels);
712 base_ref_iterator_free(ref_iterator);
713 return ITER_DONE;
714}
715
716static struct ref_iterator_vtable cache_ref_iterator_vtable = {
717 cache_ref_iterator_advance,
718 cache_ref_iterator_peel,
719 cache_ref_iterator_abort
720};
721
722static struct ref_iterator *cache_ref_iterator_begin(struct ref_dir *dir)
723{
724 struct cache_ref_iterator *iter;
725 struct ref_iterator *ref_iterator;
726 struct cache_ref_iterator_level *level;
727
728 iter = xcalloc(1, sizeof(*iter));
729 ref_iterator = &iter->base;
730 base_ref_iterator_init(ref_iterator, &cache_ref_iterator_vtable);
731 ALLOC_GROW(iter->levels, 10, iter->levels_alloc);
732
733 iter->levels_nr = 1;
734 level = &iter->levels[0];
735 level->index = -1;
736 level->dir = dir;
737
738 return ref_iterator;
739}
740
7bd9bcf3
MH
741struct nonmatching_ref_data {
742 const struct string_list *skip;
743 const char *conflicting_refname;
744};
745
746static int nonmatching_ref_fn(struct ref_entry *entry, void *vdata)
747{
748 struct nonmatching_ref_data *data = vdata;
749
750 if (data->skip && string_list_has_string(data->skip, entry->name))
751 return 0;
752
753 data->conflicting_refname = entry->name;
754 return 1;
755}
756
757/*
758 * Return 0 if a reference named refname could be created without
759 * conflicting with the name of an existing reference in dir.
760 * See verify_refname_available for more information.
761 */
762static int verify_refname_available_dir(const char *refname,
763 const struct string_list *extras,
764 const struct string_list *skip,
765 struct ref_dir *dir,
766 struct strbuf *err)
767{
768 const char *slash;
0845122c 769 const char *extra_refname;
7bd9bcf3
MH
770 int pos;
771 struct strbuf dirname = STRBUF_INIT;
772 int ret = -1;
773
774 /*
775 * For the sake of comments in this function, suppose that
776 * refname is "refs/foo/bar".
777 */
778
779 assert(err);
780
781 strbuf_grow(&dirname, strlen(refname) + 1);
782 for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) {
783 /* Expand dirname to the new prefix, not including the trailing slash: */
784 strbuf_add(&dirname, refname + dirname.len, slash - refname - dirname.len);
785
786 /*
787 * We are still at a leading dir of the refname (e.g.,
788 * "refs/foo"; if there is a reference with that name,
789 * it is a conflict, *unless* it is in skip.
790 */
791 if (dir) {
792 pos = search_ref_dir(dir, dirname.buf, dirname.len);
793 if (pos >= 0 &&
794 (!skip || !string_list_has_string(skip, dirname.buf))) {
795 /*
796 * We found a reference whose name is
797 * a proper prefix of refname; e.g.,
798 * "refs/foo", and is not in skip.
799 */
800 strbuf_addf(err, "'%s' exists; cannot create '%s'",
801 dirname.buf, refname);
802 goto cleanup;
803 }
804 }
805
806 if (extras && string_list_has_string(extras, dirname.buf) &&
807 (!skip || !string_list_has_string(skip, dirname.buf))) {
808 strbuf_addf(err, "cannot process '%s' and '%s' at the same time",
809 refname, dirname.buf);
810 goto cleanup;
811 }
812
813 /*
814 * Otherwise, we can try to continue our search with
815 * the next component. So try to look up the
816 * directory, e.g., "refs/foo/". If we come up empty,
817 * we know there is nothing under this whole prefix,
818 * but even in that case we still have to continue the
819 * search for conflicts with extras.
820 */
821 strbuf_addch(&dirname, '/');
822 if (dir) {
823 pos = search_ref_dir(dir, dirname.buf, dirname.len);
824 if (pos < 0) {
825 /*
826 * There was no directory "refs/foo/",
827 * so there is nothing under this
828 * whole prefix. So there is no need
829 * to continue looking for conflicting
830 * references. But we need to continue
831 * looking for conflicting extras.
832 */
833 dir = NULL;
834 } else {
835 dir = get_ref_dir(dir->entries[pos]);
836 }
837 }
838 }
839
840 /*
841 * We are at the leaf of our refname (e.g., "refs/foo/bar").
842 * There is no point in searching for a reference with that
843 * name, because a refname isn't considered to conflict with
844 * itself. But we still need to check for references whose
845 * names are in the "refs/foo/bar/" namespace, because they
846 * *do* conflict.
847 */
848 strbuf_addstr(&dirname, refname + dirname.len);
849 strbuf_addch(&dirname, '/');
850
851 if (dir) {
852 pos = search_ref_dir(dir, dirname.buf, dirname.len);
853
854 if (pos >= 0) {
855 /*
856 * We found a directory named "$refname/"
857 * (e.g., "refs/foo/bar/"). It is a problem
858 * iff it contains any ref that is not in
859 * "skip".
860 */
861 struct nonmatching_ref_data data;
862
863 data.skip = skip;
864 data.conflicting_refname = NULL;
865 dir = get_ref_dir(dir->entries[pos]);
866 sort_ref_dir(dir);
867 if (do_for_each_entry_in_dir(dir, 0, nonmatching_ref_fn, &data)) {
868 strbuf_addf(err, "'%s' exists; cannot create '%s'",
869 data.conflicting_refname, refname);
870 goto cleanup;
871 }
872 }
873 }
874
0845122c
DT
875 extra_refname = find_descendant_ref(dirname.buf, extras, skip);
876 if (extra_refname)
877 strbuf_addf(err, "cannot process '%s' and '%s' at the same time",
878 refname, extra_refname);
879 else
880 ret = 0;
7bd9bcf3
MH
881
882cleanup:
883 strbuf_release(&dirname);
884 return ret;
885}
886
887struct packed_ref_cache {
888 struct ref_entry *root;
889
890 /*
891 * Count of references to the data structure in this instance,
65a0a8e5
MH
892 * including the pointer from files_ref_store::packed if any.
893 * The data will not be freed as long as the reference count
894 * is nonzero.
7bd9bcf3
MH
895 */
896 unsigned int referrers;
897
898 /*
899 * Iff the packed-refs file associated with this instance is
900 * currently locked for writing, this points at the associated
901 * lock (which is owned by somebody else). The referrer count
902 * is also incremented when the file is locked and decremented
903 * when it is unlocked.
904 */
905 struct lock_file *lock;
906
907 /* The metadata from when this packed-refs cache was read */
908 struct stat_validity validity;
909};
910
911/*
912 * Future: need to be in "struct repository"
913 * when doing a full libification.
914 */
00eebe35
MH
915struct files_ref_store {
916 struct ref_store base;
9e7ec634 917 unsigned int store_flags;
32c597e7 918
f57f37e2
NTND
919 char *gitdir;
920 char *gitcommondir;
33dfb9f3
NTND
921 char *packed_refs_path;
922
7bd9bcf3
MH
923 struct ref_entry *loose;
924 struct packed_ref_cache *packed;
00eebe35 925};
7bd9bcf3
MH
926
927/* Lock used for the main packed-refs file: */
928static struct lock_file packlock;
929
930/*
931 * Increment the reference count of *packed_refs.
932 */
933static void acquire_packed_ref_cache(struct packed_ref_cache *packed_refs)
934{
935 packed_refs->referrers++;
936}
937
938/*
939 * Decrease the reference count of *packed_refs. If it goes to zero,
940 * free *packed_refs and return true; otherwise return false.
941 */
942static int release_packed_ref_cache(struct packed_ref_cache *packed_refs)
943{
944 if (!--packed_refs->referrers) {
945 free_ref_entry(packed_refs->root);
946 stat_validity_clear(&packed_refs->validity);
947 free(packed_refs);
948 return 1;
949 } else {
950 return 0;
951 }
952}
953
65a0a8e5 954static void clear_packed_ref_cache(struct files_ref_store *refs)
7bd9bcf3
MH
955{
956 if (refs->packed) {
957 struct packed_ref_cache *packed_refs = refs->packed;
958
959 if (packed_refs->lock)
960 die("internal error: packed-ref cache cleared while locked");
961 refs->packed = NULL;
962 release_packed_ref_cache(packed_refs);
963 }
964}
965
65a0a8e5 966static void clear_loose_ref_cache(struct files_ref_store *refs)
7bd9bcf3
MH
967{
968 if (refs->loose) {
969 free_ref_entry(refs->loose);
970 refs->loose = NULL;
971 }
972}
973
a2d5156c
JK
974/*
975 * Create a new submodule ref cache and add it to the internal
976 * set of caches.
977 */
9e7ec634
NTND
978static struct ref_store *files_ref_store_create(const char *gitdir,
979 unsigned int flags)
7bd9bcf3 980{
00eebe35
MH
981 struct files_ref_store *refs = xcalloc(1, sizeof(*refs));
982 struct ref_store *ref_store = (struct ref_store *)refs;
f57f37e2 983 struct strbuf sb = STRBUF_INIT;
7bd9bcf3 984
fbfd0a29 985 base_ref_store_init(ref_store, &refs_be_files);
9e7ec634 986 refs->store_flags = flags;
7bd9bcf3 987
f57f37e2
NTND
988 refs->gitdir = xstrdup(gitdir);
989 get_common_dir_noenv(&sb, gitdir);
990 refs->gitcommondir = strbuf_detach(&sb, NULL);
991 strbuf_addf(&sb, "%s/packed-refs", refs->gitcommondir);
992 refs->packed_refs_path = strbuf_detach(&sb, NULL);
7bd9bcf3 993
00eebe35 994 return ref_store;
a2d5156c 995}
7bd9bcf3 996
32c597e7 997/*
9e7ec634
NTND
998 * Die if refs is not the main ref store. caller is used in any
999 * necessary error messages.
32c597e7
MH
1000 */
1001static void files_assert_main_repository(struct files_ref_store *refs,
1002 const char *caller)
1003{
9e7ec634
NTND
1004 if (refs->store_flags & REF_STORE_MAIN)
1005 return;
1006
1007 die("BUG: operation %s only allowed for main ref store", caller);
32c597e7
MH
1008}
1009
a2d5156c 1010/*
00eebe35 1011 * Downcast ref_store to files_ref_store. Die if ref_store is not a
9e7ec634
NTND
1012 * files_ref_store. required_flags is compared with ref_store's
1013 * store_flags to ensure the ref_store has all required capabilities.
1014 * "caller" is used in any necessary error messages.
a2d5156c 1015 */
9e7ec634
NTND
1016static struct files_ref_store *files_downcast(struct ref_store *ref_store,
1017 unsigned int required_flags,
1018 const char *caller)
a2d5156c 1019{
32c597e7
MH
1020 struct files_ref_store *refs;
1021
00eebe35
MH
1022 if (ref_store->be != &refs_be_files)
1023 die("BUG: ref_store is type \"%s\" not \"files\" in %s",
1024 ref_store->be->name, caller);
2eed2780 1025
32c597e7
MH
1026 refs = (struct files_ref_store *)ref_store;
1027
9e7ec634
NTND
1028 if ((refs->store_flags & required_flags) != required_flags)
1029 die("BUG: operation %s requires abilities 0x%x, but only have 0x%x",
1030 caller, required_flags, refs->store_flags);
2eed2780 1031
32c597e7 1032 return refs;
7bd9bcf3
MH
1033}
1034
1035/* The length of a peeled reference line in packed-refs, including EOL: */
1036#define PEELED_LINE_LENGTH 42
1037
1038/*
1039 * The packed-refs header line that we write out. Perhaps other
1040 * traits will be added later. The trailing space is required.
1041 */
1042static const char PACKED_REFS_HEADER[] =
1043 "# pack-refs with: peeled fully-peeled \n";
1044
1045/*
1046 * Parse one line from a packed-refs file. Write the SHA1 to sha1.
1047 * Return a pointer to the refname within the line (null-terminated),
1048 * or NULL if there was a problem.
1049 */
1050static const char *parse_ref_line(struct strbuf *line, unsigned char *sha1)
1051{
1052 const char *ref;
1053
1054 /*
1055 * 42: the answer to everything.
1056 *
1057 * In this case, it happens to be the answer to
1058 * 40 (length of sha1 hex representation)
1059 * +1 (space in between hex and name)
1060 * +1 (newline at the end of the line)
1061 */
1062 if (line->len <= 42)
1063 return NULL;
1064
1065 if (get_sha1_hex(line->buf, sha1) < 0)
1066 return NULL;
1067 if (!isspace(line->buf[40]))
1068 return NULL;
1069
1070 ref = line->buf + 41;
1071 if (isspace(*ref))
1072 return NULL;
1073
1074 if (line->buf[line->len - 1] != '\n')
1075 return NULL;
1076 line->buf[--line->len] = 0;
1077
1078 return ref;
1079}
1080
1081/*
1082 * Read f, which is a packed-refs file, into dir.
1083 *
1084 * A comment line of the form "# pack-refs with: " may contain zero or
1085 * more traits. We interpret the traits as follows:
1086 *
1087 * No traits:
1088 *
1089 * Probably no references are peeled. But if the file contains a
1090 * peeled value for a reference, we will use it.
1091 *
1092 * peeled:
1093 *
1094 * References under "refs/tags/", if they *can* be peeled, *are*
1095 * peeled in this file. References outside of "refs/tags/" are
1096 * probably not peeled even if they could have been, but if we find
1097 * a peeled value for such a reference we will use it.
1098 *
1099 * fully-peeled:
1100 *
1101 * All references in the file that can be peeled are peeled.
1102 * Inversely (and this is more important), any references in the
1103 * file for which no peeled value is recorded is not peelable. This
1104 * trait should typically be written alongside "peeled" for
1105 * compatibility with older clients, but we do not require it
1106 * (i.e., "peeled" is a no-op if "fully-peeled" is set).
1107 */
1108static void read_packed_refs(FILE *f, struct ref_dir *dir)
1109{
1110 struct ref_entry *last = NULL;
1111 struct strbuf line = STRBUF_INIT;
1112 enum { PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;
1113
1114 while (strbuf_getwholeline(&line, f, '\n') != EOF) {
1115 unsigned char sha1[20];
1116 const char *refname;
1117 const char *traits;
1118
1119 if (skip_prefix(line.buf, "# pack-refs with:", &traits)) {
1120 if (strstr(traits, " fully-peeled "))
1121 peeled = PEELED_FULLY;
1122 else if (strstr(traits, " peeled "))
1123 peeled = PEELED_TAGS;
1124 /* perhaps other traits later as well */
1125 continue;
1126 }
1127
1128 refname = parse_ref_line(&line, sha1);
1129 if (refname) {
1130 int flag = REF_ISPACKED;
1131
1132 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1133 if (!refname_is_safe(refname))
1134 die("packed refname is dangerous: %s", refname);
1135 hashclr(sha1);
1136 flag |= REF_BAD_NAME | REF_ISBROKEN;
1137 }
1138 last = create_ref_entry(refname, sha1, flag, 0);
1139 if (peeled == PEELED_FULLY ||
1140 (peeled == PEELED_TAGS && starts_with(refname, "refs/tags/")))
1141 last->flag |= REF_KNOWS_PEELED;
1142 add_ref(dir, last);
1143 continue;
1144 }
1145 if (last &&
1146 line.buf[0] == '^' &&
1147 line.len == PEELED_LINE_LENGTH &&
1148 line.buf[PEELED_LINE_LENGTH - 1] == '\n' &&
1149 !get_sha1_hex(line.buf + 1, sha1)) {
1150 hashcpy(last->u.value.peeled.hash, sha1);
1151 /*
1152 * Regardless of what the file header said,
1153 * we definitely know the value of *this*
1154 * reference:
1155 */
1156 last->flag |= REF_KNOWS_PEELED;
1157 }
1158 }
1159
1160 strbuf_release(&line);
1161}
1162
33dfb9f3
NTND
1163static const char *files_packed_refs_path(struct files_ref_store *refs)
1164{
1165 return refs->packed_refs_path;
1166}
1167
802de3da
NTND
1168static void files_reflog_path(struct files_ref_store *refs,
1169 struct strbuf *sb,
1170 const char *refname)
1171{
1172 if (!refname) {
f57f37e2
NTND
1173 /*
1174 * FIXME: of course this is wrong in multi worktree
1175 * setting. To be fixed real soon.
1176 */
1177 strbuf_addf(sb, "%s/logs", refs->gitcommondir);
802de3da
NTND
1178 return;
1179 }
1180
f57f37e2
NTND
1181 switch (ref_type(refname)) {
1182 case REF_TYPE_PER_WORKTREE:
1183 case REF_TYPE_PSEUDOREF:
1184 strbuf_addf(sb, "%s/logs/%s", refs->gitdir, refname);
1185 break;
1186 case REF_TYPE_NORMAL:
1187 strbuf_addf(sb, "%s/logs/%s", refs->gitcommondir, refname);
1188 break;
1189 default:
1190 die("BUG: unknown ref type %d of ref %s",
1191 ref_type(refname), refname);
1192 }
802de3da
NTND
1193}
1194
19e02f4f
NTND
1195static void files_ref_path(struct files_ref_store *refs,
1196 struct strbuf *sb,
1197 const char *refname)
1198{
f57f37e2
NTND
1199 switch (ref_type(refname)) {
1200 case REF_TYPE_PER_WORKTREE:
1201 case REF_TYPE_PSEUDOREF:
1202 strbuf_addf(sb, "%s/%s", refs->gitdir, refname);
1203 break;
1204 case REF_TYPE_NORMAL:
1205 strbuf_addf(sb, "%s/%s", refs->gitcommondir, refname);
1206 break;
1207 default:
1208 die("BUG: unknown ref type %d of ref %s",
1209 ref_type(refname), refname);
1210 }
19e02f4f
NTND
1211}
1212
7bd9bcf3 1213/*
65a0a8e5
MH
1214 * Get the packed_ref_cache for the specified files_ref_store,
1215 * creating it if necessary.
7bd9bcf3 1216 */
65a0a8e5 1217static struct packed_ref_cache *get_packed_ref_cache(struct files_ref_store *refs)
7bd9bcf3 1218{
33dfb9f3 1219 const char *packed_refs_file = files_packed_refs_path(refs);
7bd9bcf3
MH
1220
1221 if (refs->packed &&
1222 !stat_validity_check(&refs->packed->validity, packed_refs_file))
1223 clear_packed_ref_cache(refs);
1224
1225 if (!refs->packed) {
1226 FILE *f;
1227
1228 refs->packed = xcalloc(1, sizeof(*refs->packed));
1229 acquire_packed_ref_cache(refs->packed);
1230 refs->packed->root = create_dir_entry(refs, "", 0, 0);
1231 f = fopen(packed_refs_file, "r");
1232 if (f) {
1233 stat_validity_update(&refs->packed->validity, fileno(f));
1234 read_packed_refs(f, get_ref_dir(refs->packed->root));
1235 fclose(f);
1236 }
1237 }
7bd9bcf3
MH
1238 return refs->packed;
1239}
1240
1241static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)
1242{
1243 return get_ref_dir(packed_ref_cache->root);
1244}
1245
65a0a8e5 1246static struct ref_dir *get_packed_refs(struct files_ref_store *refs)
7bd9bcf3
MH
1247{
1248 return get_packed_ref_dir(get_packed_ref_cache(refs));
1249}
1250
1251/*
1252 * Add a reference to the in-memory packed reference cache. This may
1253 * only be called while the packed-refs file is locked (see
1254 * lock_packed_refs()). To actually write the packed-refs file, call
1255 * commit_packed_refs().
1256 */
d99825ab
MH
1257static void add_packed_ref(struct files_ref_store *refs,
1258 const char *refname, const unsigned char *sha1)
7bd9bcf3 1259{
00eebe35 1260 struct packed_ref_cache *packed_ref_cache = get_packed_ref_cache(refs);
7bd9bcf3
MH
1261
1262 if (!packed_ref_cache->lock)
1263 die("internal error: packed refs not locked");
1264 add_ref(get_packed_ref_dir(packed_ref_cache),
1265 create_ref_entry(refname, sha1, REF_ISPACKED, 1));
1266}
1267
1268/*
1269 * Read the loose references from the namespace dirname into dir
1270 * (without recursing). dirname must end with '/'. dir must be the
1271 * directory entry corresponding to dirname.
1272 */
1273static void read_loose_refs(const char *dirname, struct ref_dir *dir)
1274{
65a0a8e5 1275 struct files_ref_store *refs = dir->ref_store;
7bd9bcf3
MH
1276 DIR *d;
1277 struct dirent *de;
1278 int dirnamelen = strlen(dirname);
1279 struct strbuf refname;
1280 struct strbuf path = STRBUF_INIT;
1281 size_t path_baselen;
1282
19e02f4f 1283 files_ref_path(refs, &path, dirname);
7bd9bcf3
MH
1284 path_baselen = path.len;
1285
1286 d = opendir(path.buf);
1287 if (!d) {
1288 strbuf_release(&path);
1289 return;
1290 }
1291
1292 strbuf_init(&refname, dirnamelen + 257);
1293 strbuf_add(&refname, dirname, dirnamelen);
1294
1295 while ((de = readdir(d)) != NULL) {
1296 unsigned char sha1[20];
1297 struct stat st;
1298 int flag;
1299
1300 if (de->d_name[0] == '.')
1301 continue;
1302 if (ends_with(de->d_name, ".lock"))
1303 continue;
1304 strbuf_addstr(&refname, de->d_name);
1305 strbuf_addstr(&path, de->d_name);
1306 if (stat(path.buf, &st) < 0) {
1307 ; /* silently ignore */
1308 } else if (S_ISDIR(st.st_mode)) {
1309 strbuf_addch(&refname, '/');
1310 add_entry_to_dir(dir,
1311 create_dir_entry(refs, refname.buf,
1312 refname.len, 1));
1313 } else {
7d2df051 1314 if (!refs_resolve_ref_unsafe(&refs->base,
3c0cb0cb
MH
1315 refname.buf,
1316 RESOLVE_REF_READING,
1317 sha1, &flag)) {
7bd9bcf3
MH
1318 hashclr(sha1);
1319 flag |= REF_ISBROKEN;
1320 } else if (is_null_sha1(sha1)) {
1321 /*
1322 * It is so astronomically unlikely
1323 * that NULL_SHA1 is the SHA-1 of an
1324 * actual object that we consider its
1325 * appearance in a loose reference
1326 * file to be repo corruption
1327 * (probably due to a software bug).
1328 */
1329 flag |= REF_ISBROKEN;
1330 }
1331
1332 if (check_refname_format(refname.buf,
1333 REFNAME_ALLOW_ONELEVEL)) {
1334 if (!refname_is_safe(refname.buf))
1335 die("loose refname is dangerous: %s", refname.buf);
1336 hashclr(sha1);
1337 flag |= REF_BAD_NAME | REF_ISBROKEN;
1338 }
1339 add_entry_to_dir(dir,
1340 create_ref_entry(refname.buf, sha1, flag, 0));
1341 }
1342 strbuf_setlen(&refname, dirnamelen);
1343 strbuf_setlen(&path, path_baselen);
1344 }
1345 strbuf_release(&refname);
1346 strbuf_release(&path);
1347 closedir(d);
1348}
1349
65a0a8e5 1350static struct ref_dir *get_loose_refs(struct files_ref_store *refs)
7bd9bcf3
MH
1351{
1352 if (!refs->loose) {
1353 /*
1354 * Mark the top-level directory complete because we
1355 * are about to read the only subdirectory that can
1356 * hold references:
1357 */
1358 refs->loose = create_dir_entry(refs, "", 0, 0);
1359 /*
1360 * Create an incomplete entry for "refs/":
1361 */
1362 add_entry_to_dir(get_ref_dir(refs->loose),
1363 create_dir_entry(refs, "refs/", 5, 1));
1364 }
1365 return get_ref_dir(refs->loose);
1366}
1367
7bd9bcf3
MH
1368/*
1369 * Return the ref_entry for the given refname from the packed
1370 * references. If it does not exist, return NULL.
1371 */
f0d21efc
MH
1372static struct ref_entry *get_packed_ref(struct files_ref_store *refs,
1373 const char *refname)
7bd9bcf3 1374{
00eebe35 1375 return find_ref(get_packed_refs(refs), refname);
7bd9bcf3
MH
1376}
1377
1378/*
419c6f4c 1379 * A loose ref file doesn't exist; check for a packed ref.
7bd9bcf3 1380 */
611118d0
MH
1381static int resolve_packed_ref(struct files_ref_store *refs,
1382 const char *refname,
1383 unsigned char *sha1, unsigned int *flags)
7bd9bcf3
MH
1384{
1385 struct ref_entry *entry;
1386
1387 /*
1388 * The loose reference file does not exist; check for a packed
1389 * reference.
1390 */
f0d21efc 1391 entry = get_packed_ref(refs, refname);
7bd9bcf3
MH
1392 if (entry) {
1393 hashcpy(sha1, entry->u.value.oid.hash);
a70a93b7 1394 *flags |= REF_ISPACKED;
7bd9bcf3
MH
1395 return 0;
1396 }
419c6f4c
MH
1397 /* refname is not a packed reference. */
1398 return -1;
7bd9bcf3
MH
1399}
1400
e1e33b72
MH
1401static int files_read_raw_ref(struct ref_store *ref_store,
1402 const char *refname, unsigned char *sha1,
1403 struct strbuf *referent, unsigned int *type)
7bd9bcf3 1404{
4308651c 1405 struct files_ref_store *refs =
9e7ec634 1406 files_downcast(ref_store, REF_STORE_READ, "read_raw_ref");
42a38cf7
MH
1407 struct strbuf sb_contents = STRBUF_INIT;
1408 struct strbuf sb_path = STRBUF_INIT;
7048653a
DT
1409 const char *path;
1410 const char *buf;
1411 struct stat st;
1412 int fd;
42a38cf7
MH
1413 int ret = -1;
1414 int save_errno;
e8c42cb9 1415 int remaining_retries = 3;
7bd9bcf3 1416
fa96ea1b 1417 *type = 0;
42a38cf7 1418 strbuf_reset(&sb_path);
34c7ad8f 1419
19e02f4f 1420 files_ref_path(refs, &sb_path, refname);
34c7ad8f 1421
42a38cf7 1422 path = sb_path.buf;
7bd9bcf3 1423
7048653a
DT
1424stat_ref:
1425 /*
1426 * We might have to loop back here to avoid a race
1427 * condition: first we lstat() the file, then we try
1428 * to read it as a link or as a file. But if somebody
1429 * changes the type of the file (file <-> directory
1430 * <-> symlink) between the lstat() and reading, then
1431 * we don't want to report that as an error but rather
1432 * try again starting with the lstat().
e8c42cb9
JK
1433 *
1434 * We'll keep a count of the retries, though, just to avoid
1435 * any confusing situation sending us into an infinite loop.
7048653a 1436 */
7bd9bcf3 1437
e8c42cb9
JK
1438 if (remaining_retries-- <= 0)
1439 goto out;
1440
7048653a
DT
1441 if (lstat(path, &st) < 0) {
1442 if (errno != ENOENT)
42a38cf7 1443 goto out;
611118d0 1444 if (resolve_packed_ref(refs, refname, sha1, type)) {
7048653a 1445 errno = ENOENT;
42a38cf7 1446 goto out;
7bd9bcf3 1447 }
42a38cf7
MH
1448 ret = 0;
1449 goto out;
7bd9bcf3 1450 }
7bd9bcf3 1451
7048653a
DT
1452 /* Follow "normalized" - ie "refs/.." symlinks by hand */
1453 if (S_ISLNK(st.st_mode)) {
42a38cf7
MH
1454 strbuf_reset(&sb_contents);
1455 if (strbuf_readlink(&sb_contents, path, 0) < 0) {
7048653a 1456 if (errno == ENOENT || errno == EINVAL)
7bd9bcf3
MH
1457 /* inconsistent with lstat; retry */
1458 goto stat_ref;
1459 else
42a38cf7 1460 goto out;
7bd9bcf3 1461 }
42a38cf7
MH
1462 if (starts_with(sb_contents.buf, "refs/") &&
1463 !check_refname_format(sb_contents.buf, 0)) {
92b38093 1464 strbuf_swap(&sb_contents, referent);
3a0b6b9a 1465 *type |= REF_ISSYMREF;
42a38cf7
MH
1466 ret = 0;
1467 goto out;
7bd9bcf3 1468 }
3f7bd767
JK
1469 /*
1470 * It doesn't look like a refname; fall through to just
1471 * treating it like a non-symlink, and reading whatever it
1472 * points to.
1473 */
7048653a 1474 }
7bd9bcf3 1475
7048653a
DT
1476 /* Is it a directory? */
1477 if (S_ISDIR(st.st_mode)) {
e167a567
MH
1478 /*
1479 * Even though there is a directory where the loose
1480 * ref is supposed to be, there could still be a
1481 * packed ref:
1482 */
611118d0 1483 if (resolve_packed_ref(refs, refname, sha1, type)) {
e167a567
MH
1484 errno = EISDIR;
1485 goto out;
1486 }
1487 ret = 0;
42a38cf7 1488 goto out;
7048653a
DT
1489 }
1490
1491 /*
1492 * Anything else, just open it and try to use it as
1493 * a ref
1494 */
1495 fd = open(path, O_RDONLY);
1496 if (fd < 0) {
3f7bd767 1497 if (errno == ENOENT && !S_ISLNK(st.st_mode))
7048653a
DT
1498 /* inconsistent with lstat; retry */
1499 goto stat_ref;
1500 else
42a38cf7 1501 goto out;
7048653a 1502 }
42a38cf7
MH
1503 strbuf_reset(&sb_contents);
1504 if (strbuf_read(&sb_contents, fd, 256) < 0) {
7048653a
DT
1505 int save_errno = errno;
1506 close(fd);
1507 errno = save_errno;
42a38cf7 1508 goto out;
7048653a
DT
1509 }
1510 close(fd);
42a38cf7
MH
1511 strbuf_rtrim(&sb_contents);
1512 buf = sb_contents.buf;
7048653a
DT
1513 if (starts_with(buf, "ref:")) {
1514 buf += 4;
7bd9bcf3
MH
1515 while (isspace(*buf))
1516 buf++;
7048653a 1517
92b38093
MH
1518 strbuf_reset(referent);
1519 strbuf_addstr(referent, buf);
3a0b6b9a 1520 *type |= REF_ISSYMREF;
42a38cf7
MH
1521 ret = 0;
1522 goto out;
7bd9bcf3 1523 }
7bd9bcf3 1524
7048653a
DT
1525 /*
1526 * Please note that FETCH_HEAD has additional
1527 * data after the sha.
1528 */
1529 if (get_sha1_hex(buf, sha1) ||
1530 (buf[40] != '\0' && !isspace(buf[40]))) {
3a0b6b9a 1531 *type |= REF_ISBROKEN;
7048653a 1532 errno = EINVAL;
42a38cf7 1533 goto out;
7048653a
DT
1534 }
1535
42a38cf7 1536 ret = 0;
7bd9bcf3 1537
42a38cf7
MH
1538out:
1539 save_errno = errno;
7bd9bcf3
MH
1540 strbuf_release(&sb_path);
1541 strbuf_release(&sb_contents);
42a38cf7 1542 errno = save_errno;
7bd9bcf3
MH
1543 return ret;
1544}
1545
8415d247
MH
1546static void unlock_ref(struct ref_lock *lock)
1547{
1548 /* Do not free lock->lk -- atexit() still looks at them */
1549 if (lock->lk)
1550 rollback_lock_file(lock->lk);
1551 free(lock->ref_name);
8415d247
MH
1552 free(lock);
1553}
1554
92b1551b
MH
1555/*
1556 * Lock refname, without following symrefs, and set *lock_p to point
1557 * at a newly-allocated lock object. Fill in lock->old_oid, referent,
1558 * and type similarly to read_raw_ref().
1559 *
1560 * The caller must verify that refname is a "safe" reference name (in
1561 * the sense of refname_is_safe()) before calling this function.
1562 *
1563 * If the reference doesn't already exist, verify that refname doesn't
1564 * have a D/F conflict with any existing references. extras and skip
1565 * are passed to verify_refname_available_dir() for this check.
1566 *
1567 * If mustexist is not set and the reference is not found or is
1568 * broken, lock the reference anyway but clear sha1.
1569 *
1570 * Return 0 on success. On failure, write an error message to err and
1571 * return TRANSACTION_NAME_CONFLICT or TRANSACTION_GENERIC_ERROR.
1572 *
1573 * Implementation note: This function is basically
1574 *
1575 * lock reference
1576 * read_raw_ref()
1577 *
1578 * but it includes a lot more code to
1579 * - Deal with possible races with other processes
1580 * - Avoid calling verify_refname_available_dir() when it can be
1581 * avoided, namely if we were successfully able to read the ref
1582 * - Generate informative error messages in the case of failure
1583 */
f7b0a987
MH
1584static int lock_raw_ref(struct files_ref_store *refs,
1585 const char *refname, int mustexist,
92b1551b
MH
1586 const struct string_list *extras,
1587 const struct string_list *skip,
1588 struct ref_lock **lock_p,
1589 struct strbuf *referent,
1590 unsigned int *type,
1591 struct strbuf *err)
1592{
1593 struct ref_lock *lock;
1594 struct strbuf ref_file = STRBUF_INIT;
1595 int attempts_remaining = 3;
1596 int ret = TRANSACTION_GENERIC_ERROR;
1597
1598 assert(err);
32c597e7 1599 files_assert_main_repository(refs, "lock_raw_ref");
f7b0a987 1600
92b1551b
MH
1601 *type = 0;
1602
1603 /* First lock the file so it can't change out from under us. */
1604
1605 *lock_p = lock = xcalloc(1, sizeof(*lock));
1606
1607 lock->ref_name = xstrdup(refname);
19e02f4f 1608 files_ref_path(refs, &ref_file, refname);
92b1551b
MH
1609
1610retry:
1611 switch (safe_create_leading_directories(ref_file.buf)) {
1612 case SCLD_OK:
1613 break; /* success */
1614 case SCLD_EXISTS:
1615 /*
1616 * Suppose refname is "refs/foo/bar". We just failed
1617 * to create the containing directory, "refs/foo",
1618 * because there was a non-directory in the way. This
1619 * indicates a D/F conflict, probably because of
1620 * another reference such as "refs/foo". There is no
1621 * reason to expect this error to be transitory.
1622 */
7d2df051
NTND
1623 if (refs_verify_refname_available(&refs->base, refname,
1624 extras, skip, err)) {
92b1551b
MH
1625 if (mustexist) {
1626 /*
1627 * To the user the relevant error is
1628 * that the "mustexist" reference is
1629 * missing:
1630 */
1631 strbuf_reset(err);
1632 strbuf_addf(err, "unable to resolve reference '%s'",
1633 refname);
1634 } else {
1635 /*
1636 * The error message set by
1637 * verify_refname_available_dir() is OK.
1638 */
1639 ret = TRANSACTION_NAME_CONFLICT;
1640 }
1641 } else {
1642 /*
1643 * The file that is in the way isn't a loose
1644 * reference. Report it as a low-level
1645 * failure.
1646 */
1647 strbuf_addf(err, "unable to create lock file %s.lock; "
1648 "non-directory in the way",
1649 ref_file.buf);
1650 }
1651 goto error_return;
1652 case SCLD_VANISHED:
1653 /* Maybe another process was tidying up. Try again. */
1654 if (--attempts_remaining > 0)
1655 goto retry;
1656 /* fall through */
1657 default:
1658 strbuf_addf(err, "unable to create directory for %s",
1659 ref_file.buf);
1660 goto error_return;
1661 }
1662
1663 if (!lock->lk)
1664 lock->lk = xcalloc(1, sizeof(struct lock_file));
1665
1666 if (hold_lock_file_for_update(lock->lk, ref_file.buf, LOCK_NO_DEREF) < 0) {
1667 if (errno == ENOENT && --attempts_remaining > 0) {
1668 /*
1669 * Maybe somebody just deleted one of the
1670 * directories leading to ref_file. Try
1671 * again:
1672 */
1673 goto retry;
1674 } else {
1675 unable_to_lock_message(ref_file.buf, errno, err);
1676 goto error_return;
1677 }
1678 }
1679
1680 /*
1681 * Now we hold the lock and can read the reference without
1682 * fear that its value will change.
1683 */
1684
f7b0a987 1685 if (files_read_raw_ref(&refs->base, refname,
e1e33b72 1686 lock->old_oid.hash, referent, type)) {
92b1551b
MH
1687 if (errno == ENOENT) {
1688 if (mustexist) {
1689 /* Garden variety missing reference. */
1690 strbuf_addf(err, "unable to resolve reference '%s'",
1691 refname);
1692 goto error_return;
1693 } else {
1694 /*
1695 * Reference is missing, but that's OK. We
1696 * know that there is not a conflict with
1697 * another loose reference because
1698 * (supposing that we are trying to lock
1699 * reference "refs/foo/bar"):
1700 *
1701 * - We were successfully able to create
1702 * the lockfile refs/foo/bar.lock, so we
1703 * know there cannot be a loose reference
1704 * named "refs/foo".
1705 *
1706 * - We got ENOENT and not EISDIR, so we
1707 * know that there cannot be a loose
1708 * reference named "refs/foo/bar/baz".
1709 */
1710 }
1711 } else if (errno == EISDIR) {
1712 /*
1713 * There is a directory in the way. It might have
1714 * contained references that have been deleted. If
1715 * we don't require that the reference already
1716 * exists, try to remove the directory so that it
1717 * doesn't cause trouble when we want to rename the
1718 * lockfile into place later.
1719 */
1720 if (mustexist) {
1721 /* Garden variety missing reference. */
1722 strbuf_addf(err, "unable to resolve reference '%s'",
1723 refname);
1724 goto error_return;
1725 } else if (remove_dir_recursively(&ref_file,
1726 REMOVE_DIR_EMPTY_ONLY)) {
1727 if (verify_refname_available_dir(
1728 refname, extras, skip,
00eebe35 1729 get_loose_refs(refs),
92b1551b
MH
1730 err)) {
1731 /*
1732 * The error message set by
1733 * verify_refname_available() is OK.
1734 */
1735 ret = TRANSACTION_NAME_CONFLICT;
1736 goto error_return;
1737 } else {
1738 /*
1739 * We can't delete the directory,
1740 * but we also don't know of any
1741 * references that it should
1742 * contain.
1743 */
1744 strbuf_addf(err, "there is a non-empty directory '%s' "
1745 "blocking reference '%s'",
1746 ref_file.buf, refname);
1747 goto error_return;
1748 }
1749 }
1750 } else if (errno == EINVAL && (*type & REF_ISBROKEN)) {
1751 strbuf_addf(err, "unable to resolve reference '%s': "
1752 "reference broken", refname);
1753 goto error_return;
1754 } else {
1755 strbuf_addf(err, "unable to resolve reference '%s': %s",
1756 refname, strerror(errno));
1757 goto error_return;
1758 }
1759
1760 /*
1761 * If the ref did not exist and we are creating it,
1762 * make sure there is no existing packed ref whose
1763 * name begins with our refname, nor a packed ref
1764 * whose name is a proper prefix of our refname.
1765 */
1766 if (verify_refname_available_dir(
1767 refname, extras, skip,
00eebe35 1768 get_packed_refs(refs),
92b1551b
MH
1769 err)) {
1770 goto error_return;
1771 }
1772 }
1773
1774 ret = 0;
1775 goto out;
1776
1777error_return:
1778 unlock_ref(lock);
1779 *lock_p = NULL;
1780
1781out:
1782 strbuf_release(&ref_file);
1783 return ret;
1784}
1785
7bd9bcf3
MH
1786/*
1787 * Peel the entry (if possible) and return its new peel_status. If
1788 * repeel is true, re-peel the entry even if there is an old peeled
1789 * value that is already stored in it.
1790 *
1791 * It is OK to call this function with a packed reference entry that
1792 * might be stale and might even refer to an object that has since
1793 * been garbage-collected. In such a case, if the entry has
1794 * REF_KNOWS_PEELED then leave the status unchanged and return
1795 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.
1796 */
1797static enum peel_status peel_entry(struct ref_entry *entry, int repeel)
1798{
1799 enum peel_status status;
1800
1801 if (entry->flag & REF_KNOWS_PEELED) {
1802 if (repeel) {
1803 entry->flag &= ~REF_KNOWS_PEELED;
1804 oidclr(&entry->u.value.peeled);
1805 } else {
1806 return is_null_oid(&entry->u.value.peeled) ?
1807 PEEL_NON_TAG : PEEL_PEELED;
1808 }
1809 }
1810 if (entry->flag & REF_ISBROKEN)
1811 return PEEL_BROKEN;
1812 if (entry->flag & REF_ISSYMREF)
1813 return PEEL_IS_SYMREF;
1814
1815 status = peel_object(entry->u.value.oid.hash, entry->u.value.peeled.hash);
1816 if (status == PEEL_PEELED || status == PEEL_NON_TAG)
1817 entry->flag |= REF_KNOWS_PEELED;
1818 return status;
1819}
1820
bd427cf2
MH
1821static int files_peel_ref(struct ref_store *ref_store,
1822 const char *refname, unsigned char *sha1)
7bd9bcf3 1823{
9e7ec634
NTND
1824 struct files_ref_store *refs =
1825 files_downcast(ref_store, REF_STORE_READ | REF_STORE_ODB,
1826 "peel_ref");
7bd9bcf3
MH
1827 int flag;
1828 unsigned char base[20];
1829
4c4de895
MH
1830 if (current_ref_iter && current_ref_iter->refname == refname) {
1831 struct object_id peeled;
1832
1833 if (ref_iterator_peel(current_ref_iter, &peeled))
7bd9bcf3 1834 return -1;
4c4de895 1835 hashcpy(sha1, peeled.hash);
7bd9bcf3
MH
1836 return 0;
1837 }
1838
2f40e954
NTND
1839 if (refs_read_ref_full(ref_store, refname,
1840 RESOLVE_REF_READING, base, &flag))
7bd9bcf3
MH
1841 return -1;
1842
1843 /*
1844 * If the reference is packed, read its ref_entry from the
1845 * cache in the hope that we already know its peeled value.
1846 * We only try this optimization on packed references because
1847 * (a) forcing the filling of the loose reference cache could
1848 * be expensive and (b) loose references anyway usually do not
1849 * have REF_KNOWS_PEELED.
1850 */
1851 if (flag & REF_ISPACKED) {
f0d21efc 1852 struct ref_entry *r = get_packed_ref(refs, refname);
7bd9bcf3
MH
1853 if (r) {
1854 if (peel_entry(r, 0))
1855 return -1;
1856 hashcpy(sha1, r->u.value.peeled.hash);
1857 return 0;
1858 }
1859 }
1860
1861 return peel_object(base, sha1);
1862}
1863
3bc581b9
MH
1864struct files_ref_iterator {
1865 struct ref_iterator base;
1866
7bd9bcf3 1867 struct packed_ref_cache *packed_ref_cache;
3bc581b9
MH
1868 struct ref_iterator *iter0;
1869 unsigned int flags;
1870};
7bd9bcf3 1871
3bc581b9
MH
1872static int files_ref_iterator_advance(struct ref_iterator *ref_iterator)
1873{
1874 struct files_ref_iterator *iter =
1875 (struct files_ref_iterator *)ref_iterator;
1876 int ok;
7bd9bcf3 1877
3bc581b9 1878 while ((ok = ref_iterator_advance(iter->iter0)) == ITER_OK) {
0c09ec07
DT
1879 if (iter->flags & DO_FOR_EACH_PER_WORKTREE_ONLY &&
1880 ref_type(iter->iter0->refname) != REF_TYPE_PER_WORKTREE)
1881 continue;
1882
3bc581b9
MH
1883 if (!(iter->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&
1884 !ref_resolves_to_object(iter->iter0->refname,
1885 iter->iter0->oid,
1886 iter->iter0->flags))
1887 continue;
1888
1889 iter->base.refname = iter->iter0->refname;
1890 iter->base.oid = iter->iter0->oid;
1891 iter->base.flags = iter->iter0->flags;
1892 return ITER_OK;
7bd9bcf3
MH
1893 }
1894
3bc581b9
MH
1895 iter->iter0 = NULL;
1896 if (ref_iterator_abort(ref_iterator) != ITER_DONE)
1897 ok = ITER_ERROR;
1898
1899 return ok;
7bd9bcf3
MH
1900}
1901
3bc581b9
MH
1902static int files_ref_iterator_peel(struct ref_iterator *ref_iterator,
1903 struct object_id *peeled)
7bd9bcf3 1904{
3bc581b9
MH
1905 struct files_ref_iterator *iter =
1906 (struct files_ref_iterator *)ref_iterator;
93770590 1907
3bc581b9
MH
1908 return ref_iterator_peel(iter->iter0, peeled);
1909}
1910
1911static int files_ref_iterator_abort(struct ref_iterator *ref_iterator)
1912{
1913 struct files_ref_iterator *iter =
1914 (struct files_ref_iterator *)ref_iterator;
1915 int ok = ITER_DONE;
1916
1917 if (iter->iter0)
1918 ok = ref_iterator_abort(iter->iter0);
1919
1920 release_packed_ref_cache(iter->packed_ref_cache);
1921 base_ref_iterator_free(ref_iterator);
1922 return ok;
1923}
1924
1925static struct ref_iterator_vtable files_ref_iterator_vtable = {
1926 files_ref_iterator_advance,
1927 files_ref_iterator_peel,
1928 files_ref_iterator_abort
1929};
1930
1a769003 1931static struct ref_iterator *files_ref_iterator_begin(
37b6f6d5 1932 struct ref_store *ref_store,
3bc581b9
MH
1933 const char *prefix, unsigned int flags)
1934{
9e7ec634 1935 struct files_ref_store *refs;
3bc581b9
MH
1936 struct ref_dir *loose_dir, *packed_dir;
1937 struct ref_iterator *loose_iter, *packed_iter;
1938 struct files_ref_iterator *iter;
1939 struct ref_iterator *ref_iterator;
1940
7bd9bcf3
MH
1941 if (ref_paranoia < 0)
1942 ref_paranoia = git_env_bool("GIT_REF_PARANOIA", 0);
1943 if (ref_paranoia)
3bc581b9
MH
1944 flags |= DO_FOR_EACH_INCLUDE_BROKEN;
1945
9e7ec634
NTND
1946 refs = files_downcast(ref_store,
1947 REF_STORE_READ | (ref_paranoia ? 0 : REF_STORE_ODB),
1948 "ref_iterator_begin");
1949
3bc581b9
MH
1950 iter = xcalloc(1, sizeof(*iter));
1951 ref_iterator = &iter->base;
1952 base_ref_iterator_init(ref_iterator, &files_ref_iterator_vtable);
1953
1954 /*
1955 * We must make sure that all loose refs are read before
1956 * accessing the packed-refs file; this avoids a race
1957 * condition if loose refs are migrated to the packed-refs
1958 * file by a simultaneous process, but our in-memory view is
1959 * from before the migration. We ensure this as follows:
1960 * First, we call prime_ref_dir(), which pre-reads the loose
1961 * references for the subtree into the cache. (If they've
1962 * already been read, that's OK; we only need to guarantee
1963 * that they're read before the packed refs, not *how much*
1964 * before.) After that, we call get_packed_ref_cache(), which
1965 * internally checks whether the packed-ref cache is up to
1966 * date with what is on disk, and re-reads it if not.
1967 */
1968
1969 loose_dir = get_loose_refs(refs);
1970
1971 if (prefix && *prefix)
1972 loose_dir = find_containing_dir(loose_dir, prefix, 0);
7bd9bcf3 1973
3bc581b9
MH
1974 if (loose_dir) {
1975 prime_ref_dir(loose_dir);
1976 loose_iter = cache_ref_iterator_begin(loose_dir);
1977 } else {
1978 /* There's nothing to iterate over. */
1979 loose_iter = empty_ref_iterator_begin();
1980 }
1981
1982 iter->packed_ref_cache = get_packed_ref_cache(refs);
1983 acquire_packed_ref_cache(iter->packed_ref_cache);
1984 packed_dir = get_packed_ref_dir(iter->packed_ref_cache);
1985
1986 if (prefix && *prefix)
1987 packed_dir = find_containing_dir(packed_dir, prefix, 0);
1988
1989 if (packed_dir) {
1990 packed_iter = cache_ref_iterator_begin(packed_dir);
1991 } else {
1992 /* There's nothing to iterate over. */
1993 packed_iter = empty_ref_iterator_begin();
1994 }
1995
1996 iter->iter0 = overlay_ref_iterator_begin(loose_iter, packed_iter);
1997 iter->flags = flags;
1998
1999 return ref_iterator;
7bd9bcf3
MH
2000}
2001
7bd9bcf3
MH
2002/*
2003 * Verify that the reference locked by lock has the value old_sha1.
2004 * Fail if the reference doesn't exist and mustexist is set. Return 0
2005 * on success. On error, write an error message to err, set errno, and
2006 * return a negative value.
2007 */
2f40e954 2008static int verify_lock(struct ref_store *ref_store, struct ref_lock *lock,
7bd9bcf3
MH
2009 const unsigned char *old_sha1, int mustexist,
2010 struct strbuf *err)
2011{
2012 assert(err);
2013
2f40e954
NTND
2014 if (refs_read_ref_full(ref_store, lock->ref_name,
2015 mustexist ? RESOLVE_REF_READING : 0,
2016 lock->old_oid.hash, NULL)) {
6294dcb4
JK
2017 if (old_sha1) {
2018 int save_errno = errno;
0568c8e9 2019 strbuf_addf(err, "can't verify ref '%s'", lock->ref_name);
6294dcb4
JK
2020 errno = save_errno;
2021 return -1;
2022 } else {
c368dde9 2023 oidclr(&lock->old_oid);
6294dcb4
JK
2024 return 0;
2025 }
7bd9bcf3 2026 }
6294dcb4 2027 if (old_sha1 && hashcmp(lock->old_oid.hash, old_sha1)) {
0568c8e9 2028 strbuf_addf(err, "ref '%s' is at %s but expected %s",
7bd9bcf3 2029 lock->ref_name,
c368dde9 2030 oid_to_hex(&lock->old_oid),
7bd9bcf3
MH
2031 sha1_to_hex(old_sha1));
2032 errno = EBUSY;
2033 return -1;
2034 }
2035 return 0;
2036}
2037
2038static int remove_empty_directories(struct strbuf *path)
2039{
2040 /*
2041 * we want to create a file but there is a directory there;
2042 * if that is an empty directory (or a directory that contains
2043 * only empty directories), remove them.
2044 */
2045 return remove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);
2046}
2047
3b5d3c98
MH
2048static int create_reflock(const char *path, void *cb)
2049{
2050 struct lock_file *lk = cb;
2051
2052 return hold_lock_file_for_update(lk, path, LOCK_NO_DEREF) < 0 ? -1 : 0;
2053}
2054
7bd9bcf3
MH
2055/*
2056 * Locks a ref returning the lock on success and NULL on failure.
2057 * On failure errno is set to something meaningful.
2058 */
7eb27cdf
MH
2059static struct ref_lock *lock_ref_sha1_basic(struct files_ref_store *refs,
2060 const char *refname,
7bd9bcf3
MH
2061 const unsigned char *old_sha1,
2062 const struct string_list *extras,
2063 const struct string_list *skip,
bcb497d0 2064 unsigned int flags, int *type,
7bd9bcf3
MH
2065 struct strbuf *err)
2066{
2067 struct strbuf ref_file = STRBUF_INIT;
7bd9bcf3
MH
2068 struct ref_lock *lock;
2069 int last_errno = 0;
7bd9bcf3 2070 int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
7a418f3a 2071 int resolve_flags = RESOLVE_REF_NO_RECURSE;
7a418f3a 2072 int resolved;
7bd9bcf3 2073
32c597e7 2074 files_assert_main_repository(refs, "lock_ref_sha1_basic");
7bd9bcf3
MH
2075 assert(err);
2076
2077 lock = xcalloc(1, sizeof(struct ref_lock));
2078
2079 if (mustexist)
2080 resolve_flags |= RESOLVE_REF_READING;
2859dcd4 2081 if (flags & REF_DELETING)
7bd9bcf3 2082 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;
7bd9bcf3 2083
19e02f4f 2084 files_ref_path(refs, &ref_file, refname);
2f40e954
NTND
2085 resolved = !!refs_resolve_ref_unsafe(&refs->base,
2086 refname, resolve_flags,
2087 lock->old_oid.hash, type);
7a418f3a 2088 if (!resolved && errno == EISDIR) {
7bd9bcf3
MH
2089 /*
2090 * we are trying to lock foo but we used to
2091 * have foo/bar which now does not exist;
2092 * it is normal for the empty directory 'foo'
2093 * to remain.
2094 */
7a418f3a 2095 if (remove_empty_directories(&ref_file)) {
7bd9bcf3 2096 last_errno = errno;
00eebe35
MH
2097 if (!verify_refname_available_dir(
2098 refname, extras, skip,
2099 get_loose_refs(refs), err))
7bd9bcf3 2100 strbuf_addf(err, "there are still refs under '%s'",
7a418f3a 2101 refname);
7bd9bcf3
MH
2102 goto error_return;
2103 }
2f40e954
NTND
2104 resolved = !!refs_resolve_ref_unsafe(&refs->base,
2105 refname, resolve_flags,
2106 lock->old_oid.hash, type);
7bd9bcf3 2107 }
7a418f3a 2108 if (!resolved) {
7bd9bcf3
MH
2109 last_errno = errno;
2110 if (last_errno != ENOTDIR ||
00eebe35
MH
2111 !verify_refname_available_dir(
2112 refname, extras, skip,
2113 get_loose_refs(refs), err))
0568c8e9 2114 strbuf_addf(err, "unable to resolve reference '%s': %s",
7a418f3a 2115 refname, strerror(last_errno));
7bd9bcf3
MH
2116
2117 goto error_return;
2118 }
2859dcd4 2119
7bd9bcf3
MH
2120 /*
2121 * If the ref did not exist and we are creating it, make sure
2122 * there is no existing packed ref whose name begins with our
2123 * refname, nor a packed ref whose name is a proper prefix of
2124 * our refname.
2125 */
2126 if (is_null_oid(&lock->old_oid) &&
2127 verify_refname_available_dir(refname, extras, skip,
00eebe35
MH
2128 get_packed_refs(refs),
2129 err)) {
7bd9bcf3
MH
2130 last_errno = ENOTDIR;
2131 goto error_return;
2132 }
2133
2134 lock->lk = xcalloc(1, sizeof(struct lock_file));
2135
7bd9bcf3 2136 lock->ref_name = xstrdup(refname);
7bd9bcf3 2137
3b5d3c98 2138 if (raceproof_create_file(ref_file.buf, create_reflock, lock->lk)) {
7bd9bcf3 2139 last_errno = errno;
3b5d3c98 2140 unable_to_lock_message(ref_file.buf, errno, err);
7bd9bcf3
MH
2141 goto error_return;
2142 }
2143
2f40e954 2144 if (verify_lock(&refs->base, lock, old_sha1, mustexist, err)) {
7bd9bcf3
MH
2145 last_errno = errno;
2146 goto error_return;
2147 }
2148 goto out;
2149
2150 error_return:
2151 unlock_ref(lock);
2152 lock = NULL;
2153
2154 out:
2155 strbuf_release(&ref_file);
7bd9bcf3
MH
2156 errno = last_errno;
2157 return lock;
2158}
2159
2160/*
2161 * Write an entry to the packed-refs file for the specified refname.
2162 * If peeled is non-NULL, write it as the entry's peeled value.
2163 */
2164static void write_packed_entry(FILE *fh, char *refname, unsigned char *sha1,
2165 unsigned char *peeled)
2166{
2167 fprintf_or_die(fh, "%s %s\n", sha1_to_hex(sha1), refname);
2168 if (peeled)
2169 fprintf_or_die(fh, "^%s\n", sha1_to_hex(peeled));
2170}
2171
2172/*
2173 * An each_ref_entry_fn that writes the entry to a packed-refs file.
2174 */
2175static int write_packed_entry_fn(struct ref_entry *entry, void *cb_data)
2176{
2177 enum peel_status peel_status = peel_entry(entry, 0);
2178
2179 if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)
2180 error("internal error: %s is not a valid packed reference!",
2181 entry->name);
2182 write_packed_entry(cb_data, entry->name, entry->u.value.oid.hash,
2183 peel_status == PEEL_PEELED ?
2184 entry->u.value.peeled.hash : NULL);
2185 return 0;
2186}
2187
2188/*
2189 * Lock the packed-refs file for writing. Flags is passed to
2190 * hold_lock_file_for_update(). Return 0 on success. On errors, set
2191 * errno appropriately and return a nonzero value.
2192 */
49c0df6a 2193static int lock_packed_refs(struct files_ref_store *refs, int flags)
7bd9bcf3
MH
2194{
2195 static int timeout_configured = 0;
2196 static int timeout_value = 1000;
7bd9bcf3
MH
2197 struct packed_ref_cache *packed_ref_cache;
2198
32c597e7 2199 files_assert_main_repository(refs, "lock_packed_refs");
49c0df6a 2200
7bd9bcf3
MH
2201 if (!timeout_configured) {
2202 git_config_get_int("core.packedrefstimeout", &timeout_value);
2203 timeout_configured = 1;
2204 }
2205
2206 if (hold_lock_file_for_update_timeout(
33dfb9f3 2207 &packlock, files_packed_refs_path(refs),
7bd9bcf3
MH
2208 flags, timeout_value) < 0)
2209 return -1;
2210 /*
2211 * Get the current packed-refs while holding the lock. If the
2212 * packed-refs file has been modified since we last read it,
2213 * this will automatically invalidate the cache and re-read
2214 * the packed-refs file.
2215 */
00eebe35 2216 packed_ref_cache = get_packed_ref_cache(refs);
7bd9bcf3
MH
2217 packed_ref_cache->lock = &packlock;
2218 /* Increment the reference count to prevent it from being freed: */
2219 acquire_packed_ref_cache(packed_ref_cache);
2220 return 0;
2221}
2222
2223/*
2224 * Write the current version of the packed refs cache from memory to
2225 * disk. The packed-refs file must already be locked for writing (see
2226 * lock_packed_refs()). Return zero on success. On errors, set errno
2227 * and return a nonzero value
2228 */
49c0df6a 2229static int commit_packed_refs(struct files_ref_store *refs)
7bd9bcf3
MH
2230{
2231 struct packed_ref_cache *packed_ref_cache =
00eebe35 2232 get_packed_ref_cache(refs);
7bd9bcf3
MH
2233 int error = 0;
2234 int save_errno = 0;
2235 FILE *out;
2236
32c597e7 2237 files_assert_main_repository(refs, "commit_packed_refs");
49c0df6a 2238
7bd9bcf3
MH
2239 if (!packed_ref_cache->lock)
2240 die("internal error: packed-refs not locked");
2241
2242 out = fdopen_lock_file(packed_ref_cache->lock, "w");
2243 if (!out)
2244 die_errno("unable to fdopen packed-refs descriptor");
2245
2246 fprintf_or_die(out, "%s", PACKED_REFS_HEADER);
2247 do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),
2248 0, write_packed_entry_fn, out);
2249
2250 if (commit_lock_file(packed_ref_cache->lock)) {
2251 save_errno = errno;
2252 error = -1;
2253 }
2254 packed_ref_cache->lock = NULL;
2255 release_packed_ref_cache(packed_ref_cache);
2256 errno = save_errno;
2257 return error;
2258}
2259
2260/*
2261 * Rollback the lockfile for the packed-refs file, and discard the
2262 * in-memory packed reference cache. (The packed-refs file will be
2263 * read anew if it is needed again after this function is called.)
2264 */
49c0df6a 2265static void rollback_packed_refs(struct files_ref_store *refs)
7bd9bcf3
MH
2266{
2267 struct packed_ref_cache *packed_ref_cache =
00eebe35 2268 get_packed_ref_cache(refs);
7bd9bcf3 2269
32c597e7 2270 files_assert_main_repository(refs, "rollback_packed_refs");
7bd9bcf3
MH
2271
2272 if (!packed_ref_cache->lock)
2273 die("internal error: packed-refs not locked");
2274 rollback_lock_file(packed_ref_cache->lock);
2275 packed_ref_cache->lock = NULL;
2276 release_packed_ref_cache(packed_ref_cache);
00eebe35 2277 clear_packed_ref_cache(refs);
7bd9bcf3
MH
2278}
2279
2280struct ref_to_prune {
2281 struct ref_to_prune *next;
2282 unsigned char sha1[20];
2283 char name[FLEX_ARRAY];
2284};
2285
2286struct pack_refs_cb_data {
2287 unsigned int flags;
2288 struct ref_dir *packed_refs;
2289 struct ref_to_prune *ref_to_prune;
2290};
2291
2292/*
2293 * An each_ref_entry_fn that is run over loose references only. If
2294 * the loose reference can be packed, add an entry in the packed ref
2295 * cache. If the reference should be pruned, also add it to
2296 * ref_to_prune in the pack_refs_cb_data.
2297 */
2298static int pack_if_possible_fn(struct ref_entry *entry, void *cb_data)
2299{
2300 struct pack_refs_cb_data *cb = cb_data;
2301 enum peel_status peel_status;
2302 struct ref_entry *packed_entry;
2303 int is_tag_ref = starts_with(entry->name, "refs/tags/");
2304
2305 /* Do not pack per-worktree refs: */
2306 if (ref_type(entry->name) != REF_TYPE_NORMAL)
2307 return 0;
2308
2309 /* ALWAYS pack tags */
2310 if (!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)
2311 return 0;
2312
2313 /* Do not pack symbolic or broken refs: */
ffeef642 2314 if ((entry->flag & REF_ISSYMREF) || !entry_resolves_to_object(entry))
7bd9bcf3
MH
2315 return 0;
2316
2317 /* Add a packed ref cache entry equivalent to the loose entry. */
2318 peel_status = peel_entry(entry, 1);
2319 if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)
2320 die("internal error peeling reference %s (%s)",
2321 entry->name, oid_to_hex(&entry->u.value.oid));
2322 packed_entry = find_ref(cb->packed_refs, entry->name);
2323 if (packed_entry) {
2324 /* Overwrite existing packed entry with info from loose entry */
2325 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;
2326 oidcpy(&packed_entry->u.value.oid, &entry->u.value.oid);
2327 } else {
2328 packed_entry = create_ref_entry(entry->name, entry->u.value.oid.hash,
2329 REF_ISPACKED | REF_KNOWS_PEELED, 0);
2330 add_ref(cb->packed_refs, packed_entry);
2331 }
2332 oidcpy(&packed_entry->u.value.peeled, &entry->u.value.peeled);
2333
2334 /* Schedule the loose reference for pruning if requested. */
2335 if ((cb->flags & PACK_REFS_PRUNE)) {
96ffc06f
JK
2336 struct ref_to_prune *n;
2337 FLEX_ALLOC_STR(n, name, entry->name);
7bd9bcf3 2338 hashcpy(n->sha1, entry->u.value.oid.hash);
7bd9bcf3
MH
2339 n->next = cb->ref_to_prune;
2340 cb->ref_to_prune = n;
2341 }
2342 return 0;
2343}
2344
a8f0db2d
MH
2345enum {
2346 REMOVE_EMPTY_PARENTS_REF = 0x01,
2347 REMOVE_EMPTY_PARENTS_REFLOG = 0x02
2348};
2349
7bd9bcf3 2350/*
a8f0db2d
MH
2351 * Remove empty parent directories associated with the specified
2352 * reference and/or its reflog, but spare [logs/]refs/ and immediate
2353 * subdirs. flags is a combination of REMOVE_EMPTY_PARENTS_REF and/or
2354 * REMOVE_EMPTY_PARENTS_REFLOG.
7bd9bcf3 2355 */
802de3da
NTND
2356static void try_remove_empty_parents(struct files_ref_store *refs,
2357 const char *refname,
2358 unsigned int flags)
7bd9bcf3 2359{
8bdaecb4 2360 struct strbuf buf = STRBUF_INIT;
e9dcc305 2361 struct strbuf sb = STRBUF_INIT;
7bd9bcf3
MH
2362 char *p, *q;
2363 int i;
8bdaecb4
MH
2364
2365 strbuf_addstr(&buf, refname);
2366 p = buf.buf;
7bd9bcf3
MH
2367 for (i = 0; i < 2; i++) { /* refs/{heads,tags,...}/ */
2368 while (*p && *p != '/')
2369 p++;
2370 /* tolerate duplicate slashes; see check_refname_format() */
2371 while (*p == '/')
2372 p++;
2373 }
8bdaecb4 2374 q = buf.buf + buf.len;
a8f0db2d 2375 while (flags & (REMOVE_EMPTY_PARENTS_REF | REMOVE_EMPTY_PARENTS_REFLOG)) {
7bd9bcf3
MH
2376 while (q > p && *q != '/')
2377 q--;
2378 while (q > p && *(q-1) == '/')
2379 q--;
2380 if (q == p)
2381 break;
8bdaecb4 2382 strbuf_setlen(&buf, q - buf.buf);
e9dcc305
NTND
2383
2384 strbuf_reset(&sb);
19e02f4f 2385 files_ref_path(refs, &sb, buf.buf);
e9dcc305 2386 if ((flags & REMOVE_EMPTY_PARENTS_REF) && rmdir(sb.buf))
a8f0db2d 2387 flags &= ~REMOVE_EMPTY_PARENTS_REF;
e9dcc305
NTND
2388
2389 strbuf_reset(&sb);
802de3da 2390 files_reflog_path(refs, &sb, buf.buf);
e9dcc305 2391 if ((flags & REMOVE_EMPTY_PARENTS_REFLOG) && rmdir(sb.buf))
a8f0db2d 2392 flags &= ~REMOVE_EMPTY_PARENTS_REFLOG;
7bd9bcf3 2393 }
8bdaecb4 2394 strbuf_release(&buf);
e9dcc305 2395 strbuf_release(&sb);
7bd9bcf3
MH
2396}
2397
2398/* make sure nobody touched the ref, and unlink */
2f40e954 2399static void prune_ref(struct files_ref_store *refs, struct ref_to_prune *r)
7bd9bcf3
MH
2400{
2401 struct ref_transaction *transaction;
2402 struct strbuf err = STRBUF_INIT;
2403
2404 if (check_refname_format(r->name, 0))
2405 return;
2406
2f40e954 2407 transaction = ref_store_transaction_begin(&refs->base, &err);
7bd9bcf3
MH
2408 if (!transaction ||
2409 ref_transaction_delete(transaction, r->name, r->sha1,
c52ce248 2410 REF_ISPRUNING | REF_NODEREF, NULL, &err) ||
7bd9bcf3
MH
2411 ref_transaction_commit(transaction, &err)) {
2412 ref_transaction_free(transaction);
2413 error("%s", err.buf);
2414 strbuf_release(&err);
2415 return;
2416 }
2417 ref_transaction_free(transaction);
2418 strbuf_release(&err);
7bd9bcf3
MH
2419}
2420
2f40e954 2421static void prune_refs(struct files_ref_store *refs, struct ref_to_prune *r)
7bd9bcf3
MH
2422{
2423 while (r) {
2f40e954 2424 prune_ref(refs, r);
7bd9bcf3
MH
2425 r = r->next;
2426 }
2427}
2428
8231527e 2429static int files_pack_refs(struct ref_store *ref_store, unsigned int flags)
7bd9bcf3 2430{
00eebe35 2431 struct files_ref_store *refs =
9e7ec634
NTND
2432 files_downcast(ref_store, REF_STORE_WRITE | REF_STORE_ODB,
2433 "pack_refs");
7bd9bcf3
MH
2434 struct pack_refs_cb_data cbdata;
2435
2436 memset(&cbdata, 0, sizeof(cbdata));
2437 cbdata.flags = flags;
2438
49c0df6a 2439 lock_packed_refs(refs, LOCK_DIE_ON_ERROR);
00eebe35 2440 cbdata.packed_refs = get_packed_refs(refs);
7bd9bcf3 2441
00eebe35 2442 do_for_each_entry_in_dir(get_loose_refs(refs), 0,
7bd9bcf3
MH
2443 pack_if_possible_fn, &cbdata);
2444
49c0df6a 2445 if (commit_packed_refs(refs))
7bd9bcf3
MH
2446 die_errno("unable to overwrite old ref-pack file");
2447
2f40e954 2448 prune_refs(refs, cbdata.ref_to_prune);
7bd9bcf3
MH
2449 return 0;
2450}
2451
2452/*
2453 * Rewrite the packed-refs file, omitting any refs listed in
2454 * 'refnames'. On error, leave packed-refs unchanged, write an error
2455 * message to 'err', and return a nonzero value.
2456 *
2457 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.
2458 */
0a95ac5f
MH
2459static int repack_without_refs(struct files_ref_store *refs,
2460 struct string_list *refnames, struct strbuf *err)
7bd9bcf3
MH
2461{
2462 struct ref_dir *packed;
2463 struct string_list_item *refname;
2464 int ret, needs_repacking = 0, removed = 0;
2465
32c597e7 2466 files_assert_main_repository(refs, "repack_without_refs");
7bd9bcf3
MH
2467 assert(err);
2468
2469 /* Look for a packed ref */
2470 for_each_string_list_item(refname, refnames) {
f0d21efc 2471 if (get_packed_ref(refs, refname->string)) {
7bd9bcf3
MH
2472 needs_repacking = 1;
2473 break;
2474 }
2475 }
2476
2477 /* Avoid locking if we have nothing to do */
2478 if (!needs_repacking)
2479 return 0; /* no refname exists in packed refs */
2480
49c0df6a 2481 if (lock_packed_refs(refs, 0)) {
33dfb9f3 2482 unable_to_lock_message(files_packed_refs_path(refs), errno, err);
7bd9bcf3
MH
2483 return -1;
2484 }
00eebe35 2485 packed = get_packed_refs(refs);
7bd9bcf3
MH
2486
2487 /* Remove refnames from the cache */
2488 for_each_string_list_item(refname, refnames)
2489 if (remove_entry(packed, refname->string) != -1)
2490 removed = 1;
2491 if (!removed) {
2492 /*
2493 * All packed entries disappeared while we were
2494 * acquiring the lock.
2495 */
49c0df6a 2496 rollback_packed_refs(refs);
7bd9bcf3
MH
2497 return 0;
2498 }
2499
2500 /* Write what remains */
49c0df6a 2501 ret = commit_packed_refs(refs);
7bd9bcf3
MH
2502 if (ret)
2503 strbuf_addf(err, "unable to overwrite old ref-pack file: %s",
2504 strerror(errno));
2505 return ret;
2506}
2507
a27dcf89
DT
2508static int files_delete_refs(struct ref_store *ref_store,
2509 struct string_list *refnames, unsigned int flags)
7bd9bcf3 2510{
0a95ac5f 2511 struct files_ref_store *refs =
9e7ec634 2512 files_downcast(ref_store, REF_STORE_WRITE, "delete_refs");
7bd9bcf3
MH
2513 struct strbuf err = STRBUF_INIT;
2514 int i, result = 0;
2515
2516 if (!refnames->nr)
2517 return 0;
2518
0a95ac5f 2519 result = repack_without_refs(refs, refnames, &err);
7bd9bcf3
MH
2520 if (result) {
2521 /*
2522 * If we failed to rewrite the packed-refs file, then
2523 * it is unsafe to try to remove loose refs, because
2524 * doing so might expose an obsolete packed value for
2525 * a reference that might even point at an object that
2526 * has been garbage collected.
2527 */
2528 if (refnames->nr == 1)
2529 error(_("could not delete reference %s: %s"),
2530 refnames->items[0].string, err.buf);
2531 else
2532 error(_("could not delete references: %s"), err.buf);
2533
2534 goto out;
2535 }
2536
2537 for (i = 0; i < refnames->nr; i++) {
2538 const char *refname = refnames->items[i].string;
2539
2f40e954 2540 if (refs_delete_ref(&refs->base, NULL, refname, NULL, flags))
7bd9bcf3
MH
2541 result |= error(_("could not remove reference %s"), refname);
2542 }
2543
2544out:
2545 strbuf_release(&err);
2546 return result;
2547}
2548
2549/*
2550 * People using contrib's git-new-workdir have .git/logs/refs ->
2551 * /some/other/path/.git/logs/refs, and that may live on another device.
2552 *
2553 * IOW, to avoid cross device rename errors, the temporary renamed log must
2554 * live into logs/refs.
2555 */
a5c1efd6 2556#define TMP_RENAMED_LOG "refs/.tmp-renamed-log"
7bd9bcf3 2557
e9dcc305
NTND
2558struct rename_cb {
2559 const char *tmp_renamed_log;
2560 int true_errno;
2561};
2562
2563static int rename_tmp_log_callback(const char *path, void *cb_data)
7bd9bcf3 2564{
e9dcc305 2565 struct rename_cb *cb = cb_data;
7bd9bcf3 2566
e9dcc305 2567 if (rename(cb->tmp_renamed_log, path)) {
6a7f3631
MH
2568 /*
2569 * rename(a, b) when b is an existing directory ought
2570 * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.
2571 * Sheesh. Record the true errno for error reporting,
2572 * but report EISDIR to raceproof_create_file() so
2573 * that it knows to retry.
2574 */
e9dcc305 2575 cb->true_errno = errno;
6a7f3631
MH
2576 if (errno == ENOTDIR)
2577 errno = EISDIR;
2578 return -1;
2579 } else {
2580 return 0;
7bd9bcf3 2581 }
6a7f3631 2582}
7bd9bcf3 2583
802de3da 2584static int rename_tmp_log(struct files_ref_store *refs, const char *newrefname)
6a7f3631 2585{
e9dcc305
NTND
2586 struct strbuf path = STRBUF_INIT;
2587 struct strbuf tmp = STRBUF_INIT;
2588 struct rename_cb cb;
2589 int ret;
6a7f3631 2590
802de3da
NTND
2591 files_reflog_path(refs, &path, newrefname);
2592 files_reflog_path(refs, &tmp, TMP_RENAMED_LOG);
e9dcc305
NTND
2593 cb.tmp_renamed_log = tmp.buf;
2594 ret = raceproof_create_file(path.buf, rename_tmp_log_callback, &cb);
6a7f3631
MH
2595 if (ret) {
2596 if (errno == EISDIR)
e9dcc305 2597 error("directory not empty: %s", path.buf);
6a7f3631 2598 else
990c98d2 2599 error("unable to move logfile %s to %s: %s",
e9dcc305
NTND
2600 tmp.buf, path.buf,
2601 strerror(cb.true_errno));
7bd9bcf3 2602 }
6a7f3631 2603
e9dcc305
NTND
2604 strbuf_release(&path);
2605 strbuf_release(&tmp);
7bd9bcf3
MH
2606 return ret;
2607}
2608
62665823
MH
2609static int files_verify_refname_available(struct ref_store *ref_store,
2610 const char *newname,
2611 const struct string_list *extras,
2612 const struct string_list *skip,
2613 struct strbuf *err)
7bd9bcf3 2614{
00eebe35 2615 struct files_ref_store *refs =
9e7ec634 2616 files_downcast(ref_store, REF_STORE_READ, "verify_refname_available");
00eebe35
MH
2617 struct ref_dir *packed_refs = get_packed_refs(refs);
2618 struct ref_dir *loose_refs = get_loose_refs(refs);
7bd9bcf3
MH
2619
2620 if (verify_refname_available_dir(newname, extras, skip,
2621 packed_refs, err) ||
2622 verify_refname_available_dir(newname, extras, skip,
2623 loose_refs, err))
2624 return -1;
2625
2626 return 0;
2627}
2628
7bd9bcf3
MH
2629static int write_ref_to_lockfile(struct ref_lock *lock,
2630 const unsigned char *sha1, struct strbuf *err);
f18a7892
MH
2631static int commit_ref_update(struct files_ref_store *refs,
2632 struct ref_lock *lock,
7bd9bcf3 2633 const unsigned char *sha1, const char *logmsg,
5d9b2de4 2634 struct strbuf *err);
7bd9bcf3 2635
9b6b40d9
DT
2636static int files_rename_ref(struct ref_store *ref_store,
2637 const char *oldrefname, const char *newrefname,
2638 const char *logmsg)
7bd9bcf3 2639{
9b6b40d9 2640 struct files_ref_store *refs =
9e7ec634 2641 files_downcast(ref_store, REF_STORE_WRITE, "rename_ref");
7bd9bcf3
MH
2642 unsigned char sha1[20], orig_sha1[20];
2643 int flag = 0, logmoved = 0;
2644 struct ref_lock *lock;
2645 struct stat loginfo;
e9dcc305
NTND
2646 struct strbuf sb_oldref = STRBUF_INIT;
2647 struct strbuf sb_newref = STRBUF_INIT;
2648 struct strbuf tmp_renamed_log = STRBUF_INIT;
2649 int log, ret;
7bd9bcf3
MH
2650 struct strbuf err = STRBUF_INIT;
2651
802de3da
NTND
2652 files_reflog_path(refs, &sb_oldref, oldrefname);
2653 files_reflog_path(refs, &sb_newref, newrefname);
2654 files_reflog_path(refs, &tmp_renamed_log, TMP_RENAMED_LOG);
e9dcc305
NTND
2655
2656 log = !lstat(sb_oldref.buf, &loginfo);
0a3f07d6
NTND
2657 if (log && S_ISLNK(loginfo.st_mode)) {
2658 ret = error("reflog for %s is a symlink", oldrefname);
2659 goto out;
2660 }
7bd9bcf3 2661
2f40e954
NTND
2662 if (!refs_resolve_ref_unsafe(&refs->base, oldrefname,
2663 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,
0a3f07d6
NTND
2664 orig_sha1, &flag)) {
2665 ret = error("refname %s not found", oldrefname);
2666 goto out;
2667 }
e711b1af 2668
0a3f07d6
NTND
2669 if (flag & REF_ISSYMREF) {
2670 ret = error("refname %s is a symbolic ref, renaming it is not supported",
2671 oldrefname);
2672 goto out;
2673 }
7d2df051 2674 if (!refs_rename_ref_available(&refs->base, oldrefname, newrefname)) {
0a3f07d6
NTND
2675 ret = 1;
2676 goto out;
2677 }
7bd9bcf3 2678
e9dcc305 2679 if (log && rename(sb_oldref.buf, tmp_renamed_log.buf)) {
a5c1efd6 2680 ret = error("unable to move logfile logs/%s to logs/"TMP_RENAMED_LOG": %s",
0a3f07d6
NTND
2681 oldrefname, strerror(errno));
2682 goto out;
2683 }
7bd9bcf3 2684
2f40e954
NTND
2685 if (refs_delete_ref(&refs->base, logmsg, oldrefname,
2686 orig_sha1, REF_NODEREF)) {
7bd9bcf3
MH
2687 error("unable to delete old %s", oldrefname);
2688 goto rollback;
2689 }
2690
12fd3496
DT
2691 /*
2692 * Since we are doing a shallow lookup, sha1 is not the
2693 * correct value to pass to delete_ref as old_sha1. But that
2694 * doesn't matter, because an old_sha1 check wouldn't add to
2695 * the safety anyway; we want to delete the reference whatever
2696 * its current value.
2697 */
2f40e954
NTND
2698 if (!refs_read_ref_full(&refs->base, newrefname,
2699 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,
2700 sha1, NULL) &&
2701 refs_delete_ref(&refs->base, NULL, newrefname,
2702 NULL, REF_NODEREF)) {
58364324 2703 if (errno == EISDIR) {
7bd9bcf3
MH
2704 struct strbuf path = STRBUF_INIT;
2705 int result;
2706
19e02f4f 2707 files_ref_path(refs, &path, newrefname);
7bd9bcf3
MH
2708 result = remove_empty_directories(&path);
2709 strbuf_release(&path);
2710
2711 if (result) {
2712 error("Directory not empty: %s", newrefname);
2713 goto rollback;
2714 }
2715 } else {
2716 error("unable to delete existing %s", newrefname);
2717 goto rollback;
2718 }
2719 }
2720
802de3da 2721 if (log && rename_tmp_log(refs, newrefname))
7bd9bcf3
MH
2722 goto rollback;
2723
2724 logmoved = log;
2725
7eb27cdf
MH
2726 lock = lock_ref_sha1_basic(refs, newrefname, NULL, NULL, NULL,
2727 REF_NODEREF, NULL, &err);
7bd9bcf3
MH
2728 if (!lock) {
2729 error("unable to rename '%s' to '%s': %s", oldrefname, newrefname, err.buf);
2730 strbuf_release(&err);
2731 goto rollback;
2732 }
2733 hashcpy(lock->old_oid.hash, orig_sha1);
2734
2735 if (write_ref_to_lockfile(lock, orig_sha1, &err) ||
f18a7892 2736 commit_ref_update(refs, lock, orig_sha1, logmsg, &err)) {
7bd9bcf3
MH
2737 error("unable to write current sha1 into %s: %s", newrefname, err.buf);
2738 strbuf_release(&err);
2739 goto rollback;
2740 }
2741
0a3f07d6
NTND
2742 ret = 0;
2743 goto out;
7bd9bcf3
MH
2744
2745 rollback:
7eb27cdf
MH
2746 lock = lock_ref_sha1_basic(refs, oldrefname, NULL, NULL, NULL,
2747 REF_NODEREF, NULL, &err);
7bd9bcf3
MH
2748 if (!lock) {
2749 error("unable to lock %s for rollback: %s", oldrefname, err.buf);
2750 strbuf_release(&err);
2751 goto rollbacklog;
2752 }
2753
2754 flag = log_all_ref_updates;
341fb286 2755 log_all_ref_updates = LOG_REFS_NONE;
7bd9bcf3 2756 if (write_ref_to_lockfile(lock, orig_sha1, &err) ||
f18a7892 2757 commit_ref_update(refs, lock, orig_sha1, NULL, &err)) {
7bd9bcf3
MH
2758 error("unable to write current sha1 into %s: %s", oldrefname, err.buf);
2759 strbuf_release(&err);
2760 }
2761 log_all_ref_updates = flag;
2762
2763 rollbacklog:
e9dcc305 2764 if (logmoved && rename(sb_newref.buf, sb_oldref.buf))
7bd9bcf3
MH
2765 error("unable to restore logfile %s from %s: %s",
2766 oldrefname, newrefname, strerror(errno));
2767 if (!logmoved && log &&
e9dcc305 2768 rename(tmp_renamed_log.buf, sb_oldref.buf))
a5c1efd6 2769 error("unable to restore logfile %s from logs/"TMP_RENAMED_LOG": %s",
7bd9bcf3 2770 oldrefname, strerror(errno));
0a3f07d6
NTND
2771 ret = 1;
2772 out:
e9dcc305
NTND
2773 strbuf_release(&sb_newref);
2774 strbuf_release(&sb_oldref);
2775 strbuf_release(&tmp_renamed_log);
2776
0a3f07d6 2777 return ret;
7bd9bcf3
MH
2778}
2779
2780static int close_ref(struct ref_lock *lock)
2781{
2782 if (close_lock_file(lock->lk))
2783 return -1;
2784 return 0;
2785}
2786
2787static int commit_ref(struct ref_lock *lock)
2788{
5387c0d8
MH
2789 char *path = get_locked_file_path(lock->lk);
2790 struct stat st;
2791
2792 if (!lstat(path, &st) && S_ISDIR(st.st_mode)) {
2793 /*
2794 * There is a directory at the path we want to rename
2795 * the lockfile to. Hopefully it is empty; try to
2796 * delete it.
2797 */
2798 size_t len = strlen(path);
2799 struct strbuf sb_path = STRBUF_INIT;
2800
2801 strbuf_attach(&sb_path, path, len, len);
2802
2803 /*
2804 * If this fails, commit_lock_file() will also fail
2805 * and will report the problem.
2806 */
2807 remove_empty_directories(&sb_path);
2808 strbuf_release(&sb_path);
2809 } else {
2810 free(path);
2811 }
2812
7bd9bcf3
MH
2813 if (commit_lock_file(lock->lk))
2814 return -1;
2815 return 0;
2816}
2817
1fb0c809
MH
2818static int open_or_create_logfile(const char *path, void *cb)
2819{
2820 int *fd = cb;
2821
2822 *fd = open(path, O_APPEND | O_WRONLY | O_CREAT, 0666);
2823 return (*fd < 0) ? -1 : 0;
2824}
2825
7bd9bcf3 2826/*
4533e534
MH
2827 * Create a reflog for a ref. If force_create = 0, only create the
2828 * reflog for certain refs (those for which should_autocreate_reflog
2829 * returns non-zero). Otherwise, create it regardless of the reference
2830 * name. If the logfile already existed or was created, return 0 and
2831 * set *logfd to the file descriptor opened for appending to the file.
2832 * If no logfile exists and we decided not to create one, return 0 and
2833 * set *logfd to -1. On failure, fill in *err, set *logfd to -1, and
2834 * return -1.
7bd9bcf3 2835 */
802de3da
NTND
2836static int log_ref_setup(struct files_ref_store *refs,
2837 const char *refname, int force_create,
4533e534 2838 int *logfd, struct strbuf *err)
7bd9bcf3 2839{
802de3da
NTND
2840 struct strbuf logfile_sb = STRBUF_INIT;
2841 char *logfile;
2842
2843 files_reflog_path(refs, &logfile_sb, refname);
2844 logfile = strbuf_detach(&logfile_sb, NULL);
7bd9bcf3 2845
7bd9bcf3 2846 if (force_create || should_autocreate_reflog(refname)) {
4533e534 2847 if (raceproof_create_file(logfile, open_or_create_logfile, logfd)) {
1fb0c809
MH
2848 if (errno == ENOENT)
2849 strbuf_addf(err, "unable to create directory for '%s': "
4533e534 2850 "%s", logfile, strerror(errno));
1fb0c809
MH
2851 else if (errno == EISDIR)
2852 strbuf_addf(err, "there are still logs under '%s'",
4533e534 2853 logfile);
1fb0c809 2854 else
854bda6b 2855 strbuf_addf(err, "unable to append to '%s': %s",
4533e534 2856 logfile, strerror(errno));
7bd9bcf3 2857
4533e534 2858 goto error;
7bd9bcf3 2859 }
854bda6b 2860 } else {
4533e534 2861 *logfd = open(logfile, O_APPEND | O_WRONLY, 0666);
e404f459 2862 if (*logfd < 0) {
854bda6b
MH
2863 if (errno == ENOENT || errno == EISDIR) {
2864 /*
2865 * The logfile doesn't already exist,
2866 * but that is not an error; it only
2867 * means that we won't write log
2868 * entries to it.
2869 */
2870 ;
2871 } else {
2872 strbuf_addf(err, "unable to append to '%s': %s",
4533e534
MH
2873 logfile, strerror(errno));
2874 goto error;
854bda6b 2875 }
7bd9bcf3
MH
2876 }
2877 }
2878
e404f459 2879 if (*logfd >= 0)
4533e534 2880 adjust_shared_perm(logfile);
854bda6b 2881
4533e534 2882 free(logfile);
7bd9bcf3 2883 return 0;
7bd9bcf3 2884
4533e534
MH
2885error:
2886 free(logfile);
2887 return -1;
7bd9bcf3 2888}
7bd9bcf3 2889
e3688bd6
DT
2890static int files_create_reflog(struct ref_store *ref_store,
2891 const char *refname, int force_create,
2892 struct strbuf *err)
7bd9bcf3 2893{
802de3da 2894 struct files_ref_store *refs =
9e7ec634 2895 files_downcast(ref_store, REF_STORE_WRITE, "create_reflog");
e404f459 2896 int fd;
7bd9bcf3 2897
802de3da 2898 if (log_ref_setup(refs, refname, force_create, &fd, err))
4533e534
MH
2899 return -1;
2900
e404f459
MH
2901 if (fd >= 0)
2902 close(fd);
4533e534
MH
2903
2904 return 0;
7bd9bcf3
MH
2905}
2906
2907static int log_ref_write_fd(int fd, const unsigned char *old_sha1,
2908 const unsigned char *new_sha1,
2909 const char *committer, const char *msg)
2910{
2911 int msglen, written;
2912 unsigned maxlen, len;
2913 char *logrec;
2914
2915 msglen = msg ? strlen(msg) : 0;
2916 maxlen = strlen(committer) + msglen + 100;
2917 logrec = xmalloc(maxlen);
2918 len = xsnprintf(logrec, maxlen, "%s %s %s\n",
2919 sha1_to_hex(old_sha1),
2920 sha1_to_hex(new_sha1),
2921 committer);
2922 if (msglen)
2923 len += copy_reflog_msg(logrec + len - 1, msg) - 1;
2924
2925 written = len <= maxlen ? write_in_full(fd, logrec, len) : -1;
2926 free(logrec);
2927 if (written != len)
2928 return -1;
2929
2930 return 0;
2931}
2932
802de3da
NTND
2933static int files_log_ref_write(struct files_ref_store *refs,
2934 const char *refname, const unsigned char *old_sha1,
11f8457f
NTND
2935 const unsigned char *new_sha1, const char *msg,
2936 int flags, struct strbuf *err)
7bd9bcf3 2937{
e404f459 2938 int logfd, result;
7bd9bcf3 2939
341fb286
CW
2940 if (log_all_ref_updates == LOG_REFS_UNSET)
2941 log_all_ref_updates = is_bare_repository() ? LOG_REFS_NONE : LOG_REFS_NORMAL;
7bd9bcf3 2942
802de3da
NTND
2943 result = log_ref_setup(refs, refname,
2944 flags & REF_FORCE_CREATE_REFLOG,
4533e534 2945 &logfd, err);
7bd9bcf3
MH
2946
2947 if (result)
2948 return result;
2949
7bd9bcf3
MH
2950 if (logfd < 0)
2951 return 0;
2952 result = log_ref_write_fd(logfd, old_sha1, new_sha1,
2953 git_committer_info(0), msg);
2954 if (result) {
e9dcc305 2955 struct strbuf sb = STRBUF_INIT;
87b21e05
MH
2956 int save_errno = errno;
2957
802de3da 2958 files_reflog_path(refs, &sb, refname);
87b21e05 2959 strbuf_addf(err, "unable to append to '%s': %s",
e9dcc305
NTND
2960 sb.buf, strerror(save_errno));
2961 strbuf_release(&sb);
7bd9bcf3
MH
2962 close(logfd);
2963 return -1;
2964 }
2965 if (close(logfd)) {
e9dcc305 2966 struct strbuf sb = STRBUF_INIT;
87b21e05
MH
2967 int save_errno = errno;
2968
802de3da 2969 files_reflog_path(refs, &sb, refname);
87b21e05 2970 strbuf_addf(err, "unable to append to '%s': %s",
e9dcc305
NTND
2971 sb.buf, strerror(save_errno));
2972 strbuf_release(&sb);
7bd9bcf3
MH
2973 return -1;
2974 }
2975 return 0;
2976}
2977
7bd9bcf3
MH
2978/*
2979 * Write sha1 into the open lockfile, then close the lockfile. On
2980 * errors, rollback the lockfile, fill in *err and
2981 * return -1.
2982 */
2983static int write_ref_to_lockfile(struct ref_lock *lock,
2984 const unsigned char *sha1, struct strbuf *err)
2985{
2986 static char term = '\n';
2987 struct object *o;
2988 int fd;
2989
2990 o = parse_object(sha1);
2991 if (!o) {
2992 strbuf_addf(err,
0568c8e9 2993 "trying to write ref '%s' with nonexistent object %s",
7bd9bcf3
MH
2994 lock->ref_name, sha1_to_hex(sha1));
2995 unlock_ref(lock);
2996 return -1;
2997 }
2998 if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
2999 strbuf_addf(err,
0568c8e9 3000 "trying to write non-commit object %s to branch '%s'",
7bd9bcf3
MH
3001 sha1_to_hex(sha1), lock->ref_name);
3002 unlock_ref(lock);
3003 return -1;
3004 }
3005 fd = get_lock_file_fd(lock->lk);
3006 if (write_in_full(fd, sha1_to_hex(sha1), 40) != 40 ||
3007 write_in_full(fd, &term, 1) != 1 ||
3008 close_ref(lock) < 0) {
3009 strbuf_addf(err,
0568c8e9 3010 "couldn't write '%s'", get_lock_file_path(lock->lk));
7bd9bcf3
MH
3011 unlock_ref(lock);
3012 return -1;
3013 }
3014 return 0;
3015}
3016
3017/*
3018 * Commit a change to a loose reference that has already been written
3019 * to the loose reference lockfile. Also update the reflogs if
3020 * necessary, using the specified lockmsg (which can be NULL).
3021 */
f18a7892
MH
3022static int commit_ref_update(struct files_ref_store *refs,
3023 struct ref_lock *lock,
7bd9bcf3 3024 const unsigned char *sha1, const char *logmsg,
5d9b2de4 3025 struct strbuf *err)
7bd9bcf3 3026{
32c597e7 3027 files_assert_main_repository(refs, "commit_ref_update");
00eebe35
MH
3028
3029 clear_loose_ref_cache(refs);
802de3da
NTND
3030 if (files_log_ref_write(refs, lock->ref_name,
3031 lock->old_oid.hash, sha1,
81b1b6d4 3032 logmsg, 0, err)) {
7bd9bcf3 3033 char *old_msg = strbuf_detach(err, NULL);
0568c8e9 3034 strbuf_addf(err, "cannot update the ref '%s': %s",
7bd9bcf3
MH
3035 lock->ref_name, old_msg);
3036 free(old_msg);
3037 unlock_ref(lock);
3038 return -1;
3039 }
7a418f3a
MH
3040
3041 if (strcmp(lock->ref_name, "HEAD") != 0) {
7bd9bcf3
MH
3042 /*
3043 * Special hack: If a branch is updated directly and HEAD
3044 * points to it (may happen on the remote side of a push
3045 * for example) then logically the HEAD reflog should be
3046 * updated too.
3047 * A generic solution implies reverse symref information,
3048 * but finding all symrefs pointing to the given branch
3049 * would be rather costly for this rare event (the direct
3050 * update of a branch) to be worth it. So let's cheat and
3051 * check with HEAD only which should cover 99% of all usage
3052 * scenarios (even 100% of the default ones).
3053 */
3054 unsigned char head_sha1[20];
3055 int head_flag;
3056 const char *head_ref;
7a418f3a 3057
2f40e954
NTND
3058 head_ref = refs_resolve_ref_unsafe(&refs->base, "HEAD",
3059 RESOLVE_REF_READING,
3060 head_sha1, &head_flag);
7bd9bcf3
MH
3061 if (head_ref && (head_flag & REF_ISSYMREF) &&
3062 !strcmp(head_ref, lock->ref_name)) {
3063 struct strbuf log_err = STRBUF_INIT;
802de3da
NTND
3064 if (files_log_ref_write(refs, "HEAD",
3065 lock->old_oid.hash, sha1,
3066 logmsg, 0, &log_err)) {
7bd9bcf3
MH
3067 error("%s", log_err.buf);
3068 strbuf_release(&log_err);
3069 }
3070 }
3071 }
7a418f3a 3072
7bd9bcf3 3073 if (commit_ref(lock)) {
0568c8e9 3074 strbuf_addf(err, "couldn't set '%s'", lock->ref_name);
7bd9bcf3
MH
3075 unlock_ref(lock);
3076 return -1;
3077 }
3078
3079 unlock_ref(lock);
3080 return 0;
3081}
3082
370e5ad6 3083static int create_ref_symlink(struct ref_lock *lock, const char *target)
7bd9bcf3 3084{
370e5ad6 3085 int ret = -1;
7bd9bcf3 3086#ifndef NO_SYMLINK_HEAD
370e5ad6
JK
3087 char *ref_path = get_locked_file_path(lock->lk);
3088 unlink(ref_path);
3089 ret = symlink(target, ref_path);
3090 free(ref_path);
3091
3092 if (ret)
7bd9bcf3 3093 fprintf(stderr, "no symlink - falling back to symbolic ref\n");
7bd9bcf3 3094#endif
370e5ad6
JK
3095 return ret;
3096}
7bd9bcf3 3097
802de3da
NTND
3098static void update_symref_reflog(struct files_ref_store *refs,
3099 struct ref_lock *lock, const char *refname,
370e5ad6
JK
3100 const char *target, const char *logmsg)
3101{
3102 struct strbuf err = STRBUF_INIT;
3103 unsigned char new_sha1[20];
2f40e954
NTND
3104 if (logmsg &&
3105 !refs_read_ref_full(&refs->base, target,
3106 RESOLVE_REF_READING, new_sha1, NULL) &&
802de3da
NTND
3107 files_log_ref_write(refs, refname, lock->old_oid.hash,
3108 new_sha1, logmsg, 0, &err)) {
7bd9bcf3
MH
3109 error("%s", err.buf);
3110 strbuf_release(&err);
3111 }
370e5ad6 3112}
7bd9bcf3 3113
802de3da
NTND
3114static int create_symref_locked(struct files_ref_store *refs,
3115 struct ref_lock *lock, const char *refname,
370e5ad6
JK
3116 const char *target, const char *logmsg)
3117{
3118 if (prefer_symlink_refs && !create_ref_symlink(lock, target)) {
802de3da 3119 update_symref_reflog(refs, lock, refname, target, logmsg);
370e5ad6
JK
3120 return 0;
3121 }
3122
3123 if (!fdopen_lock_file(lock->lk, "w"))
3124 return error("unable to fdopen %s: %s",
3125 lock->lk->tempfile.filename.buf, strerror(errno));
3126
802de3da 3127 update_symref_reflog(refs, lock, refname, target, logmsg);
396da8f7 3128
370e5ad6
JK
3129 /* no error check; commit_ref will check ferror */
3130 fprintf(lock->lk->tempfile.fp, "ref: %s\n", target);
3131 if (commit_ref(lock) < 0)
3132 return error("unable to write symref for %s: %s", refname,
3133 strerror(errno));
7bd9bcf3
MH
3134 return 0;
3135}
3136
284689ba
MH
3137static int files_create_symref(struct ref_store *ref_store,
3138 const char *refname, const char *target,
3139 const char *logmsg)
370e5ad6 3140{
7eb27cdf 3141 struct files_ref_store *refs =
9e7ec634 3142 files_downcast(ref_store, REF_STORE_WRITE, "create_symref");
370e5ad6
JK
3143 struct strbuf err = STRBUF_INIT;
3144 struct ref_lock *lock;
3145 int ret;
3146
7eb27cdf
MH
3147 lock = lock_ref_sha1_basic(refs, refname, NULL,
3148 NULL, NULL, REF_NODEREF, NULL,
370e5ad6
JK
3149 &err);
3150 if (!lock) {
3151 error("%s", err.buf);
3152 strbuf_release(&err);
3153 return -1;
3154 }
3155
802de3da 3156 ret = create_symref_locked(refs, lock, refname, target, logmsg);
370e5ad6
JK
3157 unlock_ref(lock);
3158 return ret;
3159}
3160
39ee4c6c 3161int set_worktree_head_symref(const char *gitdir, const char *target, const char *logmsg)
2233066e 3162{
802de3da
NTND
3163 /*
3164 * FIXME: this obviously will not work well for future refs
3165 * backends. This function needs to die.
3166 */
3167 struct files_ref_store *refs =
9e7ec634
NTND
3168 files_downcast(get_main_ref_store(),
3169 REF_STORE_WRITE,
3170 "set_head_symref");
802de3da 3171
2233066e
KY
3172 static struct lock_file head_lock;
3173 struct ref_lock *lock;
2233066e
KY
3174 struct strbuf head_path = STRBUF_INIT;
3175 const char *head_rel;
3176 int ret;
3177
3178 strbuf_addf(&head_path, "%s/HEAD", absolute_path(gitdir));
3179 if (hold_lock_file_for_update(&head_lock, head_path.buf,
3180 LOCK_NO_DEREF) < 0) {
18eb3a9c
KY
3181 struct strbuf err = STRBUF_INIT;
3182 unable_to_lock_message(head_path.buf, errno, &err);
2233066e
KY
3183 error("%s", err.buf);
3184 strbuf_release(&err);
3185 strbuf_release(&head_path);
3186 return -1;
3187 }
3188
3189 /* head_rel will be "HEAD" for the main tree, "worktrees/wt/HEAD" for
3190 linked trees */
3191 head_rel = remove_leading_path(head_path.buf,
3192 absolute_path(get_git_common_dir()));
3193 /* to make use of create_symref_locked(), initialize ref_lock */
3194 lock = xcalloc(1, sizeof(struct ref_lock));
3195 lock->lk = &head_lock;
3196 lock->ref_name = xstrdup(head_rel);
2233066e 3197
802de3da 3198 ret = create_symref_locked(refs, lock, head_rel, target, logmsg);
2233066e
KY
3199
3200 unlock_ref(lock); /* will free lock */
3201 strbuf_release(&head_path);
3202 return ret;
3203}
3204
e3688bd6
DT
3205static int files_reflog_exists(struct ref_store *ref_store,
3206 const char *refname)
7bd9bcf3 3207{
802de3da 3208 struct files_ref_store *refs =
9e7ec634 3209 files_downcast(ref_store, REF_STORE_READ, "reflog_exists");
e9dcc305 3210 struct strbuf sb = STRBUF_INIT;
7bd9bcf3 3211 struct stat st;
e9dcc305 3212 int ret;
7bd9bcf3 3213
802de3da 3214 files_reflog_path(refs, &sb, refname);
e9dcc305
NTND
3215 ret = !lstat(sb.buf, &st) && S_ISREG(st.st_mode);
3216 strbuf_release(&sb);
3217 return ret;
7bd9bcf3
MH
3218}
3219
e3688bd6
DT
3220static int files_delete_reflog(struct ref_store *ref_store,
3221 const char *refname)
7bd9bcf3 3222{
802de3da 3223 struct files_ref_store *refs =
9e7ec634 3224 files_downcast(ref_store, REF_STORE_WRITE, "delete_reflog");
e9dcc305
NTND
3225 struct strbuf sb = STRBUF_INIT;
3226 int ret;
3227
802de3da 3228 files_reflog_path(refs, &sb, refname);
e9dcc305
NTND
3229 ret = remove_path(sb.buf);
3230 strbuf_release(&sb);
3231 return ret;
7bd9bcf3
MH
3232}
3233
3234static int show_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn, void *cb_data)
3235{
9461d272 3236 struct object_id ooid, noid;
7bd9bcf3
MH
3237 char *email_end, *message;
3238 unsigned long timestamp;
3239 int tz;
43bc3b6c 3240 const char *p = sb->buf;
7bd9bcf3
MH
3241
3242 /* old SP new SP name <email> SP time TAB msg LF */
43bc3b6c 3243 if (!sb->len || sb->buf[sb->len - 1] != '\n' ||
3244 parse_oid_hex(p, &ooid, &p) || *p++ != ' ' ||
3245 parse_oid_hex(p, &noid, &p) || *p++ != ' ' ||
3246 !(email_end = strchr(p, '>')) ||
7bd9bcf3
MH
3247 email_end[1] != ' ' ||
3248 !(timestamp = strtoul(email_end + 2, &message, 10)) ||
3249 !message || message[0] != ' ' ||
3250 (message[1] != '+' && message[1] != '-') ||
3251 !isdigit(message[2]) || !isdigit(message[3]) ||
3252 !isdigit(message[4]) || !isdigit(message[5]))
3253 return 0; /* corrupt? */
3254 email_end[1] = '\0';
3255 tz = strtol(message + 1, NULL, 10);
3256 if (message[6] != '\t')
3257 message += 6;
3258 else
3259 message += 7;
43bc3b6c 3260 return fn(&ooid, &noid, p, timestamp, tz, message, cb_data);
7bd9bcf3
MH
3261}
3262
3263static char *find_beginning_of_line(char *bob, char *scan)
3264{
3265 while (bob < scan && *(--scan) != '\n')
3266 ; /* keep scanning backwards */
3267 /*
3268 * Return either beginning of the buffer, or LF at the end of
3269 * the previous line.
3270 */
3271 return scan;
3272}
3273
e3688bd6
DT
3274static int files_for_each_reflog_ent_reverse(struct ref_store *ref_store,
3275 const char *refname,
3276 each_reflog_ent_fn fn,
3277 void *cb_data)
7bd9bcf3 3278{
802de3da 3279 struct files_ref_store *refs =
9e7ec634
NTND
3280 files_downcast(ref_store, REF_STORE_READ,
3281 "for_each_reflog_ent_reverse");
7bd9bcf3
MH
3282 struct strbuf sb = STRBUF_INIT;
3283 FILE *logfp;
3284 long pos;
3285 int ret = 0, at_tail = 1;
3286
802de3da 3287 files_reflog_path(refs, &sb, refname);
e9dcc305
NTND
3288 logfp = fopen(sb.buf, "r");
3289 strbuf_release(&sb);
7bd9bcf3
MH
3290 if (!logfp)
3291 return -1;
3292
3293 /* Jump to the end */
3294 if (fseek(logfp, 0, SEEK_END) < 0)
3295 return error("cannot seek back reflog for %s: %s",
3296 refname, strerror(errno));
3297 pos = ftell(logfp);
3298 while (!ret && 0 < pos) {
3299 int cnt;
3300 size_t nread;
3301 char buf[BUFSIZ];
3302 char *endp, *scanp;
3303
3304 /* Fill next block from the end */
3305 cnt = (sizeof(buf) < pos) ? sizeof(buf) : pos;
3306 if (fseek(logfp, pos - cnt, SEEK_SET))
3307 return error("cannot seek back reflog for %s: %s",
3308 refname, strerror(errno));
3309 nread = fread(buf, cnt, 1, logfp);
3310 if (nread != 1)
3311 return error("cannot read %d bytes from reflog for %s: %s",
3312 cnt, refname, strerror(errno));
3313 pos -= cnt;
3314
3315 scanp = endp = buf + cnt;
3316 if (at_tail && scanp[-1] == '\n')
3317 /* Looking at the final LF at the end of the file */
3318 scanp--;
3319 at_tail = 0;
3320
3321 while (buf < scanp) {
3322 /*
3323 * terminating LF of the previous line, or the beginning
3324 * of the buffer.
3325 */
3326 char *bp;
3327
3328 bp = find_beginning_of_line(buf, scanp);
3329
3330 if (*bp == '\n') {
3331 /*
3332 * The newline is the end of the previous line,
3333 * so we know we have complete line starting
3334 * at (bp + 1). Prefix it onto any prior data
3335 * we collected for the line and process it.
3336 */
3337 strbuf_splice(&sb, 0, 0, bp + 1, endp - (bp + 1));
3338 scanp = bp;
3339 endp = bp + 1;
3340 ret = show_one_reflog_ent(&sb, fn, cb_data);
3341 strbuf_reset(&sb);
3342 if (ret)
3343 break;
3344 } else if (!pos) {
3345 /*
3346 * We are at the start of the buffer, and the
3347 * start of the file; there is no previous
3348 * line, and we have everything for this one.
3349 * Process it, and we can end the loop.
3350 */
3351 strbuf_splice(&sb, 0, 0, buf, endp - buf);
3352 ret = show_one_reflog_ent(&sb, fn, cb_data);
3353 strbuf_reset(&sb);
3354 break;
3355 }
3356
3357 if (bp == buf) {
3358 /*
3359 * We are at the start of the buffer, and there
3360 * is more file to read backwards. Which means
3361 * we are in the middle of a line. Note that we
3362 * may get here even if *bp was a newline; that
3363 * just means we are at the exact end of the
3364 * previous line, rather than some spot in the
3365 * middle.
3366 *
3367 * Save away what we have to be combined with
3368 * the data from the next read.
3369 */
3370 strbuf_splice(&sb, 0, 0, buf, endp - buf);
3371 break;
3372 }
3373 }
3374
3375 }
3376 if (!ret && sb.len)
3377 die("BUG: reverse reflog parser had leftover data");
3378
3379 fclose(logfp);
3380 strbuf_release(&sb);
3381 return ret;
3382}
3383
e3688bd6
DT
3384static int files_for_each_reflog_ent(struct ref_store *ref_store,
3385 const char *refname,
3386 each_reflog_ent_fn fn, void *cb_data)
7bd9bcf3 3387{
802de3da 3388 struct files_ref_store *refs =
9e7ec634
NTND
3389 files_downcast(ref_store, REF_STORE_READ,
3390 "for_each_reflog_ent");
7bd9bcf3
MH
3391 FILE *logfp;
3392 struct strbuf sb = STRBUF_INIT;
3393 int ret = 0;
3394
802de3da 3395 files_reflog_path(refs, &sb, refname);
e9dcc305
NTND
3396 logfp = fopen(sb.buf, "r");
3397 strbuf_release(&sb);
7bd9bcf3
MH
3398 if (!logfp)
3399 return -1;
3400
3401 while (!ret && !strbuf_getwholeline(&sb, logfp, '\n'))
3402 ret = show_one_reflog_ent(&sb, fn, cb_data);
3403 fclose(logfp);
3404 strbuf_release(&sb);
3405 return ret;
3406}
7bd9bcf3 3407
2880d16f
MH
3408struct files_reflog_iterator {
3409 struct ref_iterator base;
7bd9bcf3 3410
2f40e954 3411 struct ref_store *ref_store;
2880d16f
MH
3412 struct dir_iterator *dir_iterator;
3413 struct object_id oid;
3414};
7bd9bcf3 3415
2880d16f
MH
3416static int files_reflog_iterator_advance(struct ref_iterator *ref_iterator)
3417{
3418 struct files_reflog_iterator *iter =
3419 (struct files_reflog_iterator *)ref_iterator;
3420 struct dir_iterator *diter = iter->dir_iterator;
3421 int ok;
3422
3423 while ((ok = dir_iterator_advance(diter)) == ITER_OK) {
3424 int flags;
3425
3426 if (!S_ISREG(diter->st.st_mode))
7bd9bcf3 3427 continue;
2880d16f
MH
3428 if (diter->basename[0] == '.')
3429 continue;
3430 if (ends_with(diter->basename, ".lock"))
7bd9bcf3 3431 continue;
7bd9bcf3 3432
2f40e954
NTND
3433 if (refs_read_ref_full(iter->ref_store,
3434 diter->relative_path, 0,
3435 iter->oid.hash, &flags)) {
2880d16f
MH
3436 error("bad ref for %s", diter->path.buf);
3437 continue;
7bd9bcf3 3438 }
2880d16f
MH
3439
3440 iter->base.refname = diter->relative_path;
3441 iter->base.oid = &iter->oid;
3442 iter->base.flags = flags;
3443 return ITER_OK;
7bd9bcf3 3444 }
2880d16f
MH
3445
3446 iter->dir_iterator = NULL;
3447 if (ref_iterator_abort(ref_iterator) == ITER_ERROR)
3448 ok = ITER_ERROR;
3449 return ok;
3450}
3451
3452static int files_reflog_iterator_peel(struct ref_iterator *ref_iterator,
3453 struct object_id *peeled)
3454{
3455 die("BUG: ref_iterator_peel() called for reflog_iterator");
3456}
3457
3458static int files_reflog_iterator_abort(struct ref_iterator *ref_iterator)
3459{
3460 struct files_reflog_iterator *iter =
3461 (struct files_reflog_iterator *)ref_iterator;
3462 int ok = ITER_DONE;
3463
3464 if (iter->dir_iterator)
3465 ok = dir_iterator_abort(iter->dir_iterator);
3466
3467 base_ref_iterator_free(ref_iterator);
3468 return ok;
3469}
3470
3471static struct ref_iterator_vtable files_reflog_iterator_vtable = {
3472 files_reflog_iterator_advance,
3473 files_reflog_iterator_peel,
3474 files_reflog_iterator_abort
3475};
3476
e3688bd6 3477static struct ref_iterator *files_reflog_iterator_begin(struct ref_store *ref_store)
2880d16f 3478{
802de3da 3479 struct files_ref_store *refs =
9e7ec634
NTND
3480 files_downcast(ref_store, REF_STORE_READ,
3481 "reflog_iterator_begin");
2880d16f
MH
3482 struct files_reflog_iterator *iter = xcalloc(1, sizeof(*iter));
3483 struct ref_iterator *ref_iterator = &iter->base;
e9dcc305 3484 struct strbuf sb = STRBUF_INIT;
2880d16f
MH
3485
3486 base_ref_iterator_init(ref_iterator, &files_reflog_iterator_vtable);
802de3da 3487 files_reflog_path(refs, &sb, NULL);
e9dcc305 3488 iter->dir_iterator = dir_iterator_begin(sb.buf);
2f40e954 3489 iter->ref_store = ref_store;
e9dcc305 3490 strbuf_release(&sb);
2880d16f 3491 return ref_iterator;
7bd9bcf3
MH
3492}
3493
7bd9bcf3
MH
3494static int ref_update_reject_duplicates(struct string_list *refnames,
3495 struct strbuf *err)
3496{
3497 int i, n = refnames->nr;
3498
3499 assert(err);
3500
3501 for (i = 1; i < n; i++)
3502 if (!strcmp(refnames->items[i - 1].string, refnames->items[i].string)) {
3503 strbuf_addf(err,
0568c8e9 3504 "multiple updates for ref '%s' not allowed.",
7bd9bcf3
MH
3505 refnames->items[i].string);
3506 return 1;
3507 }
3508 return 0;
3509}
3510
165056b2 3511/*
92b1551b
MH
3512 * If update is a direct update of head_ref (the reference pointed to
3513 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.
3514 */
3515static int split_head_update(struct ref_update *update,
3516 struct ref_transaction *transaction,
3517 const char *head_ref,
3518 struct string_list *affected_refnames,
3519 struct strbuf *err)
3520{
3521 struct string_list_item *item;
3522 struct ref_update *new_update;
3523
3524 if ((update->flags & REF_LOG_ONLY) ||
3525 (update->flags & REF_ISPRUNING) ||
3526 (update->flags & REF_UPDATE_VIA_HEAD))
3527 return 0;
3528
3529 if (strcmp(update->refname, head_ref))
3530 return 0;
3531
3532 /*
3533 * First make sure that HEAD is not already in the
3534 * transaction. This insertion is O(N) in the transaction
3535 * size, but it happens at most once per transaction.
3536 */
3537 item = string_list_insert(affected_refnames, "HEAD");
3538 if (item->util) {
3539 /* An entry already existed */
3540 strbuf_addf(err,
3541 "multiple updates for 'HEAD' (including one "
3542 "via its referent '%s') are not allowed",
3543 update->refname);
3544 return TRANSACTION_NAME_CONFLICT;
3545 }
3546
3547 new_update = ref_transaction_add_update(
3548 transaction, "HEAD",
3549 update->flags | REF_LOG_ONLY | REF_NODEREF,
3550 update->new_sha1, update->old_sha1,
3551 update->msg);
3552
3553 item->util = new_update;
3554
3555 return 0;
3556}
3557
3558/*
3559 * update is for a symref that points at referent and doesn't have
3560 * REF_NODEREF set. Split it into two updates:
3561 * - The original update, but with REF_LOG_ONLY and REF_NODEREF set
3562 * - A new, separate update for the referent reference
3563 * Note that the new update will itself be subject to splitting when
3564 * the iteration gets to it.
3565 */
fcc42ea0
MH
3566static int split_symref_update(struct files_ref_store *refs,
3567 struct ref_update *update,
92b1551b
MH
3568 const char *referent,
3569 struct ref_transaction *transaction,
3570 struct string_list *affected_refnames,
3571 struct strbuf *err)
3572{
3573 struct string_list_item *item;
3574 struct ref_update *new_update;
3575 unsigned int new_flags;
3576
3577 /*
3578 * First make sure that referent is not already in the
3579 * transaction. This insertion is O(N) in the transaction
3580 * size, but it happens at most once per symref in a
3581 * transaction.
3582 */
3583 item = string_list_insert(affected_refnames, referent);
3584 if (item->util) {
3585 /* An entry already existed */
3586 strbuf_addf(err,
3587 "multiple updates for '%s' (including one "
3588 "via symref '%s') are not allowed",
3589 referent, update->refname);
3590 return TRANSACTION_NAME_CONFLICT;
3591 }
3592
3593 new_flags = update->flags;
3594 if (!strcmp(update->refname, "HEAD")) {
3595 /*
3596 * Record that the new update came via HEAD, so that
3597 * when we process it, split_head_update() doesn't try
3598 * to add another reflog update for HEAD. Note that
3599 * this bit will be propagated if the new_update
3600 * itself needs to be split.
3601 */
3602 new_flags |= REF_UPDATE_VIA_HEAD;
3603 }
3604
3605 new_update = ref_transaction_add_update(
3606 transaction, referent, new_flags,
3607 update->new_sha1, update->old_sha1,
3608 update->msg);
3609
6e30b2f6
MH
3610 new_update->parent_update = update;
3611
3612 /*
3613 * Change the symbolic ref update to log only. Also, it
3614 * doesn't need to check its old SHA-1 value, as that will be
3615 * done when new_update is processed.
3616 */
92b1551b 3617 update->flags |= REF_LOG_ONLY | REF_NODEREF;
6e30b2f6 3618 update->flags &= ~REF_HAVE_OLD;
92b1551b
MH
3619
3620 item->util = new_update;
3621
3622 return 0;
3623}
3624
6e30b2f6
MH
3625/*
3626 * Return the refname under which update was originally requested.
3627 */
3628static const char *original_update_refname(struct ref_update *update)
3629{
3630 while (update->parent_update)
3631 update = update->parent_update;
3632
3633 return update->refname;
3634}
3635
e3f51039
MH
3636/*
3637 * Check whether the REF_HAVE_OLD and old_oid values stored in update
3638 * are consistent with oid, which is the reference's current value. If
3639 * everything is OK, return 0; otherwise, write an error message to
3640 * err and return -1.
3641 */
3642static int check_old_oid(struct ref_update *update, struct object_id *oid,
3643 struct strbuf *err)
3644{
3645 if (!(update->flags & REF_HAVE_OLD) ||
3646 !hashcmp(oid->hash, update->old_sha1))
3647 return 0;
3648
3649 if (is_null_sha1(update->old_sha1))
3650 strbuf_addf(err, "cannot lock ref '%s': "
3651 "reference already exists",
3652 original_update_refname(update));
3653 else if (is_null_oid(oid))
3654 strbuf_addf(err, "cannot lock ref '%s': "
3655 "reference is missing but expected %s",
3656 original_update_refname(update),
3657 sha1_to_hex(update->old_sha1));
3658 else
3659 strbuf_addf(err, "cannot lock ref '%s': "