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