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