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