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