refs: read loose references lazily
[git] / refs.c
1 #include "cache.h"
2 #include "refs.h"
3 #include "object.h"
4 #include "tag.h"
5 #include "dir.h"
6
7 /*
8  * Make sure "ref" is something reasonable to have under ".git/refs/";
9  * We do not like it if:
10  *
11  * - any path component of it begins with ".", or
12  * - it has double dots "..", or
13  * - it has ASCII control character, "~", "^", ":" or SP, anywhere, or
14  * - it ends with a "/".
15  * - it ends with ".lock"
16  * - it contains a "\" (backslash)
17  */
18
19 /* Return true iff ch is not allowed in reference names. */
20 static inline int bad_ref_char(int ch)
21 {
22         if (((unsigned) ch) <= ' ' || ch == 0x7f ||
23             ch == '~' || ch == '^' || ch == ':' || ch == '\\')
24                 return 1;
25         /* 2.13 Pattern Matching Notation */
26         if (ch == '*' || ch == '?' || ch == '[') /* Unsupported */
27                 return 1;
28         return 0;
29 }
30
31 /*
32  * Try to read one refname component from the front of refname.  Return
33  * the length of the component found, or -1 if the component is not
34  * legal.
35  */
36 static int check_refname_component(const char *refname, int flags)
37 {
38         const char *cp;
39         char last = '\0';
40
41         for (cp = refname; ; cp++) {
42                 char ch = *cp;
43                 if (ch == '\0' || ch == '/')
44                         break;
45                 if (bad_ref_char(ch))
46                         return -1; /* Illegal character in refname. */
47                 if (last == '.' && ch == '.')
48                         return -1; /* Refname contains "..". */
49                 if (last == '@' && ch == '{')
50                         return -1; /* Refname contains "@{". */
51                 last = ch;
52         }
53         if (cp == refname)
54                 return 0; /* Component has zero length. */
55         if (refname[0] == '.') {
56                 if (!(flags & REFNAME_DOT_COMPONENT))
57                         return -1; /* Component starts with '.'. */
58                 /*
59                  * Even if leading dots are allowed, don't allow "."
60                  * as a component (".." is prevented by a rule above).
61                  */
62                 if (refname[1] == '\0')
63                         return -1; /* Component equals ".". */
64         }
65         if (cp - refname >= 5 && !memcmp(cp - 5, ".lock", 5))
66                 return -1; /* Refname ends with ".lock". */
67         return cp - refname;
68 }
69
70 int check_refname_format(const char *refname, int flags)
71 {
72         int component_len, component_count = 0;
73
74         while (1) {
75                 /* We are at the start of a path component. */
76                 component_len = check_refname_component(refname, flags);
77                 if (component_len <= 0) {
78                         if ((flags & REFNAME_REFSPEC_PATTERN) &&
79                                         refname[0] == '*' &&
80                                         (refname[1] == '\0' || refname[1] == '/')) {
81                                 /* Accept one wildcard as a full refname component. */
82                                 flags &= ~REFNAME_REFSPEC_PATTERN;
83                                 component_len = 1;
84                         } else {
85                                 return -1;
86                         }
87                 }
88                 component_count++;
89                 if (refname[component_len] == '\0')
90                         break;
91                 /* Skip to next component. */
92                 refname += component_len + 1;
93         }
94
95         if (refname[component_len - 1] == '.')
96                 return -1; /* Refname ends with '.'. */
97         if (!(flags & REFNAME_ALLOW_ONELEVEL) && component_count < 2)
98                 return -1; /* Refname has only one component. */
99         return 0;
100 }
101
102 struct ref_entry;
103
104 /*
105  * Information used (along with the information in ref_entry) to
106  * describe a single cached reference.  This data structure only
107  * occurs embedded in a union in struct ref_entry, and only when
108  * (ref_entry->flag & REF_DIR) is zero.
109  */
110 struct ref_value {
111         unsigned char sha1[20];
112         unsigned char peeled[20];
113 };
114
115 struct ref_cache;
116
117 /*
118  * Information used (along with the information in ref_entry) to
119  * describe a level in the hierarchy of references.  This data
120  * structure only occurs embedded in a union in struct ref_entry, and
121  * only when (ref_entry.flag & REF_DIR) is set.  In that case,
122  * (ref_entry.flag & REF_INCOMPLETE) determines whether the references
123  * in the directory have already been read:
124  *
125  *     (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose
126  *         or packed references, already read.
127  *
128  *     (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose
129  *         references that hasn't been read yet (nor has any of its
130  *         subdirectories).
131  *
132  * Entries within a directory are stored within a growable array of
133  * pointers to ref_entries (entries, nr, alloc).  Entries 0 <= i <
134  * sorted are sorted by their component name in strcmp() order and the
135  * remaining entries are unsorted.
136  *
137  * Loose references are read lazily, one directory at a time.  When a
138  * directory of loose references is read, then all of the references
139  * in that directory are stored, and REF_INCOMPLETE stubs are created
140  * for any subdirectories, but the subdirectories themselves are not
141  * read.  The reading is triggered by get_ref_dir().
142  */
143 struct ref_dir {
144         int nr, alloc;
145
146         /*
147          * Entries with index 0 <= i < sorted are sorted by name.  New
148          * entries are appended to the list unsorted, and are sorted
149          * only when required; thus we avoid the need to sort the list
150          * after the addition of every reference.
151          */
152         int sorted;
153
154         /* A pointer to the ref_cache that contains this ref_dir. */
155         struct ref_cache *ref_cache;
156
157         struct ref_entry **entries;
158 };
159
160 /* ISSYMREF=0x01, ISPACKED=0x02, and ISBROKEN=0x04 are public interfaces */
161 #define REF_KNOWS_PEELED 0x08
162
163 /* ref_entry represents a directory of references */
164 #define REF_DIR 0x10
165
166 /*
167  * Entry has not yet been read from disk (used only for REF_DIR
168  * entries representing loose references)
169  */
170 #define REF_INCOMPLETE 0x20
171
172 /*
173  * A ref_entry represents either a reference or a "subdirectory" of
174  * references.
175  *
176  * Each directory in the reference namespace is represented by a
177  * ref_entry with (flags & REF_DIR) set and containing a subdir member
178  * that holds the entries in that directory that have been read so
179  * far.  If (flags & REF_INCOMPLETE) is set, then the directory and
180  * its subdirectories haven't been read yet.  REF_INCOMPLETE is only
181  * used for loose reference directories.
182  *
183  * References are represented by a ref_entry with (flags & REF_DIR)
184  * unset and a value member that describes the reference's value.  The
185  * flag member is at the ref_entry level, but it is also needed to
186  * interpret the contents of the value field (in other words, a
187  * ref_value object is not very much use without the enclosing
188  * ref_entry).
189  *
190  * Reference names cannot end with slash and directories' names are
191  * always stored with a trailing slash (except for the top-level
192  * directory, which is always denoted by "").  This has two nice
193  * consequences: (1) when the entries in each subdir are sorted
194  * lexicographically by name (as they usually are), the references in
195  * a whole tree can be generated in lexicographic order by traversing
196  * the tree in left-to-right, depth-first order; (2) the names of
197  * references and subdirectories cannot conflict, and therefore the
198  * presence of an empty subdirectory does not block the creation of a
199  * similarly-named reference.  (The fact that reference names with the
200  * same leading components can conflict *with each other* is a
201  * separate issue that is regulated by is_refname_available().)
202  *
203  * Please note that the name field contains the fully-qualified
204  * reference (or subdirectory) name.  Space could be saved by only
205  * storing the relative names.  But that would require the full names
206  * to be generated on the fly when iterating in do_for_each_ref(), and
207  * would break callback functions, who have always been able to assume
208  * that the name strings that they are passed will not be freed during
209  * the iteration.
210  */
211 struct ref_entry {
212         unsigned char flag; /* ISSYMREF? ISPACKED? */
213         union {
214                 struct ref_value value; /* if not (flags&REF_DIR) */
215                 struct ref_dir subdir; /* if (flags&REF_DIR) */
216         } u;
217         /*
218          * The full name of the reference (e.g., "refs/heads/master")
219          * or the full name of the directory with a trailing slash
220          * (e.g., "refs/heads/"):
221          */
222         char name[FLEX_ARRAY];
223 };
224
225 static void read_loose_refs(const char *dirname, struct ref_dir *dir);
226
227 static struct ref_dir *get_ref_dir(struct ref_entry *entry)
228 {
229         struct ref_dir *dir;
230         assert(entry->flag & REF_DIR);
231         dir = &entry->u.subdir;
232         if (entry->flag & REF_INCOMPLETE) {
233                 read_loose_refs(entry->name, dir);
234                 entry->flag &= ~REF_INCOMPLETE;
235         }
236         return dir;
237 }
238
239 static struct ref_entry *create_ref_entry(const char *refname,
240                                           const unsigned char *sha1, int flag,
241                                           int check_name)
242 {
243         int len;
244         struct ref_entry *ref;
245
246         if (check_name &&
247             check_refname_format(refname, REFNAME_ALLOW_ONELEVEL|REFNAME_DOT_COMPONENT))
248                 die("Reference has invalid format: '%s'", refname);
249         len = strlen(refname) + 1;
250         ref = xmalloc(sizeof(struct ref_entry) + len);
251         hashcpy(ref->u.value.sha1, sha1);
252         hashclr(ref->u.value.peeled);
253         memcpy(ref->name, refname, len);
254         ref->flag = flag;
255         return ref;
256 }
257
258 static void clear_ref_dir(struct ref_dir *dir);
259
260 static void free_ref_entry(struct ref_entry *entry)
261 {
262         if (entry->flag & REF_DIR)
263                 clear_ref_dir(get_ref_dir(entry));
264         free(entry);
265 }
266
267 /*
268  * Add a ref_entry to the end of dir (unsorted).  Entry is always
269  * stored directly in dir; no recursion into subdirectories is
270  * done.
271  */
272 static void add_entry_to_dir(struct ref_dir *dir, struct ref_entry *entry)
273 {
274         ALLOC_GROW(dir->entries, dir->nr + 1, dir->alloc);
275         dir->entries[dir->nr++] = entry;
276 }
277
278 /*
279  * Clear and free all entries in dir, recursively.
280  */
281 static void clear_ref_dir(struct ref_dir *dir)
282 {
283         int i;
284         for (i = 0; i < dir->nr; i++)
285                 free_ref_entry(dir->entries[i]);
286         free(dir->entries);
287         dir->sorted = dir->nr = dir->alloc = 0;
288         dir->entries = NULL;
289 }
290
291 /*
292  * Create a struct ref_entry object for the specified dirname.
293  * dirname is the name of the directory with a trailing slash (e.g.,
294  * "refs/heads/") or "" for the top-level directory.
295  */
296 static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache,
297                                           const char *dirname, int incomplete)
298 {
299         struct ref_entry *direntry;
300         int len = strlen(dirname);
301         direntry = xcalloc(1, sizeof(struct ref_entry) + len + 1);
302         memcpy(direntry->name, dirname, len + 1);
303         direntry->u.subdir.ref_cache = ref_cache;
304         direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE : 0);
305         return direntry;
306 }
307
308 static int ref_entry_cmp(const void *a, const void *b)
309 {
310         struct ref_entry *one = *(struct ref_entry **)a;
311         struct ref_entry *two = *(struct ref_entry **)b;
312         return strcmp(one->name, two->name);
313 }
314
315 static void sort_ref_dir(struct ref_dir *dir);
316
317 /*
318  * Return the entry with the given refname from the ref_dir
319  * (non-recursively), sorting dir if necessary.  Return NULL if no
320  * such entry is found.  dir must already be complete.
321  */
322 static struct ref_entry *search_ref_dir(struct ref_dir *dir, const char *refname)
323 {
324         struct ref_entry *e, **r;
325         int len;
326
327         if (refname == NULL || !dir->nr)
328                 return NULL;
329
330         sort_ref_dir(dir);
331
332         len = strlen(refname) + 1;
333         e = xmalloc(sizeof(struct ref_entry) + len);
334         memcpy(e->name, refname, len);
335
336         r = bsearch(&e, dir->entries, dir->nr, sizeof(*dir->entries), ref_entry_cmp);
337
338         free(e);
339
340         if (r == NULL)
341                 return NULL;
342
343         return *r;
344 }
345
346 /*
347  * Search for a directory entry directly within dir (without
348  * recursing).  Sort dir if necessary.  subdirname must be a directory
349  * name (i.e., end in '/').  If mkdir is set, then create the
350  * directory if it is missing; otherwise, return NULL if the desired
351  * directory cannot be found.  dir must already be complete.
352  */
353 static struct ref_dir *search_for_subdir(struct ref_dir *dir,
354                                          const char *subdirname, int mkdir)
355 {
356         struct ref_entry *entry = search_ref_dir(dir, subdirname);
357         if (!entry) {
358                 if (!mkdir)
359                         return NULL;
360                 /*
361                  * Since dir is complete, the absence of a subdir
362                  * means that the subdir really doesn't exist;
363                  * therefore, create an empty record for it but mark
364                  * the record complete.
365                  */
366                 entry = create_dir_entry(dir->ref_cache, subdirname, 0);
367                 add_entry_to_dir(dir, entry);
368         }
369         return get_ref_dir(entry);
370 }
371
372 /*
373  * If refname is a reference name, find the ref_dir within the dir
374  * tree that should hold refname.  If refname is a directory name
375  * (i.e., ends in '/'), then return that ref_dir itself.  dir must
376  * represent the top-level directory and must already be complete.
377  * Sort ref_dirs and recurse into subdirectories as necessary.  If
378  * mkdir is set, then create any missing directories; otherwise,
379  * return NULL if the desired directory cannot be found.
380  */
381 static struct ref_dir *find_containing_dir(struct ref_dir *dir,
382                                            const char *refname, int mkdir)
383 {
384         struct strbuf dirname;
385         const char *slash;
386         strbuf_init(&dirname, PATH_MAX);
387         for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) {
388                 struct ref_dir *subdir;
389                 strbuf_add(&dirname,
390                            refname + dirname.len,
391                            (slash + 1) - (refname + dirname.len));
392                 subdir = search_for_subdir(dir, dirname.buf, mkdir);
393                 if (!subdir)
394                         break;
395                 dir = subdir;
396         }
397
398         strbuf_release(&dirname);
399         return dir;
400 }
401
402 /*
403  * Find the value entry with the given name in dir, sorting ref_dirs
404  * and recursing into subdirectories as necessary.  If the name is not
405  * found or it corresponds to a directory entry, return NULL.
406  */
407 static struct ref_entry *find_ref(struct ref_dir *dir, const char *refname)
408 {
409         struct ref_entry *entry;
410         dir = find_containing_dir(dir, refname, 0);
411         if (!dir)
412                 return NULL;
413         entry = search_ref_dir(dir, refname);
414         return (entry && !(entry->flag & REF_DIR)) ? entry : NULL;
415 }
416
417 /*
418  * Add a ref_entry to the ref_dir (unsorted), recursing into
419  * subdirectories as necessary.  dir must represent the top-level
420  * directory.  Return 0 on success.
421  */
422 static int add_ref(struct ref_dir *dir, struct ref_entry *ref)
423 {
424         dir = find_containing_dir(dir, ref->name, 1);
425         if (!dir)
426                 return -1;
427         add_entry_to_dir(dir, ref);
428         return 0;
429 }
430
431 /*
432  * Emit a warning and return true iff ref1 and ref2 have the same name
433  * and the same sha1.  Die if they have the same name but different
434  * sha1s.
435  */
436 static int is_dup_ref(const struct ref_entry *ref1, const struct ref_entry *ref2)
437 {
438         if (strcmp(ref1->name, ref2->name))
439                 return 0;
440
441         /* Duplicate name; make sure that they don't conflict: */
442
443         if ((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR))
444                 /* This is impossible by construction */
445                 die("Reference directory conflict: %s", ref1->name);
446
447         if (hashcmp(ref1->u.value.sha1, ref2->u.value.sha1))
448                 die("Duplicated ref, and SHA1s don't match: %s", ref1->name);
449
450         warning("Duplicated ref: %s", ref1->name);
451         return 1;
452 }
453
454 /*
455  * Sort the entries in dir non-recursively (if they are not already
456  * sorted) and remove any duplicate entries.
457  */
458 static void sort_ref_dir(struct ref_dir *dir)
459 {
460         int i, j;
461         struct ref_entry *last = NULL;
462
463         /*
464          * This check also prevents passing a zero-length array to qsort(),
465          * which is a problem on some platforms.
466          */
467         if (dir->sorted == dir->nr)
468                 return;
469
470         qsort(dir->entries, dir->nr, sizeof(*dir->entries), ref_entry_cmp);
471
472         /* Remove any duplicates: */
473         for (i = 0, j = 0; j < dir->nr; j++) {
474                 struct ref_entry *entry = dir->entries[j];
475                 if (last && is_dup_ref(last, entry))
476                         free_ref_entry(entry);
477                 else
478                         last = dir->entries[i++] = entry;
479         }
480         dir->sorted = dir->nr = i;
481 }
482
483 #define DO_FOR_EACH_INCLUDE_BROKEN 01
484
485 static struct ref_entry *current_ref;
486
487 static int do_one_ref(const char *base, each_ref_fn fn, int trim,
488                       int flags, void *cb_data, struct ref_entry *entry)
489 {
490         int retval;
491         if (prefixcmp(entry->name, base))
492                 return 0;
493
494         if (!(flags & DO_FOR_EACH_INCLUDE_BROKEN)) {
495                 if (entry->flag & REF_ISBROKEN)
496                         return 0; /* ignore broken refs e.g. dangling symref */
497                 if (!has_sha1_file(entry->u.value.sha1)) {
498                         error("%s does not point to a valid object!", entry->name);
499                         return 0;
500                 }
501         }
502         current_ref = entry;
503         retval = fn(entry->name + trim, entry->u.value.sha1, entry->flag, cb_data);
504         current_ref = NULL;
505         return retval;
506 }
507
508 /*
509  * Call fn for each reference in dir that has index in the range
510  * offset <= index < dir->nr.  Recurse into subdirectories that are in
511  * that index range, sorting them before iterating.  This function
512  * does not sort dir itself; it should be sorted beforehand.
513  */
514 static int do_for_each_ref_in_dir(struct ref_dir *dir, int offset,
515                                   const char *base,
516                                   each_ref_fn fn, int trim, int flags, void *cb_data)
517 {
518         int i;
519         assert(dir->sorted == dir->nr);
520         for (i = offset; i < dir->nr; i++) {
521                 struct ref_entry *entry = dir->entries[i];
522                 int retval;
523                 if (entry->flag & REF_DIR) {
524                         struct ref_dir *subdir = get_ref_dir(entry);
525                         sort_ref_dir(subdir);
526                         retval = do_for_each_ref_in_dir(subdir, 0,
527                                                         base, fn, trim, flags, cb_data);
528                 } else {
529                         retval = do_one_ref(base, fn, trim, flags, cb_data, entry);
530                 }
531                 if (retval)
532                         return retval;
533         }
534         return 0;
535 }
536
537 /*
538  * Call fn for each reference in the union of dir1 and dir2, in order
539  * by refname.  Recurse into subdirectories.  If a value entry appears
540  * in both dir1 and dir2, then only process the version that is in
541  * dir2.  The input dirs must already be sorted, but subdirs will be
542  * sorted as needed.
543  */
544 static int do_for_each_ref_in_dirs(struct ref_dir *dir1,
545                                    struct ref_dir *dir2,
546                                    const char *base, each_ref_fn fn, int trim,
547                                    int flags, void *cb_data)
548 {
549         int retval;
550         int i1 = 0, i2 = 0;
551
552         assert(dir1->sorted == dir1->nr);
553         assert(dir2->sorted == dir2->nr);
554         while (1) {
555                 struct ref_entry *e1, *e2;
556                 int cmp;
557                 if (i1 == dir1->nr) {
558                         return do_for_each_ref_in_dir(dir2, i2,
559                                                       base, fn, trim, flags, cb_data);
560                 }
561                 if (i2 == dir2->nr) {
562                         return do_for_each_ref_in_dir(dir1, i1,
563                                                       base, fn, trim, flags, cb_data);
564                 }
565                 e1 = dir1->entries[i1];
566                 e2 = dir2->entries[i2];
567                 cmp = strcmp(e1->name, e2->name);
568                 if (cmp == 0) {
569                         if ((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) {
570                                 /* Both are directories; descend them in parallel. */
571                                 struct ref_dir *subdir1 = get_ref_dir(e1);
572                                 struct ref_dir *subdir2 = get_ref_dir(e2);
573                                 sort_ref_dir(subdir1);
574                                 sort_ref_dir(subdir2);
575                                 retval = do_for_each_ref_in_dirs(
576                                                 subdir1, subdir2,
577                                                 base, fn, trim, flags, cb_data);
578                                 i1++;
579                                 i2++;
580                         } else if (!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) {
581                                 /* Both are references; ignore the one from dir1. */
582                                 retval = do_one_ref(base, fn, trim, flags, cb_data, e2);
583                                 i1++;
584                                 i2++;
585                         } else {
586                                 die("conflict between reference and directory: %s",
587                                     e1->name);
588                         }
589                 } else {
590                         struct ref_entry *e;
591                         if (cmp < 0) {
592                                 e = e1;
593                                 i1++;
594                         } else {
595                                 e = e2;
596                                 i2++;
597                         }
598                         if (e->flag & REF_DIR) {
599                                 struct ref_dir *subdir = get_ref_dir(e);
600                                 sort_ref_dir(subdir);
601                                 retval = do_for_each_ref_in_dir(
602                                                 subdir, 0,
603                                                 base, fn, trim, flags, cb_data);
604                         } else {
605                                 retval = do_one_ref(base, fn, trim, flags, cb_data, e);
606                         }
607                 }
608                 if (retval)
609                         return retval;
610         }
611         if (i1 < dir1->nr)
612                 return do_for_each_ref_in_dir(dir1, i1,
613                                               base, fn, trim, flags, cb_data);
614         if (i2 < dir2->nr)
615                 return do_for_each_ref_in_dir(dir2, i2,
616                                               base, fn, trim, flags, cb_data);
617         return 0;
618 }
619
620 /*
621  * Return true iff refname1 and refname2 conflict with each other.
622  * Two reference names conflict if one of them exactly matches the
623  * leading components of the other; e.g., "foo/bar" conflicts with
624  * both "foo" and with "foo/bar/baz" but not with "foo/bar" or
625  * "foo/barbados".
626  */
627 static int names_conflict(const char *refname1, const char *refname2)
628 {
629         for (; *refname1 && *refname1 == *refname2; refname1++, refname2++)
630                 ;
631         return (*refname1 == '\0' && *refname2 == '/')
632                 || (*refname1 == '/' && *refname2 == '\0');
633 }
634
635 struct name_conflict_cb {
636         const char *refname;
637         const char *oldrefname;
638         const char *conflicting_refname;
639 };
640
641 static int name_conflict_fn(const char *existingrefname, const unsigned char *sha1,
642                             int flags, void *cb_data)
643 {
644         struct name_conflict_cb *data = (struct name_conflict_cb *)cb_data;
645         if (data->oldrefname && !strcmp(data->oldrefname, existingrefname))
646                 return 0;
647         if (names_conflict(data->refname, existingrefname)) {
648                 data->conflicting_refname = existingrefname;
649                 return 1;
650         }
651         return 0;
652 }
653
654 /*
655  * Return true iff a reference named refname could be created without
656  * conflicting with the name of an existing reference in array.  If
657  * oldrefname is non-NULL, ignore potential conflicts with oldrefname
658  * (e.g., because oldrefname is scheduled for deletion in the same
659  * operation).
660  */
661 static int is_refname_available(const char *refname, const char *oldrefname,
662                                 struct ref_dir *dir)
663 {
664         struct name_conflict_cb data;
665         data.refname = refname;
666         data.oldrefname = oldrefname;
667         data.conflicting_refname = NULL;
668
669         sort_ref_dir(dir);
670         if (do_for_each_ref_in_dir(dir, 0, "", name_conflict_fn,
671                                    0, DO_FOR_EACH_INCLUDE_BROKEN,
672                                    &data)) {
673                 error("'%s' exists; cannot create '%s'",
674                       data.conflicting_refname, refname);
675                 return 0;
676         }
677         return 1;
678 }
679
680 /*
681  * Future: need to be in "struct repository"
682  * when doing a full libification.
683  */
684 static struct ref_cache {
685         struct ref_cache *next;
686         struct ref_entry *loose;
687         struct ref_entry *packed;
688         /* The submodule name, or "" for the main repo. */
689         char name[FLEX_ARRAY];
690 } *ref_cache;
691
692 static void clear_packed_ref_cache(struct ref_cache *refs)
693 {
694         if (refs->packed) {
695                 free_ref_entry(refs->packed);
696                 refs->packed = NULL;
697         }
698 }
699
700 static void clear_loose_ref_cache(struct ref_cache *refs)
701 {
702         if (refs->loose) {
703                 free_ref_entry(refs->loose);
704                 refs->loose = NULL;
705         }
706 }
707
708 static struct ref_cache *create_ref_cache(const char *submodule)
709 {
710         int len;
711         struct ref_cache *refs;
712         if (!submodule)
713                 submodule = "";
714         len = strlen(submodule) + 1;
715         refs = xcalloc(1, sizeof(struct ref_cache) + len);
716         memcpy(refs->name, submodule, len);
717         return refs;
718 }
719
720 /*
721  * Return a pointer to a ref_cache for the specified submodule. For
722  * the main repository, use submodule==NULL. The returned structure
723  * will be allocated and initialized but not necessarily populated; it
724  * should not be freed.
725  */
726 static struct ref_cache *get_ref_cache(const char *submodule)
727 {
728         struct ref_cache *refs = ref_cache;
729         if (!submodule)
730                 submodule = "";
731         while (refs) {
732                 if (!strcmp(submodule, refs->name))
733                         return refs;
734                 refs = refs->next;
735         }
736
737         refs = create_ref_cache(submodule);
738         refs->next = ref_cache;
739         ref_cache = refs;
740         return refs;
741 }
742
743 void invalidate_ref_cache(const char *submodule)
744 {
745         struct ref_cache *refs = get_ref_cache(submodule);
746         clear_packed_ref_cache(refs);
747         clear_loose_ref_cache(refs);
748 }
749
750 /*
751  * Parse one line from a packed-refs file.  Write the SHA1 to sha1.
752  * Return a pointer to the refname within the line (null-terminated),
753  * or NULL if there was a problem.
754  */
755 static const char *parse_ref_line(char *line, unsigned char *sha1)
756 {
757         /*
758          * 42: the answer to everything.
759          *
760          * In this case, it happens to be the answer to
761          *  40 (length of sha1 hex representation)
762          *  +1 (space in between hex and name)
763          *  +1 (newline at the end of the line)
764          */
765         int len = strlen(line) - 42;
766
767         if (len <= 0)
768                 return NULL;
769         if (get_sha1_hex(line, sha1) < 0)
770                 return NULL;
771         if (!isspace(line[40]))
772                 return NULL;
773         line += 41;
774         if (isspace(*line))
775                 return NULL;
776         if (line[len] != '\n')
777                 return NULL;
778         line[len] = 0;
779
780         return line;
781 }
782
783 static void read_packed_refs(FILE *f, struct ref_dir *dir)
784 {
785         struct ref_entry *last = NULL;
786         char refline[PATH_MAX];
787         int flag = REF_ISPACKED;
788
789         while (fgets(refline, sizeof(refline), f)) {
790                 unsigned char sha1[20];
791                 const char *refname;
792                 static const char header[] = "# pack-refs with:";
793
794                 if (!strncmp(refline, header, sizeof(header)-1)) {
795                         const char *traits = refline + sizeof(header) - 1;
796                         if (strstr(traits, " peeled "))
797                                 flag |= REF_KNOWS_PEELED;
798                         /* perhaps other traits later as well */
799                         continue;
800                 }
801
802                 refname = parse_ref_line(refline, sha1);
803                 if (refname) {
804                         last = create_ref_entry(refname, sha1, flag, 1);
805                         add_ref(dir, last);
806                         continue;
807                 }
808                 if (last &&
809                     refline[0] == '^' &&
810                     strlen(refline) == 42 &&
811                     refline[41] == '\n' &&
812                     !get_sha1_hex(refline + 1, sha1))
813                         hashcpy(last->u.value.peeled, sha1);
814         }
815 }
816
817 static struct ref_dir *get_packed_refs(struct ref_cache *refs)
818 {
819         if (!refs->packed) {
820                 const char *packed_refs_file;
821                 FILE *f;
822
823                 refs->packed = create_dir_entry(refs, "", 0);
824                 if (*refs->name)
825                         packed_refs_file = git_path_submodule(refs->name, "packed-refs");
826                 else
827                         packed_refs_file = git_path("packed-refs");
828                 f = fopen(packed_refs_file, "r");
829                 if (f) {
830                         read_packed_refs(f, get_ref_dir(refs->packed));
831                         fclose(f);
832                 }
833         }
834         return get_ref_dir(refs->packed);
835 }
836
837 void add_packed_ref(const char *refname, const unsigned char *sha1)
838 {
839         add_ref(get_packed_refs(get_ref_cache(NULL)),
840                         create_ref_entry(refname, sha1, REF_ISPACKED, 1));
841 }
842
843 /*
844  * Read the loose references from the namespace dirname into dir
845  * (without recursing).  dirname must end with '/'.  dir must be the
846  * directory entry corresponding to dirname.
847  */
848 static void read_loose_refs(const char *dirname, struct ref_dir *dir)
849 {
850         struct ref_cache *refs = dir->ref_cache;
851         DIR *d;
852         const char *path;
853         struct dirent *de;
854         int dirnamelen = strlen(dirname);
855         struct strbuf refname;
856
857         if (*refs->name)
858                 path = git_path_submodule(refs->name, "%s", dirname);
859         else
860                 path = git_path("%s", dirname);
861
862         d = opendir(path);
863         if (!d)
864                 return;
865
866         strbuf_init(&refname, dirnamelen + 257);
867         strbuf_add(&refname, dirname, dirnamelen);
868
869         while ((de = readdir(d)) != NULL) {
870                 unsigned char sha1[20];
871                 struct stat st;
872                 int flag;
873                 const char *refdir;
874
875                 if (de->d_name[0] == '.')
876                         continue;
877                 if (has_extension(de->d_name, ".lock"))
878                         continue;
879                 strbuf_addstr(&refname, de->d_name);
880                 refdir = *refs->name
881                         ? git_path_submodule(refs->name, "%s", refname.buf)
882                         : git_path("%s", refname.buf);
883                 if (stat(refdir, &st) < 0) {
884                         ; /* silently ignore */
885                 } else if (S_ISDIR(st.st_mode)) {
886                         strbuf_addch(&refname, '/');
887                         add_entry_to_dir(dir,
888                                          create_dir_entry(refs, refname.buf, 1));
889                 } else {
890                         if (*refs->name) {
891                                 hashclr(sha1);
892                                 flag = 0;
893                                 if (resolve_gitlink_ref(refs->name, refname.buf, sha1) < 0) {
894                                         hashclr(sha1);
895                                         flag |= REF_ISBROKEN;
896                                 }
897                         } else if (read_ref_full(refname.buf, sha1, 1, &flag)) {
898                                 hashclr(sha1);
899                                 flag |= REF_ISBROKEN;
900                         }
901                         add_entry_to_dir(dir,
902                                          create_ref_entry(refname.buf, sha1, flag, 1));
903                 }
904                 strbuf_setlen(&refname, dirnamelen);
905         }
906         strbuf_release(&refname);
907         closedir(d);
908 }
909
910 static struct ref_dir *get_loose_refs(struct ref_cache *refs)
911 {
912         if (!refs->loose) {
913                 /*
914                  * Mark the top-level directory complete because we
915                  * are about to read the only subdirectory that can
916                  * hold references:
917                  */
918                 refs->loose = create_dir_entry(refs, "", 0);
919                 /*
920                  * Create an incomplete entry for "refs/":
921                  */
922                 add_entry_to_dir(get_ref_dir(refs->loose),
923                                  create_dir_entry(refs, "refs/", 1));
924         }
925         return get_ref_dir(refs->loose);
926 }
927
928 /* We allow "recursive" symbolic refs. Only within reason, though */
929 #define MAXDEPTH 5
930 #define MAXREFLEN (1024)
931
932 /*
933  * Called by resolve_gitlink_ref_recursive() after it failed to read
934  * from the loose refs in ref_cache refs. Find <refname> in the
935  * packed-refs file for the submodule.
936  */
937 static int resolve_gitlink_packed_ref(struct ref_cache *refs,
938                                       const char *refname, unsigned char *sha1)
939 {
940         struct ref_entry *ref;
941         struct ref_dir *dir = get_packed_refs(refs);
942
943         ref = find_ref(dir, refname);
944         if (ref == NULL)
945                 return -1;
946
947         memcpy(sha1, ref->u.value.sha1, 20);
948         return 0;
949 }
950
951 static int resolve_gitlink_ref_recursive(struct ref_cache *refs,
952                                          const char *refname, unsigned char *sha1,
953                                          int recursion)
954 {
955         int fd, len;
956         char buffer[128], *p;
957         char *path;
958
959         if (recursion > MAXDEPTH || strlen(refname) > MAXREFLEN)
960                 return -1;
961         path = *refs->name
962                 ? git_path_submodule(refs->name, "%s", refname)
963                 : git_path("%s", refname);
964         fd = open(path, O_RDONLY);
965         if (fd < 0)
966                 return resolve_gitlink_packed_ref(refs, refname, sha1);
967
968         len = read(fd, buffer, sizeof(buffer)-1);
969         close(fd);
970         if (len < 0)
971                 return -1;
972         while (len && isspace(buffer[len-1]))
973                 len--;
974         buffer[len] = 0;
975
976         /* Was it a detached head or an old-fashioned symlink? */
977         if (!get_sha1_hex(buffer, sha1))
978                 return 0;
979
980         /* Symref? */
981         if (strncmp(buffer, "ref:", 4))
982                 return -1;
983         p = buffer + 4;
984         while (isspace(*p))
985                 p++;
986
987         return resolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);
988 }
989
990 int resolve_gitlink_ref(const char *path, const char *refname, unsigned char *sha1)
991 {
992         int len = strlen(path), retval;
993         char *submodule;
994         struct ref_cache *refs;
995
996         while (len && path[len-1] == '/')
997                 len--;
998         if (!len)
999                 return -1;
1000         submodule = xstrndup(path, len);
1001         refs = get_ref_cache(submodule);
1002         free(submodule);
1003
1004         retval = resolve_gitlink_ref_recursive(refs, refname, sha1, 0);
1005         return retval;
1006 }
1007
1008 /*
1009  * Try to read ref from the packed references.  On success, set sha1
1010  * and return 0; otherwise, return -1.
1011  */
1012 static int get_packed_ref(const char *refname, unsigned char *sha1)
1013 {
1014         struct ref_dir *packed = get_packed_refs(get_ref_cache(NULL));
1015         struct ref_entry *entry = find_ref(packed, refname);
1016         if (entry) {
1017                 hashcpy(sha1, entry->u.value.sha1);
1018                 return 0;
1019         }
1020         return -1;
1021 }
1022
1023 const char *resolve_ref_unsafe(const char *refname, unsigned char *sha1, int reading, int *flag)
1024 {
1025         int depth = MAXDEPTH;
1026         ssize_t len;
1027         char buffer[256];
1028         static char refname_buffer[256];
1029
1030         if (flag)
1031                 *flag = 0;
1032
1033         if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL))
1034                 return NULL;
1035
1036         for (;;) {
1037                 char path[PATH_MAX];
1038                 struct stat st;
1039                 char *buf;
1040                 int fd;
1041
1042                 if (--depth < 0)
1043                         return NULL;
1044
1045                 git_snpath(path, sizeof(path), "%s", refname);
1046
1047                 if (lstat(path, &st) < 0) {
1048                         if (errno != ENOENT)
1049                                 return NULL;
1050                         /*
1051                          * The loose reference file does not exist;
1052                          * check for a packed reference.
1053                          */
1054                         if (!get_packed_ref(refname, sha1)) {
1055                                 if (flag)
1056                                         *flag |= REF_ISPACKED;
1057                                 return refname;
1058                         }
1059                         /* The reference is not a packed reference, either. */
1060                         if (reading) {
1061                                 return NULL;
1062                         } else {
1063                                 hashclr(sha1);
1064                                 return refname;
1065                         }
1066                 }
1067
1068                 /* Follow "normalized" - ie "refs/.." symlinks by hand */
1069                 if (S_ISLNK(st.st_mode)) {
1070                         len = readlink(path, buffer, sizeof(buffer)-1);
1071                         if (len < 0)
1072                                 return NULL;
1073                         buffer[len] = 0;
1074                         if (!prefixcmp(buffer, "refs/") &&
1075                                         !check_refname_format(buffer, 0)) {
1076                                 strcpy(refname_buffer, buffer);
1077                                 refname = refname_buffer;
1078                                 if (flag)
1079                                         *flag |= REF_ISSYMREF;
1080                                 continue;
1081                         }
1082                 }
1083
1084                 /* Is it a directory? */
1085                 if (S_ISDIR(st.st_mode)) {
1086                         errno = EISDIR;
1087                         return NULL;
1088                 }
1089
1090                 /*
1091                  * Anything else, just open it and try to use it as
1092                  * a ref
1093                  */
1094                 fd = open(path, O_RDONLY);
1095                 if (fd < 0)
1096                         return NULL;
1097                 len = read_in_full(fd, buffer, sizeof(buffer)-1);
1098                 close(fd);
1099                 if (len < 0)
1100                         return NULL;
1101                 while (len && isspace(buffer[len-1]))
1102                         len--;
1103                 buffer[len] = '\0';
1104
1105                 /*
1106                  * Is it a symbolic ref?
1107                  */
1108                 if (prefixcmp(buffer, "ref:"))
1109                         break;
1110                 if (flag)
1111                         *flag |= REF_ISSYMREF;
1112                 buf = buffer + 4;
1113                 while (isspace(*buf))
1114                         buf++;
1115                 if (check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {
1116                         if (flag)
1117                                 *flag |= REF_ISBROKEN;
1118                         return NULL;
1119                 }
1120                 refname = strcpy(refname_buffer, buf);
1121         }
1122         /* Please note that FETCH_HEAD has a second line containing other data. */
1123         if (get_sha1_hex(buffer, sha1) || (buffer[40] != '\0' && !isspace(buffer[40]))) {
1124                 if (flag)
1125                         *flag |= REF_ISBROKEN;
1126                 return NULL;
1127         }
1128         return refname;
1129 }
1130
1131 char *resolve_refdup(const char *ref, unsigned char *sha1, int reading, int *flag)
1132 {
1133         const char *ret = resolve_ref_unsafe(ref, sha1, reading, flag);
1134         return ret ? xstrdup(ret) : NULL;
1135 }
1136
1137 /* The argument to filter_refs */
1138 struct ref_filter {
1139         const char *pattern;
1140         each_ref_fn *fn;
1141         void *cb_data;
1142 };
1143
1144 int read_ref_full(const char *refname, unsigned char *sha1, int reading, int *flags)
1145 {
1146         if (resolve_ref_unsafe(refname, sha1, reading, flags))
1147                 return 0;
1148         return -1;
1149 }
1150
1151 int read_ref(const char *refname, unsigned char *sha1)
1152 {
1153         return read_ref_full(refname, sha1, 1, NULL);
1154 }
1155
1156 int ref_exists(const char *refname)
1157 {
1158         unsigned char sha1[20];
1159         return !!resolve_ref_unsafe(refname, sha1, 1, NULL);
1160 }
1161
1162 static int filter_refs(const char *refname, const unsigned char *sha1, int flags,
1163                        void *data)
1164 {
1165         struct ref_filter *filter = (struct ref_filter *)data;
1166         if (fnmatch(filter->pattern, refname, 0))
1167                 return 0;
1168         return filter->fn(refname, sha1, flags, filter->cb_data);
1169 }
1170
1171 int peel_ref(const char *refname, unsigned char *sha1)
1172 {
1173         int flag;
1174         unsigned char base[20];
1175         struct object *o;
1176
1177         if (current_ref && (current_ref->name == refname
1178                 || !strcmp(current_ref->name, refname))) {
1179                 if (current_ref->flag & REF_KNOWS_PEELED) {
1180                         hashcpy(sha1, current_ref->u.value.peeled);
1181                         return 0;
1182                 }
1183                 hashcpy(base, current_ref->u.value.sha1);
1184                 goto fallback;
1185         }
1186
1187         if (read_ref_full(refname, base, 1, &flag))
1188                 return -1;
1189
1190         if ((flag & REF_ISPACKED)) {
1191                 struct ref_dir *dir = get_packed_refs(get_ref_cache(NULL));
1192                 struct ref_entry *r = find_ref(dir, refname);
1193
1194                 if (r != NULL && r->flag & REF_KNOWS_PEELED) {
1195                         hashcpy(sha1, r->u.value.peeled);
1196                         return 0;
1197                 }
1198         }
1199
1200 fallback:
1201         o = parse_object(base);
1202         if (o && o->type == OBJ_TAG) {
1203                 o = deref_tag(o, refname, 0);
1204                 if (o) {
1205                         hashcpy(sha1, o->sha1);
1206                         return 0;
1207                 }
1208         }
1209         return -1;
1210 }
1211
1212 struct warn_if_dangling_data {
1213         FILE *fp;
1214         const char *refname;
1215         const char *msg_fmt;
1216 };
1217
1218 static int warn_if_dangling_symref(const char *refname, const unsigned char *sha1,
1219                                    int flags, void *cb_data)
1220 {
1221         struct warn_if_dangling_data *d = cb_data;
1222         const char *resolves_to;
1223         unsigned char junk[20];
1224
1225         if (!(flags & REF_ISSYMREF))
1226                 return 0;
1227
1228         resolves_to = resolve_ref_unsafe(refname, junk, 0, NULL);
1229         if (!resolves_to || strcmp(resolves_to, d->refname))
1230                 return 0;
1231
1232         fprintf(d->fp, d->msg_fmt, refname);
1233         return 0;
1234 }
1235
1236 void warn_dangling_symref(FILE *fp, const char *msg_fmt, const char *refname)
1237 {
1238         struct warn_if_dangling_data data;
1239
1240         data.fp = fp;
1241         data.refname = refname;
1242         data.msg_fmt = msg_fmt;
1243         for_each_rawref(warn_if_dangling_symref, &data);
1244 }
1245
1246 static int do_for_each_ref(const char *submodule, const char *base, each_ref_fn fn,
1247                            int trim, int flags, void *cb_data)
1248 {
1249         struct ref_cache *refs = get_ref_cache(submodule);
1250         struct ref_dir *packed_dir = get_packed_refs(refs);
1251         struct ref_dir *loose_dir = get_loose_refs(refs);
1252         int retval = 0;
1253
1254         if (base && *base) {
1255                 packed_dir = find_containing_dir(packed_dir, base, 0);
1256                 loose_dir = find_containing_dir(loose_dir, base, 0);
1257         }
1258
1259         if (packed_dir && loose_dir) {
1260                 sort_ref_dir(packed_dir);
1261                 sort_ref_dir(loose_dir);
1262                 retval = do_for_each_ref_in_dirs(
1263                                 packed_dir, loose_dir,
1264                                 base, fn, trim, flags, cb_data);
1265         } else if (packed_dir) {
1266                 sort_ref_dir(packed_dir);
1267                 retval = do_for_each_ref_in_dir(
1268                                 packed_dir, 0,
1269                                 base, fn, trim, flags, cb_data);
1270         } else if (loose_dir) {
1271                 sort_ref_dir(loose_dir);
1272                 retval = do_for_each_ref_in_dir(
1273                                 loose_dir, 0,
1274                                 base, fn, trim, flags, cb_data);
1275         }
1276
1277         return retval;
1278 }
1279
1280 static int do_head_ref(const char *submodule, each_ref_fn fn, void *cb_data)
1281 {
1282         unsigned char sha1[20];
1283         int flag;
1284
1285         if (submodule) {
1286                 if (resolve_gitlink_ref(submodule, "HEAD", sha1) == 0)
1287                         return fn("HEAD", sha1, 0, cb_data);
1288
1289                 return 0;
1290         }
1291
1292         if (!read_ref_full("HEAD", sha1, 1, &flag))
1293                 return fn("HEAD", sha1, flag, cb_data);
1294
1295         return 0;
1296 }
1297
1298 int head_ref(each_ref_fn fn, void *cb_data)
1299 {
1300         return do_head_ref(NULL, fn, cb_data);
1301 }
1302
1303 int head_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1304 {
1305         return do_head_ref(submodule, fn, cb_data);
1306 }
1307
1308 int for_each_ref(each_ref_fn fn, void *cb_data)
1309 {
1310         return do_for_each_ref(NULL, "", fn, 0, 0, cb_data);
1311 }
1312
1313 int for_each_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1314 {
1315         return do_for_each_ref(submodule, "", fn, 0, 0, cb_data);
1316 }
1317
1318 int for_each_ref_in(const char *prefix, each_ref_fn fn, void *cb_data)
1319 {
1320         return do_for_each_ref(NULL, prefix, fn, strlen(prefix), 0, cb_data);
1321 }
1322
1323 int for_each_ref_in_submodule(const char *submodule, const char *prefix,
1324                 each_ref_fn fn, void *cb_data)
1325 {
1326         return do_for_each_ref(submodule, prefix, fn, strlen(prefix), 0, cb_data);
1327 }
1328
1329 int for_each_tag_ref(each_ref_fn fn, void *cb_data)
1330 {
1331         return for_each_ref_in("refs/tags/", fn, cb_data);
1332 }
1333
1334 int for_each_tag_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1335 {
1336         return for_each_ref_in_submodule(submodule, "refs/tags/", fn, cb_data);
1337 }
1338
1339 int for_each_branch_ref(each_ref_fn fn, void *cb_data)
1340 {
1341         return for_each_ref_in("refs/heads/", fn, cb_data);
1342 }
1343
1344 int for_each_branch_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1345 {
1346         return for_each_ref_in_submodule(submodule, "refs/heads/", fn, cb_data);
1347 }
1348
1349 int for_each_remote_ref(each_ref_fn fn, void *cb_data)
1350 {
1351         return for_each_ref_in("refs/remotes/", fn, cb_data);
1352 }
1353
1354 int for_each_remote_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1355 {
1356         return for_each_ref_in_submodule(submodule, "refs/remotes/", fn, cb_data);
1357 }
1358
1359 int for_each_replace_ref(each_ref_fn fn, void *cb_data)
1360 {
1361         return do_for_each_ref(NULL, "refs/replace/", fn, 13, 0, cb_data);
1362 }
1363
1364 int head_ref_namespaced(each_ref_fn fn, void *cb_data)
1365 {
1366         struct strbuf buf = STRBUF_INIT;
1367         int ret = 0;
1368         unsigned char sha1[20];
1369         int flag;
1370
1371         strbuf_addf(&buf, "%sHEAD", get_git_namespace());
1372         if (!read_ref_full(buf.buf, sha1, 1, &flag))
1373                 ret = fn(buf.buf, sha1, flag, cb_data);
1374         strbuf_release(&buf);
1375
1376         return ret;
1377 }
1378
1379 int for_each_namespaced_ref(each_ref_fn fn, void *cb_data)
1380 {
1381         struct strbuf buf = STRBUF_INIT;
1382         int ret;
1383         strbuf_addf(&buf, "%srefs/", get_git_namespace());
1384         ret = do_for_each_ref(NULL, buf.buf, fn, 0, 0, cb_data);
1385         strbuf_release(&buf);
1386         return ret;
1387 }
1388
1389 int for_each_glob_ref_in(each_ref_fn fn, const char *pattern,
1390         const char *prefix, void *cb_data)
1391 {
1392         struct strbuf real_pattern = STRBUF_INIT;
1393         struct ref_filter filter;
1394         int ret;
1395
1396         if (!prefix && prefixcmp(pattern, "refs/"))
1397                 strbuf_addstr(&real_pattern, "refs/");
1398         else if (prefix)
1399                 strbuf_addstr(&real_pattern, prefix);
1400         strbuf_addstr(&real_pattern, pattern);
1401
1402         if (!has_glob_specials(pattern)) {
1403                 /* Append implied '/' '*' if not present. */
1404                 if (real_pattern.buf[real_pattern.len - 1] != '/')
1405                         strbuf_addch(&real_pattern, '/');
1406                 /* No need to check for '*', there is none. */
1407                 strbuf_addch(&real_pattern, '*');
1408         }
1409
1410         filter.pattern = real_pattern.buf;
1411         filter.fn = fn;
1412         filter.cb_data = cb_data;
1413         ret = for_each_ref(filter_refs, &filter);
1414
1415         strbuf_release(&real_pattern);
1416         return ret;
1417 }
1418
1419 int for_each_glob_ref(each_ref_fn fn, const char *pattern, void *cb_data)
1420 {
1421         return for_each_glob_ref_in(fn, pattern, NULL, cb_data);
1422 }
1423
1424 int for_each_rawref(each_ref_fn fn, void *cb_data)
1425 {
1426         return do_for_each_ref(NULL, "", fn, 0,
1427                                DO_FOR_EACH_INCLUDE_BROKEN, cb_data);
1428 }
1429
1430 const char *prettify_refname(const char *name)
1431 {
1432         return name + (
1433                 !prefixcmp(name, "refs/heads/") ? 11 :
1434                 !prefixcmp(name, "refs/tags/") ? 10 :
1435                 !prefixcmp(name, "refs/remotes/") ? 13 :
1436                 0);
1437 }
1438
1439 const char *ref_rev_parse_rules[] = {
1440         "%.*s",
1441         "refs/%.*s",
1442         "refs/tags/%.*s",
1443         "refs/heads/%.*s",
1444         "refs/remotes/%.*s",
1445         "refs/remotes/%.*s/HEAD",
1446         NULL
1447 };
1448
1449 int refname_match(const char *abbrev_name, const char *full_name, const char **rules)
1450 {
1451         const char **p;
1452         const int abbrev_name_len = strlen(abbrev_name);
1453
1454         for (p = rules; *p; p++) {
1455                 if (!strcmp(full_name, mkpath(*p, abbrev_name_len, abbrev_name))) {
1456                         return 1;
1457                 }
1458         }
1459
1460         return 0;
1461 }
1462
1463 static struct ref_lock *verify_lock(struct ref_lock *lock,
1464         const unsigned char *old_sha1, int mustexist)
1465 {
1466         if (read_ref_full(lock->ref_name, lock->old_sha1, mustexist, NULL)) {
1467                 error("Can't verify ref %s", lock->ref_name);
1468                 unlock_ref(lock);
1469                 return NULL;
1470         }
1471         if (hashcmp(lock->old_sha1, old_sha1)) {
1472                 error("Ref %s is at %s but expected %s", lock->ref_name,
1473                         sha1_to_hex(lock->old_sha1), sha1_to_hex(old_sha1));
1474                 unlock_ref(lock);
1475                 return NULL;
1476         }
1477         return lock;
1478 }
1479
1480 static int remove_empty_directories(const char *file)
1481 {
1482         /* we want to create a file but there is a directory there;
1483          * if that is an empty directory (or a directory that contains
1484          * only empty directories), remove them.
1485          */
1486         struct strbuf path;
1487         int result;
1488
1489         strbuf_init(&path, 20);
1490         strbuf_addstr(&path, file);
1491
1492         result = remove_dir_recursively(&path, REMOVE_DIR_EMPTY_ONLY);
1493
1494         strbuf_release(&path);
1495
1496         return result;
1497 }
1498
1499 /*
1500  * *string and *len will only be substituted, and *string returned (for
1501  * later free()ing) if the string passed in is a magic short-hand form
1502  * to name a branch.
1503  */
1504 static char *substitute_branch_name(const char **string, int *len)
1505 {
1506         struct strbuf buf = STRBUF_INIT;
1507         int ret = interpret_branch_name(*string, &buf);
1508
1509         if (ret == *len) {
1510                 size_t size;
1511                 *string = strbuf_detach(&buf, &size);
1512                 *len = size;
1513                 return (char *)*string;
1514         }
1515
1516         return NULL;
1517 }
1518
1519 int dwim_ref(const char *str, int len, unsigned char *sha1, char **ref)
1520 {
1521         char *last_branch = substitute_branch_name(&str, &len);
1522         const char **p, *r;
1523         int refs_found = 0;
1524
1525         *ref = NULL;
1526         for (p = ref_rev_parse_rules; *p; p++) {
1527                 char fullref[PATH_MAX];
1528                 unsigned char sha1_from_ref[20];
1529                 unsigned char *this_result;
1530                 int flag;
1531
1532                 this_result = refs_found ? sha1_from_ref : sha1;
1533                 mksnpath(fullref, sizeof(fullref), *p, len, str);
1534                 r = resolve_ref_unsafe(fullref, this_result, 1, &flag);
1535                 if (r) {
1536                         if (!refs_found++)
1537                                 *ref = xstrdup(r);
1538                         if (!warn_ambiguous_refs)
1539                                 break;
1540                 } else if ((flag & REF_ISSYMREF) && strcmp(fullref, "HEAD")) {
1541                         warning("ignoring dangling symref %s.", fullref);
1542                 } else if ((flag & REF_ISBROKEN) && strchr(fullref, '/')) {
1543                         warning("ignoring broken ref %s.", fullref);
1544                 }
1545         }
1546         free(last_branch);
1547         return refs_found;
1548 }
1549
1550 int dwim_log(const char *str, int len, unsigned char *sha1, char **log)
1551 {
1552         char *last_branch = substitute_branch_name(&str, &len);
1553         const char **p;
1554         int logs_found = 0;
1555
1556         *log = NULL;
1557         for (p = ref_rev_parse_rules; *p; p++) {
1558                 struct stat st;
1559                 unsigned char hash[20];
1560                 char path[PATH_MAX];
1561                 const char *ref, *it;
1562
1563                 mksnpath(path, sizeof(path), *p, len, str);
1564                 ref = resolve_ref_unsafe(path, hash, 1, NULL);
1565                 if (!ref)
1566                         continue;
1567                 if (!stat(git_path("logs/%s", path), &st) &&
1568                     S_ISREG(st.st_mode))
1569                         it = path;
1570                 else if (strcmp(ref, path) &&
1571                          !stat(git_path("logs/%s", ref), &st) &&
1572                          S_ISREG(st.st_mode))
1573                         it = ref;
1574                 else
1575                         continue;
1576                 if (!logs_found++) {
1577                         *log = xstrdup(it);
1578                         hashcpy(sha1, hash);
1579                 }
1580                 if (!warn_ambiguous_refs)
1581                         break;
1582         }
1583         free(last_branch);
1584         return logs_found;
1585 }
1586
1587 static struct ref_lock *lock_ref_sha1_basic(const char *refname,
1588                                             const unsigned char *old_sha1,
1589                                             int flags, int *type_p)
1590 {
1591         char *ref_file;
1592         const char *orig_refname = refname;
1593         struct ref_lock *lock;
1594         int last_errno = 0;
1595         int type, lflags;
1596         int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
1597         int missing = 0;
1598
1599         lock = xcalloc(1, sizeof(struct ref_lock));
1600         lock->lock_fd = -1;
1601
1602         refname = resolve_ref_unsafe(refname, lock->old_sha1, mustexist, &type);
1603         if (!refname && errno == EISDIR) {
1604                 /* we are trying to lock foo but we used to
1605                  * have foo/bar which now does not exist;
1606                  * it is normal for the empty directory 'foo'
1607                  * to remain.
1608                  */
1609                 ref_file = git_path("%s", orig_refname);
1610                 if (remove_empty_directories(ref_file)) {
1611                         last_errno = errno;
1612                         error("there are still refs under '%s'", orig_refname);
1613                         goto error_return;
1614                 }
1615                 refname = resolve_ref_unsafe(orig_refname, lock->old_sha1, mustexist, &type);
1616         }
1617         if (type_p)
1618             *type_p = type;
1619         if (!refname) {
1620                 last_errno = errno;
1621                 error("unable to resolve reference %s: %s",
1622                         orig_refname, strerror(errno));
1623                 goto error_return;
1624         }
1625         missing = is_null_sha1(lock->old_sha1);
1626         /* When the ref did not exist and we are creating it,
1627          * make sure there is no existing ref that is packed
1628          * whose name begins with our refname, nor a ref whose
1629          * name is a proper prefix of our refname.
1630          */
1631         if (missing &&
1632              !is_refname_available(refname, NULL, get_packed_refs(get_ref_cache(NULL)))) {
1633                 last_errno = ENOTDIR;
1634                 goto error_return;
1635         }
1636
1637         lock->lk = xcalloc(1, sizeof(struct lock_file));
1638
1639         lflags = LOCK_DIE_ON_ERROR;
1640         if (flags & REF_NODEREF) {
1641                 refname = orig_refname;
1642                 lflags |= LOCK_NODEREF;
1643         }
1644         lock->ref_name = xstrdup(refname);
1645         lock->orig_ref_name = xstrdup(orig_refname);
1646         ref_file = git_path("%s", refname);
1647         if (missing)
1648                 lock->force_write = 1;
1649         if ((flags & REF_NODEREF) && (type & REF_ISSYMREF))
1650                 lock->force_write = 1;
1651
1652         if (safe_create_leading_directories(ref_file)) {
1653                 last_errno = errno;
1654                 error("unable to create directory for %s", ref_file);
1655                 goto error_return;
1656         }
1657
1658         lock->lock_fd = hold_lock_file_for_update(lock->lk, ref_file, lflags);
1659         return old_sha1 ? verify_lock(lock, old_sha1, mustexist) : lock;
1660
1661  error_return:
1662         unlock_ref(lock);
1663         errno = last_errno;
1664         return NULL;
1665 }
1666
1667 struct ref_lock *lock_ref_sha1(const char *refname, const unsigned char *old_sha1)
1668 {
1669         char refpath[PATH_MAX];
1670         if (check_refname_format(refname, 0))
1671                 return NULL;
1672         strcpy(refpath, mkpath("refs/%s", refname));
1673         return lock_ref_sha1_basic(refpath, old_sha1, 0, NULL);
1674 }
1675
1676 struct ref_lock *lock_any_ref_for_update(const char *refname,
1677                                          const unsigned char *old_sha1, int flags)
1678 {
1679         if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL))
1680                 return NULL;
1681         return lock_ref_sha1_basic(refname, old_sha1, flags, NULL);
1682 }
1683
1684 struct repack_without_ref_sb {
1685         const char *refname;
1686         int fd;
1687 };
1688
1689 static int repack_without_ref_fn(const char *refname, const unsigned char *sha1,
1690                                  int flags, void *cb_data)
1691 {
1692         struct repack_without_ref_sb *data = cb_data;
1693         char line[PATH_MAX + 100];
1694         int len;
1695
1696         if (!strcmp(data->refname, refname))
1697                 return 0;
1698         len = snprintf(line, sizeof(line), "%s %s\n",
1699                        sha1_to_hex(sha1), refname);
1700         /* this should not happen but just being defensive */
1701         if (len > sizeof(line))
1702                 die("too long a refname '%s'", refname);
1703         write_or_die(data->fd, line, len);
1704         return 0;
1705 }
1706
1707 static struct lock_file packlock;
1708
1709 static int repack_without_ref(const char *refname)
1710 {
1711         struct repack_without_ref_sb data;
1712         struct ref_dir *packed = get_packed_refs(get_ref_cache(NULL));
1713         if (find_ref(packed, refname) == NULL)
1714                 return 0;
1715         data.refname = refname;
1716         data.fd = hold_lock_file_for_update(&packlock, git_path("packed-refs"), 0);
1717         if (data.fd < 0) {
1718                 unable_to_lock_error(git_path("packed-refs"), errno);
1719                 return error("cannot delete '%s' from packed refs", refname);
1720         }
1721         do_for_each_ref_in_dir(packed, 0, "", repack_without_ref_fn, 0, 0, &data);
1722         return commit_lock_file(&packlock);
1723 }
1724
1725 int delete_ref(const char *refname, const unsigned char *sha1, int delopt)
1726 {
1727         struct ref_lock *lock;
1728         int err, i = 0, ret = 0, flag = 0;
1729
1730         lock = lock_ref_sha1_basic(refname, sha1, 0, &flag);
1731         if (!lock)
1732                 return 1;
1733         if (!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {
1734                 /* loose */
1735                 const char *path;
1736
1737                 if (!(delopt & REF_NODEREF)) {
1738                         i = strlen(lock->lk->filename) - 5; /* .lock */
1739                         lock->lk->filename[i] = 0;
1740                         path = lock->lk->filename;
1741                 } else {
1742                         path = git_path("%s", refname);
1743                 }
1744                 err = unlink_or_warn(path);
1745                 if (err && errno != ENOENT)
1746                         ret = 1;
1747
1748                 if (!(delopt & REF_NODEREF))
1749                         lock->lk->filename[i] = '.';
1750         }
1751         /* removing the loose one could have resurrected an earlier
1752          * packed one.  Also, if it was not loose we need to repack
1753          * without it.
1754          */
1755         ret |= repack_without_ref(refname);
1756
1757         unlink_or_warn(git_path("logs/%s", lock->ref_name));
1758         invalidate_ref_cache(NULL);
1759         unlock_ref(lock);
1760         return ret;
1761 }
1762
1763 /*
1764  * People using contrib's git-new-workdir have .git/logs/refs ->
1765  * /some/other/path/.git/logs/refs, and that may live on another device.
1766  *
1767  * IOW, to avoid cross device rename errors, the temporary renamed log must
1768  * live into logs/refs.
1769  */
1770 #define TMP_RENAMED_LOG  "logs/refs/.tmp-renamed-log"
1771
1772 int rename_ref(const char *oldrefname, const char *newrefname, const char *logmsg)
1773 {
1774         unsigned char sha1[20], orig_sha1[20];
1775         int flag = 0, logmoved = 0;
1776         struct ref_lock *lock;
1777         struct stat loginfo;
1778         int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);
1779         const char *symref = NULL;
1780         struct ref_cache *refs = get_ref_cache(NULL);
1781
1782         if (log && S_ISLNK(loginfo.st_mode))
1783                 return error("reflog for %s is a symlink", oldrefname);
1784
1785         symref = resolve_ref_unsafe(oldrefname, orig_sha1, 1, &flag);
1786         if (flag & REF_ISSYMREF)
1787                 return error("refname %s is a symbolic ref, renaming it is not supported",
1788                         oldrefname);
1789         if (!symref)
1790                 return error("refname %s not found", oldrefname);
1791
1792         if (!is_refname_available(newrefname, oldrefname, get_packed_refs(refs)))
1793                 return 1;
1794
1795         if (!is_refname_available(newrefname, oldrefname, get_loose_refs(refs)))
1796                 return 1;
1797
1798         if (log && rename(git_path("logs/%s", oldrefname), git_path(TMP_RENAMED_LOG)))
1799                 return error("unable to move logfile logs/%s to "TMP_RENAMED_LOG": %s",
1800                         oldrefname, strerror(errno));
1801
1802         if (delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {
1803                 error("unable to delete old %s", oldrefname);
1804                 goto rollback;
1805         }
1806
1807         if (!read_ref_full(newrefname, sha1, 1, &flag) &&
1808             delete_ref(newrefname, sha1, REF_NODEREF)) {
1809                 if (errno==EISDIR) {
1810                         if (remove_empty_directories(git_path("%s", newrefname))) {
1811                                 error("Directory not empty: %s", newrefname);
1812                                 goto rollback;
1813                         }
1814                 } else {
1815                         error("unable to delete existing %s", newrefname);
1816                         goto rollback;
1817                 }
1818         }
1819
1820         if (log && safe_create_leading_directories(git_path("logs/%s", newrefname))) {
1821                 error("unable to create directory for %s", newrefname);
1822                 goto rollback;
1823         }
1824
1825  retry:
1826         if (log && rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", newrefname))) {
1827                 if (errno==EISDIR || errno==ENOTDIR) {
1828                         /*
1829                          * rename(a, b) when b is an existing
1830                          * directory ought to result in ISDIR, but
1831                          * Solaris 5.8 gives ENOTDIR.  Sheesh.
1832                          */
1833                         if (remove_empty_directories(git_path("logs/%s", newrefname))) {
1834                                 error("Directory not empty: logs/%s", newrefname);
1835                                 goto rollback;
1836                         }
1837                         goto retry;
1838                 } else {
1839                         error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s: %s",
1840                                 newrefname, strerror(errno));
1841                         goto rollback;
1842                 }
1843         }
1844         logmoved = log;
1845
1846         lock = lock_ref_sha1_basic(newrefname, NULL, 0, NULL);
1847         if (!lock) {
1848                 error("unable to lock %s for update", newrefname);
1849                 goto rollback;
1850         }
1851         lock->force_write = 1;
1852         hashcpy(lock->old_sha1, orig_sha1);
1853         if (write_ref_sha1(lock, orig_sha1, logmsg)) {
1854                 error("unable to write current sha1 into %s", newrefname);
1855                 goto rollback;
1856         }
1857
1858         return 0;
1859
1860  rollback:
1861         lock = lock_ref_sha1_basic(oldrefname, NULL, 0, NULL);
1862         if (!lock) {
1863                 error("unable to lock %s for rollback", oldrefname);
1864                 goto rollbacklog;
1865         }
1866
1867         lock->force_write = 1;
1868         flag = log_all_ref_updates;
1869         log_all_ref_updates = 0;
1870         if (write_ref_sha1(lock, orig_sha1, NULL))
1871                 error("unable to write current sha1 into %s", oldrefname);
1872         log_all_ref_updates = flag;
1873
1874  rollbacklog:
1875         if (logmoved && rename(git_path("logs/%s", newrefname), git_path("logs/%s", oldrefname)))
1876                 error("unable to restore logfile %s from %s: %s",
1877                         oldrefname, newrefname, strerror(errno));
1878         if (!logmoved && log &&
1879             rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", oldrefname)))
1880                 error("unable to restore logfile %s from "TMP_RENAMED_LOG": %s",
1881                         oldrefname, strerror(errno));
1882
1883         return 1;
1884 }
1885
1886 int close_ref(struct ref_lock *lock)
1887 {
1888         if (close_lock_file(lock->lk))
1889                 return -1;
1890         lock->lock_fd = -1;
1891         return 0;
1892 }
1893
1894 int commit_ref(struct ref_lock *lock)
1895 {
1896         if (commit_lock_file(lock->lk))
1897                 return -1;
1898         lock->lock_fd = -1;
1899         return 0;
1900 }
1901
1902 void unlock_ref(struct ref_lock *lock)
1903 {
1904         /* Do not free lock->lk -- atexit() still looks at them */
1905         if (lock->lk)
1906                 rollback_lock_file(lock->lk);
1907         free(lock->ref_name);
1908         free(lock->orig_ref_name);
1909         free(lock);
1910 }
1911
1912 /*
1913  * copy the reflog message msg to buf, which has been allocated sufficiently
1914  * large, while cleaning up the whitespaces.  Especially, convert LF to space,
1915  * because reflog file is one line per entry.
1916  */
1917 static int copy_msg(char *buf, const char *msg)
1918 {
1919         char *cp = buf;
1920         char c;
1921         int wasspace = 1;
1922
1923         *cp++ = '\t';
1924         while ((c = *msg++)) {
1925                 if (wasspace && isspace(c))
1926                         continue;
1927                 wasspace = isspace(c);
1928                 if (wasspace)
1929                         c = ' ';
1930                 *cp++ = c;
1931         }
1932         while (buf < cp && isspace(cp[-1]))
1933                 cp--;
1934         *cp++ = '\n';
1935         return cp - buf;
1936 }
1937
1938 int log_ref_setup(const char *refname, char *logfile, int bufsize)
1939 {
1940         int logfd, oflags = O_APPEND | O_WRONLY;
1941
1942         git_snpath(logfile, bufsize, "logs/%s", refname);
1943         if (log_all_ref_updates &&
1944             (!prefixcmp(refname, "refs/heads/") ||
1945              !prefixcmp(refname, "refs/remotes/") ||
1946              !prefixcmp(refname, "refs/notes/") ||
1947              !strcmp(refname, "HEAD"))) {
1948                 if (safe_create_leading_directories(logfile) < 0)
1949                         return error("unable to create directory for %s",
1950                                      logfile);
1951                 oflags |= O_CREAT;
1952         }
1953
1954         logfd = open(logfile, oflags, 0666);
1955         if (logfd < 0) {
1956                 if (!(oflags & O_CREAT) && errno == ENOENT)
1957                         return 0;
1958
1959                 if ((oflags & O_CREAT) && errno == EISDIR) {
1960                         if (remove_empty_directories(logfile)) {
1961                                 return error("There are still logs under '%s'",
1962                                              logfile);
1963                         }
1964                         logfd = open(logfile, oflags, 0666);
1965                 }
1966
1967                 if (logfd < 0)
1968                         return error("Unable to append to %s: %s",
1969                                      logfile, strerror(errno));
1970         }
1971
1972         adjust_shared_perm(logfile);
1973         close(logfd);
1974         return 0;
1975 }
1976
1977 static int log_ref_write(const char *refname, const unsigned char *old_sha1,
1978                          const unsigned char *new_sha1, const char *msg)
1979 {
1980         int logfd, result, written, oflags = O_APPEND | O_WRONLY;
1981         unsigned maxlen, len;
1982         int msglen;
1983         char log_file[PATH_MAX];
1984         char *logrec;
1985         const char *committer;
1986
1987         if (log_all_ref_updates < 0)
1988                 log_all_ref_updates = !is_bare_repository();
1989
1990         result = log_ref_setup(refname, log_file, sizeof(log_file));
1991         if (result)
1992                 return result;
1993
1994         logfd = open(log_file, oflags);
1995         if (logfd < 0)
1996                 return 0;
1997         msglen = msg ? strlen(msg) : 0;
1998         committer = git_committer_info(0);
1999         maxlen = strlen(committer) + msglen + 100;
2000         logrec = xmalloc(maxlen);
2001         len = sprintf(logrec, "%s %s %s\n",
2002                       sha1_to_hex(old_sha1),
2003                       sha1_to_hex(new_sha1),
2004                       committer);
2005         if (msglen)
2006                 len += copy_msg(logrec + len - 1, msg) - 1;
2007         written = len <= maxlen ? write_in_full(logfd, logrec, len) : -1;
2008         free(logrec);
2009         if (close(logfd) != 0 || written != len)
2010                 return error("Unable to append to %s", log_file);
2011         return 0;
2012 }
2013
2014 static int is_branch(const char *refname)
2015 {
2016         return !strcmp(refname, "HEAD") || !prefixcmp(refname, "refs/heads/");
2017 }
2018
2019 int write_ref_sha1(struct ref_lock *lock,
2020         const unsigned char *sha1, const char *logmsg)
2021 {
2022         static char term = '\n';
2023         struct object *o;
2024
2025         if (!lock)
2026                 return -1;
2027         if (!lock->force_write && !hashcmp(lock->old_sha1, sha1)) {
2028                 unlock_ref(lock);
2029                 return 0;
2030         }
2031         o = parse_object(sha1);
2032         if (!o) {
2033                 error("Trying to write ref %s with nonexistent object %s",
2034                         lock->ref_name, sha1_to_hex(sha1));
2035                 unlock_ref(lock);
2036                 return -1;
2037         }
2038         if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
2039                 error("Trying to write non-commit object %s to branch %s",
2040                         sha1_to_hex(sha1), lock->ref_name);
2041                 unlock_ref(lock);
2042                 return -1;
2043         }
2044         if (write_in_full(lock->lock_fd, sha1_to_hex(sha1), 40) != 40 ||
2045             write_in_full(lock->lock_fd, &term, 1) != 1
2046                 || close_ref(lock) < 0) {
2047                 error("Couldn't write %s", lock->lk->filename);
2048                 unlock_ref(lock);
2049                 return -1;
2050         }
2051         clear_loose_ref_cache(get_ref_cache(NULL));
2052         if (log_ref_write(lock->ref_name, lock->old_sha1, sha1, logmsg) < 0 ||
2053             (strcmp(lock->ref_name, lock->orig_ref_name) &&
2054              log_ref_write(lock->orig_ref_name, lock->old_sha1, sha1, logmsg) < 0)) {
2055                 unlock_ref(lock);
2056                 return -1;
2057         }
2058         if (strcmp(lock->orig_ref_name, "HEAD") != 0) {
2059                 /*
2060                  * Special hack: If a branch is updated directly and HEAD
2061                  * points to it (may happen on the remote side of a push
2062                  * for example) then logically the HEAD reflog should be
2063                  * updated too.
2064                  * A generic solution implies reverse symref information,
2065                  * but finding all symrefs pointing to the given branch
2066                  * would be rather costly for this rare event (the direct
2067                  * update of a branch) to be worth it.  So let's cheat and
2068                  * check with HEAD only which should cover 99% of all usage
2069                  * scenarios (even 100% of the default ones).
2070                  */
2071                 unsigned char head_sha1[20];
2072                 int head_flag;
2073                 const char *head_ref;
2074                 head_ref = resolve_ref_unsafe("HEAD", head_sha1, 1, &head_flag);
2075                 if (head_ref && (head_flag & REF_ISSYMREF) &&
2076                     !strcmp(head_ref, lock->ref_name))
2077                         log_ref_write("HEAD", lock->old_sha1, sha1, logmsg);
2078         }
2079         if (commit_ref(lock)) {
2080                 error("Couldn't set %s", lock->ref_name);
2081                 unlock_ref(lock);
2082                 return -1;
2083         }
2084         unlock_ref(lock);
2085         return 0;
2086 }
2087
2088 int create_symref(const char *ref_target, const char *refs_heads_master,
2089                   const char *logmsg)
2090 {
2091         const char *lockpath;
2092         char ref[1000];
2093         int fd, len, written;
2094         char *git_HEAD = git_pathdup("%s", ref_target);
2095         unsigned char old_sha1[20], new_sha1[20];
2096
2097         if (logmsg && read_ref(ref_target, old_sha1))
2098                 hashclr(old_sha1);
2099
2100         if (safe_create_leading_directories(git_HEAD) < 0)
2101                 return error("unable to create directory for %s", git_HEAD);
2102
2103 #ifndef NO_SYMLINK_HEAD
2104         if (prefer_symlink_refs) {
2105                 unlink(git_HEAD);
2106                 if (!symlink(refs_heads_master, git_HEAD))
2107                         goto done;
2108                 fprintf(stderr, "no symlink - falling back to symbolic ref\n");
2109         }
2110 #endif
2111
2112         len = snprintf(ref, sizeof(ref), "ref: %s\n", refs_heads_master);
2113         if (sizeof(ref) <= len) {
2114                 error("refname too long: %s", refs_heads_master);
2115                 goto error_free_return;
2116         }
2117         lockpath = mkpath("%s.lock", git_HEAD);
2118         fd = open(lockpath, O_CREAT | O_EXCL | O_WRONLY, 0666);
2119         if (fd < 0) {
2120                 error("Unable to open %s for writing", lockpath);
2121                 goto error_free_return;
2122         }
2123         written = write_in_full(fd, ref, len);
2124         if (close(fd) != 0 || written != len) {
2125                 error("Unable to write to %s", lockpath);
2126                 goto error_unlink_return;
2127         }
2128         if (rename(lockpath, git_HEAD) < 0) {
2129                 error("Unable to create %s", git_HEAD);
2130                 goto error_unlink_return;
2131         }
2132         if (adjust_shared_perm(git_HEAD)) {
2133                 error("Unable to fix permissions on %s", lockpath);
2134         error_unlink_return:
2135                 unlink_or_warn(lockpath);
2136         error_free_return:
2137                 free(git_HEAD);
2138                 return -1;
2139         }
2140
2141 #ifndef NO_SYMLINK_HEAD
2142         done:
2143 #endif
2144         if (logmsg && !read_ref(refs_heads_master, new_sha1))
2145                 log_ref_write(ref_target, old_sha1, new_sha1, logmsg);
2146
2147         free(git_HEAD);
2148         return 0;
2149 }
2150
2151 static char *ref_msg(const char *line, const char *endp)
2152 {
2153         const char *ep;
2154         line += 82;
2155         ep = memchr(line, '\n', endp - line);
2156         if (!ep)
2157                 ep = endp;
2158         return xmemdupz(line, ep - line);
2159 }
2160
2161 int read_ref_at(const char *refname, unsigned long at_time, int cnt,
2162                 unsigned char *sha1, char **msg,
2163                 unsigned long *cutoff_time, int *cutoff_tz, int *cutoff_cnt)
2164 {
2165         const char *logfile, *logdata, *logend, *rec, *lastgt, *lastrec;
2166         char *tz_c;
2167         int logfd, tz, reccnt = 0;
2168         struct stat st;
2169         unsigned long date;
2170         unsigned char logged_sha1[20];
2171         void *log_mapped;
2172         size_t mapsz;
2173
2174         logfile = git_path("logs/%s", refname);
2175         logfd = open(logfile, O_RDONLY, 0);
2176         if (logfd < 0)
2177                 die_errno("Unable to read log '%s'", logfile);
2178         fstat(logfd, &st);
2179         if (!st.st_size)
2180                 die("Log %s is empty.", logfile);
2181         mapsz = xsize_t(st.st_size);
2182         log_mapped = xmmap(NULL, mapsz, PROT_READ, MAP_PRIVATE, logfd, 0);
2183         logdata = log_mapped;
2184         close(logfd);
2185
2186         lastrec = NULL;
2187         rec = logend = logdata + st.st_size;
2188         while (logdata < rec) {
2189                 reccnt++;
2190                 if (logdata < rec && *(rec-1) == '\n')
2191                         rec--;
2192                 lastgt = NULL;
2193                 while (logdata < rec && *(rec-1) != '\n') {
2194                         rec--;
2195                         if (*rec == '>')
2196                                 lastgt = rec;
2197                 }
2198                 if (!lastgt)
2199                         die("Log %s is corrupt.", logfile);
2200                 date = strtoul(lastgt + 1, &tz_c, 10);
2201                 if (date <= at_time || cnt == 0) {
2202                         tz = strtoul(tz_c, NULL, 10);
2203                         if (msg)
2204                                 *msg = ref_msg(rec, logend);
2205                         if (cutoff_time)
2206                                 *cutoff_time = date;
2207                         if (cutoff_tz)
2208                                 *cutoff_tz = tz;
2209                         if (cutoff_cnt)
2210                                 *cutoff_cnt = reccnt - 1;
2211                         if (lastrec) {
2212                                 if (get_sha1_hex(lastrec, logged_sha1))
2213                                         die("Log %s is corrupt.", logfile);
2214                                 if (get_sha1_hex(rec + 41, sha1))
2215                                         die("Log %s is corrupt.", logfile);
2216                                 if (hashcmp(logged_sha1, sha1)) {
2217                                         warning("Log %s has gap after %s.",
2218                                                 logfile, show_date(date, tz, DATE_RFC2822));
2219                                 }
2220                         }
2221                         else if (date == at_time) {
2222                                 if (get_sha1_hex(rec + 41, sha1))
2223                                         die("Log %s is corrupt.", logfile);
2224                         }
2225                         else {
2226                                 if (get_sha1_hex(rec + 41, logged_sha1))
2227                                         die("Log %s is corrupt.", logfile);
2228                                 if (hashcmp(logged_sha1, sha1)) {
2229                                         warning("Log %s unexpectedly ended on %s.",
2230                                                 logfile, show_date(date, tz, DATE_RFC2822));
2231                                 }
2232                         }
2233                         munmap(log_mapped, mapsz);
2234                         return 0;
2235                 }
2236                 lastrec = rec;
2237                 if (cnt > 0)
2238                         cnt--;
2239         }
2240
2241         rec = logdata;
2242         while (rec < logend && *rec != '>' && *rec != '\n')
2243                 rec++;
2244         if (rec == logend || *rec == '\n')
2245                 die("Log %s is corrupt.", logfile);
2246         date = strtoul(rec + 1, &tz_c, 10);
2247         tz = strtoul(tz_c, NULL, 10);
2248         if (get_sha1_hex(logdata, sha1))
2249                 die("Log %s is corrupt.", logfile);
2250         if (is_null_sha1(sha1)) {
2251                 if (get_sha1_hex(logdata + 41, sha1))
2252                         die("Log %s is corrupt.", logfile);
2253         }
2254         if (msg)
2255                 *msg = ref_msg(logdata, logend);
2256         munmap(log_mapped, mapsz);
2257
2258         if (cutoff_time)
2259                 *cutoff_time = date;
2260         if (cutoff_tz)
2261                 *cutoff_tz = tz;
2262         if (cutoff_cnt)
2263                 *cutoff_cnt = reccnt;
2264         return 1;
2265 }
2266
2267 int for_each_recent_reflog_ent(const char *refname, each_reflog_ent_fn fn, long ofs, void *cb_data)
2268 {
2269         const char *logfile;
2270         FILE *logfp;
2271         struct strbuf sb = STRBUF_INIT;
2272         int ret = 0;
2273
2274         logfile = git_path("logs/%s", refname);
2275         logfp = fopen(logfile, "r");
2276         if (!logfp)
2277                 return -1;
2278
2279         if (ofs) {
2280                 struct stat statbuf;
2281                 if (fstat(fileno(logfp), &statbuf) ||
2282                     statbuf.st_size < ofs ||
2283                     fseek(logfp, -ofs, SEEK_END) ||
2284                     strbuf_getwholeline(&sb, logfp, '\n')) {
2285                         fclose(logfp);
2286                         strbuf_release(&sb);
2287                         return -1;
2288                 }
2289         }
2290
2291         while (!strbuf_getwholeline(&sb, logfp, '\n')) {
2292                 unsigned char osha1[20], nsha1[20];
2293                 char *email_end, *message;
2294                 unsigned long timestamp;
2295                 int tz;
2296
2297                 /* old SP new SP name <email> SP time TAB msg LF */
2298                 if (sb.len < 83 || sb.buf[sb.len - 1] != '\n' ||
2299                     get_sha1_hex(sb.buf, osha1) || sb.buf[40] != ' ' ||
2300                     get_sha1_hex(sb.buf + 41, nsha1) || sb.buf[81] != ' ' ||
2301                     !(email_end = strchr(sb.buf + 82, '>')) ||
2302                     email_end[1] != ' ' ||
2303                     !(timestamp = strtoul(email_end + 2, &message, 10)) ||
2304                     !message || message[0] != ' ' ||
2305                     (message[1] != '+' && message[1] != '-') ||
2306                     !isdigit(message[2]) || !isdigit(message[3]) ||
2307                     !isdigit(message[4]) || !isdigit(message[5]))
2308                         continue; /* corrupt? */
2309                 email_end[1] = '\0';
2310                 tz = strtol(message + 1, NULL, 10);
2311                 if (message[6] != '\t')
2312                         message += 6;
2313                 else
2314                         message += 7;
2315                 ret = fn(osha1, nsha1, sb.buf + 82, timestamp, tz, message,
2316                          cb_data);
2317                 if (ret)
2318                         break;
2319         }
2320         fclose(logfp);
2321         strbuf_release(&sb);
2322         return ret;
2323 }
2324
2325 int for_each_reflog_ent(const char *refname, each_reflog_ent_fn fn, void *cb_data)
2326 {
2327         return for_each_recent_reflog_ent(refname, fn, 0, cb_data);
2328 }
2329
2330 /*
2331  * Call fn for each reflog in the namespace indicated by name.  name
2332  * must be empty or end with '/'.  Name will be used as a scratch
2333  * space, but its contents will be restored before return.
2334  */
2335 static int do_for_each_reflog(struct strbuf *name, each_ref_fn fn, void *cb_data)
2336 {
2337         DIR *d = opendir(git_path("logs/%s", name->buf));
2338         int retval = 0;
2339         struct dirent *de;
2340         int oldlen = name->len;
2341
2342         if (!d)
2343                 return name->len ? errno : 0;
2344
2345         while ((de = readdir(d)) != NULL) {
2346                 struct stat st;
2347
2348                 if (de->d_name[0] == '.')
2349                         continue;
2350                 if (has_extension(de->d_name, ".lock"))
2351                         continue;
2352                 strbuf_addstr(name, de->d_name);
2353                 if (stat(git_path("logs/%s", name->buf), &st) < 0) {
2354                         ; /* silently ignore */
2355                 } else {
2356                         if (S_ISDIR(st.st_mode)) {
2357                                 strbuf_addch(name, '/');
2358                                 retval = do_for_each_reflog(name, fn, cb_data);
2359                         } else {
2360                                 unsigned char sha1[20];
2361                                 if (read_ref_full(name->buf, sha1, 0, NULL))
2362                                         retval = error("bad ref for %s", name->buf);
2363                                 else
2364                                         retval = fn(name->buf, sha1, 0, cb_data);
2365                         }
2366                         if (retval)
2367                                 break;
2368                 }
2369                 strbuf_setlen(name, oldlen);
2370         }
2371         closedir(d);
2372         return retval;
2373 }
2374
2375 int for_each_reflog(each_ref_fn fn, void *cb_data)
2376 {
2377         int retval;
2378         struct strbuf name;
2379         strbuf_init(&name, PATH_MAX);
2380         retval = do_for_each_reflog(&name, fn, cb_data);
2381         strbuf_release(&name);
2382         return retval;
2383 }
2384
2385 int update_ref(const char *action, const char *refname,
2386                 const unsigned char *sha1, const unsigned char *oldval,
2387                 int flags, enum action_on_err onerr)
2388 {
2389         static struct ref_lock *lock;
2390         lock = lock_any_ref_for_update(refname, oldval, flags);
2391         if (!lock) {
2392                 const char *str = "Cannot lock the ref '%s'.";
2393                 switch (onerr) {
2394                 case MSG_ON_ERR: error(str, refname); break;
2395                 case DIE_ON_ERR: die(str, refname); break;
2396                 case QUIET_ON_ERR: break;
2397                 }
2398                 return 1;
2399         }
2400         if (write_ref_sha1(lock, sha1, action) < 0) {
2401                 const char *str = "Cannot update the ref '%s'.";
2402                 switch (onerr) {
2403                 case MSG_ON_ERR: error(str, refname); break;
2404                 case DIE_ON_ERR: die(str, refname); break;
2405                 case QUIET_ON_ERR: break;
2406                 }
2407                 return 1;
2408         }
2409         return 0;
2410 }
2411
2412 struct ref *find_ref_by_name(const struct ref *list, const char *name)
2413 {
2414         for ( ; list; list = list->next)
2415                 if (!strcmp(list->name, name))
2416                         return (struct ref *)list;
2417         return NULL;
2418 }
2419
2420 /*
2421  * generate a format suitable for scanf from a ref_rev_parse_rules
2422  * rule, that is replace the "%.*s" spec with a "%s" spec
2423  */
2424 static void gen_scanf_fmt(char *scanf_fmt, const char *rule)
2425 {
2426         char *spec;
2427
2428         spec = strstr(rule, "%.*s");
2429         if (!spec || strstr(spec + 4, "%.*s"))
2430                 die("invalid rule in ref_rev_parse_rules: %s", rule);
2431
2432         /* copy all until spec */
2433         strncpy(scanf_fmt, rule, spec - rule);
2434         scanf_fmt[spec - rule] = '\0';
2435         /* copy new spec */
2436         strcat(scanf_fmt, "%s");
2437         /* copy remaining rule */
2438         strcat(scanf_fmt, spec + 4);
2439
2440         return;
2441 }
2442
2443 char *shorten_unambiguous_ref(const char *refname, int strict)
2444 {
2445         int i;
2446         static char **scanf_fmts;
2447         static int nr_rules;
2448         char *short_name;
2449
2450         /* pre generate scanf formats from ref_rev_parse_rules[] */
2451         if (!nr_rules) {
2452                 size_t total_len = 0;
2453
2454                 /* the rule list is NULL terminated, count them first */
2455                 for (; ref_rev_parse_rules[nr_rules]; nr_rules++)
2456                         /* no +1 because strlen("%s") < strlen("%.*s") */
2457                         total_len += strlen(ref_rev_parse_rules[nr_rules]);
2458
2459                 scanf_fmts = xmalloc(nr_rules * sizeof(char *) + total_len);
2460
2461                 total_len = 0;
2462                 for (i = 0; i < nr_rules; i++) {
2463                         scanf_fmts[i] = (char *)&scanf_fmts[nr_rules]
2464                                         + total_len;
2465                         gen_scanf_fmt(scanf_fmts[i], ref_rev_parse_rules[i]);
2466                         total_len += strlen(ref_rev_parse_rules[i]);
2467                 }
2468         }
2469
2470         /* bail out if there are no rules */
2471         if (!nr_rules)
2472                 return xstrdup(refname);
2473
2474         /* buffer for scanf result, at most refname must fit */
2475         short_name = xstrdup(refname);
2476
2477         /* skip first rule, it will always match */
2478         for (i = nr_rules - 1; i > 0 ; --i) {
2479                 int j;
2480                 int rules_to_fail = i;
2481                 int short_name_len;
2482
2483                 if (1 != sscanf(refname, scanf_fmts[i], short_name))
2484                         continue;
2485
2486                 short_name_len = strlen(short_name);
2487
2488                 /*
2489                  * in strict mode, all (except the matched one) rules
2490                  * must fail to resolve to a valid non-ambiguous ref
2491                  */
2492                 if (strict)
2493                         rules_to_fail = nr_rules;
2494
2495                 /*
2496                  * check if the short name resolves to a valid ref,
2497                  * but use only rules prior to the matched one
2498                  */
2499                 for (j = 0; j < rules_to_fail; j++) {
2500                         const char *rule = ref_rev_parse_rules[j];
2501                         char refname[PATH_MAX];
2502
2503                         /* skip matched rule */
2504                         if (i == j)
2505                                 continue;
2506
2507                         /*
2508                          * the short name is ambiguous, if it resolves
2509                          * (with this previous rule) to a valid ref
2510                          * read_ref() returns 0 on success
2511                          */
2512                         mksnpath(refname, sizeof(refname),
2513                                  rule, short_name_len, short_name);
2514                         if (ref_exists(refname))
2515                                 break;
2516                 }
2517
2518                 /*
2519                  * short name is non-ambiguous if all previous rules
2520                  * haven't resolved to a valid ref
2521                  */
2522                 if (j == rules_to_fail)
2523                         return short_name;
2524         }
2525
2526         free(short_name);
2527         return xstrdup(refname);
2528 }