refs: use strings directly in find_containing_dir()
[git.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, size_t len,
298                                           int incomplete)
299 {
300         struct ref_entry *direntry;
301         direntry = xcalloc(1, sizeof(struct ref_entry) + len + 1);
302         memcpy(direntry->name, dirname, len);
303         direntry->name[len] = '\0';
304         direntry->u.subdir.ref_cache = ref_cache;
305         direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE : 0);
306         return direntry;
307 }
308
309 static int ref_entry_cmp(const void *a, const void *b)
310 {
311         struct ref_entry *one = *(struct ref_entry **)a;
312         struct ref_entry *two = *(struct ref_entry **)b;
313         return strcmp(one->name, two->name);
314 }
315
316 static void sort_ref_dir(struct ref_dir *dir);
317
318 /*
319  * Return the entry with the given refname from the ref_dir
320  * (non-recursively), sorting dir if necessary.  Return NULL if no
321  * such entry is found.  dir must already be complete.
322  */
323 static struct ref_entry *search_ref_dir(struct ref_dir *dir,
324                                         const char *refname, size_t len)
325 {
326         struct ref_entry *e, **r;
327
328         if (refname == NULL || !dir->nr)
329                 return NULL;
330
331         sort_ref_dir(dir);
332
333         e = xmalloc(sizeof(struct ref_entry) + len + 1);
334         memcpy(e->name, refname, len);
335         e->name[len] = '\0';
336
337         r = bsearch(&e, dir->entries, dir->nr, sizeof(*dir->entries), ref_entry_cmp);
338
339         free(e);
340
341         if (r == NULL)
342                 return NULL;
343
344         return *r;
345 }
346
347 /*
348  * Search for a directory entry directly within dir (without
349  * recursing).  Sort dir if necessary.  subdirname must be a directory
350  * name (i.e., end in '/').  If mkdir is set, then create the
351  * directory if it is missing; otherwise, return NULL if the desired
352  * directory cannot be found.  dir must already be complete.
353  */
354 static struct ref_dir *search_for_subdir(struct ref_dir *dir,
355                                          const char *subdirname, size_t len,
356                                          int mkdir)
357 {
358         struct ref_entry *entry = search_ref_dir(dir, subdirname, len);
359         if (!entry) {
360                 if (!mkdir)
361                         return NULL;
362                 /*
363                  * Since dir is complete, the absence of a subdir
364                  * means that the subdir really doesn't exist;
365                  * therefore, create an empty record for it but mark
366                  * the record complete.
367                  */
368                 entry = create_dir_entry(dir->ref_cache, subdirname, len, 0);
369                 add_entry_to_dir(dir, entry);
370         }
371         return get_ref_dir(entry);
372 }
373
374 /*
375  * If refname is a reference name, find the ref_dir within the dir
376  * tree that should hold refname.  If refname is a directory name
377  * (i.e., ends in '/'), then return that ref_dir itself.  dir must
378  * represent the top-level directory and must already be complete.
379  * Sort ref_dirs and recurse into subdirectories as necessary.  If
380  * mkdir is set, then create any missing directories; otherwise,
381  * return NULL if the desired directory cannot be found.
382  */
383 static struct ref_dir *find_containing_dir(struct ref_dir *dir,
384                                            const char *refname, int mkdir)
385 {
386         const char *slash;
387         for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) {
388                 size_t dirnamelen = slash - refname + 1;
389                 struct ref_dir *subdir;
390                 subdir = search_for_subdir(dir, refname, dirnamelen, mkdir);
391                 if (!subdir) {
392                         dir = NULL;
393                         break;
394                 }
395                 dir = subdir;
396         }
397
398         return dir;
399 }
400
401 /*
402  * Find the value entry with the given name in dir, sorting ref_dirs
403  * and recursing into subdirectories as necessary.  If the name is not
404  * found or it corresponds to a directory entry, return NULL.
405  */
406 static struct ref_entry *find_ref(struct ref_dir *dir, const char *refname)
407 {
408         struct ref_entry *entry;
409         dir = find_containing_dir(dir, refname, 0);
410         if (!dir)
411                 return NULL;
412         entry = search_ref_dir(dir, refname, strlen(refname));
413         return (entry && !(entry->flag & REF_DIR)) ? entry : NULL;
414 }
415
416 /*
417  * Add a ref_entry to the ref_dir (unsorted), recursing into
418  * subdirectories as necessary.  dir must represent the top-level
419  * directory.  Return 0 on success.
420  */
421 static int add_ref(struct ref_dir *dir, struct ref_entry *ref)
422 {
423         dir = find_containing_dir(dir, ref->name, 1);
424         if (!dir)
425                 return -1;
426         add_entry_to_dir(dir, ref);
427         return 0;
428 }
429
430 /*
431  * Emit a warning and return true iff ref1 and ref2 have the same name
432  * and the same sha1.  Die if they have the same name but different
433  * sha1s.
434  */
435 static int is_dup_ref(const struct ref_entry *ref1, const struct ref_entry *ref2)
436 {
437         if (strcmp(ref1->name, ref2->name))
438                 return 0;
439
440         /* Duplicate name; make sure that they don't conflict: */
441
442         if ((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR))
443                 /* This is impossible by construction */
444                 die("Reference directory conflict: %s", ref1->name);
445
446         if (hashcmp(ref1->u.value.sha1, ref2->u.value.sha1))
447                 die("Duplicated ref, and SHA1s don't match: %s", ref1->name);
448
449         warning("Duplicated ref: %s", ref1->name);
450         return 1;
451 }
452
453 /*
454  * Sort the entries in dir non-recursively (if they are not already
455  * sorted) and remove any duplicate entries.
456  */
457 static void sort_ref_dir(struct ref_dir *dir)
458 {
459         int i, j;
460         struct ref_entry *last = NULL;
461
462         /*
463          * This check also prevents passing a zero-length array to qsort(),
464          * which is a problem on some platforms.
465          */
466         if (dir->sorted == dir->nr)
467                 return;
468
469         qsort(dir->entries, dir->nr, sizeof(*dir->entries), ref_entry_cmp);
470
471         /* Remove any duplicates: */
472         for (i = 0, j = 0; j < dir->nr; j++) {
473                 struct ref_entry *entry = dir->entries[j];
474                 if (last && is_dup_ref(last, entry))
475                         free_ref_entry(entry);
476                 else
477                         last = dir->entries[i++] = entry;
478         }
479         dir->sorted = dir->nr = i;
480 }
481
482 #define DO_FOR_EACH_INCLUDE_BROKEN 01
483
484 static struct ref_entry *current_ref;
485
486 static int do_one_ref(const char *base, each_ref_fn fn, int trim,
487                       int flags, void *cb_data, struct ref_entry *entry)
488 {
489         int retval;
490         if (prefixcmp(entry->name, base))
491                 return 0;
492
493         if (!(flags & DO_FOR_EACH_INCLUDE_BROKEN)) {
494                 if (entry->flag & REF_ISBROKEN)
495                         return 0; /* ignore broken refs e.g. dangling symref */
496                 if (!has_sha1_file(entry->u.value.sha1)) {
497                         error("%s does not point to a valid object!", entry->name);
498                         return 0;
499                 }
500         }
501         current_ref = entry;
502         retval = fn(entry->name + trim, entry->u.value.sha1, entry->flag, cb_data);
503         current_ref = NULL;
504         return retval;
505 }
506
507 /*
508  * Call fn for each reference in dir that has index in the range
509  * offset <= index < dir->nr.  Recurse into subdirectories that are in
510  * that index range, sorting them before iterating.  This function
511  * does not sort dir itself; it should be sorted beforehand.
512  */
513 static int do_for_each_ref_in_dir(struct ref_dir *dir, int offset,
514                                   const char *base,
515                                   each_ref_fn fn, int trim, int flags, void *cb_data)
516 {
517         int i;
518         assert(dir->sorted == dir->nr);
519         for (i = offset; i < dir->nr; i++) {
520                 struct ref_entry *entry = dir->entries[i];
521                 int retval;
522                 if (entry->flag & REF_DIR) {
523                         struct ref_dir *subdir = get_ref_dir(entry);
524                         sort_ref_dir(subdir);
525                         retval = do_for_each_ref_in_dir(subdir, 0,
526                                                         base, fn, trim, flags, cb_data);
527                 } else {
528                         retval = do_one_ref(base, fn, trim, flags, cb_data, entry);
529                 }
530                 if (retval)
531                         return retval;
532         }
533         return 0;
534 }
535
536 /*
537  * Call fn for each reference in the union of dir1 and dir2, in order
538  * by refname.  Recurse into subdirectories.  If a value entry appears
539  * in both dir1 and dir2, then only process the version that is in
540  * dir2.  The input dirs must already be sorted, but subdirs will be
541  * sorted as needed.
542  */
543 static int do_for_each_ref_in_dirs(struct ref_dir *dir1,
544                                    struct ref_dir *dir2,
545                                    const char *base, each_ref_fn fn, int trim,
546                                    int flags, void *cb_data)
547 {
548         int retval;
549         int i1 = 0, i2 = 0;
550
551         assert(dir1->sorted == dir1->nr);
552         assert(dir2->sorted == dir2->nr);
553         while (1) {
554                 struct ref_entry *e1, *e2;
555                 int cmp;
556                 if (i1 == dir1->nr) {
557                         return do_for_each_ref_in_dir(dir2, i2,
558                                                       base, fn, trim, flags, cb_data);
559                 }
560                 if (i2 == dir2->nr) {
561                         return do_for_each_ref_in_dir(dir1, i1,
562                                                       base, fn, trim, flags, cb_data);
563                 }
564                 e1 = dir1->entries[i1];
565                 e2 = dir2->entries[i2];
566                 cmp = strcmp(e1->name, e2->name);
567                 if (cmp == 0) {
568                         if ((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) {
569                                 /* Both are directories; descend them in parallel. */
570                                 struct ref_dir *subdir1 = get_ref_dir(e1);
571                                 struct ref_dir *subdir2 = get_ref_dir(e2);
572                                 sort_ref_dir(subdir1);
573                                 sort_ref_dir(subdir2);
574                                 retval = do_for_each_ref_in_dirs(
575                                                 subdir1, subdir2,
576                                                 base, fn, trim, flags, cb_data);
577                                 i1++;
578                                 i2++;
579                         } else if (!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) {
580                                 /* Both are references; ignore the one from dir1. */
581                                 retval = do_one_ref(base, fn, trim, flags, cb_data, e2);
582                                 i1++;
583                                 i2++;
584                         } else {
585                                 die("conflict between reference and directory: %s",
586                                     e1->name);
587                         }
588                 } else {
589                         struct ref_entry *e;
590                         if (cmp < 0) {
591                                 e = e1;
592                                 i1++;
593                         } else {
594                                 e = e2;
595                                 i2++;
596                         }
597                         if (e->flag & REF_DIR) {
598                                 struct ref_dir *subdir = get_ref_dir(e);
599                                 sort_ref_dir(subdir);
600                                 retval = do_for_each_ref_in_dir(
601                                                 subdir, 0,
602                                                 base, fn, trim, flags, cb_data);
603                         } else {
604                                 retval = do_one_ref(base, fn, trim, flags, cb_data, e);
605                         }
606                 }
607                 if (retval)
608                         return retval;
609         }
610         if (i1 < dir1->nr)
611                 return do_for_each_ref_in_dir(dir1, i1,
612                                               base, fn, trim, flags, cb_data);
613         if (i2 < dir2->nr)
614                 return do_for_each_ref_in_dir(dir2, i2,
615                                               base, fn, trim, flags, cb_data);
616         return 0;
617 }
618
619 /*
620  * Return true iff refname1 and refname2 conflict with each other.
621  * Two reference names conflict if one of them exactly matches the
622  * leading components of the other; e.g., "foo/bar" conflicts with
623  * both "foo" and with "foo/bar/baz" but not with "foo/bar" or
624  * "foo/barbados".
625  */
626 static int names_conflict(const char *refname1, const char *refname2)
627 {
628         for (; *refname1 && *refname1 == *refname2; refname1++, refname2++)
629                 ;
630         return (*refname1 == '\0' && *refname2 == '/')
631                 || (*refname1 == '/' && *refname2 == '\0');
632 }
633
634 struct name_conflict_cb {
635         const char *refname;
636         const char *oldrefname;
637         const char *conflicting_refname;
638 };
639
640 static int name_conflict_fn(const char *existingrefname, const unsigned char *sha1,
641                             int flags, void *cb_data)
642 {
643         struct name_conflict_cb *data = (struct name_conflict_cb *)cb_data;
644         if (data->oldrefname && !strcmp(data->oldrefname, existingrefname))
645                 return 0;
646         if (names_conflict(data->refname, existingrefname)) {
647                 data->conflicting_refname = existingrefname;
648                 return 1;
649         }
650         return 0;
651 }
652
653 /*
654  * Return true iff a reference named refname could be created without
655  * conflicting with the name of an existing reference in array.  If
656  * oldrefname is non-NULL, ignore potential conflicts with oldrefname
657  * (e.g., because oldrefname is scheduled for deletion in the same
658  * operation).
659  */
660 static int is_refname_available(const char *refname, const char *oldrefname,
661                                 struct ref_dir *dir)
662 {
663         struct name_conflict_cb data;
664         data.refname = refname;
665         data.oldrefname = oldrefname;
666         data.conflicting_refname = NULL;
667
668         sort_ref_dir(dir);
669         if (do_for_each_ref_in_dir(dir, 0, "", name_conflict_fn,
670                                    0, DO_FOR_EACH_INCLUDE_BROKEN,
671                                    &data)) {
672                 error("'%s' exists; cannot create '%s'",
673                       data.conflicting_refname, refname);
674                 return 0;
675         }
676         return 1;
677 }
678
679 /*
680  * Future: need to be in "struct repository"
681  * when doing a full libification.
682  */
683 static struct ref_cache {
684         struct ref_cache *next;
685         struct ref_entry *loose;
686         struct ref_entry *packed;
687         /* The submodule name, or "" for the main repo. */
688         char name[FLEX_ARRAY];
689 } *ref_cache;
690
691 static void clear_packed_ref_cache(struct ref_cache *refs)
692 {
693         if (refs->packed) {
694                 free_ref_entry(refs->packed);
695                 refs->packed = NULL;
696         }
697 }
698
699 static void clear_loose_ref_cache(struct ref_cache *refs)
700 {
701         if (refs->loose) {
702                 free_ref_entry(refs->loose);
703                 refs->loose = NULL;
704         }
705 }
706
707 static struct ref_cache *create_ref_cache(const char *submodule)
708 {
709         int len;
710         struct ref_cache *refs;
711         if (!submodule)
712                 submodule = "";
713         len = strlen(submodule) + 1;
714         refs = xcalloc(1, sizeof(struct ref_cache) + len);
715         memcpy(refs->name, submodule, len);
716         return refs;
717 }
718
719 /*
720  * Return a pointer to a ref_cache for the specified submodule. For
721  * the main repository, use submodule==NULL. The returned structure
722  * will be allocated and initialized but not necessarily populated; it
723  * should not be freed.
724  */
725 static struct ref_cache *get_ref_cache(const char *submodule)
726 {
727         struct ref_cache *refs = ref_cache;
728         if (!submodule)
729                 submodule = "";
730         while (refs) {
731                 if (!strcmp(submodule, refs->name))
732                         return refs;
733                 refs = refs->next;
734         }
735
736         refs = create_ref_cache(submodule);
737         refs->next = ref_cache;
738         ref_cache = refs;
739         return refs;
740 }
741
742 void invalidate_ref_cache(const char *submodule)
743 {
744         struct ref_cache *refs = get_ref_cache(submodule);
745         clear_packed_ref_cache(refs);
746         clear_loose_ref_cache(refs);
747 }
748
749 /*
750  * Parse one line from a packed-refs file.  Write the SHA1 to sha1.
751  * Return a pointer to the refname within the line (null-terminated),
752  * or NULL if there was a problem.
753  */
754 static const char *parse_ref_line(char *line, unsigned char *sha1)
755 {
756         /*
757          * 42: the answer to everything.
758          *
759          * In this case, it happens to be the answer to
760          *  40 (length of sha1 hex representation)
761          *  +1 (space in between hex and name)
762          *  +1 (newline at the end of the line)
763          */
764         int len = strlen(line) - 42;
765
766         if (len <= 0)
767                 return NULL;
768         if (get_sha1_hex(line, sha1) < 0)
769                 return NULL;
770         if (!isspace(line[40]))
771                 return NULL;
772         line += 41;
773         if (isspace(*line))
774                 return NULL;
775         if (line[len] != '\n')
776                 return NULL;
777         line[len] = 0;
778
779         return line;
780 }
781
782 static void read_packed_refs(FILE *f, struct ref_dir *dir)
783 {
784         struct ref_entry *last = NULL;
785         char refline[PATH_MAX];
786         int flag = REF_ISPACKED;
787
788         while (fgets(refline, sizeof(refline), f)) {
789                 unsigned char sha1[20];
790                 const char *refname;
791                 static const char header[] = "# pack-refs with:";
792
793                 if (!strncmp(refline, header, sizeof(header)-1)) {
794                         const char *traits = refline + sizeof(header) - 1;
795                         if (strstr(traits, " peeled "))
796                                 flag |= REF_KNOWS_PEELED;
797                         /* perhaps other traits later as well */
798                         continue;
799                 }
800
801                 refname = parse_ref_line(refline, sha1);
802                 if (refname) {
803                         last = create_ref_entry(refname, sha1, flag, 1);
804                         add_ref(dir, last);
805                         continue;
806                 }
807                 if (last &&
808                     refline[0] == '^' &&
809                     strlen(refline) == 42 &&
810                     refline[41] == '\n' &&
811                     !get_sha1_hex(refline + 1, sha1))
812                         hashcpy(last->u.value.peeled, sha1);
813         }
814 }
815
816 static struct ref_dir *get_packed_refs(struct ref_cache *refs)
817 {
818         if (!refs->packed) {
819                 const char *packed_refs_file;
820                 FILE *f;
821
822                 refs->packed = create_dir_entry(refs, "", 0, 0);
823                 if (*refs->name)
824                         packed_refs_file = git_path_submodule(refs->name, "packed-refs");
825                 else
826                         packed_refs_file = git_path("packed-refs");
827                 f = fopen(packed_refs_file, "r");
828                 if (f) {
829                         read_packed_refs(f, get_ref_dir(refs->packed));
830                         fclose(f);
831                 }
832         }
833         return get_ref_dir(refs->packed);
834 }
835
836 void add_packed_ref(const char *refname, const unsigned char *sha1)
837 {
838         add_ref(get_packed_refs(get_ref_cache(NULL)),
839                         create_ref_entry(refname, sha1, REF_ISPACKED, 1));
840 }
841
842 /*
843  * Read the loose references from the namespace dirname into dir
844  * (without recursing).  dirname must end with '/'.  dir must be the
845  * directory entry corresponding to dirname.
846  */
847 static void read_loose_refs(const char *dirname, struct ref_dir *dir)
848 {
849         struct ref_cache *refs = dir->ref_cache;
850         DIR *d;
851         const char *path;
852         struct dirent *de;
853         int dirnamelen = strlen(dirname);
854         struct strbuf refname;
855
856         if (*refs->name)
857                 path = git_path_submodule(refs->name, "%s", dirname);
858         else
859                 path = git_path("%s", dirname);
860
861         d = opendir(path);
862         if (!d)
863                 return;
864
865         strbuf_init(&refname, dirnamelen + 257);
866         strbuf_add(&refname, dirname, dirnamelen);
867
868         while ((de = readdir(d)) != NULL) {
869                 unsigned char sha1[20];
870                 struct stat st;
871                 int flag;
872                 const char *refdir;
873
874                 if (de->d_name[0] == '.')
875                         continue;
876                 if (has_extension(de->d_name, ".lock"))
877                         continue;
878                 strbuf_addstr(&refname, de->d_name);
879                 refdir = *refs->name
880                         ? git_path_submodule(refs->name, "%s", refname.buf)
881                         : git_path("%s", refname.buf);
882                 if (stat(refdir, &st) < 0) {
883                         ; /* silently ignore */
884                 } else if (S_ISDIR(st.st_mode)) {
885                         strbuf_addch(&refname, '/');
886                         add_entry_to_dir(dir,
887                                          create_dir_entry(refs, refname.buf,
888                                                           refname.len, 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, 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/", 5, 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         fputc('\n', d->fp);
1234         return 0;
1235 }
1236
1237 void warn_dangling_symref(FILE *fp, const char *msg_fmt, const char *refname)
1238 {
1239         struct warn_if_dangling_data data;
1240
1241         data.fp = fp;
1242         data.refname = refname;
1243         data.msg_fmt = msg_fmt;
1244         for_each_rawref(warn_if_dangling_symref, &data);
1245 }
1246
1247 static int do_for_each_ref(const char *submodule, const char *base, each_ref_fn fn,
1248                            int trim, int flags, void *cb_data)
1249 {
1250         struct ref_cache *refs = get_ref_cache(submodule);
1251         struct ref_dir *packed_dir = get_packed_refs(refs);
1252         struct ref_dir *loose_dir = get_loose_refs(refs);
1253         int retval = 0;
1254
1255         if (base && *base) {
1256                 packed_dir = find_containing_dir(packed_dir, base, 0);
1257                 loose_dir = find_containing_dir(loose_dir, base, 0);
1258         }
1259
1260         if (packed_dir && loose_dir) {
1261                 sort_ref_dir(packed_dir);
1262                 sort_ref_dir(loose_dir);
1263                 retval = do_for_each_ref_in_dirs(
1264                                 packed_dir, loose_dir,
1265                                 base, fn, trim, flags, cb_data);
1266         } else if (packed_dir) {
1267                 sort_ref_dir(packed_dir);
1268                 retval = do_for_each_ref_in_dir(
1269                                 packed_dir, 0,
1270                                 base, fn, trim, flags, cb_data);
1271         } else if (loose_dir) {
1272                 sort_ref_dir(loose_dir);
1273                 retval = do_for_each_ref_in_dir(
1274                                 loose_dir, 0,
1275                                 base, fn, trim, flags, cb_data);
1276         }
1277
1278         return retval;
1279 }
1280
1281 static int do_head_ref(const char *submodule, each_ref_fn fn, void *cb_data)
1282 {
1283         unsigned char sha1[20];
1284         int flag;
1285
1286         if (submodule) {
1287                 if (resolve_gitlink_ref(submodule, "HEAD", sha1) == 0)
1288                         return fn("HEAD", sha1, 0, cb_data);
1289
1290                 return 0;
1291         }
1292
1293         if (!read_ref_full("HEAD", sha1, 1, &flag))
1294                 return fn("HEAD", sha1, flag, cb_data);
1295
1296         return 0;
1297 }
1298
1299 int head_ref(each_ref_fn fn, void *cb_data)
1300 {
1301         return do_head_ref(NULL, fn, cb_data);
1302 }
1303
1304 int head_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1305 {
1306         return do_head_ref(submodule, fn, cb_data);
1307 }
1308
1309 int for_each_ref(each_ref_fn fn, void *cb_data)
1310 {
1311         return do_for_each_ref(NULL, "", fn, 0, 0, cb_data);
1312 }
1313
1314 int for_each_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1315 {
1316         return do_for_each_ref(submodule, "", fn, 0, 0, cb_data);
1317 }
1318
1319 int for_each_ref_in(const char *prefix, each_ref_fn fn, void *cb_data)
1320 {
1321         return do_for_each_ref(NULL, prefix, fn, strlen(prefix), 0, cb_data);
1322 }
1323
1324 int for_each_ref_in_submodule(const char *submodule, const char *prefix,
1325                 each_ref_fn fn, void *cb_data)
1326 {
1327         return do_for_each_ref(submodule, prefix, fn, strlen(prefix), 0, cb_data);
1328 }
1329
1330 int for_each_tag_ref(each_ref_fn fn, void *cb_data)
1331 {
1332         return for_each_ref_in("refs/tags/", fn, cb_data);
1333 }
1334
1335 int for_each_tag_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1336 {
1337         return for_each_ref_in_submodule(submodule, "refs/tags/", fn, cb_data);
1338 }
1339
1340 int for_each_branch_ref(each_ref_fn fn, void *cb_data)
1341 {
1342         return for_each_ref_in("refs/heads/", fn, cb_data);
1343 }
1344
1345 int for_each_branch_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1346 {
1347         return for_each_ref_in_submodule(submodule, "refs/heads/", fn, cb_data);
1348 }
1349
1350 int for_each_remote_ref(each_ref_fn fn, void *cb_data)
1351 {
1352         return for_each_ref_in("refs/remotes/", fn, cb_data);
1353 }
1354
1355 int for_each_remote_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1356 {
1357         return for_each_ref_in_submodule(submodule, "refs/remotes/", fn, cb_data);
1358 }
1359
1360 int for_each_replace_ref(each_ref_fn fn, void *cb_data)
1361 {
1362         return do_for_each_ref(NULL, "refs/replace/", fn, 13, 0, cb_data);
1363 }
1364
1365 int head_ref_namespaced(each_ref_fn fn, void *cb_data)
1366 {
1367         struct strbuf buf = STRBUF_INIT;
1368         int ret = 0;
1369         unsigned char sha1[20];
1370         int flag;
1371
1372         strbuf_addf(&buf, "%sHEAD", get_git_namespace());
1373         if (!read_ref_full(buf.buf, sha1, 1, &flag))
1374                 ret = fn(buf.buf, sha1, flag, cb_data);
1375         strbuf_release(&buf);
1376
1377         return ret;
1378 }
1379
1380 int for_each_namespaced_ref(each_ref_fn fn, void *cb_data)
1381 {
1382         struct strbuf buf = STRBUF_INIT;
1383         int ret;
1384         strbuf_addf(&buf, "%srefs/", get_git_namespace());
1385         ret = do_for_each_ref(NULL, buf.buf, fn, 0, 0, cb_data);
1386         strbuf_release(&buf);
1387         return ret;
1388 }
1389
1390 int for_each_glob_ref_in(each_ref_fn fn, const char *pattern,
1391         const char *prefix, void *cb_data)
1392 {
1393         struct strbuf real_pattern = STRBUF_INIT;
1394         struct ref_filter filter;
1395         int ret;
1396
1397         if (!prefix && prefixcmp(pattern, "refs/"))
1398                 strbuf_addstr(&real_pattern, "refs/");
1399         else if (prefix)
1400                 strbuf_addstr(&real_pattern, prefix);
1401         strbuf_addstr(&real_pattern, pattern);
1402
1403         if (!has_glob_specials(pattern)) {
1404                 /* Append implied '/' '*' if not present. */
1405                 if (real_pattern.buf[real_pattern.len - 1] != '/')
1406                         strbuf_addch(&real_pattern, '/');
1407                 /* No need to check for '*', there is none. */
1408                 strbuf_addch(&real_pattern, '*');
1409         }
1410
1411         filter.pattern = real_pattern.buf;
1412         filter.fn = fn;
1413         filter.cb_data = cb_data;
1414         ret = for_each_ref(filter_refs, &filter);
1415
1416         strbuf_release(&real_pattern);
1417         return ret;
1418 }
1419
1420 int for_each_glob_ref(each_ref_fn fn, const char *pattern, void *cb_data)
1421 {
1422         return for_each_glob_ref_in(fn, pattern, NULL, cb_data);
1423 }
1424
1425 int for_each_rawref(each_ref_fn fn, void *cb_data)
1426 {
1427         return do_for_each_ref(NULL, "", fn, 0,
1428                                DO_FOR_EACH_INCLUDE_BROKEN, cb_data);
1429 }
1430
1431 const char *prettify_refname(const char *name)
1432 {
1433         return name + (
1434                 !prefixcmp(name, "refs/heads/") ? 11 :
1435                 !prefixcmp(name, "refs/tags/") ? 10 :
1436                 !prefixcmp(name, "refs/remotes/") ? 13 :
1437                 0);
1438 }
1439
1440 const char *ref_rev_parse_rules[] = {
1441         "%.*s",
1442         "refs/%.*s",
1443         "refs/tags/%.*s",
1444         "refs/heads/%.*s",
1445         "refs/remotes/%.*s",
1446         "refs/remotes/%.*s/HEAD",
1447         NULL
1448 };
1449
1450 int refname_match(const char *abbrev_name, const char *full_name, const char **rules)
1451 {
1452         const char **p;
1453         const int abbrev_name_len = strlen(abbrev_name);
1454
1455         for (p = rules; *p; p++) {
1456                 if (!strcmp(full_name, mkpath(*p, abbrev_name_len, abbrev_name))) {
1457                         return 1;
1458                 }
1459         }
1460
1461         return 0;
1462 }
1463
1464 static struct ref_lock *verify_lock(struct ref_lock *lock,
1465         const unsigned char *old_sha1, int mustexist)
1466 {
1467         if (read_ref_full(lock->ref_name, lock->old_sha1, mustexist, NULL)) {
1468                 error("Can't verify ref %s", lock->ref_name);
1469                 unlock_ref(lock);
1470                 return NULL;
1471         }
1472         if (hashcmp(lock->old_sha1, old_sha1)) {
1473                 error("Ref %s is at %s but expected %s", lock->ref_name,
1474                         sha1_to_hex(lock->old_sha1), sha1_to_hex(old_sha1));
1475                 unlock_ref(lock);
1476                 return NULL;
1477         }
1478         return lock;
1479 }
1480
1481 static int remove_empty_directories(const char *file)
1482 {
1483         /* we want to create a file but there is a directory there;
1484          * if that is an empty directory (or a directory that contains
1485          * only empty directories), remove them.
1486          */
1487         struct strbuf path;
1488         int result;
1489
1490         strbuf_init(&path, 20);
1491         strbuf_addstr(&path, file);
1492
1493         result = remove_dir_recursively(&path, REMOVE_DIR_EMPTY_ONLY);
1494
1495         strbuf_release(&path);
1496
1497         return result;
1498 }
1499
1500 /*
1501  * *string and *len will only be substituted, and *string returned (for
1502  * later free()ing) if the string passed in is a magic short-hand form
1503  * to name a branch.
1504  */
1505 static char *substitute_branch_name(const char **string, int *len)
1506 {
1507         struct strbuf buf = STRBUF_INIT;
1508         int ret = interpret_branch_name(*string, &buf);
1509
1510         if (ret == *len) {
1511                 size_t size;
1512                 *string = strbuf_detach(&buf, &size);
1513                 *len = size;
1514                 return (char *)*string;
1515         }
1516
1517         return NULL;
1518 }
1519
1520 int dwim_ref(const char *str, int len, unsigned char *sha1, char **ref)
1521 {
1522         char *last_branch = substitute_branch_name(&str, &len);
1523         const char **p, *r;
1524         int refs_found = 0;
1525
1526         *ref = NULL;
1527         for (p = ref_rev_parse_rules; *p; p++) {
1528                 char fullref[PATH_MAX];
1529                 unsigned char sha1_from_ref[20];
1530                 unsigned char *this_result;
1531                 int flag;
1532
1533                 this_result = refs_found ? sha1_from_ref : sha1;
1534                 mksnpath(fullref, sizeof(fullref), *p, len, str);
1535                 r = resolve_ref_unsafe(fullref, this_result, 1, &flag);
1536                 if (r) {
1537                         if (!refs_found++)
1538                                 *ref = xstrdup(r);
1539                         if (!warn_ambiguous_refs)
1540                                 break;
1541                 } else if ((flag & REF_ISSYMREF) && strcmp(fullref, "HEAD")) {
1542                         warning("ignoring dangling symref %s.", fullref);
1543                 } else if ((flag & REF_ISBROKEN) && strchr(fullref, '/')) {
1544                         warning("ignoring broken ref %s.", fullref);
1545                 }
1546         }
1547         free(last_branch);
1548         return refs_found;
1549 }
1550
1551 int dwim_log(const char *str, int len, unsigned char *sha1, char **log)
1552 {
1553         char *last_branch = substitute_branch_name(&str, &len);
1554         const char **p;
1555         int logs_found = 0;
1556
1557         *log = NULL;
1558         for (p = ref_rev_parse_rules; *p; p++) {
1559                 struct stat st;
1560                 unsigned char hash[20];
1561                 char path[PATH_MAX];
1562                 const char *ref, *it;
1563
1564                 mksnpath(path, sizeof(path), *p, len, str);
1565                 ref = resolve_ref_unsafe(path, hash, 1, NULL);
1566                 if (!ref)
1567                         continue;
1568                 if (!stat(git_path("logs/%s", path), &st) &&
1569                     S_ISREG(st.st_mode))
1570                         it = path;
1571                 else if (strcmp(ref, path) &&
1572                          !stat(git_path("logs/%s", ref), &st) &&
1573                          S_ISREG(st.st_mode))
1574                         it = ref;
1575                 else
1576                         continue;
1577                 if (!logs_found++) {
1578                         *log = xstrdup(it);
1579                         hashcpy(sha1, hash);
1580                 }
1581                 if (!warn_ambiguous_refs)
1582                         break;
1583         }
1584         free(last_branch);
1585         return logs_found;
1586 }
1587
1588 static struct ref_lock *lock_ref_sha1_basic(const char *refname,
1589                                             const unsigned char *old_sha1,
1590                                             int flags, int *type_p)
1591 {
1592         char *ref_file;
1593         const char *orig_refname = refname;
1594         struct ref_lock *lock;
1595         int last_errno = 0;
1596         int type, lflags;
1597         int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
1598         int missing = 0;
1599
1600         lock = xcalloc(1, sizeof(struct ref_lock));
1601         lock->lock_fd = -1;
1602
1603         refname = resolve_ref_unsafe(refname, lock->old_sha1, mustexist, &type);
1604         if (!refname && errno == EISDIR) {
1605                 /* we are trying to lock foo but we used to
1606                  * have foo/bar which now does not exist;
1607                  * it is normal for the empty directory 'foo'
1608                  * to remain.
1609                  */
1610                 ref_file = git_path("%s", orig_refname);
1611                 if (remove_empty_directories(ref_file)) {
1612                         last_errno = errno;
1613                         error("there are still refs under '%s'", orig_refname);
1614                         goto error_return;
1615                 }
1616                 refname = resolve_ref_unsafe(orig_refname, lock->old_sha1, mustexist, &type);
1617         }
1618         if (type_p)
1619             *type_p = type;
1620         if (!refname) {
1621                 last_errno = errno;
1622                 error("unable to resolve reference %s: %s",
1623                         orig_refname, strerror(errno));
1624                 goto error_return;
1625         }
1626         missing = is_null_sha1(lock->old_sha1);
1627         /* When the ref did not exist and we are creating it,
1628          * make sure there is no existing ref that is packed
1629          * whose name begins with our refname, nor a ref whose
1630          * name is a proper prefix of our refname.
1631          */
1632         if (missing &&
1633              !is_refname_available(refname, NULL, get_packed_refs(get_ref_cache(NULL)))) {
1634                 last_errno = ENOTDIR;
1635                 goto error_return;
1636         }
1637
1638         lock->lk = xcalloc(1, sizeof(struct lock_file));
1639
1640         lflags = LOCK_DIE_ON_ERROR;
1641         if (flags & REF_NODEREF) {
1642                 refname = orig_refname;
1643                 lflags |= LOCK_NODEREF;
1644         }
1645         lock->ref_name = xstrdup(refname);
1646         lock->orig_ref_name = xstrdup(orig_refname);
1647         ref_file = git_path("%s", refname);
1648         if (missing)
1649                 lock->force_write = 1;
1650         if ((flags & REF_NODEREF) && (type & REF_ISSYMREF))
1651                 lock->force_write = 1;
1652
1653         if (safe_create_leading_directories(ref_file)) {
1654                 last_errno = errno;
1655                 error("unable to create directory for %s", ref_file);
1656                 goto error_return;
1657         }
1658
1659         lock->lock_fd = hold_lock_file_for_update(lock->lk, ref_file, lflags);
1660         return old_sha1 ? verify_lock(lock, old_sha1, mustexist) : lock;
1661
1662  error_return:
1663         unlock_ref(lock);
1664         errno = last_errno;
1665         return NULL;
1666 }
1667
1668 struct ref_lock *lock_ref_sha1(const char *refname, const unsigned char *old_sha1)
1669 {
1670         char refpath[PATH_MAX];
1671         if (check_refname_format(refname, 0))
1672                 return NULL;
1673         strcpy(refpath, mkpath("refs/%s", refname));
1674         return lock_ref_sha1_basic(refpath, old_sha1, 0, NULL);
1675 }
1676
1677 struct ref_lock *lock_any_ref_for_update(const char *refname,
1678                                          const unsigned char *old_sha1, int flags)
1679 {
1680         if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL))
1681                 return NULL;
1682         return lock_ref_sha1_basic(refname, old_sha1, flags, NULL);
1683 }
1684
1685 struct repack_without_ref_sb {
1686         const char *refname;
1687         int fd;
1688 };
1689
1690 static int repack_without_ref_fn(const char *refname, const unsigned char *sha1,
1691                                  int flags, void *cb_data)
1692 {
1693         struct repack_without_ref_sb *data = cb_data;
1694         char line[PATH_MAX + 100];
1695         int len;
1696
1697         if (!strcmp(data->refname, refname))
1698                 return 0;
1699         len = snprintf(line, sizeof(line), "%s %s\n",
1700                        sha1_to_hex(sha1), refname);
1701         /* this should not happen but just being defensive */
1702         if (len > sizeof(line))
1703                 die("too long a refname '%s'", refname);
1704         write_or_die(data->fd, line, len);
1705         return 0;
1706 }
1707
1708 static struct lock_file packlock;
1709
1710 static int repack_without_ref(const char *refname)
1711 {
1712         struct repack_without_ref_sb data;
1713         struct ref_dir *packed = get_packed_refs(get_ref_cache(NULL));
1714         if (find_ref(packed, refname) == NULL)
1715                 return 0;
1716         data.refname = refname;
1717         data.fd = hold_lock_file_for_update(&packlock, git_path("packed-refs"), 0);
1718         if (data.fd < 0) {
1719                 unable_to_lock_error(git_path("packed-refs"), errno);
1720                 return error("cannot delete '%s' from packed refs", refname);
1721         }
1722         do_for_each_ref_in_dir(packed, 0, "", repack_without_ref_fn, 0, 0, &data);
1723         return commit_lock_file(&packlock);
1724 }
1725
1726 int delete_ref(const char *refname, const unsigned char *sha1, int delopt)
1727 {
1728         struct ref_lock *lock;
1729         int err, i = 0, ret = 0, flag = 0;
1730
1731         lock = lock_ref_sha1_basic(refname, sha1, 0, &flag);
1732         if (!lock)
1733                 return 1;
1734         if (!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {
1735                 /* loose */
1736                 const char *path;
1737
1738                 if (!(delopt & REF_NODEREF)) {
1739                         i = strlen(lock->lk->filename) - 5; /* .lock */
1740                         lock->lk->filename[i] = 0;
1741                         path = lock->lk->filename;
1742                 } else {
1743                         path = git_path("%s", refname);
1744                 }
1745                 err = unlink_or_warn(path);
1746                 if (err && errno != ENOENT)
1747                         ret = 1;
1748
1749                 if (!(delopt & REF_NODEREF))
1750                         lock->lk->filename[i] = '.';
1751         }
1752         /* removing the loose one could have resurrected an earlier
1753          * packed one.  Also, if it was not loose we need to repack
1754          * without it.
1755          */
1756         ret |= repack_without_ref(refname);
1757
1758         unlink_or_warn(git_path("logs/%s", lock->ref_name));
1759         invalidate_ref_cache(NULL);
1760         unlock_ref(lock);
1761         return ret;
1762 }
1763
1764 /*
1765  * People using contrib's git-new-workdir have .git/logs/refs ->
1766  * /some/other/path/.git/logs/refs, and that may live on another device.
1767  *
1768  * IOW, to avoid cross device rename errors, the temporary renamed log must
1769  * live into logs/refs.
1770  */
1771 #define TMP_RENAMED_LOG  "logs/refs/.tmp-renamed-log"
1772
1773 int rename_ref(const char *oldrefname, const char *newrefname, const char *logmsg)
1774 {
1775         unsigned char sha1[20], orig_sha1[20];
1776         int flag = 0, logmoved = 0;
1777         struct ref_lock *lock;
1778         struct stat loginfo;
1779         int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);
1780         const char *symref = NULL;
1781         struct ref_cache *refs = get_ref_cache(NULL);
1782
1783         if (log && S_ISLNK(loginfo.st_mode))
1784                 return error("reflog for %s is a symlink", oldrefname);
1785
1786         symref = resolve_ref_unsafe(oldrefname, orig_sha1, 1, &flag);
1787         if (flag & REF_ISSYMREF)
1788                 return error("refname %s is a symbolic ref, renaming it is not supported",
1789                         oldrefname);
1790         if (!symref)
1791                 return error("refname %s not found", oldrefname);
1792
1793         if (!is_refname_available(newrefname, oldrefname, get_packed_refs(refs)))
1794                 return 1;
1795
1796         if (!is_refname_available(newrefname, oldrefname, get_loose_refs(refs)))
1797                 return 1;
1798
1799         if (log && rename(git_path("logs/%s", oldrefname), git_path(TMP_RENAMED_LOG)))
1800                 return error("unable to move logfile logs/%s to "TMP_RENAMED_LOG": %s",
1801                         oldrefname, strerror(errno));
1802
1803         if (delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {
1804                 error("unable to delete old %s", oldrefname);
1805                 goto rollback;
1806         }
1807
1808         if (!read_ref_full(newrefname, sha1, 1, &flag) &&
1809             delete_ref(newrefname, sha1, REF_NODEREF)) {
1810                 if (errno==EISDIR) {
1811                         if (remove_empty_directories(git_path("%s", newrefname))) {
1812                                 error("Directory not empty: %s", newrefname);
1813                                 goto rollback;
1814                         }
1815                 } else {
1816                         error("unable to delete existing %s", newrefname);
1817                         goto rollback;
1818                 }
1819         }
1820
1821         if (log && safe_create_leading_directories(git_path("logs/%s", newrefname))) {
1822                 error("unable to create directory for %s", newrefname);
1823                 goto rollback;
1824         }
1825
1826  retry:
1827         if (log && rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", newrefname))) {
1828                 if (errno==EISDIR || errno==ENOTDIR) {
1829                         /*
1830                          * rename(a, b) when b is an existing
1831                          * directory ought to result in ISDIR, but
1832                          * Solaris 5.8 gives ENOTDIR.  Sheesh.
1833                          */
1834                         if (remove_empty_directories(git_path("logs/%s", newrefname))) {
1835                                 error("Directory not empty: logs/%s", newrefname);
1836                                 goto rollback;
1837                         }
1838                         goto retry;
1839                 } else {
1840                         error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s: %s",
1841                                 newrefname, strerror(errno));
1842                         goto rollback;
1843                 }
1844         }
1845         logmoved = log;
1846
1847         lock = lock_ref_sha1_basic(newrefname, NULL, 0, NULL);
1848         if (!lock) {
1849                 error("unable to lock %s for update", newrefname);
1850                 goto rollback;
1851         }
1852         lock->force_write = 1;
1853         hashcpy(lock->old_sha1, orig_sha1);
1854         if (write_ref_sha1(lock, orig_sha1, logmsg)) {
1855                 error("unable to write current sha1 into %s", newrefname);
1856                 goto rollback;
1857         }
1858
1859         return 0;
1860
1861  rollback:
1862         lock = lock_ref_sha1_basic(oldrefname, NULL, 0, NULL);
1863         if (!lock) {
1864                 error("unable to lock %s for rollback", oldrefname);
1865                 goto rollbacklog;
1866         }
1867
1868         lock->force_write = 1;
1869         flag = log_all_ref_updates;
1870         log_all_ref_updates = 0;
1871         if (write_ref_sha1(lock, orig_sha1, NULL))
1872                 error("unable to write current sha1 into %s", oldrefname);
1873         log_all_ref_updates = flag;
1874
1875  rollbacklog:
1876         if (logmoved && rename(git_path("logs/%s", newrefname), git_path("logs/%s", oldrefname)))
1877                 error("unable to restore logfile %s from %s: %s",
1878                         oldrefname, newrefname, strerror(errno));
1879         if (!logmoved && log &&
1880             rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", oldrefname)))
1881                 error("unable to restore logfile %s from "TMP_RENAMED_LOG": %s",
1882                         oldrefname, strerror(errno));
1883
1884         return 1;
1885 }
1886
1887 int close_ref(struct ref_lock *lock)
1888 {
1889         if (close_lock_file(lock->lk))
1890                 return -1;
1891         lock->lock_fd = -1;
1892         return 0;
1893 }
1894
1895 int commit_ref(struct ref_lock *lock)
1896 {
1897         if (commit_lock_file(lock->lk))
1898                 return -1;
1899         lock->lock_fd = -1;
1900         return 0;
1901 }
1902
1903 void unlock_ref(struct ref_lock *lock)
1904 {
1905         /* Do not free lock->lk -- atexit() still looks at them */
1906         if (lock->lk)
1907                 rollback_lock_file(lock->lk);
1908         free(lock->ref_name);
1909         free(lock->orig_ref_name);
1910         free(lock);
1911 }
1912
1913 /*
1914  * copy the reflog message msg to buf, which has been allocated sufficiently
1915  * large, while cleaning up the whitespaces.  Especially, convert LF to space,
1916  * because reflog file is one line per entry.
1917  */
1918 static int copy_msg(char *buf, const char *msg)
1919 {
1920         char *cp = buf;
1921         char c;
1922         int wasspace = 1;
1923
1924         *cp++ = '\t';
1925         while ((c = *msg++)) {
1926                 if (wasspace && isspace(c))
1927                         continue;
1928                 wasspace = isspace(c);
1929                 if (wasspace)
1930                         c = ' ';
1931                 *cp++ = c;
1932         }
1933         while (buf < cp && isspace(cp[-1]))
1934                 cp--;
1935         *cp++ = '\n';
1936         return cp - buf;
1937 }
1938
1939 int log_ref_setup(const char *refname, char *logfile, int bufsize)
1940 {
1941         int logfd, oflags = O_APPEND | O_WRONLY;
1942
1943         git_snpath(logfile, bufsize, "logs/%s", refname);
1944         if (log_all_ref_updates &&
1945             (!prefixcmp(refname, "refs/heads/") ||
1946              !prefixcmp(refname, "refs/remotes/") ||
1947              !prefixcmp(refname, "refs/notes/") ||
1948              !strcmp(refname, "HEAD"))) {
1949                 if (safe_create_leading_directories(logfile) < 0)
1950                         return error("unable to create directory for %s",
1951                                      logfile);
1952                 oflags |= O_CREAT;
1953         }
1954
1955         logfd = open(logfile, oflags, 0666);
1956         if (logfd < 0) {
1957                 if (!(oflags & O_CREAT) && errno == ENOENT)
1958                         return 0;
1959
1960                 if ((oflags & O_CREAT) && errno == EISDIR) {
1961                         if (remove_empty_directories(logfile)) {
1962                                 return error("There are still logs under '%s'",
1963                                              logfile);
1964                         }
1965                         logfd = open(logfile, oflags, 0666);
1966                 }
1967
1968                 if (logfd < 0)
1969                         return error("Unable to append to %s: %s",
1970                                      logfile, strerror(errno));
1971         }
1972
1973         adjust_shared_perm(logfile);
1974         close(logfd);
1975         return 0;
1976 }
1977
1978 static int log_ref_write(const char *refname, const unsigned char *old_sha1,
1979                          const unsigned char *new_sha1, const char *msg)
1980 {
1981         int logfd, result, written, oflags = O_APPEND | O_WRONLY;
1982         unsigned maxlen, len;
1983         int msglen;
1984         char log_file[PATH_MAX];
1985         char *logrec;
1986         const char *committer;
1987
1988         if (log_all_ref_updates < 0)
1989                 log_all_ref_updates = !is_bare_repository();
1990
1991         result = log_ref_setup(refname, log_file, sizeof(log_file));
1992         if (result)
1993                 return result;
1994
1995         logfd = open(log_file, oflags);
1996         if (logfd < 0)
1997                 return 0;
1998         msglen = msg ? strlen(msg) : 0;
1999         committer = git_committer_info(0);
2000         maxlen = strlen(committer) + msglen + 100;
2001         logrec = xmalloc(maxlen);
2002         len = sprintf(logrec, "%s %s %s\n",
2003                       sha1_to_hex(old_sha1),
2004                       sha1_to_hex(new_sha1),
2005                       committer);
2006         if (msglen)
2007                 len += copy_msg(logrec + len - 1, msg) - 1;
2008         written = len <= maxlen ? write_in_full(logfd, logrec, len) : -1;
2009         free(logrec);
2010         if (close(logfd) != 0 || written != len)
2011                 return error("Unable to append to %s", log_file);
2012         return 0;
2013 }
2014
2015 static int is_branch(const char *refname)
2016 {
2017         return !strcmp(refname, "HEAD") || !prefixcmp(refname, "refs/heads/");
2018 }
2019
2020 int write_ref_sha1(struct ref_lock *lock,
2021         const unsigned char *sha1, const char *logmsg)
2022 {
2023         static char term = '\n';
2024         struct object *o;
2025
2026         if (!lock)
2027                 return -1;
2028         if (!lock->force_write && !hashcmp(lock->old_sha1, sha1)) {
2029                 unlock_ref(lock);
2030                 return 0;
2031         }
2032         o = parse_object(sha1);
2033         if (!o) {
2034                 error("Trying to write ref %s with nonexistent object %s",
2035                         lock->ref_name, sha1_to_hex(sha1));
2036                 unlock_ref(lock);
2037                 return -1;
2038         }
2039         if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
2040                 error("Trying to write non-commit object %s to branch %s",
2041                         sha1_to_hex(sha1), lock->ref_name);
2042                 unlock_ref(lock);
2043                 return -1;
2044         }
2045         if (write_in_full(lock->lock_fd, sha1_to_hex(sha1), 40) != 40 ||
2046             write_in_full(lock->lock_fd, &term, 1) != 1
2047                 || close_ref(lock) < 0) {
2048                 error("Couldn't write %s", lock->lk->filename);
2049                 unlock_ref(lock);
2050                 return -1;
2051         }
2052         clear_loose_ref_cache(get_ref_cache(NULL));
2053         if (log_ref_write(lock->ref_name, lock->old_sha1, sha1, logmsg) < 0 ||
2054             (strcmp(lock->ref_name, lock->orig_ref_name) &&
2055              log_ref_write(lock->orig_ref_name, lock->old_sha1, sha1, logmsg) < 0)) {
2056                 unlock_ref(lock);
2057                 return -1;
2058         }
2059         if (strcmp(lock->orig_ref_name, "HEAD") != 0) {
2060                 /*
2061                  * Special hack: If a branch is updated directly and HEAD
2062                  * points to it (may happen on the remote side of a push
2063                  * for example) then logically the HEAD reflog should be
2064                  * updated too.
2065                  * A generic solution implies reverse symref information,
2066                  * but finding all symrefs pointing to the given branch
2067                  * would be rather costly for this rare event (the direct
2068                  * update of a branch) to be worth it.  So let's cheat and
2069                  * check with HEAD only which should cover 99% of all usage
2070                  * scenarios (even 100% of the default ones).
2071                  */
2072                 unsigned char head_sha1[20];
2073                 int head_flag;
2074                 const char *head_ref;
2075                 head_ref = resolve_ref_unsafe("HEAD", head_sha1, 1, &head_flag);
2076                 if (head_ref && (head_flag & REF_ISSYMREF) &&
2077                     !strcmp(head_ref, lock->ref_name))
2078                         log_ref_write("HEAD", lock->old_sha1, sha1, logmsg);
2079         }
2080         if (commit_ref(lock)) {
2081                 error("Couldn't set %s", lock->ref_name);
2082                 unlock_ref(lock);
2083                 return -1;
2084         }
2085         unlock_ref(lock);
2086         return 0;
2087 }
2088
2089 int create_symref(const char *ref_target, const char *refs_heads_master,
2090                   const char *logmsg)
2091 {
2092         const char *lockpath;
2093         char ref[1000];
2094         int fd, len, written;
2095         char *git_HEAD = git_pathdup("%s", ref_target);
2096         unsigned char old_sha1[20], new_sha1[20];
2097
2098         if (logmsg && read_ref(ref_target, old_sha1))
2099                 hashclr(old_sha1);
2100
2101         if (safe_create_leading_directories(git_HEAD) < 0)
2102                 return error("unable to create directory for %s", git_HEAD);
2103
2104 #ifndef NO_SYMLINK_HEAD
2105         if (prefer_symlink_refs) {
2106                 unlink(git_HEAD);
2107                 if (!symlink(refs_heads_master, git_HEAD))
2108                         goto done;
2109                 fprintf(stderr, "no symlink - falling back to symbolic ref\n");
2110         }
2111 #endif
2112
2113         len = snprintf(ref, sizeof(ref), "ref: %s\n", refs_heads_master);
2114         if (sizeof(ref) <= len) {
2115                 error("refname too long: %s", refs_heads_master);
2116                 goto error_free_return;
2117         }
2118         lockpath = mkpath("%s.lock", git_HEAD);
2119         fd = open(lockpath, O_CREAT | O_EXCL | O_WRONLY, 0666);
2120         if (fd < 0) {
2121                 error("Unable to open %s for writing", lockpath);
2122                 goto error_free_return;
2123         }
2124         written = write_in_full(fd, ref, len);
2125         if (close(fd) != 0 || written != len) {
2126                 error("Unable to write to %s", lockpath);
2127                 goto error_unlink_return;
2128         }
2129         if (rename(lockpath, git_HEAD) < 0) {
2130                 error("Unable to create %s", git_HEAD);
2131                 goto error_unlink_return;
2132         }
2133         if (adjust_shared_perm(git_HEAD)) {
2134                 error("Unable to fix permissions on %s", lockpath);
2135         error_unlink_return:
2136                 unlink_or_warn(lockpath);
2137         error_free_return:
2138                 free(git_HEAD);
2139                 return -1;
2140         }
2141
2142 #ifndef NO_SYMLINK_HEAD
2143         done:
2144 #endif
2145         if (logmsg && !read_ref(refs_heads_master, new_sha1))
2146                 log_ref_write(ref_target, old_sha1, new_sha1, logmsg);
2147
2148         free(git_HEAD);
2149         return 0;
2150 }
2151
2152 static char *ref_msg(const char *line, const char *endp)
2153 {
2154         const char *ep;
2155         line += 82;
2156         ep = memchr(line, '\n', endp - line);
2157         if (!ep)
2158                 ep = endp;
2159         return xmemdupz(line, ep - line);
2160 }
2161
2162 int read_ref_at(const char *refname, unsigned long at_time, int cnt,
2163                 unsigned char *sha1, char **msg,
2164                 unsigned long *cutoff_time, int *cutoff_tz, int *cutoff_cnt)
2165 {
2166         const char *logfile, *logdata, *logend, *rec, *lastgt, *lastrec;
2167         char *tz_c;
2168         int logfd, tz, reccnt = 0;
2169         struct stat st;
2170         unsigned long date;
2171         unsigned char logged_sha1[20];
2172         void *log_mapped;
2173         size_t mapsz;
2174
2175         logfile = git_path("logs/%s", refname);
2176         logfd = open(logfile, O_RDONLY, 0);
2177         if (logfd < 0)
2178                 die_errno("Unable to read log '%s'", logfile);
2179         fstat(logfd, &st);
2180         if (!st.st_size)
2181                 die("Log %s is empty.", logfile);
2182         mapsz = xsize_t(st.st_size);
2183         log_mapped = xmmap(NULL, mapsz, PROT_READ, MAP_PRIVATE, logfd, 0);
2184         logdata = log_mapped;
2185         close(logfd);
2186
2187         lastrec = NULL;
2188         rec = logend = logdata + st.st_size;
2189         while (logdata < rec) {
2190                 reccnt++;
2191                 if (logdata < rec && *(rec-1) == '\n')
2192                         rec--;
2193                 lastgt = NULL;
2194                 while (logdata < rec && *(rec-1) != '\n') {
2195                         rec--;
2196                         if (*rec == '>')
2197                                 lastgt = rec;
2198                 }
2199                 if (!lastgt)
2200                         die("Log %s is corrupt.", logfile);
2201                 date = strtoul(lastgt + 1, &tz_c, 10);
2202                 if (date <= at_time || cnt == 0) {
2203                         tz = strtoul(tz_c, NULL, 10);
2204                         if (msg)
2205                                 *msg = ref_msg(rec, logend);
2206                         if (cutoff_time)
2207                                 *cutoff_time = date;
2208                         if (cutoff_tz)
2209                                 *cutoff_tz = tz;
2210                         if (cutoff_cnt)
2211                                 *cutoff_cnt = reccnt - 1;
2212                         if (lastrec) {
2213                                 if (get_sha1_hex(lastrec, logged_sha1))
2214                                         die("Log %s is corrupt.", logfile);
2215                                 if (get_sha1_hex(rec + 41, sha1))
2216                                         die("Log %s is corrupt.", logfile);
2217                                 if (hashcmp(logged_sha1, sha1)) {
2218                                         warning("Log %s has gap after %s.",
2219                                                 logfile, show_date(date, tz, DATE_RFC2822));
2220                                 }
2221                         }
2222                         else if (date == at_time) {
2223                                 if (get_sha1_hex(rec + 41, sha1))
2224                                         die("Log %s is corrupt.", logfile);
2225                         }
2226                         else {
2227                                 if (get_sha1_hex(rec + 41, logged_sha1))
2228                                         die("Log %s is corrupt.", logfile);
2229                                 if (hashcmp(logged_sha1, sha1)) {
2230                                         warning("Log %s unexpectedly ended on %s.",
2231                                                 logfile, show_date(date, tz, DATE_RFC2822));
2232                                 }
2233                         }
2234                         munmap(log_mapped, mapsz);
2235                         return 0;
2236                 }
2237                 lastrec = rec;
2238                 if (cnt > 0)
2239                         cnt--;
2240         }
2241
2242         rec = logdata;
2243         while (rec < logend && *rec != '>' && *rec != '\n')
2244                 rec++;
2245         if (rec == logend || *rec == '\n')
2246                 die("Log %s is corrupt.", logfile);
2247         date = strtoul(rec + 1, &tz_c, 10);
2248         tz = strtoul(tz_c, NULL, 10);
2249         if (get_sha1_hex(logdata, sha1))
2250                 die("Log %s is corrupt.", logfile);
2251         if (is_null_sha1(sha1)) {
2252                 if (get_sha1_hex(logdata + 41, sha1))
2253                         die("Log %s is corrupt.", logfile);
2254         }
2255         if (msg)
2256                 *msg = ref_msg(logdata, logend);
2257         munmap(log_mapped, mapsz);
2258
2259         if (cutoff_time)
2260                 *cutoff_time = date;
2261         if (cutoff_tz)
2262                 *cutoff_tz = tz;
2263         if (cutoff_cnt)
2264                 *cutoff_cnt = reccnt;
2265         return 1;
2266 }
2267
2268 int for_each_recent_reflog_ent(const char *refname, each_reflog_ent_fn fn, long ofs, void *cb_data)
2269 {
2270         const char *logfile;
2271         FILE *logfp;
2272         struct strbuf sb = STRBUF_INIT;
2273         int ret = 0;
2274
2275         logfile = git_path("logs/%s", refname);
2276         logfp = fopen(logfile, "r");
2277         if (!logfp)
2278                 return -1;
2279
2280         if (ofs) {
2281                 struct stat statbuf;
2282                 if (fstat(fileno(logfp), &statbuf) ||
2283                     statbuf.st_size < ofs ||
2284                     fseek(logfp, -ofs, SEEK_END) ||
2285                     strbuf_getwholeline(&sb, logfp, '\n')) {
2286                         fclose(logfp);
2287                         strbuf_release(&sb);
2288                         return -1;
2289                 }
2290         }
2291
2292         while (!strbuf_getwholeline(&sb, logfp, '\n')) {
2293                 unsigned char osha1[20], nsha1[20];
2294                 char *email_end, *message;
2295                 unsigned long timestamp;
2296                 int tz;
2297
2298                 /* old SP new SP name <email> SP time TAB msg LF */
2299                 if (sb.len < 83 || sb.buf[sb.len - 1] != '\n' ||
2300                     get_sha1_hex(sb.buf, osha1) || sb.buf[40] != ' ' ||
2301                     get_sha1_hex(sb.buf + 41, nsha1) || sb.buf[81] != ' ' ||
2302                     !(email_end = strchr(sb.buf + 82, '>')) ||
2303                     email_end[1] != ' ' ||
2304                     !(timestamp = strtoul(email_end + 2, &message, 10)) ||
2305                     !message || message[0] != ' ' ||
2306                     (message[1] != '+' && message[1] != '-') ||
2307                     !isdigit(message[2]) || !isdigit(message[3]) ||
2308                     !isdigit(message[4]) || !isdigit(message[5]))
2309                         continue; /* corrupt? */
2310                 email_end[1] = '\0';
2311                 tz = strtol(message + 1, NULL, 10);
2312                 if (message[6] != '\t')
2313                         message += 6;
2314                 else
2315                         message += 7;
2316                 ret = fn(osha1, nsha1, sb.buf + 82, timestamp, tz, message,
2317                          cb_data);
2318                 if (ret)
2319                         break;
2320         }
2321         fclose(logfp);
2322         strbuf_release(&sb);
2323         return ret;
2324 }
2325
2326 int for_each_reflog_ent(const char *refname, each_reflog_ent_fn fn, void *cb_data)
2327 {
2328         return for_each_recent_reflog_ent(refname, fn, 0, cb_data);
2329 }
2330
2331 /*
2332  * Call fn for each reflog in the namespace indicated by name.  name
2333  * must be empty or end with '/'.  Name will be used as a scratch
2334  * space, but its contents will be restored before return.
2335  */
2336 static int do_for_each_reflog(struct strbuf *name, each_ref_fn fn, void *cb_data)
2337 {
2338         DIR *d = opendir(git_path("logs/%s", name->buf));
2339         int retval = 0;
2340         struct dirent *de;
2341         int oldlen = name->len;
2342
2343         if (!d)
2344                 return name->len ? errno : 0;
2345
2346         while ((de = readdir(d)) != NULL) {
2347                 struct stat st;
2348
2349                 if (de->d_name[0] == '.')
2350                         continue;
2351                 if (has_extension(de->d_name, ".lock"))
2352                         continue;
2353                 strbuf_addstr(name, de->d_name);
2354                 if (stat(git_path("logs/%s", name->buf), &st) < 0) {
2355                         ; /* silently ignore */
2356                 } else {
2357                         if (S_ISDIR(st.st_mode)) {
2358                                 strbuf_addch(name, '/');
2359                                 retval = do_for_each_reflog(name, fn, cb_data);
2360                         } else {
2361                                 unsigned char sha1[20];
2362                                 if (read_ref_full(name->buf, sha1, 0, NULL))
2363                                         retval = error("bad ref for %s", name->buf);
2364                                 else
2365                                         retval = fn(name->buf, sha1, 0, cb_data);
2366                         }
2367                         if (retval)
2368                                 break;
2369                 }
2370                 strbuf_setlen(name, oldlen);
2371         }
2372         closedir(d);
2373         return retval;
2374 }
2375
2376 int for_each_reflog(each_ref_fn fn, void *cb_data)
2377 {
2378         int retval;
2379         struct strbuf name;
2380         strbuf_init(&name, PATH_MAX);
2381         retval = do_for_each_reflog(&name, fn, cb_data);
2382         strbuf_release(&name);
2383         return retval;
2384 }
2385
2386 int update_ref(const char *action, const char *refname,
2387                 const unsigned char *sha1, const unsigned char *oldval,
2388                 int flags, enum action_on_err onerr)
2389 {
2390         static struct ref_lock *lock;
2391         lock = lock_any_ref_for_update(refname, oldval, flags);
2392         if (!lock) {
2393                 const char *str = "Cannot lock the ref '%s'.";
2394                 switch (onerr) {
2395                 case MSG_ON_ERR: error(str, refname); break;
2396                 case DIE_ON_ERR: die(str, refname); break;
2397                 case QUIET_ON_ERR: break;
2398                 }
2399                 return 1;
2400         }
2401         if (write_ref_sha1(lock, sha1, action) < 0) {
2402                 const char *str = "Cannot update the ref '%s'.";
2403                 switch (onerr) {
2404                 case MSG_ON_ERR: error(str, refname); break;
2405                 case DIE_ON_ERR: die(str, refname); break;
2406                 case QUIET_ON_ERR: break;
2407                 }
2408                 return 1;
2409         }
2410         return 0;
2411 }
2412
2413 struct ref *find_ref_by_name(const struct ref *list, const char *name)
2414 {
2415         for ( ; list; list = list->next)
2416                 if (!strcmp(list->name, name))
2417                         return (struct ref *)list;
2418         return NULL;
2419 }
2420
2421 /*
2422  * generate a format suitable for scanf from a ref_rev_parse_rules
2423  * rule, that is replace the "%.*s" spec with a "%s" spec
2424  */
2425 static void gen_scanf_fmt(char *scanf_fmt, const char *rule)
2426 {
2427         char *spec;
2428
2429         spec = strstr(rule, "%.*s");
2430         if (!spec || strstr(spec + 4, "%.*s"))
2431                 die("invalid rule in ref_rev_parse_rules: %s", rule);
2432
2433         /* copy all until spec */
2434         strncpy(scanf_fmt, rule, spec - rule);
2435         scanf_fmt[spec - rule] = '\0';
2436         /* copy new spec */
2437         strcat(scanf_fmt, "%s");
2438         /* copy remaining rule */
2439         strcat(scanf_fmt, spec + 4);
2440
2441         return;
2442 }
2443
2444 char *shorten_unambiguous_ref(const char *refname, int strict)
2445 {
2446         int i;
2447         static char **scanf_fmts;
2448         static int nr_rules;
2449         char *short_name;
2450
2451         /* pre generate scanf formats from ref_rev_parse_rules[] */
2452         if (!nr_rules) {
2453                 size_t total_len = 0;
2454
2455                 /* the rule list is NULL terminated, count them first */
2456                 for (; ref_rev_parse_rules[nr_rules]; nr_rules++)
2457                         /* no +1 because strlen("%s") < strlen("%.*s") */
2458                         total_len += strlen(ref_rev_parse_rules[nr_rules]);
2459
2460                 scanf_fmts = xmalloc(nr_rules * sizeof(char *) + total_len);
2461
2462                 total_len = 0;
2463                 for (i = 0; i < nr_rules; i++) {
2464                         scanf_fmts[i] = (char *)&scanf_fmts[nr_rules]
2465                                         + total_len;
2466                         gen_scanf_fmt(scanf_fmts[i], ref_rev_parse_rules[i]);
2467                         total_len += strlen(ref_rev_parse_rules[i]);
2468                 }
2469         }
2470
2471         /* bail out if there are no rules */
2472         if (!nr_rules)
2473                 return xstrdup(refname);
2474
2475         /* buffer for scanf result, at most refname must fit */
2476         short_name = xstrdup(refname);
2477
2478         /* skip first rule, it will always match */
2479         for (i = nr_rules - 1; i > 0 ; --i) {
2480                 int j;
2481                 int rules_to_fail = i;
2482                 int short_name_len;
2483
2484                 if (1 != sscanf(refname, scanf_fmts[i], short_name))
2485                         continue;
2486
2487                 short_name_len = strlen(short_name);
2488
2489                 /*
2490                  * in strict mode, all (except the matched one) rules
2491                  * must fail to resolve to a valid non-ambiguous ref
2492                  */
2493                 if (strict)
2494                         rules_to_fail = nr_rules;
2495
2496                 /*
2497                  * check if the short name resolves to a valid ref,
2498                  * but use only rules prior to the matched one
2499                  */
2500                 for (j = 0; j < rules_to_fail; j++) {
2501                         const char *rule = ref_rev_parse_rules[j];
2502                         char refname[PATH_MAX];
2503
2504                         /* skip matched rule */
2505                         if (i == j)
2506                                 continue;
2507
2508                         /*
2509                          * the short name is ambiguous, if it resolves
2510                          * (with this previous rule) to a valid ref
2511                          * read_ref() returns 0 on success
2512                          */
2513                         mksnpath(refname, sizeof(refname),
2514                                  rule, short_name_len, short_name);
2515                         if (ref_exists(refname))
2516                                 break;
2517                 }
2518
2519                 /*
2520                  * short name is non-ambiguous if all previous rules
2521                  * haven't resolved to a valid ref
2522                  */
2523                 if (j == rules_to_fail)
2524                         return short_name;
2525         }
2526
2527         free(short_name);
2528         return xstrdup(refname);
2529 }