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