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