read_raw_ref(): move docstring to header file
[git] / refs / files-backend.c
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
8 struct ref_lock {
9         char *ref_name;
10         char *orig_ref_name;
11         struct lock_file *lk;
12         struct object_id old_oid;
13 };
14
15 struct 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  */
23 struct 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
41 struct 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  */
69 struct 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  */
147 struct 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
161 static void read_loose_refs(const char *dirname, struct ref_dir *dir);
162 static int search_ref_dir(struct ref_dir *dir, const char *refname, size_t len);
163 static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache,
164                                           const char *dirname, size_t len,
165                                           int incomplete);
166 static void add_entry_to_dir(struct ref_dir *dir, struct ref_entry *entry);
167
168 static 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
198 static struct ref_entry *create_ref_entry(const char *refname,
199                                           const unsigned char *sha1, int flag,
200                                           int check_name)
201 {
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);
207         FLEX_ALLOC_STR(ref, name, refname);
208         hashcpy(ref->u.value.oid.hash, sha1);
209         oidclr(&ref->u.value.peeled);
210         ref->flag = flag;
211         return ref;
212 }
213
214 static void clear_ref_dir(struct ref_dir *dir);
215
216 static 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  */
233 static 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  */
248 static 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  */
263 static 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;
268         FLEX_ALLOC_MEM(direntry, name, dirname, len);
269         direntry->u.subdir.ref_cache = ref_cache;
270         direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE : 0);
271         return direntry;
272 }
273
274 static 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
281 static void sort_ref_dir(struct ref_dir *dir);
282
283 struct string_slice {
284         size_t len;
285         const char *str;
286 };
287
288 static 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  */
303 static 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  */
330 static 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  */
362 static 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  */
385 static 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  */
413 static 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  */
455 static 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  */
469 static 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  */
491 static 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
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  */
521 static 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  */
541 static struct ref_entry *current_ref;
542
543 typedef int each_ref_entry_fn(struct ref_entry *entry, void *cb_data);
544
545 struct 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  */
557 static 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  */
586 static 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  */
615 static 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  */
685 static 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
695 struct nonmatching_ref_data {
696         const struct string_list *skip;
697         const char *conflicting_refname;
698 };
699
700 static 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  */
716 static 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;
723         const char *extra_refname;
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
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;
835
836 cleanup:
837         strbuf_release(&dirname);
838         return ret;
839 }
840
841 struct 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  */
869 static 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: */
882 static struct lock_file packlock;
883
884 /*
885  * Increment the reference count of *packed_refs.
886  */
887 static 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  */
896 static 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
908 static 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
920 static 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
928 /*
929  * Create a new submodule ref cache and add it to the internal
930  * set of caches.
931  */
932 static struct ref_cache *create_ref_cache(const char *submodule)
933 {
934         struct ref_cache *refs;
935         if (!submodule)
936                 submodule = "";
937         FLEX_ALLOC_STR(refs, name, submodule);
938         refs->next = submodule_ref_caches;
939         submodule_ref_caches = refs;
940         return refs;
941 }
942
943 static struct ref_cache *lookup_ref_cache(const char *submodule)
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;
953         return NULL;
954 }
955
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  */
962 static 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);
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  */
977 static 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  */
985 static 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  */
1043 static 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  */
1102 static 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
1132 static 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
1137 static 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  */
1148 static 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  */
1164 static 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
1254 static 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
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  */
1279 static 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
1293 static 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
1301         if (recursion > SYMREF_MAXDEPTH || strlen(refname) > MAXREFLEN)
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
1333 int resolve_gitlink_ref(const char *path, const char *refname, unsigned char *sha1)
1334 {
1335         int len = strlen(path), retval;
1336         struct strbuf submodule = STRBUF_INIT;
1337         struct ref_cache *refs;
1338
1339         while (len && path[len-1] == '/')
1340                 len--;
1341         if (!len)
1342                 return -1;
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);
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  */
1363 static struct ref_entry *get_packed_ref(const char *refname)
1364 {
1365         return find_ref(get_packed_refs(&ref_cache), refname);
1366 }
1367
1368 /*
1369  * A loose ref file doesn't exist; check for a packed ref.
1370  */
1371 static int resolve_missing_loose_ref(const char *refname,
1372                                      unsigned char *sha1,
1373                                      unsigned int *flags)
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);
1384                 *flags |= REF_ISPACKED;
1385                 return 0;
1386         }
1387         /* refname is not a packed reference. */
1388         return -1;
1389 }
1390
1391 int read_raw_ref(const char *refname, unsigned char *sha1,
1392                  struct strbuf *referent, unsigned int *type)
1393 {
1394         struct strbuf sb_contents = STRBUF_INIT;
1395         struct strbuf sb_path = STRBUF_INIT;
1396         const char *path;
1397         const char *buf;
1398         struct stat st;
1399         int fd;
1400         int ret = -1;
1401         int save_errno;
1402
1403         *type = 0;
1404         strbuf_reset(&sb_path);
1405         strbuf_git_path(&sb_path, "%s", refname);
1406         path = sb_path.buf;
1407
1408 stat_ref:
1409         /*
1410          * We might have to loop back here to avoid a race
1411          * condition: first we lstat() the file, then we try
1412          * to read it as a link or as a file.  But if somebody
1413          * changes the type of the file (file <-> directory
1414          * <-> symlink) between the lstat() and reading, then
1415          * we don't want to report that as an error but rather
1416          * try again starting with the lstat().
1417          */
1418
1419         if (lstat(path, &st) < 0) {
1420                 if (errno != ENOENT)
1421                         goto out;
1422                 if (resolve_missing_loose_ref(refname, sha1, type)) {
1423                         errno = ENOENT;
1424                         goto out;
1425                 }
1426                 ret = 0;
1427                 goto out;
1428         }
1429
1430         /* Follow "normalized" - ie "refs/.." symlinks by hand */
1431         if (S_ISLNK(st.st_mode)) {
1432                 strbuf_reset(&sb_contents);
1433                 if (strbuf_readlink(&sb_contents, path, 0) < 0) {
1434                         if (errno == ENOENT || errno == EINVAL)
1435                                 /* inconsistent with lstat; retry */
1436                                 goto stat_ref;
1437                         else
1438                                 goto out;
1439                 }
1440                 if (starts_with(sb_contents.buf, "refs/") &&
1441                     !check_refname_format(sb_contents.buf, 0)) {
1442                         strbuf_swap(&sb_contents, referent);
1443                         *type |= REF_ISSYMREF;
1444                         ret = 0;
1445                         goto out;
1446                 }
1447         }
1448
1449         /* Is it a directory? */
1450         if (S_ISDIR(st.st_mode)) {
1451                 /*
1452                  * Even though there is a directory where the loose
1453                  * ref is supposed to be, there could still be a
1454                  * packed ref:
1455                  */
1456                 if (resolve_missing_loose_ref(refname, sha1, type)) {
1457                         errno = EISDIR;
1458                         goto out;
1459                 }
1460                 ret = 0;
1461                 goto out;
1462         }
1463
1464         /*
1465          * Anything else, just open it and try to use it as
1466          * a ref
1467          */
1468         fd = open(path, O_RDONLY);
1469         if (fd < 0) {
1470                 if (errno == ENOENT)
1471                         /* inconsistent with lstat; retry */
1472                         goto stat_ref;
1473                 else
1474                         goto out;
1475         }
1476         strbuf_reset(&sb_contents);
1477         if (strbuf_read(&sb_contents, fd, 256) < 0) {
1478                 int save_errno = errno;
1479                 close(fd);
1480                 errno = save_errno;
1481                 goto out;
1482         }
1483         close(fd);
1484         strbuf_rtrim(&sb_contents);
1485         buf = sb_contents.buf;
1486         if (starts_with(buf, "ref:")) {
1487                 buf += 4;
1488                 while (isspace(*buf))
1489                         buf++;
1490
1491                 strbuf_reset(referent);
1492                 strbuf_addstr(referent, buf);
1493                 *type |= REF_ISSYMREF;
1494                 ret = 0;
1495                 goto out;
1496         }
1497
1498         /*
1499          * Please note that FETCH_HEAD has additional
1500          * data after the sha.
1501          */
1502         if (get_sha1_hex(buf, sha1) ||
1503             (buf[40] != '\0' && !isspace(buf[40]))) {
1504                 *type |= REF_ISBROKEN;
1505                 errno = EINVAL;
1506                 goto out;
1507         }
1508
1509         ret = 0;
1510
1511 out:
1512         save_errno = errno;
1513         strbuf_release(&sb_path);
1514         strbuf_release(&sb_contents);
1515         errno = save_errno;
1516         return ret;
1517 }
1518
1519 /*
1520  * Peel the entry (if possible) and return its new peel_status.  If
1521  * repeel is true, re-peel the entry even if there is an old peeled
1522  * value that is already stored in it.
1523  *
1524  * It is OK to call this function with a packed reference entry that
1525  * might be stale and might even refer to an object that has since
1526  * been garbage-collected.  In such a case, if the entry has
1527  * REF_KNOWS_PEELED then leave the status unchanged and return
1528  * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.
1529  */
1530 static enum peel_status peel_entry(struct ref_entry *entry, int repeel)
1531 {
1532         enum peel_status status;
1533
1534         if (entry->flag & REF_KNOWS_PEELED) {
1535                 if (repeel) {
1536                         entry->flag &= ~REF_KNOWS_PEELED;
1537                         oidclr(&entry->u.value.peeled);
1538                 } else {
1539                         return is_null_oid(&entry->u.value.peeled) ?
1540                                 PEEL_NON_TAG : PEEL_PEELED;
1541                 }
1542         }
1543         if (entry->flag & REF_ISBROKEN)
1544                 return PEEL_BROKEN;
1545         if (entry->flag & REF_ISSYMREF)
1546                 return PEEL_IS_SYMREF;
1547
1548         status = peel_object(entry->u.value.oid.hash, entry->u.value.peeled.hash);
1549         if (status == PEEL_PEELED || status == PEEL_NON_TAG)
1550                 entry->flag |= REF_KNOWS_PEELED;
1551         return status;
1552 }
1553
1554 int peel_ref(const char *refname, unsigned char *sha1)
1555 {
1556         int flag;
1557         unsigned char base[20];
1558
1559         if (current_ref && (current_ref->name == refname
1560                             || !strcmp(current_ref->name, refname))) {
1561                 if (peel_entry(current_ref, 0))
1562                         return -1;
1563                 hashcpy(sha1, current_ref->u.value.peeled.hash);
1564                 return 0;
1565         }
1566
1567         if (read_ref_full(refname, RESOLVE_REF_READING, base, &flag))
1568                 return -1;
1569
1570         /*
1571          * If the reference is packed, read its ref_entry from the
1572          * cache in the hope that we already know its peeled value.
1573          * We only try this optimization on packed references because
1574          * (a) forcing the filling of the loose reference cache could
1575          * be expensive and (b) loose references anyway usually do not
1576          * have REF_KNOWS_PEELED.
1577          */
1578         if (flag & REF_ISPACKED) {
1579                 struct ref_entry *r = get_packed_ref(refname);
1580                 if (r) {
1581                         if (peel_entry(r, 0))
1582                                 return -1;
1583                         hashcpy(sha1, r->u.value.peeled.hash);
1584                         return 0;
1585                 }
1586         }
1587
1588         return peel_object(base, sha1);
1589 }
1590
1591 /*
1592  * Call fn for each reference in the specified ref_cache, omitting
1593  * references not in the containing_dir of base.  fn is called for all
1594  * references, including broken ones.  If fn ever returns a non-zero
1595  * value, stop the iteration and return that value; otherwise, return
1596  * 0.
1597  */
1598 static int do_for_each_entry(struct ref_cache *refs, const char *base,
1599                              each_ref_entry_fn fn, void *cb_data)
1600 {
1601         struct packed_ref_cache *packed_ref_cache;
1602         struct ref_dir *loose_dir;
1603         struct ref_dir *packed_dir;
1604         int retval = 0;
1605
1606         /*
1607          * We must make sure that all loose refs are read before accessing the
1608          * packed-refs file; this avoids a race condition in which loose refs
1609          * are migrated to the packed-refs file by a simultaneous process, but
1610          * our in-memory view is from before the migration. get_packed_ref_cache()
1611          * takes care of making sure our view is up to date with what is on
1612          * disk.
1613          */
1614         loose_dir = get_loose_refs(refs);
1615         if (base && *base) {
1616                 loose_dir = find_containing_dir(loose_dir, base, 0);
1617         }
1618         if (loose_dir)
1619                 prime_ref_dir(loose_dir);
1620
1621         packed_ref_cache = get_packed_ref_cache(refs);
1622         acquire_packed_ref_cache(packed_ref_cache);
1623         packed_dir = get_packed_ref_dir(packed_ref_cache);
1624         if (base && *base) {
1625                 packed_dir = find_containing_dir(packed_dir, base, 0);
1626         }
1627
1628         if (packed_dir && loose_dir) {
1629                 sort_ref_dir(packed_dir);
1630                 sort_ref_dir(loose_dir);
1631                 retval = do_for_each_entry_in_dirs(
1632                                 packed_dir, loose_dir, fn, cb_data);
1633         } else if (packed_dir) {
1634                 sort_ref_dir(packed_dir);
1635                 retval = do_for_each_entry_in_dir(
1636                                 packed_dir, 0, fn, cb_data);
1637         } else if (loose_dir) {
1638                 sort_ref_dir(loose_dir);
1639                 retval = do_for_each_entry_in_dir(
1640                                 loose_dir, 0, fn, cb_data);
1641         }
1642
1643         release_packed_ref_cache(packed_ref_cache);
1644         return retval;
1645 }
1646
1647 /*
1648  * Call fn for each reference in the specified ref_cache for which the
1649  * refname begins with base.  If trim is non-zero, then trim that many
1650  * characters off the beginning of each refname before passing the
1651  * refname to fn.  flags can be DO_FOR_EACH_INCLUDE_BROKEN to include
1652  * broken references in the iteration.  If fn ever returns a non-zero
1653  * value, stop the iteration and return that value; otherwise, return
1654  * 0.
1655  */
1656 int do_for_each_ref(const char *submodule, const char *base,
1657                     each_ref_fn fn, int trim, int flags, void *cb_data)
1658 {
1659         struct ref_entry_cb data;
1660         struct ref_cache *refs;
1661
1662         refs = get_ref_cache(submodule);
1663         data.base = base;
1664         data.trim = trim;
1665         data.flags = flags;
1666         data.fn = fn;
1667         data.cb_data = cb_data;
1668
1669         if (ref_paranoia < 0)
1670                 ref_paranoia = git_env_bool("GIT_REF_PARANOIA", 0);
1671         if (ref_paranoia)
1672                 data.flags |= DO_FOR_EACH_INCLUDE_BROKEN;
1673
1674         return do_for_each_entry(refs, base, do_one_ref, &data);
1675 }
1676
1677 static void unlock_ref(struct ref_lock *lock)
1678 {
1679         /* Do not free lock->lk -- atexit() still looks at them */
1680         if (lock->lk)
1681                 rollback_lock_file(lock->lk);
1682         free(lock->ref_name);
1683         free(lock->orig_ref_name);
1684         free(lock);
1685 }
1686
1687 /*
1688  * Verify that the reference locked by lock has the value old_sha1.
1689  * Fail if the reference doesn't exist and mustexist is set. Return 0
1690  * on success. On error, write an error message to err, set errno, and
1691  * return a negative value.
1692  */
1693 static int verify_lock(struct ref_lock *lock,
1694                        const unsigned char *old_sha1, int mustexist,
1695                        struct strbuf *err)
1696 {
1697         assert(err);
1698
1699         if (read_ref_full(lock->ref_name,
1700                           mustexist ? RESOLVE_REF_READING : 0,
1701                           lock->old_oid.hash, NULL)) {
1702                 if (old_sha1) {
1703                         int save_errno = errno;
1704                         strbuf_addf(err, "can't verify ref %s", lock->ref_name);
1705                         errno = save_errno;
1706                         return -1;
1707                 } else {
1708                         hashclr(lock->old_oid.hash);
1709                         return 0;
1710                 }
1711         }
1712         if (old_sha1 && hashcmp(lock->old_oid.hash, old_sha1)) {
1713                 strbuf_addf(err, "ref %s is at %s but expected %s",
1714                             lock->ref_name,
1715                             sha1_to_hex(lock->old_oid.hash),
1716                             sha1_to_hex(old_sha1));
1717                 errno = EBUSY;
1718                 return -1;
1719         }
1720         return 0;
1721 }
1722
1723 static int remove_empty_directories(struct strbuf *path)
1724 {
1725         /*
1726          * we want to create a file but there is a directory there;
1727          * if that is an empty directory (or a directory that contains
1728          * only empty directories), remove them.
1729          */
1730         return remove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);
1731 }
1732
1733 /*
1734  * Locks a ref returning the lock on success and NULL on failure.
1735  * On failure errno is set to something meaningful.
1736  */
1737 static struct ref_lock *lock_ref_sha1_basic(const char *refname,
1738                                             const unsigned char *old_sha1,
1739                                             const struct string_list *extras,
1740                                             const struct string_list *skip,
1741                                             unsigned int flags, int *type_p,
1742                                             struct strbuf *err)
1743 {
1744         struct strbuf ref_file = STRBUF_INIT;
1745         struct strbuf orig_ref_file = STRBUF_INIT;
1746         const char *orig_refname = refname;
1747         struct ref_lock *lock;
1748         int last_errno = 0;
1749         int type;
1750         int lflags = 0;
1751         int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
1752         int resolve_flags = 0;
1753         int attempts_remaining = 3;
1754
1755         assert(err);
1756
1757         lock = xcalloc(1, sizeof(struct ref_lock));
1758
1759         if (mustexist)
1760                 resolve_flags |= RESOLVE_REF_READING;
1761         if (flags & REF_DELETING)
1762                 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;
1763         if (flags & REF_NODEREF) {
1764                 resolve_flags |= RESOLVE_REF_NO_RECURSE;
1765                 lflags |= LOCK_NO_DEREF;
1766         }
1767
1768         refname = resolve_ref_unsafe(refname, resolve_flags,
1769                                      lock->old_oid.hash, &type);
1770         if (!refname && errno == EISDIR) {
1771                 /*
1772                  * we are trying to lock foo but we used to
1773                  * have foo/bar which now does not exist;
1774                  * it is normal for the empty directory 'foo'
1775                  * to remain.
1776                  */
1777                 strbuf_git_path(&orig_ref_file, "%s", orig_refname);
1778                 if (remove_empty_directories(&orig_ref_file)) {
1779                         last_errno = errno;
1780                         if (!verify_refname_available_dir(orig_refname, extras, skip,
1781                                                           get_loose_refs(&ref_cache), err))
1782                                 strbuf_addf(err, "there are still refs under '%s'",
1783                                             orig_refname);
1784                         goto error_return;
1785                 }
1786                 refname = resolve_ref_unsafe(orig_refname, resolve_flags,
1787                                              lock->old_oid.hash, &type);
1788         }
1789         if (type_p)
1790             *type_p = type;
1791         if (!refname) {
1792                 last_errno = errno;
1793                 if (last_errno != ENOTDIR ||
1794                     !verify_refname_available_dir(orig_refname, extras, skip,
1795                                                   get_loose_refs(&ref_cache), err))
1796                         strbuf_addf(err, "unable to resolve reference %s: %s",
1797                                     orig_refname, strerror(last_errno));
1798
1799                 goto error_return;
1800         }
1801
1802         if (flags & REF_NODEREF)
1803                 refname = orig_refname;
1804
1805         /*
1806          * If the ref did not exist and we are creating it, make sure
1807          * there is no existing packed ref whose name begins with our
1808          * refname, nor a packed ref whose name is a proper prefix of
1809          * our refname.
1810          */
1811         if (is_null_oid(&lock->old_oid) &&
1812             verify_refname_available_dir(refname, extras, skip,
1813                                          get_packed_refs(&ref_cache), err)) {
1814                 last_errno = ENOTDIR;
1815                 goto error_return;
1816         }
1817
1818         lock->lk = xcalloc(1, sizeof(struct lock_file));
1819
1820         lock->ref_name = xstrdup(refname);
1821         lock->orig_ref_name = xstrdup(orig_refname);
1822         strbuf_git_path(&ref_file, "%s", refname);
1823
1824  retry:
1825         switch (safe_create_leading_directories_const(ref_file.buf)) {
1826         case SCLD_OK:
1827                 break; /* success */
1828         case SCLD_VANISHED:
1829                 if (--attempts_remaining > 0)
1830                         goto retry;
1831                 /* fall through */
1832         default:
1833                 last_errno = errno;
1834                 strbuf_addf(err, "unable to create directory for %s",
1835                             ref_file.buf);
1836                 goto error_return;
1837         }
1838
1839         if (hold_lock_file_for_update(lock->lk, ref_file.buf, lflags) < 0) {
1840                 last_errno = errno;
1841                 if (errno == ENOENT && --attempts_remaining > 0)
1842                         /*
1843                          * Maybe somebody just deleted one of the
1844                          * directories leading to ref_file.  Try
1845                          * again:
1846                          */
1847                         goto retry;
1848                 else {
1849                         unable_to_lock_message(ref_file.buf, errno, err);
1850                         goto error_return;
1851                 }
1852         }
1853         if (verify_lock(lock, old_sha1, mustexist, err)) {
1854                 last_errno = errno;
1855                 goto error_return;
1856         }
1857         goto out;
1858
1859  error_return:
1860         unlock_ref(lock);
1861         lock = NULL;
1862
1863  out:
1864         strbuf_release(&ref_file);
1865         strbuf_release(&orig_ref_file);
1866         errno = last_errno;
1867         return lock;
1868 }
1869
1870 /*
1871  * Write an entry to the packed-refs file for the specified refname.
1872  * If peeled is non-NULL, write it as the entry's peeled value.
1873  */
1874 static void write_packed_entry(FILE *fh, char *refname, unsigned char *sha1,
1875                                unsigned char *peeled)
1876 {
1877         fprintf_or_die(fh, "%s %s\n", sha1_to_hex(sha1), refname);
1878         if (peeled)
1879                 fprintf_or_die(fh, "^%s\n", sha1_to_hex(peeled));
1880 }
1881
1882 /*
1883  * An each_ref_entry_fn that writes the entry to a packed-refs file.
1884  */
1885 static int write_packed_entry_fn(struct ref_entry *entry, void *cb_data)
1886 {
1887         enum peel_status peel_status = peel_entry(entry, 0);
1888
1889         if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)
1890                 error("internal error: %s is not a valid packed reference!",
1891                       entry->name);
1892         write_packed_entry(cb_data, entry->name, entry->u.value.oid.hash,
1893                            peel_status == PEEL_PEELED ?
1894                            entry->u.value.peeled.hash : NULL);
1895         return 0;
1896 }
1897
1898 /*
1899  * Lock the packed-refs file for writing. Flags is passed to
1900  * hold_lock_file_for_update(). Return 0 on success. On errors, set
1901  * errno appropriately and return a nonzero value.
1902  */
1903 static int lock_packed_refs(int flags)
1904 {
1905         static int timeout_configured = 0;
1906         static int timeout_value = 1000;
1907
1908         struct packed_ref_cache *packed_ref_cache;
1909
1910         if (!timeout_configured) {
1911                 git_config_get_int("core.packedrefstimeout", &timeout_value);
1912                 timeout_configured = 1;
1913         }
1914
1915         if (hold_lock_file_for_update_timeout(
1916                             &packlock, git_path("packed-refs"),
1917                             flags, timeout_value) < 0)
1918                 return -1;
1919         /*
1920          * Get the current packed-refs while holding the lock.  If the
1921          * packed-refs file has been modified since we last read it,
1922          * this will automatically invalidate the cache and re-read
1923          * the packed-refs file.
1924          */
1925         packed_ref_cache = get_packed_ref_cache(&ref_cache);
1926         packed_ref_cache->lock = &packlock;
1927         /* Increment the reference count to prevent it from being freed: */
1928         acquire_packed_ref_cache(packed_ref_cache);
1929         return 0;
1930 }
1931
1932 /*
1933  * Write the current version of the packed refs cache from memory to
1934  * disk. The packed-refs file must already be locked for writing (see
1935  * lock_packed_refs()). Return zero on success. On errors, set errno
1936  * and return a nonzero value
1937  */
1938 static int commit_packed_refs(void)
1939 {
1940         struct packed_ref_cache *packed_ref_cache =
1941                 get_packed_ref_cache(&ref_cache);
1942         int error = 0;
1943         int save_errno = 0;
1944         FILE *out;
1945
1946         if (!packed_ref_cache->lock)
1947                 die("internal error: packed-refs not locked");
1948
1949         out = fdopen_lock_file(packed_ref_cache->lock, "w");
1950         if (!out)
1951                 die_errno("unable to fdopen packed-refs descriptor");
1952
1953         fprintf_or_die(out, "%s", PACKED_REFS_HEADER);
1954         do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),
1955                                  0, write_packed_entry_fn, out);
1956
1957         if (commit_lock_file(packed_ref_cache->lock)) {
1958                 save_errno = errno;
1959                 error = -1;
1960         }
1961         packed_ref_cache->lock = NULL;
1962         release_packed_ref_cache(packed_ref_cache);
1963         errno = save_errno;
1964         return error;
1965 }
1966
1967 /*
1968  * Rollback the lockfile for the packed-refs file, and discard the
1969  * in-memory packed reference cache.  (The packed-refs file will be
1970  * read anew if it is needed again after this function is called.)
1971  */
1972 static void rollback_packed_refs(void)
1973 {
1974         struct packed_ref_cache *packed_ref_cache =
1975                 get_packed_ref_cache(&ref_cache);
1976
1977         if (!packed_ref_cache->lock)
1978                 die("internal error: packed-refs not locked");
1979         rollback_lock_file(packed_ref_cache->lock);
1980         packed_ref_cache->lock = NULL;
1981         release_packed_ref_cache(packed_ref_cache);
1982         clear_packed_ref_cache(&ref_cache);
1983 }
1984
1985 struct ref_to_prune {
1986         struct ref_to_prune *next;
1987         unsigned char sha1[20];
1988         char name[FLEX_ARRAY];
1989 };
1990
1991 struct pack_refs_cb_data {
1992         unsigned int flags;
1993         struct ref_dir *packed_refs;
1994         struct ref_to_prune *ref_to_prune;
1995 };
1996
1997 /*
1998  * An each_ref_entry_fn that is run over loose references only.  If
1999  * the loose reference can be packed, add an entry in the packed ref
2000  * cache.  If the reference should be pruned, also add it to
2001  * ref_to_prune in the pack_refs_cb_data.
2002  */
2003 static int pack_if_possible_fn(struct ref_entry *entry, void *cb_data)
2004 {
2005         struct pack_refs_cb_data *cb = cb_data;
2006         enum peel_status peel_status;
2007         struct ref_entry *packed_entry;
2008         int is_tag_ref = starts_with(entry->name, "refs/tags/");
2009
2010         /* Do not pack per-worktree refs: */
2011         if (ref_type(entry->name) != REF_TYPE_NORMAL)
2012                 return 0;
2013
2014         /* ALWAYS pack tags */
2015         if (!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)
2016                 return 0;
2017
2018         /* Do not pack symbolic or broken refs: */
2019         if ((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))
2020                 return 0;
2021
2022         /* Add a packed ref cache entry equivalent to the loose entry. */
2023         peel_status = peel_entry(entry, 1);
2024         if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)
2025                 die("internal error peeling reference %s (%s)",
2026                     entry->name, oid_to_hex(&entry->u.value.oid));
2027         packed_entry = find_ref(cb->packed_refs, entry->name);
2028         if (packed_entry) {
2029                 /* Overwrite existing packed entry with info from loose entry */
2030                 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;
2031                 oidcpy(&packed_entry->u.value.oid, &entry->u.value.oid);
2032         } else {
2033                 packed_entry = create_ref_entry(entry->name, entry->u.value.oid.hash,
2034                                                 REF_ISPACKED | REF_KNOWS_PEELED, 0);
2035                 add_ref(cb->packed_refs, packed_entry);
2036         }
2037         oidcpy(&packed_entry->u.value.peeled, &entry->u.value.peeled);
2038
2039         /* Schedule the loose reference for pruning if requested. */
2040         if ((cb->flags & PACK_REFS_PRUNE)) {
2041                 struct ref_to_prune *n;
2042                 FLEX_ALLOC_STR(n, name, entry->name);
2043                 hashcpy(n->sha1, entry->u.value.oid.hash);
2044                 n->next = cb->ref_to_prune;
2045                 cb->ref_to_prune = n;
2046         }
2047         return 0;
2048 }
2049
2050 /*
2051  * Remove empty parents, but spare refs/ and immediate subdirs.
2052  * Note: munges *name.
2053  */
2054 static void try_remove_empty_parents(char *name)
2055 {
2056         char *p, *q;
2057         int i;
2058         p = name;
2059         for (i = 0; i < 2; i++) { /* refs/{heads,tags,...}/ */
2060                 while (*p && *p != '/')
2061                         p++;
2062                 /* tolerate duplicate slashes; see check_refname_format() */
2063                 while (*p == '/')
2064                         p++;
2065         }
2066         for (q = p; *q; q++)
2067                 ;
2068         while (1) {
2069                 while (q > p && *q != '/')
2070                         q--;
2071                 while (q > p && *(q-1) == '/')
2072                         q--;
2073                 if (q == p)
2074                         break;
2075                 *q = '\0';
2076                 if (rmdir(git_path("%s", name)))
2077                         break;
2078         }
2079 }
2080
2081 /* make sure nobody touched the ref, and unlink */
2082 static void prune_ref(struct ref_to_prune *r)
2083 {
2084         struct ref_transaction *transaction;
2085         struct strbuf err = STRBUF_INIT;
2086
2087         if (check_refname_format(r->name, 0))
2088                 return;
2089
2090         transaction = ref_transaction_begin(&err);
2091         if (!transaction ||
2092             ref_transaction_delete(transaction, r->name, r->sha1,
2093                                    REF_ISPRUNING, NULL, &err) ||
2094             ref_transaction_commit(transaction, &err)) {
2095                 ref_transaction_free(transaction);
2096                 error("%s", err.buf);
2097                 strbuf_release(&err);
2098                 return;
2099         }
2100         ref_transaction_free(transaction);
2101         strbuf_release(&err);
2102         try_remove_empty_parents(r->name);
2103 }
2104
2105 static void prune_refs(struct ref_to_prune *r)
2106 {
2107         while (r) {
2108                 prune_ref(r);
2109                 r = r->next;
2110         }
2111 }
2112
2113 int pack_refs(unsigned int flags)
2114 {
2115         struct pack_refs_cb_data cbdata;
2116
2117         memset(&cbdata, 0, sizeof(cbdata));
2118         cbdata.flags = flags;
2119
2120         lock_packed_refs(LOCK_DIE_ON_ERROR);
2121         cbdata.packed_refs = get_packed_refs(&ref_cache);
2122
2123         do_for_each_entry_in_dir(get_loose_refs(&ref_cache), 0,
2124                                  pack_if_possible_fn, &cbdata);
2125
2126         if (commit_packed_refs())
2127                 die_errno("unable to overwrite old ref-pack file");
2128
2129         prune_refs(cbdata.ref_to_prune);
2130         return 0;
2131 }
2132
2133 /*
2134  * Rewrite the packed-refs file, omitting any refs listed in
2135  * 'refnames'. On error, leave packed-refs unchanged, write an error
2136  * message to 'err', and return a nonzero value.
2137  *
2138  * The refs in 'refnames' needn't be sorted. `err` must not be NULL.
2139  */
2140 static int repack_without_refs(struct string_list *refnames, struct strbuf *err)
2141 {
2142         struct ref_dir *packed;
2143         struct string_list_item *refname;
2144         int ret, needs_repacking = 0, removed = 0;
2145
2146         assert(err);
2147
2148         /* Look for a packed ref */
2149         for_each_string_list_item(refname, refnames) {
2150                 if (get_packed_ref(refname->string)) {
2151                         needs_repacking = 1;
2152                         break;
2153                 }
2154         }
2155
2156         /* Avoid locking if we have nothing to do */
2157         if (!needs_repacking)
2158                 return 0; /* no refname exists in packed refs */
2159
2160         if (lock_packed_refs(0)) {
2161                 unable_to_lock_message(git_path("packed-refs"), errno, err);
2162                 return -1;
2163         }
2164         packed = get_packed_refs(&ref_cache);
2165
2166         /* Remove refnames from the cache */
2167         for_each_string_list_item(refname, refnames)
2168                 if (remove_entry(packed, refname->string) != -1)
2169                         removed = 1;
2170         if (!removed) {
2171                 /*
2172                  * All packed entries disappeared while we were
2173                  * acquiring the lock.
2174                  */
2175                 rollback_packed_refs();
2176                 return 0;
2177         }
2178
2179         /* Write what remains */
2180         ret = commit_packed_refs();
2181         if (ret)
2182                 strbuf_addf(err, "unable to overwrite old ref-pack file: %s",
2183                             strerror(errno));
2184         return ret;
2185 }
2186
2187 static int delete_ref_loose(struct ref_lock *lock, int flag, struct strbuf *err)
2188 {
2189         assert(err);
2190
2191         if (!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {
2192                 /*
2193                  * loose.  The loose file name is the same as the
2194                  * lockfile name, minus ".lock":
2195                  */
2196                 char *loose_filename = get_locked_file_path(lock->lk);
2197                 int res = unlink_or_msg(loose_filename, err);
2198                 free(loose_filename);
2199                 if (res)
2200                         return 1;
2201         }
2202         return 0;
2203 }
2204
2205 int delete_refs(struct string_list *refnames)
2206 {
2207         struct strbuf err = STRBUF_INIT;
2208         int i, result = 0;
2209
2210         if (!refnames->nr)
2211                 return 0;
2212
2213         result = repack_without_refs(refnames, &err);
2214         if (result) {
2215                 /*
2216                  * If we failed to rewrite the packed-refs file, then
2217                  * it is unsafe to try to remove loose refs, because
2218                  * doing so might expose an obsolete packed value for
2219                  * a reference that might even point at an object that
2220                  * has been garbage collected.
2221                  */
2222                 if (refnames->nr == 1)
2223                         error(_("could not delete reference %s: %s"),
2224                               refnames->items[0].string, err.buf);
2225                 else
2226                         error(_("could not delete references: %s"), err.buf);
2227
2228                 goto out;
2229         }
2230
2231         for (i = 0; i < refnames->nr; i++) {
2232                 const char *refname = refnames->items[i].string;
2233
2234                 if (delete_ref(refname, NULL, 0))
2235                         result |= error(_("could not remove reference %s"), refname);
2236         }
2237
2238 out:
2239         strbuf_release(&err);
2240         return result;
2241 }
2242
2243 /*
2244  * People using contrib's git-new-workdir have .git/logs/refs ->
2245  * /some/other/path/.git/logs/refs, and that may live on another device.
2246  *
2247  * IOW, to avoid cross device rename errors, the temporary renamed log must
2248  * live into logs/refs.
2249  */
2250 #define TMP_RENAMED_LOG  "logs/refs/.tmp-renamed-log"
2251
2252 static int rename_tmp_log(const char *newrefname)
2253 {
2254         int attempts_remaining = 4;
2255         struct strbuf path = STRBUF_INIT;
2256         int ret = -1;
2257
2258  retry:
2259         strbuf_reset(&path);
2260         strbuf_git_path(&path, "logs/%s", newrefname);
2261         switch (safe_create_leading_directories_const(path.buf)) {
2262         case SCLD_OK:
2263                 break; /* success */
2264         case SCLD_VANISHED:
2265                 if (--attempts_remaining > 0)
2266                         goto retry;
2267                 /* fall through */
2268         default:
2269                 error("unable to create directory for %s", newrefname);
2270                 goto out;
2271         }
2272
2273         if (rename(git_path(TMP_RENAMED_LOG), path.buf)) {
2274                 if ((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining > 0) {
2275                         /*
2276                          * rename(a, b) when b is an existing
2277                          * directory ought to result in ISDIR, but
2278                          * Solaris 5.8 gives ENOTDIR.  Sheesh.
2279                          */
2280                         if (remove_empty_directories(&path)) {
2281                                 error("Directory not empty: logs/%s", newrefname);
2282                                 goto out;
2283                         }
2284                         goto retry;
2285                 } else if (errno == ENOENT && --attempts_remaining > 0) {
2286                         /*
2287                          * Maybe another process just deleted one of
2288                          * the directories in the path to newrefname.
2289                          * Try again from the beginning.
2290                          */
2291                         goto retry;
2292                 } else {
2293                         error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s: %s",
2294                                 newrefname, strerror(errno));
2295                         goto out;
2296                 }
2297         }
2298         ret = 0;
2299 out:
2300         strbuf_release(&path);
2301         return ret;
2302 }
2303
2304 int verify_refname_available(const char *newname,
2305                              struct string_list *extras,
2306                              struct string_list *skip,
2307                              struct strbuf *err)
2308 {
2309         struct ref_dir *packed_refs = get_packed_refs(&ref_cache);
2310         struct ref_dir *loose_refs = get_loose_refs(&ref_cache);
2311
2312         if (verify_refname_available_dir(newname, extras, skip,
2313                                          packed_refs, err) ||
2314             verify_refname_available_dir(newname, extras, skip,
2315                                          loose_refs, err))
2316                 return -1;
2317
2318         return 0;
2319 }
2320
2321 static int write_ref_to_lockfile(struct ref_lock *lock,
2322                                  const unsigned char *sha1, struct strbuf *err);
2323 static int commit_ref_update(struct ref_lock *lock,
2324                              const unsigned char *sha1, const char *logmsg,
2325                              int flags, struct strbuf *err);
2326
2327 int rename_ref(const char *oldrefname, const char *newrefname, const char *logmsg)
2328 {
2329         unsigned char sha1[20], orig_sha1[20];
2330         int flag = 0, logmoved = 0;
2331         struct ref_lock *lock;
2332         struct stat loginfo;
2333         int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);
2334         struct strbuf err = STRBUF_INIT;
2335
2336         if (log && S_ISLNK(loginfo.st_mode))
2337                 return error("reflog for %s is a symlink", oldrefname);
2338
2339         if (!resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING, orig_sha1, &flag))
2340                 return error("refname %s not found", oldrefname);
2341
2342         if (flag & REF_ISSYMREF)
2343                 return error("refname %s is a symbolic ref, renaming it is not supported",
2344                         oldrefname);
2345         if (!rename_ref_available(oldrefname, newrefname))
2346                 return 1;
2347
2348         if (log && rename(git_path("logs/%s", oldrefname), git_path(TMP_RENAMED_LOG)))
2349                 return error("unable to move logfile logs/%s to "TMP_RENAMED_LOG": %s",
2350                         oldrefname, strerror(errno));
2351
2352         if (delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {
2353                 error("unable to delete old %s", oldrefname);
2354                 goto rollback;
2355         }
2356
2357         if (!read_ref_full(newrefname, RESOLVE_REF_READING, sha1, NULL) &&
2358             delete_ref(newrefname, sha1, REF_NODEREF)) {
2359                 if (errno==EISDIR) {
2360                         struct strbuf path = STRBUF_INIT;
2361                         int result;
2362
2363                         strbuf_git_path(&path, "%s", newrefname);
2364                         result = remove_empty_directories(&path);
2365                         strbuf_release(&path);
2366
2367                         if (result) {
2368                                 error("Directory not empty: %s", newrefname);
2369                                 goto rollback;
2370                         }
2371                 } else {
2372                         error("unable to delete existing %s", newrefname);
2373                         goto rollback;
2374                 }
2375         }
2376
2377         if (log && rename_tmp_log(newrefname))
2378                 goto rollback;
2379
2380         logmoved = log;
2381
2382         lock = lock_ref_sha1_basic(newrefname, NULL, NULL, NULL, 0, NULL, &err);
2383         if (!lock) {
2384                 error("unable to rename '%s' to '%s': %s", oldrefname, newrefname, err.buf);
2385                 strbuf_release(&err);
2386                 goto rollback;
2387         }
2388         hashcpy(lock->old_oid.hash, orig_sha1);
2389
2390         if (write_ref_to_lockfile(lock, orig_sha1, &err) ||
2391             commit_ref_update(lock, orig_sha1, logmsg, 0, &err)) {
2392                 error("unable to write current sha1 into %s: %s", newrefname, err.buf);
2393                 strbuf_release(&err);
2394                 goto rollback;
2395         }
2396
2397         return 0;
2398
2399  rollback:
2400         lock = lock_ref_sha1_basic(oldrefname, NULL, NULL, NULL, 0, NULL, &err);
2401         if (!lock) {
2402                 error("unable to lock %s for rollback: %s", oldrefname, err.buf);
2403                 strbuf_release(&err);
2404                 goto rollbacklog;
2405         }
2406
2407         flag = log_all_ref_updates;
2408         log_all_ref_updates = 0;
2409         if (write_ref_to_lockfile(lock, orig_sha1, &err) ||
2410             commit_ref_update(lock, orig_sha1, NULL, 0, &err)) {
2411                 error("unable to write current sha1 into %s: %s", oldrefname, err.buf);
2412                 strbuf_release(&err);
2413         }
2414         log_all_ref_updates = flag;
2415
2416  rollbacklog:
2417         if (logmoved && rename(git_path("logs/%s", newrefname), git_path("logs/%s", oldrefname)))
2418                 error("unable to restore logfile %s from %s: %s",
2419                         oldrefname, newrefname, strerror(errno));
2420         if (!logmoved && log &&
2421             rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", oldrefname)))
2422                 error("unable to restore logfile %s from "TMP_RENAMED_LOG": %s",
2423                         oldrefname, strerror(errno));
2424
2425         return 1;
2426 }
2427
2428 static int close_ref(struct ref_lock *lock)
2429 {
2430         if (close_lock_file(lock->lk))
2431                 return -1;
2432         return 0;
2433 }
2434
2435 static int commit_ref(struct ref_lock *lock)
2436 {
2437         char *path = get_locked_file_path(lock->lk);
2438         struct stat st;
2439
2440         if (!lstat(path, &st) && S_ISDIR(st.st_mode)) {
2441                 /*
2442                  * There is a directory at the path we want to rename
2443                  * the lockfile to. Hopefully it is empty; try to
2444                  * delete it.
2445                  */
2446                 size_t len = strlen(path);
2447                 struct strbuf sb_path = STRBUF_INIT;
2448
2449                 strbuf_attach(&sb_path, path, len, len);
2450
2451                 /*
2452                  * If this fails, commit_lock_file() will also fail
2453                  * and will report the problem.
2454                  */
2455                 remove_empty_directories(&sb_path);
2456                 strbuf_release(&sb_path);
2457         } else {
2458                 free(path);
2459         }
2460
2461         if (commit_lock_file(lock->lk))
2462                 return -1;
2463         return 0;
2464 }
2465
2466 /*
2467  * Create a reflog for a ref.  If force_create = 0, the reflog will
2468  * only be created for certain refs (those for which
2469  * should_autocreate_reflog returns non-zero.  Otherwise, create it
2470  * regardless of the ref name.  Fill in *err and return -1 on failure.
2471  */
2472 static int log_ref_setup(const char *refname, struct strbuf *logfile, struct strbuf *err, int force_create)
2473 {
2474         int logfd, oflags = O_APPEND | O_WRONLY;
2475
2476         strbuf_git_path(logfile, "logs/%s", refname);
2477         if (force_create || should_autocreate_reflog(refname)) {
2478                 if (safe_create_leading_directories(logfile->buf) < 0) {
2479                         strbuf_addf(err, "unable to create directory for %s: "
2480                                     "%s", logfile->buf, strerror(errno));
2481                         return -1;
2482                 }
2483                 oflags |= O_CREAT;
2484         }
2485
2486         logfd = open(logfile->buf, oflags, 0666);
2487         if (logfd < 0) {
2488                 if (!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))
2489                         return 0;
2490
2491                 if (errno == EISDIR) {
2492                         if (remove_empty_directories(logfile)) {
2493                                 strbuf_addf(err, "There are still logs under "
2494                                             "'%s'", logfile->buf);
2495                                 return -1;
2496                         }
2497                         logfd = open(logfile->buf, oflags, 0666);
2498                 }
2499
2500                 if (logfd < 0) {
2501                         strbuf_addf(err, "unable to append to %s: %s",
2502                                     logfile->buf, strerror(errno));
2503                         return -1;
2504                 }
2505         }
2506
2507         adjust_shared_perm(logfile->buf);
2508         close(logfd);
2509         return 0;
2510 }
2511
2512
2513 int safe_create_reflog(const char *refname, int force_create, struct strbuf *err)
2514 {
2515         int ret;
2516         struct strbuf sb = STRBUF_INIT;
2517
2518         ret = log_ref_setup(refname, &sb, err, force_create);
2519         strbuf_release(&sb);
2520         return ret;
2521 }
2522
2523 static int log_ref_write_fd(int fd, const unsigned char *old_sha1,
2524                             const unsigned char *new_sha1,
2525                             const char *committer, const char *msg)
2526 {
2527         int msglen, written;
2528         unsigned maxlen, len;
2529         char *logrec;
2530
2531         msglen = msg ? strlen(msg) : 0;
2532         maxlen = strlen(committer) + msglen + 100;
2533         logrec = xmalloc(maxlen);
2534         len = xsnprintf(logrec, maxlen, "%s %s %s\n",
2535                         sha1_to_hex(old_sha1),
2536                         sha1_to_hex(new_sha1),
2537                         committer);
2538         if (msglen)
2539                 len += copy_reflog_msg(logrec + len - 1, msg) - 1;
2540
2541         written = len <= maxlen ? write_in_full(fd, logrec, len) : -1;
2542         free(logrec);
2543         if (written != len)
2544                 return -1;
2545
2546         return 0;
2547 }
2548
2549 static int log_ref_write_1(const char *refname, const unsigned char *old_sha1,
2550                            const unsigned char *new_sha1, const char *msg,
2551                            struct strbuf *logfile, int flags,
2552                            struct strbuf *err)
2553 {
2554         int logfd, result, oflags = O_APPEND | O_WRONLY;
2555
2556         if (log_all_ref_updates < 0)
2557                 log_all_ref_updates = !is_bare_repository();
2558
2559         result = log_ref_setup(refname, logfile, err, flags & REF_FORCE_CREATE_REFLOG);
2560
2561         if (result)
2562                 return result;
2563
2564         logfd = open(logfile->buf, oflags);
2565         if (logfd < 0)
2566                 return 0;
2567         result = log_ref_write_fd(logfd, old_sha1, new_sha1,
2568                                   git_committer_info(0), msg);
2569         if (result) {
2570                 strbuf_addf(err, "unable to append to %s: %s", logfile->buf,
2571                             strerror(errno));
2572                 close(logfd);
2573                 return -1;
2574         }
2575         if (close(logfd)) {
2576                 strbuf_addf(err, "unable to append to %s: %s", logfile->buf,
2577                             strerror(errno));
2578                 return -1;
2579         }
2580         return 0;
2581 }
2582
2583 static int log_ref_write(const char *refname, const unsigned char *old_sha1,
2584                          const unsigned char *new_sha1, const char *msg,
2585                          int flags, struct strbuf *err)
2586 {
2587         return files_log_ref_write(refname, old_sha1, new_sha1, msg, flags,
2588                                    err);
2589 }
2590
2591 int files_log_ref_write(const char *refname, const unsigned char *old_sha1,
2592                         const unsigned char *new_sha1, const char *msg,
2593                         int flags, struct strbuf *err)
2594 {
2595         struct strbuf sb = STRBUF_INIT;
2596         int ret = log_ref_write_1(refname, old_sha1, new_sha1, msg, &sb, flags,
2597                                   err);
2598         strbuf_release(&sb);
2599         return ret;
2600 }
2601
2602 /*
2603  * Write sha1 into the open lockfile, then close the lockfile. On
2604  * errors, rollback the lockfile, fill in *err and
2605  * return -1.
2606  */
2607 static int write_ref_to_lockfile(struct ref_lock *lock,
2608                                  const unsigned char *sha1, struct strbuf *err)
2609 {
2610         static char term = '\n';
2611         struct object *o;
2612         int fd;
2613
2614         o = parse_object(sha1);
2615         if (!o) {
2616                 strbuf_addf(err,
2617                             "Trying to write ref %s with nonexistent object %s",
2618                             lock->ref_name, sha1_to_hex(sha1));
2619                 unlock_ref(lock);
2620                 return -1;
2621         }
2622         if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
2623                 strbuf_addf(err,
2624                             "Trying to write non-commit object %s to branch %s",
2625                             sha1_to_hex(sha1), lock->ref_name);
2626                 unlock_ref(lock);
2627                 return -1;
2628         }
2629         fd = get_lock_file_fd(lock->lk);
2630         if (write_in_full(fd, sha1_to_hex(sha1), 40) != 40 ||
2631             write_in_full(fd, &term, 1) != 1 ||
2632             close_ref(lock) < 0) {
2633                 strbuf_addf(err,
2634                             "Couldn't write %s", get_lock_file_path(lock->lk));
2635                 unlock_ref(lock);
2636                 return -1;
2637         }
2638         return 0;
2639 }
2640
2641 /*
2642  * Commit a change to a loose reference that has already been written
2643  * to the loose reference lockfile. Also update the reflogs if
2644  * necessary, using the specified lockmsg (which can be NULL).
2645  */
2646 static int commit_ref_update(struct ref_lock *lock,
2647                              const unsigned char *sha1, const char *logmsg,
2648                              int flags, struct strbuf *err)
2649 {
2650         clear_loose_ref_cache(&ref_cache);
2651         if (log_ref_write(lock->ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) < 0 ||
2652             (strcmp(lock->ref_name, lock->orig_ref_name) &&
2653              log_ref_write(lock->orig_ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) < 0)) {
2654                 char *old_msg = strbuf_detach(err, NULL);
2655                 strbuf_addf(err, "Cannot update the ref '%s': %s",
2656                             lock->ref_name, old_msg);
2657                 free(old_msg);
2658                 unlock_ref(lock);
2659                 return -1;
2660         }
2661         if (strcmp(lock->orig_ref_name, "HEAD") != 0) {
2662                 /*
2663                  * Special hack: If a branch is updated directly and HEAD
2664                  * points to it (may happen on the remote side of a push
2665                  * for example) then logically the HEAD reflog should be
2666                  * updated too.
2667                  * A generic solution implies reverse symref information,
2668                  * but finding all symrefs pointing to the given branch
2669                  * would be rather costly for this rare event (the direct
2670                  * update of a branch) to be worth it.  So let's cheat and
2671                  * check with HEAD only which should cover 99% of all usage
2672                  * scenarios (even 100% of the default ones).
2673                  */
2674                 unsigned char head_sha1[20];
2675                 int head_flag;
2676                 const char *head_ref;
2677                 head_ref = resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
2678                                               head_sha1, &head_flag);
2679                 if (head_ref && (head_flag & REF_ISSYMREF) &&
2680                     !strcmp(head_ref, lock->ref_name)) {
2681                         struct strbuf log_err = STRBUF_INIT;
2682                         if (log_ref_write("HEAD", lock->old_oid.hash, sha1,
2683                                           logmsg, 0, &log_err)) {
2684                                 error("%s", log_err.buf);
2685                                 strbuf_release(&log_err);
2686                         }
2687                 }
2688         }
2689         if (commit_ref(lock)) {
2690                 strbuf_addf(err, "Couldn't set %s", lock->ref_name);
2691                 unlock_ref(lock);
2692                 return -1;
2693         }
2694
2695         unlock_ref(lock);
2696         return 0;
2697 }
2698
2699 static int create_ref_symlink(struct ref_lock *lock, const char *target)
2700 {
2701         int ret = -1;
2702 #ifndef NO_SYMLINK_HEAD
2703         char *ref_path = get_locked_file_path(lock->lk);
2704         unlink(ref_path);
2705         ret = symlink(target, ref_path);
2706         free(ref_path);
2707
2708         if (ret)
2709                 fprintf(stderr, "no symlink - falling back to symbolic ref\n");
2710 #endif
2711         return ret;
2712 }
2713
2714 static void update_symref_reflog(struct ref_lock *lock, const char *refname,
2715                                  const char *target, const char *logmsg)
2716 {
2717         struct strbuf err = STRBUF_INIT;
2718         unsigned char new_sha1[20];
2719         if (logmsg && !read_ref(target, new_sha1) &&
2720             log_ref_write(refname, lock->old_oid.hash, new_sha1, logmsg, 0, &err)) {
2721                 error("%s", err.buf);
2722                 strbuf_release(&err);
2723         }
2724 }
2725
2726 static int create_symref_locked(struct ref_lock *lock, const char *refname,
2727                                 const char *target, const char *logmsg)
2728 {
2729         if (prefer_symlink_refs && !create_ref_symlink(lock, target)) {
2730                 update_symref_reflog(lock, refname, target, logmsg);
2731                 return 0;
2732         }
2733
2734         if (!fdopen_lock_file(lock->lk, "w"))
2735                 return error("unable to fdopen %s: %s",
2736                              lock->lk->tempfile.filename.buf, strerror(errno));
2737
2738         update_symref_reflog(lock, refname, target, logmsg);
2739
2740         /* no error check; commit_ref will check ferror */
2741         fprintf(lock->lk->tempfile.fp, "ref: %s\n", target);
2742         if (commit_ref(lock) < 0)
2743                 return error("unable to write symref for %s: %s", refname,
2744                              strerror(errno));
2745         return 0;
2746 }
2747
2748 int create_symref(const char *refname, const char *target, const char *logmsg)
2749 {
2750         struct strbuf err = STRBUF_INIT;
2751         struct ref_lock *lock;
2752         int ret;
2753
2754         lock = lock_ref_sha1_basic(refname, NULL, NULL, NULL, REF_NODEREF, NULL,
2755                                    &err);
2756         if (!lock) {
2757                 error("%s", err.buf);
2758                 strbuf_release(&err);
2759                 return -1;
2760         }
2761
2762         ret = create_symref_locked(lock, refname, target, logmsg);
2763         unlock_ref(lock);
2764         return ret;
2765 }
2766
2767 int set_worktree_head_symref(const char *gitdir, const char *target)
2768 {
2769         static struct lock_file head_lock;
2770         struct ref_lock *lock;
2771         struct strbuf head_path = STRBUF_INIT;
2772         const char *head_rel;
2773         int ret;
2774
2775         strbuf_addf(&head_path, "%s/HEAD", absolute_path(gitdir));
2776         if (hold_lock_file_for_update(&head_lock, head_path.buf,
2777                                       LOCK_NO_DEREF) < 0) {
2778                 struct strbuf err = STRBUF_INIT;
2779                 unable_to_lock_message(head_path.buf, errno, &err);
2780                 error("%s", err.buf);
2781                 strbuf_release(&err);
2782                 strbuf_release(&head_path);
2783                 return -1;
2784         }
2785
2786         /* head_rel will be "HEAD" for the main tree, "worktrees/wt/HEAD" for
2787            linked trees */
2788         head_rel = remove_leading_path(head_path.buf,
2789                                        absolute_path(get_git_common_dir()));
2790         /* to make use of create_symref_locked(), initialize ref_lock */
2791         lock = xcalloc(1, sizeof(struct ref_lock));
2792         lock->lk = &head_lock;
2793         lock->ref_name = xstrdup(head_rel);
2794         lock->orig_ref_name = xstrdup(head_rel);
2795
2796         ret = create_symref_locked(lock, head_rel, target, NULL);
2797
2798         unlock_ref(lock); /* will free lock */
2799         strbuf_release(&head_path);
2800         return ret;
2801 }
2802
2803 int reflog_exists(const char *refname)
2804 {
2805         struct stat st;
2806
2807         return !lstat(git_path("logs/%s", refname), &st) &&
2808                 S_ISREG(st.st_mode);
2809 }
2810
2811 int delete_reflog(const char *refname)
2812 {
2813         return remove_path(git_path("logs/%s", refname));
2814 }
2815
2816 static int show_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn, void *cb_data)
2817 {
2818         unsigned char osha1[20], nsha1[20];
2819         char *email_end, *message;
2820         unsigned long timestamp;
2821         int tz;
2822
2823         /* old SP new SP name <email> SP time TAB msg LF */
2824         if (sb->len < 83 || sb->buf[sb->len - 1] != '\n' ||
2825             get_sha1_hex(sb->buf, osha1) || sb->buf[40] != ' ' ||
2826             get_sha1_hex(sb->buf + 41, nsha1) || sb->buf[81] != ' ' ||
2827             !(email_end = strchr(sb->buf + 82, '>')) ||
2828             email_end[1] != ' ' ||
2829             !(timestamp = strtoul(email_end + 2, &message, 10)) ||
2830             !message || message[0] != ' ' ||
2831             (message[1] != '+' && message[1] != '-') ||
2832             !isdigit(message[2]) || !isdigit(message[3]) ||
2833             !isdigit(message[4]) || !isdigit(message[5]))
2834                 return 0; /* corrupt? */
2835         email_end[1] = '\0';
2836         tz = strtol(message + 1, NULL, 10);
2837         if (message[6] != '\t')
2838                 message += 6;
2839         else
2840                 message += 7;
2841         return fn(osha1, nsha1, sb->buf + 82, timestamp, tz, message, cb_data);
2842 }
2843
2844 static char *find_beginning_of_line(char *bob, char *scan)
2845 {
2846         while (bob < scan && *(--scan) != '\n')
2847                 ; /* keep scanning backwards */
2848         /*
2849          * Return either beginning of the buffer, or LF at the end of
2850          * the previous line.
2851          */
2852         return scan;
2853 }
2854
2855 int for_each_reflog_ent_reverse(const char *refname, each_reflog_ent_fn fn, void *cb_data)
2856 {
2857         struct strbuf sb = STRBUF_INIT;
2858         FILE *logfp;
2859         long pos;
2860         int ret = 0, at_tail = 1;
2861
2862         logfp = fopen(git_path("logs/%s", refname), "r");
2863         if (!logfp)
2864                 return -1;
2865
2866         /* Jump to the end */
2867         if (fseek(logfp, 0, SEEK_END) < 0)
2868                 return error("cannot seek back reflog for %s: %s",
2869                              refname, strerror(errno));
2870         pos = ftell(logfp);
2871         while (!ret && 0 < pos) {
2872                 int cnt;
2873                 size_t nread;
2874                 char buf[BUFSIZ];
2875                 char *endp, *scanp;
2876
2877                 /* Fill next block from the end */
2878                 cnt = (sizeof(buf) < pos) ? sizeof(buf) : pos;
2879                 if (fseek(logfp, pos - cnt, SEEK_SET))
2880                         return error("cannot seek back reflog for %s: %s",
2881                                      refname, strerror(errno));
2882                 nread = fread(buf, cnt, 1, logfp);
2883                 if (nread != 1)
2884                         return error("cannot read %d bytes from reflog for %s: %s",
2885                                      cnt, refname, strerror(errno));
2886                 pos -= cnt;
2887
2888                 scanp = endp = buf + cnt;
2889                 if (at_tail && scanp[-1] == '\n')
2890                         /* Looking at the final LF at the end of the file */
2891                         scanp--;
2892                 at_tail = 0;
2893
2894                 while (buf < scanp) {
2895                         /*
2896                          * terminating LF of the previous line, or the beginning
2897                          * of the buffer.
2898                          */
2899                         char *bp;
2900
2901                         bp = find_beginning_of_line(buf, scanp);
2902
2903                         if (*bp == '\n') {
2904                                 /*
2905                                  * The newline is the end of the previous line,
2906                                  * so we know we have complete line starting
2907                                  * at (bp + 1). Prefix it onto any prior data
2908                                  * we collected for the line and process it.
2909                                  */
2910                                 strbuf_splice(&sb, 0, 0, bp + 1, endp - (bp + 1));
2911                                 scanp = bp;
2912                                 endp = bp + 1;
2913                                 ret = show_one_reflog_ent(&sb, fn, cb_data);
2914                                 strbuf_reset(&sb);
2915                                 if (ret)
2916                                         break;
2917                         } else if (!pos) {
2918                                 /*
2919                                  * We are at the start of the buffer, and the
2920                                  * start of the file; there is no previous
2921                                  * line, and we have everything for this one.
2922                                  * Process it, and we can end the loop.
2923                                  */
2924                                 strbuf_splice(&sb, 0, 0, buf, endp - buf);
2925                                 ret = show_one_reflog_ent(&sb, fn, cb_data);
2926                                 strbuf_reset(&sb);
2927                                 break;
2928                         }
2929
2930                         if (bp == buf) {
2931                                 /*
2932                                  * We are at the start of the buffer, and there
2933                                  * is more file to read backwards. Which means
2934                                  * we are in the middle of a line. Note that we
2935                                  * may get here even if *bp was a newline; that
2936                                  * just means we are at the exact end of the
2937                                  * previous line, rather than some spot in the
2938                                  * middle.
2939                                  *
2940                                  * Save away what we have to be combined with
2941                                  * the data from the next read.
2942                                  */
2943                                 strbuf_splice(&sb, 0, 0, buf, endp - buf);
2944                                 break;
2945                         }
2946                 }
2947
2948         }
2949         if (!ret && sb.len)
2950                 die("BUG: reverse reflog parser had leftover data");
2951
2952         fclose(logfp);
2953         strbuf_release(&sb);
2954         return ret;
2955 }
2956
2957 int for_each_reflog_ent(const char *refname, each_reflog_ent_fn fn, void *cb_data)
2958 {
2959         FILE *logfp;
2960         struct strbuf sb = STRBUF_INIT;
2961         int ret = 0;
2962
2963         logfp = fopen(git_path("logs/%s", refname), "r");
2964         if (!logfp)
2965                 return -1;
2966
2967         while (!ret && !strbuf_getwholeline(&sb, logfp, '\n'))
2968                 ret = show_one_reflog_ent(&sb, fn, cb_data);
2969         fclose(logfp);
2970         strbuf_release(&sb);
2971         return ret;
2972 }
2973 /*
2974  * Call fn for each reflog in the namespace indicated by name.  name
2975  * must be empty or end with '/'.  Name will be used as a scratch
2976  * space, but its contents will be restored before return.
2977  */
2978 static int do_for_each_reflog(struct strbuf *name, each_ref_fn fn, void *cb_data)
2979 {
2980         DIR *d = opendir(git_path("logs/%s", name->buf));
2981         int retval = 0;
2982         struct dirent *de;
2983         int oldlen = name->len;
2984
2985         if (!d)
2986                 return name->len ? errno : 0;
2987
2988         while ((de = readdir(d)) != NULL) {
2989                 struct stat st;
2990
2991                 if (de->d_name[0] == '.')
2992                         continue;
2993                 if (ends_with(de->d_name, ".lock"))
2994                         continue;
2995                 strbuf_addstr(name, de->d_name);
2996                 if (stat(git_path("logs/%s", name->buf), &st) < 0) {
2997                         ; /* silently ignore */
2998                 } else {
2999                         if (S_ISDIR(st.st_mode)) {
3000                                 strbuf_addch(name, '/');
3001                                 retval = do_for_each_reflog(name, fn, cb_data);
3002                         } else {
3003                                 struct object_id oid;
3004
3005                                 if (read_ref_full(name->buf, 0, oid.hash, NULL))
3006                                         retval = error("bad ref for %s", name->buf);
3007                                 else
3008                                         retval = fn(name->buf, &oid, 0, cb_data);
3009                         }
3010                         if (retval)
3011                                 break;
3012                 }
3013                 strbuf_setlen(name, oldlen);
3014         }
3015         closedir(d);
3016         return retval;
3017 }
3018
3019 int for_each_reflog(each_ref_fn fn, void *cb_data)
3020 {
3021         int retval;
3022         struct strbuf name;
3023         strbuf_init(&name, PATH_MAX);
3024         retval = do_for_each_reflog(&name, fn, cb_data);
3025         strbuf_release(&name);
3026         return retval;
3027 }
3028
3029 static int ref_update_reject_duplicates(struct string_list *refnames,
3030                                         struct strbuf *err)
3031 {
3032         int i, n = refnames->nr;
3033
3034         assert(err);
3035
3036         for (i = 1; i < n; i++)
3037                 if (!strcmp(refnames->items[i - 1].string, refnames->items[i].string)) {
3038                         strbuf_addf(err,
3039                                     "Multiple updates for ref '%s' not allowed.",
3040                                     refnames->items[i].string);
3041                         return 1;
3042                 }
3043         return 0;
3044 }
3045
3046 int ref_transaction_commit(struct ref_transaction *transaction,
3047                            struct strbuf *err)
3048 {
3049         int ret = 0, i;
3050         struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;
3051         struct string_list_item *ref_to_delete;
3052         struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
3053
3054         assert(err);
3055
3056         if (transaction->state != REF_TRANSACTION_OPEN)
3057                 die("BUG: commit called for transaction that is not open");
3058
3059         if (!transaction->nr) {
3060                 transaction->state = REF_TRANSACTION_CLOSED;
3061                 return 0;
3062         }
3063
3064         /* Fail if a refname appears more than once in the transaction: */
3065         for (i = 0; i < transaction->nr; i++)
3066                 string_list_append(&affected_refnames,
3067                                    transaction->updates[i]->refname);
3068         string_list_sort(&affected_refnames);
3069         if (ref_update_reject_duplicates(&affected_refnames, err)) {
3070                 ret = TRANSACTION_GENERIC_ERROR;
3071                 goto cleanup;
3072         }
3073
3074         /*
3075          * Acquire all locks, verify old values if provided, check
3076          * that new values are valid, and write new values to the
3077          * lockfiles, ready to be activated. Only keep one lockfile
3078          * open at a time to avoid running out of file descriptors.
3079          */
3080         for (i = 0; i < transaction->nr; i++) {
3081                 struct ref_update *update = transaction->updates[i];
3082
3083                 if ((update->flags & REF_HAVE_NEW) &&
3084                     is_null_sha1(update->new_sha1))
3085                         update->flags |= REF_DELETING;
3086                 update->lock = lock_ref_sha1_basic(
3087                                 update->refname,
3088                                 ((update->flags & REF_HAVE_OLD) ?
3089                                  update->old_sha1 : NULL),
3090                                 &affected_refnames, NULL,
3091                                 update->flags,
3092                                 &update->type,
3093                                 err);
3094                 if (!update->lock) {
3095                         char *reason;
3096
3097                         ret = (errno == ENOTDIR)
3098                                 ? TRANSACTION_NAME_CONFLICT
3099                                 : TRANSACTION_GENERIC_ERROR;
3100                         reason = strbuf_detach(err, NULL);
3101                         strbuf_addf(err, "cannot lock ref '%s': %s",
3102                                     update->refname, reason);
3103                         free(reason);
3104                         goto cleanup;
3105                 }
3106                 if ((update->flags & REF_HAVE_NEW) &&
3107                     !(update->flags & REF_DELETING)) {
3108                         int overwriting_symref = ((update->type & REF_ISSYMREF) &&
3109                                                   (update->flags & REF_NODEREF));
3110
3111                         if (!overwriting_symref &&
3112                             !hashcmp(update->lock->old_oid.hash, update->new_sha1)) {
3113                                 /*
3114                                  * The reference already has the desired
3115                                  * value, so we don't need to write it.
3116                                  */
3117                         } else if (write_ref_to_lockfile(update->lock,
3118                                                          update->new_sha1,
3119                                                          err)) {
3120                                 char *write_err = strbuf_detach(err, NULL);
3121
3122                                 /*
3123                                  * The lock was freed upon failure of
3124                                  * write_ref_to_lockfile():
3125                                  */
3126                                 update->lock = NULL;
3127                                 strbuf_addf(err,
3128                                             "cannot update the ref '%s': %s",
3129                                             update->refname, write_err);
3130                                 free(write_err);
3131                                 ret = TRANSACTION_GENERIC_ERROR;
3132                                 goto cleanup;
3133                         } else {
3134                                 update->flags |= REF_NEEDS_COMMIT;
3135                         }
3136                 }
3137                 if (!(update->flags & REF_NEEDS_COMMIT)) {
3138                         /*
3139                          * We didn't have to write anything to the lockfile.
3140                          * Close it to free up the file descriptor:
3141                          */
3142                         if (close_ref(update->lock)) {
3143                                 strbuf_addf(err, "Couldn't close %s.lock",
3144                                             update->refname);
3145                                 goto cleanup;
3146                         }
3147                 }
3148         }
3149
3150         /* Perform updates first so live commits remain referenced */
3151         for (i = 0; i < transaction->nr; i++) {
3152                 struct ref_update *update = transaction->updates[i];
3153
3154                 if (update->flags & REF_NEEDS_COMMIT) {
3155                         if (commit_ref_update(update->lock,
3156                                               update->new_sha1, update->msg,
3157                                               update->flags, err)) {
3158                                 /* freed by commit_ref_update(): */
3159                                 update->lock = NULL;
3160                                 ret = TRANSACTION_GENERIC_ERROR;
3161                                 goto cleanup;
3162                         } else {
3163                                 /* freed by commit_ref_update(): */
3164                                 update->lock = NULL;
3165                         }
3166                 }
3167         }
3168
3169         /* Perform deletes now that updates are safely completed */
3170         for (i = 0; i < transaction->nr; i++) {
3171                 struct ref_update *update = transaction->updates[i];
3172
3173                 if (update->flags & REF_DELETING) {
3174                         if (delete_ref_loose(update->lock, update->type, err)) {
3175                                 ret = TRANSACTION_GENERIC_ERROR;
3176                                 goto cleanup;
3177                         }
3178
3179                         if (!(update->flags & REF_ISPRUNING))
3180                                 string_list_append(&refs_to_delete,
3181                                                    update->lock->ref_name);
3182                 }
3183         }
3184
3185         if (repack_without_refs(&refs_to_delete, err)) {
3186                 ret = TRANSACTION_GENERIC_ERROR;
3187                 goto cleanup;
3188         }
3189         for_each_string_list_item(ref_to_delete, &refs_to_delete)
3190                 unlink_or_warn(git_path("logs/%s", ref_to_delete->string));
3191         clear_loose_ref_cache(&ref_cache);
3192
3193 cleanup:
3194         transaction->state = REF_TRANSACTION_CLOSED;
3195
3196         for (i = 0; i < transaction->nr; i++)
3197                 if (transaction->updates[i]->lock)
3198                         unlock_ref(transaction->updates[i]->lock);
3199         string_list_clear(&refs_to_delete, 0);
3200         string_list_clear(&affected_refnames, 0);
3201         return ret;
3202 }
3203
3204 static int ref_present(const char *refname,
3205                        const struct object_id *oid, int flags, void *cb_data)
3206 {
3207         struct string_list *affected_refnames = cb_data;
3208
3209         return string_list_has_string(affected_refnames, refname);
3210 }
3211
3212 int initial_ref_transaction_commit(struct ref_transaction *transaction,
3213                                    struct strbuf *err)
3214 {
3215         int ret = 0, i;
3216         struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
3217
3218         assert(err);
3219
3220         if (transaction->state != REF_TRANSACTION_OPEN)
3221                 die("BUG: commit called for transaction that is not open");
3222
3223         /* Fail if a refname appears more than once in the transaction: */
3224         for (i = 0; i < transaction->nr; i++)
3225                 string_list_append(&affected_refnames,
3226                                    transaction->updates[i]->refname);
3227         string_list_sort(&affected_refnames);
3228         if (ref_update_reject_duplicates(&affected_refnames, err)) {
3229                 ret = TRANSACTION_GENERIC_ERROR;
3230                 goto cleanup;
3231         }
3232
3233         /*
3234          * It's really undefined to call this function in an active
3235          * repository or when there are existing references: we are
3236          * only locking and changing packed-refs, so (1) any
3237          * simultaneous processes might try to change a reference at
3238          * the same time we do, and (2) any existing loose versions of
3239          * the references that we are setting would have precedence
3240          * over our values. But some remote helpers create the remote
3241          * "HEAD" and "master" branches before calling this function,
3242          * so here we really only check that none of the references
3243          * that we are creating already exists.
3244          */
3245         if (for_each_rawref(ref_present, &affected_refnames))
3246                 die("BUG: initial ref transaction called with existing refs");
3247
3248         for (i = 0; i < transaction->nr; i++) {
3249                 struct ref_update *update = transaction->updates[i];
3250
3251                 if ((update->flags & REF_HAVE_OLD) &&
3252                     !is_null_sha1(update->old_sha1))
3253                         die("BUG: initial ref transaction with old_sha1 set");
3254                 if (verify_refname_available(update->refname,
3255                                              &affected_refnames, NULL,
3256                                              err)) {
3257                         ret = TRANSACTION_NAME_CONFLICT;
3258                         goto cleanup;
3259                 }
3260         }
3261
3262         if (lock_packed_refs(0)) {
3263                 strbuf_addf(err, "unable to lock packed-refs file: %s",
3264                             strerror(errno));
3265                 ret = TRANSACTION_GENERIC_ERROR;
3266                 goto cleanup;
3267         }
3268
3269         for (i = 0; i < transaction->nr; i++) {
3270                 struct ref_update *update = transaction->updates[i];
3271
3272                 if ((update->flags & REF_HAVE_NEW) &&
3273                     !is_null_sha1(update->new_sha1))
3274                         add_packed_ref(update->refname, update->new_sha1);
3275         }
3276
3277         if (commit_packed_refs()) {
3278                 strbuf_addf(err, "unable to commit packed-refs file: %s",
3279                             strerror(errno));
3280                 ret = TRANSACTION_GENERIC_ERROR;
3281                 goto cleanup;
3282         }
3283
3284 cleanup:
3285         transaction->state = REF_TRANSACTION_CLOSED;
3286         string_list_clear(&affected_refnames, 0);
3287         return ret;
3288 }
3289
3290 struct expire_reflog_cb {
3291         unsigned int flags;
3292         reflog_expiry_should_prune_fn *should_prune_fn;
3293         void *policy_cb;
3294         FILE *newlog;
3295         unsigned char last_kept_sha1[20];
3296 };
3297
3298 static int expire_reflog_ent(unsigned char *osha1, unsigned char *nsha1,
3299                              const char *email, unsigned long timestamp, int tz,
3300                              const char *message, void *cb_data)
3301 {
3302         struct expire_reflog_cb *cb = cb_data;
3303         struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;
3304
3305         if (cb->flags & EXPIRE_REFLOGS_REWRITE)
3306                 osha1 = cb->last_kept_sha1;
3307
3308         if ((*cb->should_prune_fn)(osha1, nsha1, email, timestamp, tz,
3309                                    message, policy_cb)) {
3310                 if (!cb->newlog)
3311                         printf("would prune %s", message);
3312                 else if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
3313                         printf("prune %s", message);
3314         } else {
3315                 if (cb->newlog) {
3316                         fprintf(cb->newlog, "%s %s %s %lu %+05d\t%s",
3317                                 sha1_to_hex(osha1), sha1_to_hex(nsha1),
3318                                 email, timestamp, tz, message);
3319                         hashcpy(cb->last_kept_sha1, nsha1);
3320                 }
3321                 if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
3322                         printf("keep %s", message);
3323         }
3324         return 0;
3325 }
3326
3327 int reflog_expire(const char *refname, const unsigned char *sha1,
3328                  unsigned int flags,
3329                  reflog_expiry_prepare_fn prepare_fn,
3330                  reflog_expiry_should_prune_fn should_prune_fn,
3331                  reflog_expiry_cleanup_fn cleanup_fn,
3332                  void *policy_cb_data)
3333 {
3334         static struct lock_file reflog_lock;
3335         struct expire_reflog_cb cb;
3336         struct ref_lock *lock;
3337         char *log_file;
3338         int status = 0;
3339         int type;
3340         struct strbuf err = STRBUF_INIT;
3341
3342         memset(&cb, 0, sizeof(cb));
3343         cb.flags = flags;
3344         cb.policy_cb = policy_cb_data;
3345         cb.should_prune_fn = should_prune_fn;
3346
3347         /*
3348          * The reflog file is locked by holding the lock on the
3349          * reference itself, plus we might need to update the
3350          * reference if --updateref was specified:
3351          */
3352         lock = lock_ref_sha1_basic(refname, sha1, NULL, NULL, REF_NODEREF,
3353                                    &type, &err);
3354         if (!lock) {
3355                 error("cannot lock ref '%s': %s", refname, err.buf);
3356                 strbuf_release(&err);
3357                 return -1;
3358         }
3359         if (!reflog_exists(refname)) {
3360                 unlock_ref(lock);
3361                 return 0;
3362         }
3363
3364         log_file = git_pathdup("logs/%s", refname);
3365         if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
3366                 /*
3367                  * Even though holding $GIT_DIR/logs/$reflog.lock has
3368                  * no locking implications, we use the lock_file
3369                  * machinery here anyway because it does a lot of the
3370                  * work we need, including cleaning up if the program
3371                  * exits unexpectedly.
3372                  */
3373                 if (hold_lock_file_for_update(&reflog_lock, log_file, 0) < 0) {
3374                         struct strbuf err = STRBUF_INIT;
3375                         unable_to_lock_message(log_file, errno, &err);
3376                         error("%s", err.buf);
3377                         strbuf_release(&err);
3378                         goto failure;
3379                 }
3380                 cb.newlog = fdopen_lock_file(&reflog_lock, "w");
3381                 if (!cb.newlog) {
3382                         error("cannot fdopen %s (%s)",
3383                               get_lock_file_path(&reflog_lock), strerror(errno));
3384                         goto failure;
3385                 }
3386         }
3387
3388         (*prepare_fn)(refname, sha1, cb.policy_cb);
3389         for_each_reflog_ent(refname, expire_reflog_ent, &cb);
3390         (*cleanup_fn)(cb.policy_cb);
3391
3392         if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
3393                 /*
3394                  * It doesn't make sense to adjust a reference pointed
3395                  * to by a symbolic ref based on expiring entries in
3396                  * the symbolic reference's reflog. Nor can we update
3397                  * a reference if there are no remaining reflog
3398                  * entries.
3399                  */
3400                 int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&
3401                         !(type & REF_ISSYMREF) &&
3402                         !is_null_sha1(cb.last_kept_sha1);
3403
3404                 if (close_lock_file(&reflog_lock)) {
3405                         status |= error("couldn't write %s: %s", log_file,
3406                                         strerror(errno));
3407                 } else if (update &&
3408                            (write_in_full(get_lock_file_fd(lock->lk),
3409                                 sha1_to_hex(cb.last_kept_sha1), 40) != 40 ||
3410                             write_str_in_full(get_lock_file_fd(lock->lk), "\n") != 1 ||
3411                             close_ref(lock) < 0)) {
3412                         status |= error("couldn't write %s",
3413                                         get_lock_file_path(lock->lk));
3414                         rollback_lock_file(&reflog_lock);
3415                 } else if (commit_lock_file(&reflog_lock)) {
3416                         status |= error("unable to write reflog '%s' (%s)",
3417                                         log_file, strerror(errno));
3418                 } else if (update && commit_ref(lock)) {
3419                         status |= error("couldn't set %s", lock->ref_name);
3420                 }
3421         }
3422         free(log_file);
3423         unlock_ref(lock);
3424         return status;
3425
3426  failure:
3427         rollback_lock_file(&reflog_lock);
3428         free(log_file);
3429         unlock_ref(lock);
3430         return -1;
3431 }