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