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