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