6 #include "string-list.h"
9 * Make sure "ref" is something reasonable to have under ".git/refs/";
10 * We do not like it if:
12 * - any path component of it begins with ".", or
13 * - it has double dots "..", or
14 * - it has ASCII control character, "~", "^", ":" or SP, anywhere, or
15 * - it ends with a "/".
16 * - it ends with ".lock"
17 * - it contains a "\" (backslash)
20 /* Return true iff ch is not allowed in reference names. */
21 static inline int bad_ref_char(int ch)
23 if (((unsigned) ch) <= ' ' || ch == 0x7f ||
24 ch == '~' || ch == '^' || ch == ':' || ch == '\\')
26 /* 2.13 Pattern Matching Notation */
27 if (ch == '*' || ch == '?' || ch == '[') /* Unsupported */
33 * Try to read one refname component from the front of refname. Return
34 * the length of the component found, or -1 if the component is not
37 static int check_refname_component(const char *refname, int flags)
42 for (cp = refname; ; cp++) {
44 if (ch == '\0' || ch == '/')
47 return -1; /* Illegal character in refname. */
48 if (last == '.' && ch == '.')
49 return -1; /* Refname contains "..". */
50 if (last == '@' && ch == '{')
51 return -1; /* Refname contains "@{". */
55 return 0; /* Component has zero length. */
56 if (refname[0] == '.') {
57 if (!(flags & REFNAME_DOT_COMPONENT))
58 return -1; /* Component starts with '.'. */
60 * Even if leading dots are allowed, don't allow "."
61 * as a component (".." is prevented by a rule above).
63 if (refname[1] == '\0')
64 return -1; /* Component equals ".". */
66 if (cp - refname >= 5 && !memcmp(cp - 5, ".lock", 5))
67 return -1; /* Refname ends with ".lock". */
71 int check_refname_format(const char *refname, int flags)
73 int component_len, component_count = 0;
75 if (!strcmp(refname, "@"))
76 /* Refname is a single character '@'. */
80 /* We are at the start of a path component. */
81 component_len = check_refname_component(refname, flags);
82 if (component_len <= 0) {
83 if ((flags & REFNAME_REFSPEC_PATTERN) &&
85 (refname[1] == '\0' || refname[1] == '/')) {
86 /* Accept one wildcard as a full refname component. */
87 flags &= ~REFNAME_REFSPEC_PATTERN;
94 if (refname[component_len] == '\0')
96 /* Skip to next component. */
97 refname += component_len + 1;
100 if (refname[component_len - 1] == '.')
101 return -1; /* Refname ends with '.'. */
102 if (!(flags & REFNAME_ALLOW_ONELEVEL) && component_count < 2)
103 return -1; /* Refname has only one component. */
110 * Information used (along with the information in ref_entry) to
111 * describe a single cached reference. This data structure only
112 * occurs embedded in a union in struct ref_entry, and only when
113 * (ref_entry->flag & REF_DIR) is zero.
116 unsigned char sha1[20];
117 unsigned char peeled[20];
123 * Information used (along with the information in ref_entry) to
124 * describe a level in the hierarchy of references. This data
125 * structure only occurs embedded in a union in struct ref_entry, and
126 * only when (ref_entry.flag & REF_DIR) is set. In that case,
127 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references
128 * in the directory have already been read:
130 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose
131 * or packed references, already read.
133 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose
134 * references that hasn't been read yet (nor has any of its
137 * Entries within a directory are stored within a growable array of
138 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i <
139 * sorted are sorted by their component name in strcmp() order and the
140 * remaining entries are unsorted.
142 * Loose references are read lazily, one directory at a time. When a
143 * directory of loose references is read, then all of the references
144 * in that directory are stored, and REF_INCOMPLETE stubs are created
145 * for any subdirectories, but the subdirectories themselves are not
146 * read. The reading is triggered by get_ref_dir().
152 * Entries with index 0 <= i < sorted are sorted by name. New
153 * entries are appended to the list unsorted, and are sorted
154 * only when required; thus we avoid the need to sort the list
155 * after the addition of every reference.
159 /* A pointer to the ref_cache that contains this ref_dir. */
160 struct ref_cache *ref_cache;
162 struct ref_entry **entries;
165 /* ISSYMREF=0x01, ISPACKED=0x02, and ISBROKEN=0x04 are public interfaces */
166 #define REF_KNOWS_PEELED 0x08
168 /* ref_entry represents a directory of references */
172 * Entry has not yet been read from disk (used only for REF_DIR
173 * entries representing loose references)
175 #define REF_INCOMPLETE 0x20
178 * A ref_entry represents either a reference or a "subdirectory" of
181 * Each directory in the reference namespace is represented by a
182 * ref_entry with (flags & REF_DIR) set and containing a subdir member
183 * that holds the entries in that directory that have been read so
184 * far. If (flags & REF_INCOMPLETE) is set, then the directory and
185 * its subdirectories haven't been read yet. REF_INCOMPLETE is only
186 * used for loose reference directories.
188 * References are represented by a ref_entry with (flags & REF_DIR)
189 * unset and a value member that describes the reference's value. The
190 * flag member is at the ref_entry level, but it is also needed to
191 * interpret the contents of the value field (in other words, a
192 * ref_value object is not very much use without the enclosing
195 * Reference names cannot end with slash and directories' names are
196 * always stored with a trailing slash (except for the top-level
197 * directory, which is always denoted by ""). This has two nice
198 * consequences: (1) when the entries in each subdir are sorted
199 * lexicographically by name (as they usually are), the references in
200 * a whole tree can be generated in lexicographic order by traversing
201 * the tree in left-to-right, depth-first order; (2) the names of
202 * references and subdirectories cannot conflict, and therefore the
203 * presence of an empty subdirectory does not block the creation of a
204 * similarly-named reference. (The fact that reference names with the
205 * same leading components can conflict *with each other* is a
206 * separate issue that is regulated by is_refname_available().)
208 * Please note that the name field contains the fully-qualified
209 * reference (or subdirectory) name. Space could be saved by only
210 * storing the relative names. But that would require the full names
211 * to be generated on the fly when iterating in do_for_each_ref(), and
212 * would break callback functions, who have always been able to assume
213 * that the name strings that they are passed will not be freed during
217 unsigned char flag; /* ISSYMREF? ISPACKED? */
219 struct ref_value value; /* if not (flags&REF_DIR) */
220 struct ref_dir subdir; /* if (flags&REF_DIR) */
223 * The full name of the reference (e.g., "refs/heads/master")
224 * or the full name of the directory with a trailing slash
225 * (e.g., "refs/heads/"):
227 char name[FLEX_ARRAY];
230 static void read_loose_refs(const char *dirname, struct ref_dir *dir);
232 static struct ref_dir *get_ref_dir(struct ref_entry *entry)
235 assert(entry->flag & REF_DIR);
236 dir = &entry->u.subdir;
237 if (entry->flag & REF_INCOMPLETE) {
238 read_loose_refs(entry->name, dir);
239 entry->flag &= ~REF_INCOMPLETE;
244 static struct ref_entry *create_ref_entry(const char *refname,
245 const unsigned char *sha1, int flag,
249 struct ref_entry *ref;
252 check_refname_format(refname, REFNAME_ALLOW_ONELEVEL|REFNAME_DOT_COMPONENT))
253 die("Reference has invalid format: '%s'", refname);
254 len = strlen(refname) + 1;
255 ref = xmalloc(sizeof(struct ref_entry) + len);
256 hashcpy(ref->u.value.sha1, sha1);
257 hashclr(ref->u.value.peeled);
258 memcpy(ref->name, refname, len);
263 static void clear_ref_dir(struct ref_dir *dir);
265 static void free_ref_entry(struct ref_entry *entry)
267 if (entry->flag & REF_DIR) {
269 * Do not use get_ref_dir() here, as that might
270 * trigger the reading of loose refs.
272 clear_ref_dir(&entry->u.subdir);
278 * Add a ref_entry to the end of dir (unsorted). Entry is always
279 * stored directly in dir; no recursion into subdirectories is
282 static void add_entry_to_dir(struct ref_dir *dir, struct ref_entry *entry)
284 ALLOC_GROW(dir->entries, dir->nr + 1, dir->alloc);
285 dir->entries[dir->nr++] = entry;
286 /* optimize for the case that entries are added in order */
288 (dir->nr == dir->sorted + 1 &&
289 strcmp(dir->entries[dir->nr - 2]->name,
290 dir->entries[dir->nr - 1]->name) < 0))
291 dir->sorted = dir->nr;
295 * Clear and free all entries in dir, recursively.
297 static void clear_ref_dir(struct ref_dir *dir)
300 for (i = 0; i < dir->nr; i++)
301 free_ref_entry(dir->entries[i]);
303 dir->sorted = dir->nr = dir->alloc = 0;
308 * Create a struct ref_entry object for the specified dirname.
309 * dirname is the name of the directory with a trailing slash (e.g.,
310 * "refs/heads/") or "" for the top-level directory.
312 static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache,
313 const char *dirname, size_t len,
316 struct ref_entry *direntry;
317 direntry = xcalloc(1, sizeof(struct ref_entry) + len + 1);
318 memcpy(direntry->name, dirname, len);
319 direntry->name[len] = '\0';
320 direntry->u.subdir.ref_cache = ref_cache;
321 direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE : 0);
325 static int ref_entry_cmp(const void *a, const void *b)
327 struct ref_entry *one = *(struct ref_entry **)a;
328 struct ref_entry *two = *(struct ref_entry **)b;
329 return strcmp(one->name, two->name);
332 static void sort_ref_dir(struct ref_dir *dir);
334 struct string_slice {
339 static int ref_entry_cmp_sslice(const void *key_, const void *ent_)
341 const struct string_slice *key = key_;
342 const struct ref_entry *ent = *(const struct ref_entry * const *)ent_;
343 int cmp = strncmp(key->str, ent->name, key->len);
346 return '\0' - (unsigned char)ent->name[key->len];
350 * Return the entry with the given refname from the ref_dir
351 * (non-recursively), sorting dir if necessary. Return NULL if no
352 * such entry is found. dir must already be complete.
354 static struct ref_entry *search_ref_dir(struct ref_dir *dir,
355 const char *refname, size_t len)
357 struct ref_entry **r;
358 struct string_slice key;
360 if (refname == NULL || !dir->nr)
366 r = bsearch(&key, dir->entries, dir->nr, sizeof(*dir->entries),
367 ref_entry_cmp_sslice);
376 * Search for a directory entry directly within dir (without
377 * recursing). Sort dir if necessary. subdirname must be a directory
378 * name (i.e., end in '/'). If mkdir is set, then create the
379 * directory if it is missing; otherwise, return NULL if the desired
380 * directory cannot be found. dir must already be complete.
382 static struct ref_dir *search_for_subdir(struct ref_dir *dir,
383 const char *subdirname, size_t len,
386 struct ref_entry *entry = search_ref_dir(dir, subdirname, len);
391 * Since dir is complete, the absence of a subdir
392 * means that the subdir really doesn't exist;
393 * therefore, create an empty record for it but mark
394 * the record complete.
396 entry = create_dir_entry(dir->ref_cache, subdirname, len, 0);
397 add_entry_to_dir(dir, entry);
399 return get_ref_dir(entry);
403 * If refname is a reference name, find the ref_dir within the dir
404 * tree that should hold refname. If refname is a directory name
405 * (i.e., ends in '/'), then return that ref_dir itself. dir must
406 * represent the top-level directory and must already be complete.
407 * Sort ref_dirs and recurse into subdirectories as necessary. If
408 * mkdir is set, then create any missing directories; otherwise,
409 * return NULL if the desired directory cannot be found.
411 static struct ref_dir *find_containing_dir(struct ref_dir *dir,
412 const char *refname, int mkdir)
415 for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) {
416 size_t dirnamelen = slash - refname + 1;
417 struct ref_dir *subdir;
418 subdir = search_for_subdir(dir, refname, dirnamelen, mkdir);
430 * Find the value entry with the given name in dir, sorting ref_dirs
431 * and recursing into subdirectories as necessary. If the name is not
432 * found or it corresponds to a directory entry, return NULL.
434 static struct ref_entry *find_ref(struct ref_dir *dir, const char *refname)
436 struct ref_entry *entry;
437 dir = find_containing_dir(dir, refname, 0);
440 entry = search_ref_dir(dir, refname, strlen(refname));
441 return (entry && !(entry->flag & REF_DIR)) ? entry : NULL;
445 * Add a ref_entry to the ref_dir (unsorted), recursing into
446 * subdirectories as necessary. dir must represent the top-level
447 * directory. Return 0 on success.
449 static int add_ref(struct ref_dir *dir, struct ref_entry *ref)
451 dir = find_containing_dir(dir, ref->name, 1);
454 add_entry_to_dir(dir, ref);
459 * Emit a warning and return true iff ref1 and ref2 have the same name
460 * and the same sha1. Die if they have the same name but different
463 static int is_dup_ref(const struct ref_entry *ref1, const struct ref_entry *ref2)
465 if (strcmp(ref1->name, ref2->name))
468 /* Duplicate name; make sure that they don't conflict: */
470 if ((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR))
471 /* This is impossible by construction */
472 die("Reference directory conflict: %s", ref1->name);
474 if (hashcmp(ref1->u.value.sha1, ref2->u.value.sha1))
475 die("Duplicated ref, and SHA1s don't match: %s", ref1->name);
477 warning("Duplicated ref: %s", ref1->name);
482 * Sort the entries in dir non-recursively (if they are not already
483 * sorted) and remove any duplicate entries.
485 static void sort_ref_dir(struct ref_dir *dir)
488 struct ref_entry *last = NULL;
491 * This check also prevents passing a zero-length array to qsort(),
492 * which is a problem on some platforms.
494 if (dir->sorted == dir->nr)
497 qsort(dir->entries, dir->nr, sizeof(*dir->entries), ref_entry_cmp);
499 /* Remove any duplicates: */
500 for (i = 0, j = 0; j < dir->nr; j++) {
501 struct ref_entry *entry = dir->entries[j];
502 if (last && is_dup_ref(last, entry))
503 free_ref_entry(entry);
505 last = dir->entries[i++] = entry;
507 dir->sorted = dir->nr = i;
510 #define DO_FOR_EACH_INCLUDE_BROKEN 01
512 static struct ref_entry *current_ref;
514 static int do_one_ref(const char *base, each_ref_fn fn, int trim,
515 int flags, void *cb_data, struct ref_entry *entry)
518 if (prefixcmp(entry->name, base))
521 if (!(flags & DO_FOR_EACH_INCLUDE_BROKEN)) {
522 if (entry->flag & REF_ISBROKEN)
523 return 0; /* ignore broken refs e.g. dangling symref */
524 if (!has_sha1_file(entry->u.value.sha1)) {
525 error("%s does not point to a valid object!", entry->name);
530 retval = fn(entry->name + trim, entry->u.value.sha1, entry->flag, cb_data);
536 * Call fn for each reference in dir that has index in the range
537 * offset <= index < dir->nr. Recurse into subdirectories that are in
538 * that index range, sorting them before iterating. This function
539 * does not sort dir itself; it should be sorted beforehand.
541 static int do_for_each_ref_in_dir(struct ref_dir *dir, int offset,
543 each_ref_fn fn, int trim, int flags, void *cb_data)
546 assert(dir->sorted == dir->nr);
547 for (i = offset; i < dir->nr; i++) {
548 struct ref_entry *entry = dir->entries[i];
550 if (entry->flag & REF_DIR) {
551 struct ref_dir *subdir = get_ref_dir(entry);
552 sort_ref_dir(subdir);
553 retval = do_for_each_ref_in_dir(subdir, 0,
554 base, fn, trim, flags, cb_data);
556 retval = do_one_ref(base, fn, trim, flags, cb_data, entry);
565 * Call fn for each reference in the union of dir1 and dir2, in order
566 * by refname. Recurse into subdirectories. If a value entry appears
567 * in both dir1 and dir2, then only process the version that is in
568 * dir2. The input dirs must already be sorted, but subdirs will be
571 static int do_for_each_ref_in_dirs(struct ref_dir *dir1,
572 struct ref_dir *dir2,
573 const char *base, each_ref_fn fn, int trim,
574 int flags, void *cb_data)
579 assert(dir1->sorted == dir1->nr);
580 assert(dir2->sorted == dir2->nr);
582 struct ref_entry *e1, *e2;
584 if (i1 == dir1->nr) {
585 return do_for_each_ref_in_dir(dir2, i2,
586 base, fn, trim, flags, cb_data);
588 if (i2 == dir2->nr) {
589 return do_for_each_ref_in_dir(dir1, i1,
590 base, fn, trim, flags, cb_data);
592 e1 = dir1->entries[i1];
593 e2 = dir2->entries[i2];
594 cmp = strcmp(e1->name, e2->name);
596 if ((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) {
597 /* Both are directories; descend them in parallel. */
598 struct ref_dir *subdir1 = get_ref_dir(e1);
599 struct ref_dir *subdir2 = get_ref_dir(e2);
600 sort_ref_dir(subdir1);
601 sort_ref_dir(subdir2);
602 retval = do_for_each_ref_in_dirs(
604 base, fn, trim, flags, cb_data);
607 } else if (!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) {
608 /* Both are references; ignore the one from dir1. */
609 retval = do_one_ref(base, fn, trim, flags, cb_data, e2);
613 die("conflict between reference and directory: %s",
625 if (e->flag & REF_DIR) {
626 struct ref_dir *subdir = get_ref_dir(e);
627 sort_ref_dir(subdir);
628 retval = do_for_each_ref_in_dir(
630 base, fn, trim, flags, cb_data);
632 retval = do_one_ref(base, fn, trim, flags, cb_data, e);
639 return do_for_each_ref_in_dir(dir1, i1,
640 base, fn, trim, flags, cb_data);
642 return do_for_each_ref_in_dir(dir2, i2,
643 base, fn, trim, flags, cb_data);
648 * Return true iff refname1 and refname2 conflict with each other.
649 * Two reference names conflict if one of them exactly matches the
650 * leading components of the other; e.g., "foo/bar" conflicts with
651 * both "foo" and with "foo/bar/baz" but not with "foo/bar" or
654 static int names_conflict(const char *refname1, const char *refname2)
656 for (; *refname1 && *refname1 == *refname2; refname1++, refname2++)
658 return (*refname1 == '\0' && *refname2 == '/')
659 || (*refname1 == '/' && *refname2 == '\0');
662 struct name_conflict_cb {
664 const char *oldrefname;
665 const char *conflicting_refname;
668 static int name_conflict_fn(const char *existingrefname, const unsigned char *sha1,
669 int flags, void *cb_data)
671 struct name_conflict_cb *data = (struct name_conflict_cb *)cb_data;
672 if (data->oldrefname && !strcmp(data->oldrefname, existingrefname))
674 if (names_conflict(data->refname, existingrefname)) {
675 data->conflicting_refname = existingrefname;
682 * Return true iff a reference named refname could be created without
683 * conflicting with the name of an existing reference in array. If
684 * oldrefname is non-NULL, ignore potential conflicts with oldrefname
685 * (e.g., because oldrefname is scheduled for deletion in the same
688 static int is_refname_available(const char *refname, const char *oldrefname,
691 struct name_conflict_cb data;
692 data.refname = refname;
693 data.oldrefname = oldrefname;
694 data.conflicting_refname = NULL;
697 if (do_for_each_ref_in_dir(dir, 0, "", name_conflict_fn,
698 0, DO_FOR_EACH_INCLUDE_BROKEN,
700 error("'%s' exists; cannot create '%s'",
701 data.conflicting_refname, refname);
708 * Future: need to be in "struct repository"
709 * when doing a full libification.
711 static struct ref_cache {
712 struct ref_cache *next;
713 struct ref_entry *loose;
714 struct ref_entry *packed;
715 /* The submodule name, or "" for the main repo. */
716 char name[FLEX_ARRAY];
719 static void clear_packed_ref_cache(struct ref_cache *refs)
722 free_ref_entry(refs->packed);
727 static void clear_loose_ref_cache(struct ref_cache *refs)
730 free_ref_entry(refs->loose);
735 static struct ref_cache *create_ref_cache(const char *submodule)
738 struct ref_cache *refs;
741 len = strlen(submodule) + 1;
742 refs = xcalloc(1, sizeof(struct ref_cache) + len);
743 memcpy(refs->name, submodule, len);
748 * Return a pointer to a ref_cache for the specified submodule. For
749 * the main repository, use submodule==NULL. The returned structure
750 * will be allocated and initialized but not necessarily populated; it
751 * should not be freed.
753 static struct ref_cache *get_ref_cache(const char *submodule)
755 struct ref_cache *refs = ref_cache;
759 if (!strcmp(submodule, refs->name))
764 refs = create_ref_cache(submodule);
765 refs->next = ref_cache;
770 void invalidate_ref_cache(const char *submodule)
772 struct ref_cache *refs = get_ref_cache(submodule);
773 clear_packed_ref_cache(refs);
774 clear_loose_ref_cache(refs);
778 * Parse one line from a packed-refs file. Write the SHA1 to sha1.
779 * Return a pointer to the refname within the line (null-terminated),
780 * or NULL if there was a problem.
782 static const char *parse_ref_line(char *line, unsigned char *sha1)
785 * 42: the answer to everything.
787 * In this case, it happens to be the answer to
788 * 40 (length of sha1 hex representation)
789 * +1 (space in between hex and name)
790 * +1 (newline at the end of the line)
792 int len = strlen(line) - 42;
796 if (get_sha1_hex(line, sha1) < 0)
798 if (!isspace(line[40]))
803 if (line[len] != '\n')
811 * Read f, which is a packed-refs file, into dir.
813 * A comment line of the form "# pack-refs with: " may contain zero or
814 * more traits. We interpret the traits as follows:
818 * Probably no references are peeled. But if the file contains a
819 * peeled value for a reference, we will use it.
823 * References under "refs/tags/", if they *can* be peeled, *are*
824 * peeled in this file. References outside of "refs/tags/" are
825 * probably not peeled even if they could have been, but if we find
826 * a peeled value for such a reference we will use it.
830 * All references in the file that can be peeled are peeled.
831 * Inversely (and this is more important), any references in the
832 * file for which no peeled value is recorded is not peelable. This
833 * trait should typically be written alongside "peeled" for
834 * compatibility with older clients, but we do not require it
835 * (i.e., "peeled" is a no-op if "fully-peeled" is set).
837 static void read_packed_refs(FILE *f, struct ref_dir *dir)
839 struct ref_entry *last = NULL;
840 char refline[PATH_MAX];
841 enum { PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;
843 while (fgets(refline, sizeof(refline), f)) {
844 unsigned char sha1[20];
846 static const char header[] = "# pack-refs with:";
848 if (!strncmp(refline, header, sizeof(header)-1)) {
849 const char *traits = refline + sizeof(header) - 1;
850 if (strstr(traits, " fully-peeled "))
851 peeled = PEELED_FULLY;
852 else if (strstr(traits, " peeled "))
853 peeled = PEELED_TAGS;
854 /* perhaps other traits later as well */
858 refname = parse_ref_line(refline, sha1);
860 last = create_ref_entry(refname, sha1, REF_ISPACKED, 1);
861 if (peeled == PEELED_FULLY ||
862 (peeled == PEELED_TAGS && !prefixcmp(refname, "refs/tags/")))
863 last->flag |= REF_KNOWS_PEELED;
869 strlen(refline) == 42 &&
870 refline[41] == '\n' &&
871 !get_sha1_hex(refline + 1, sha1)) {
872 hashcpy(last->u.value.peeled, sha1);
874 * Regardless of what the file header said,
875 * we definitely know the value of *this*
878 last->flag |= REF_KNOWS_PEELED;
883 static struct ref_dir *get_packed_refs(struct ref_cache *refs)
886 const char *packed_refs_file;
889 refs->packed = create_dir_entry(refs, "", 0, 0);
891 packed_refs_file = git_path_submodule(refs->name, "packed-refs");
893 packed_refs_file = git_path("packed-refs");
894 f = fopen(packed_refs_file, "r");
896 read_packed_refs(f, get_ref_dir(refs->packed));
900 return get_ref_dir(refs->packed);
903 void add_packed_ref(const char *refname, const unsigned char *sha1)
905 add_ref(get_packed_refs(get_ref_cache(NULL)),
906 create_ref_entry(refname, sha1, REF_ISPACKED, 1));
910 * Read the loose references from the namespace dirname into dir
911 * (without recursing). dirname must end with '/'. dir must be the
912 * directory entry corresponding to dirname.
914 static void read_loose_refs(const char *dirname, struct ref_dir *dir)
916 struct ref_cache *refs = dir->ref_cache;
920 int dirnamelen = strlen(dirname);
921 struct strbuf refname;
924 path = git_path_submodule(refs->name, "%s", dirname);
926 path = git_path("%s", dirname);
932 strbuf_init(&refname, dirnamelen + 257);
933 strbuf_add(&refname, dirname, dirnamelen);
935 while ((de = readdir(d)) != NULL) {
936 unsigned char sha1[20];
941 if (de->d_name[0] == '.')
943 if (has_extension(de->d_name, ".lock"))
945 strbuf_addstr(&refname, de->d_name);
947 ? git_path_submodule(refs->name, "%s", refname.buf)
948 : git_path("%s", refname.buf);
949 if (stat(refdir, &st) < 0) {
950 ; /* silently ignore */
951 } else if (S_ISDIR(st.st_mode)) {
952 strbuf_addch(&refname, '/');
953 add_entry_to_dir(dir,
954 create_dir_entry(refs, refname.buf,
960 if (resolve_gitlink_ref(refs->name, refname.buf, sha1) < 0) {
962 flag |= REF_ISBROKEN;
964 } else if (read_ref_full(refname.buf, sha1, 1, &flag)) {
966 flag |= REF_ISBROKEN;
968 add_entry_to_dir(dir,
969 create_ref_entry(refname.buf, sha1, flag, 1));
971 strbuf_setlen(&refname, dirnamelen);
973 strbuf_release(&refname);
977 static struct ref_dir *get_loose_refs(struct ref_cache *refs)
981 * Mark the top-level directory complete because we
982 * are about to read the only subdirectory that can
985 refs->loose = create_dir_entry(refs, "", 0, 0);
987 * Create an incomplete entry for "refs/":
989 add_entry_to_dir(get_ref_dir(refs->loose),
990 create_dir_entry(refs, "refs/", 5, 1));
992 return get_ref_dir(refs->loose);
995 /* We allow "recursive" symbolic refs. Only within reason, though */
997 #define MAXREFLEN (1024)
1000 * Called by resolve_gitlink_ref_recursive() after it failed to read
1001 * from the loose refs in ref_cache refs. Find <refname> in the
1002 * packed-refs file for the submodule.
1004 static int resolve_gitlink_packed_ref(struct ref_cache *refs,
1005 const char *refname, unsigned char *sha1)
1007 struct ref_entry *ref;
1008 struct ref_dir *dir = get_packed_refs(refs);
1010 ref = find_ref(dir, refname);
1014 memcpy(sha1, ref->u.value.sha1, 20);
1018 static int resolve_gitlink_ref_recursive(struct ref_cache *refs,
1019 const char *refname, unsigned char *sha1,
1023 char buffer[128], *p;
1026 if (recursion > MAXDEPTH || strlen(refname) > MAXREFLEN)
1029 ? git_path_submodule(refs->name, "%s", refname)
1030 : git_path("%s", refname);
1031 fd = open(path, O_RDONLY);
1033 return resolve_gitlink_packed_ref(refs, refname, sha1);
1035 len = read(fd, buffer, sizeof(buffer)-1);
1039 while (len && isspace(buffer[len-1]))
1043 /* Was it a detached head or an old-fashioned symlink? */
1044 if (!get_sha1_hex(buffer, sha1))
1048 if (strncmp(buffer, "ref:", 4))
1054 return resolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);
1057 int resolve_gitlink_ref(const char *path, const char *refname, unsigned char *sha1)
1059 int len = strlen(path), retval;
1061 struct ref_cache *refs;
1063 while (len && path[len-1] == '/')
1067 submodule = xstrndup(path, len);
1068 refs = get_ref_cache(submodule);
1071 retval = resolve_gitlink_ref_recursive(refs, refname, sha1, 0);
1076 * Try to read ref from the packed references. On success, set sha1
1077 * and return 0; otherwise, return -1.
1079 static int get_packed_ref(const char *refname, unsigned char *sha1)
1081 struct ref_dir *packed = get_packed_refs(get_ref_cache(NULL));
1082 struct ref_entry *entry = find_ref(packed, refname);
1084 hashcpy(sha1, entry->u.value.sha1);
1090 const char *resolve_ref_unsafe(const char *refname, unsigned char *sha1, int reading, int *flag)
1092 int depth = MAXDEPTH;
1095 static char refname_buffer[256];
1100 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL))
1104 char path[PATH_MAX];
1112 git_snpath(path, sizeof(path), "%s", refname);
1114 if (lstat(path, &st) < 0) {
1115 if (errno != ENOENT)
1118 * The loose reference file does not exist;
1119 * check for a packed reference.
1121 if (!get_packed_ref(refname, sha1)) {
1123 *flag |= REF_ISPACKED;
1126 /* The reference is not a packed reference, either. */
1135 /* Follow "normalized" - ie "refs/.." symlinks by hand */
1136 if (S_ISLNK(st.st_mode)) {
1137 len = readlink(path, buffer, sizeof(buffer)-1);
1141 if (!prefixcmp(buffer, "refs/") &&
1142 !check_refname_format(buffer, 0)) {
1143 strcpy(refname_buffer, buffer);
1144 refname = refname_buffer;
1146 *flag |= REF_ISSYMREF;
1151 /* Is it a directory? */
1152 if (S_ISDIR(st.st_mode)) {
1158 * Anything else, just open it and try to use it as
1161 fd = open(path, O_RDONLY);
1164 len = read_in_full(fd, buffer, sizeof(buffer)-1);
1168 while (len && isspace(buffer[len-1]))
1173 * Is it a symbolic ref?
1175 if (prefixcmp(buffer, "ref:"))
1178 *flag |= REF_ISSYMREF;
1180 while (isspace(*buf))
1182 if (check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {
1184 *flag |= REF_ISBROKEN;
1187 refname = strcpy(refname_buffer, buf);
1189 /* Please note that FETCH_HEAD has a second line containing other data. */
1190 if (get_sha1_hex(buffer, sha1) || (buffer[40] != '\0' && !isspace(buffer[40]))) {
1192 *flag |= REF_ISBROKEN;
1198 char *resolve_refdup(const char *ref, unsigned char *sha1, int reading, int *flag)
1200 const char *ret = resolve_ref_unsafe(ref, sha1, reading, flag);
1201 return ret ? xstrdup(ret) : NULL;
1204 /* The argument to filter_refs */
1206 const char *pattern;
1211 int read_ref_full(const char *refname, unsigned char *sha1, int reading, int *flags)
1213 if (resolve_ref_unsafe(refname, sha1, reading, flags))
1218 int read_ref(const char *refname, unsigned char *sha1)
1220 return read_ref_full(refname, sha1, 1, NULL);
1223 int ref_exists(const char *refname)
1225 unsigned char sha1[20];
1226 return !!resolve_ref_unsafe(refname, sha1, 1, NULL);
1229 static int filter_refs(const char *refname, const unsigned char *sha1, int flags,
1232 struct ref_filter *filter = (struct ref_filter *)data;
1233 if (fnmatch(filter->pattern, refname, 0))
1235 return filter->fn(refname, sha1, flags, filter->cb_data);
1238 int peel_ref(const char *refname, unsigned char *sha1)
1241 unsigned char base[20];
1244 if (current_ref && (current_ref->name == refname
1245 || !strcmp(current_ref->name, refname))) {
1246 if (current_ref->flag & REF_KNOWS_PEELED) {
1247 if (is_null_sha1(current_ref->u.value.peeled))
1249 hashcpy(sha1, current_ref->u.value.peeled);
1252 hashcpy(base, current_ref->u.value.sha1);
1256 if (read_ref_full(refname, base, 1, &flag))
1259 if ((flag & REF_ISPACKED)) {
1260 struct ref_dir *dir = get_packed_refs(get_ref_cache(NULL));
1261 struct ref_entry *r = find_ref(dir, refname);
1263 if (r != NULL && r->flag & REF_KNOWS_PEELED) {
1264 hashcpy(sha1, r->u.value.peeled);
1270 o = lookup_unknown_object(base);
1271 if (o->type == OBJ_NONE) {
1272 int type = sha1_object_info(base, NULL);
1278 if (o->type == OBJ_TAG) {
1279 o = deref_tag_noverify(o);
1281 hashcpy(sha1, o->sha1);
1288 struct warn_if_dangling_data {
1290 const char *refname;
1291 const char *msg_fmt;
1294 static int warn_if_dangling_symref(const char *refname, const unsigned char *sha1,
1295 int flags, void *cb_data)
1297 struct warn_if_dangling_data *d = cb_data;
1298 const char *resolves_to;
1299 unsigned char junk[20];
1301 if (!(flags & REF_ISSYMREF))
1304 resolves_to = resolve_ref_unsafe(refname, junk, 0, NULL);
1305 if (!resolves_to || strcmp(resolves_to, d->refname))
1308 fprintf(d->fp, d->msg_fmt, refname);
1313 void warn_dangling_symref(FILE *fp, const char *msg_fmt, const char *refname)
1315 struct warn_if_dangling_data data;
1318 data.refname = refname;
1319 data.msg_fmt = msg_fmt;
1320 for_each_rawref(warn_if_dangling_symref, &data);
1323 static int do_for_each_ref(const char *submodule, const char *base, each_ref_fn fn,
1324 int trim, int flags, void *cb_data)
1326 struct ref_cache *refs = get_ref_cache(submodule);
1327 struct ref_dir *packed_dir = get_packed_refs(refs);
1328 struct ref_dir *loose_dir = get_loose_refs(refs);
1331 if (base && *base) {
1332 packed_dir = find_containing_dir(packed_dir, base, 0);
1333 loose_dir = find_containing_dir(loose_dir, base, 0);
1336 if (packed_dir && loose_dir) {
1337 sort_ref_dir(packed_dir);
1338 sort_ref_dir(loose_dir);
1339 retval = do_for_each_ref_in_dirs(
1340 packed_dir, loose_dir,
1341 base, fn, trim, flags, cb_data);
1342 } else if (packed_dir) {
1343 sort_ref_dir(packed_dir);
1344 retval = do_for_each_ref_in_dir(
1346 base, fn, trim, flags, cb_data);
1347 } else if (loose_dir) {
1348 sort_ref_dir(loose_dir);
1349 retval = do_for_each_ref_in_dir(
1351 base, fn, trim, flags, cb_data);
1357 static int do_head_ref(const char *submodule, each_ref_fn fn, void *cb_data)
1359 unsigned char sha1[20];
1363 if (resolve_gitlink_ref(submodule, "HEAD", sha1) == 0)
1364 return fn("HEAD", sha1, 0, cb_data);
1369 if (!read_ref_full("HEAD", sha1, 1, &flag))
1370 return fn("HEAD", sha1, flag, cb_data);
1375 int head_ref(each_ref_fn fn, void *cb_data)
1377 return do_head_ref(NULL, fn, cb_data);
1380 int head_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1382 return do_head_ref(submodule, fn, cb_data);
1385 int for_each_ref(each_ref_fn fn, void *cb_data)
1387 return do_for_each_ref(NULL, "", fn, 0, 0, cb_data);
1390 int for_each_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1392 return do_for_each_ref(submodule, "", fn, 0, 0, cb_data);
1395 int for_each_ref_in(const char *prefix, each_ref_fn fn, void *cb_data)
1397 return do_for_each_ref(NULL, prefix, fn, strlen(prefix), 0, cb_data);
1400 int for_each_ref_in_submodule(const char *submodule, const char *prefix,
1401 each_ref_fn fn, void *cb_data)
1403 return do_for_each_ref(submodule, prefix, fn, strlen(prefix), 0, cb_data);
1406 int for_each_tag_ref(each_ref_fn fn, void *cb_data)
1408 return for_each_ref_in("refs/tags/", fn, cb_data);
1411 int for_each_tag_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1413 return for_each_ref_in_submodule(submodule, "refs/tags/", fn, cb_data);
1416 int for_each_branch_ref(each_ref_fn fn, void *cb_data)
1418 return for_each_ref_in("refs/heads/", fn, cb_data);
1421 int for_each_branch_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1423 return for_each_ref_in_submodule(submodule, "refs/heads/", fn, cb_data);
1426 int for_each_remote_ref(each_ref_fn fn, void *cb_data)
1428 return for_each_ref_in("refs/remotes/", fn, cb_data);
1431 int for_each_remote_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1433 return for_each_ref_in_submodule(submodule, "refs/remotes/", fn, cb_data);
1436 int for_each_replace_ref(each_ref_fn fn, void *cb_data)
1438 return do_for_each_ref(NULL, "refs/replace/", fn, 13, 0, cb_data);
1441 int head_ref_namespaced(each_ref_fn fn, void *cb_data)
1443 struct strbuf buf = STRBUF_INIT;
1445 unsigned char sha1[20];
1448 strbuf_addf(&buf, "%sHEAD", get_git_namespace());
1449 if (!read_ref_full(buf.buf, sha1, 1, &flag))
1450 ret = fn(buf.buf, sha1, flag, cb_data);
1451 strbuf_release(&buf);
1456 int for_each_namespaced_ref(each_ref_fn fn, void *cb_data)
1458 struct strbuf buf = STRBUF_INIT;
1460 strbuf_addf(&buf, "%srefs/", get_git_namespace());
1461 ret = do_for_each_ref(NULL, buf.buf, fn, 0, 0, cb_data);
1462 strbuf_release(&buf);
1466 int for_each_glob_ref_in(each_ref_fn fn, const char *pattern,
1467 const char *prefix, void *cb_data)
1469 struct strbuf real_pattern = STRBUF_INIT;
1470 struct ref_filter filter;
1473 if (!prefix && prefixcmp(pattern, "refs/"))
1474 strbuf_addstr(&real_pattern, "refs/");
1476 strbuf_addstr(&real_pattern, prefix);
1477 strbuf_addstr(&real_pattern, pattern);
1479 if (!has_glob_specials(pattern)) {
1480 /* Append implied '/' '*' if not present. */
1481 if (real_pattern.buf[real_pattern.len - 1] != '/')
1482 strbuf_addch(&real_pattern, '/');
1483 /* No need to check for '*', there is none. */
1484 strbuf_addch(&real_pattern, '*');
1487 filter.pattern = real_pattern.buf;
1489 filter.cb_data = cb_data;
1490 ret = for_each_ref(filter_refs, &filter);
1492 strbuf_release(&real_pattern);
1496 int for_each_glob_ref(each_ref_fn fn, const char *pattern, void *cb_data)
1498 return for_each_glob_ref_in(fn, pattern, NULL, cb_data);
1501 int for_each_rawref(each_ref_fn fn, void *cb_data)
1503 return do_for_each_ref(NULL, "", fn, 0,
1504 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);
1507 const char *prettify_refname(const char *name)
1510 !prefixcmp(name, "refs/heads/") ? 11 :
1511 !prefixcmp(name, "refs/tags/") ? 10 :
1512 !prefixcmp(name, "refs/remotes/") ? 13 :
1516 const char *ref_rev_parse_rules[] = {
1521 "refs/remotes/%.*s",
1522 "refs/remotes/%.*s/HEAD",
1526 int refname_match(const char *abbrev_name, const char *full_name, const char **rules)
1529 const int abbrev_name_len = strlen(abbrev_name);
1531 for (p = rules; *p; p++) {
1532 if (!strcmp(full_name, mkpath(*p, abbrev_name_len, abbrev_name))) {
1540 static struct ref_lock *verify_lock(struct ref_lock *lock,
1541 const unsigned char *old_sha1, int mustexist)
1543 if (read_ref_full(lock->ref_name, lock->old_sha1, mustexist, NULL)) {
1544 error("Can't verify ref %s", lock->ref_name);
1548 if (hashcmp(lock->old_sha1, old_sha1)) {
1549 error("Ref %s is at %s but expected %s", lock->ref_name,
1550 sha1_to_hex(lock->old_sha1), sha1_to_hex(old_sha1));
1557 static int remove_empty_directories(const char *file)
1559 /* we want to create a file but there is a directory there;
1560 * if that is an empty directory (or a directory that contains
1561 * only empty directories), remove them.
1566 strbuf_init(&path, 20);
1567 strbuf_addstr(&path, file);
1569 result = remove_dir_recursively(&path, REMOVE_DIR_EMPTY_ONLY);
1571 strbuf_release(&path);
1577 * *string and *len will only be substituted, and *string returned (for
1578 * later free()ing) if the string passed in is a magic short-hand form
1581 static char *substitute_branch_name(const char **string, int *len)
1583 struct strbuf buf = STRBUF_INIT;
1584 int ret = interpret_branch_name(*string, &buf);
1588 *string = strbuf_detach(&buf, &size);
1590 return (char *)*string;
1596 int dwim_ref(const char *str, int len, unsigned char *sha1, char **ref)
1598 char *last_branch = substitute_branch_name(&str, &len);
1603 for (p = ref_rev_parse_rules; *p; p++) {
1604 char fullref[PATH_MAX];
1605 unsigned char sha1_from_ref[20];
1606 unsigned char *this_result;
1609 this_result = refs_found ? sha1_from_ref : sha1;
1610 mksnpath(fullref, sizeof(fullref), *p, len, str);
1611 r = resolve_ref_unsafe(fullref, this_result, 1, &flag);
1615 if (!warn_ambiguous_refs)
1617 } else if ((flag & REF_ISSYMREF) && strcmp(fullref, "HEAD")) {
1618 warning("ignoring dangling symref %s.", fullref);
1619 } else if ((flag & REF_ISBROKEN) && strchr(fullref, '/')) {
1620 warning("ignoring broken ref %s.", fullref);
1627 int dwim_log(const char *str, int len, unsigned char *sha1, char **log)
1629 char *last_branch = substitute_branch_name(&str, &len);
1634 for (p = ref_rev_parse_rules; *p; p++) {
1636 unsigned char hash[20];
1637 char path[PATH_MAX];
1638 const char *ref, *it;
1640 mksnpath(path, sizeof(path), *p, len, str);
1641 ref = resolve_ref_unsafe(path, hash, 1, NULL);
1644 if (!stat(git_path("logs/%s", path), &st) &&
1645 S_ISREG(st.st_mode))
1647 else if (strcmp(ref, path) &&
1648 !stat(git_path("logs/%s", ref), &st) &&
1649 S_ISREG(st.st_mode))
1653 if (!logs_found++) {
1655 hashcpy(sha1, hash);
1657 if (!warn_ambiguous_refs)
1664 static struct ref_lock *lock_ref_sha1_basic(const char *refname,
1665 const unsigned char *old_sha1,
1666 int flags, int *type_p)
1669 const char *orig_refname = refname;
1670 struct ref_lock *lock;
1673 int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
1676 lock = xcalloc(1, sizeof(struct ref_lock));
1679 refname = resolve_ref_unsafe(refname, lock->old_sha1, mustexist, &type);
1680 if (!refname && errno == EISDIR) {
1681 /* we are trying to lock foo but we used to
1682 * have foo/bar which now does not exist;
1683 * it is normal for the empty directory 'foo'
1686 ref_file = git_path("%s", orig_refname);
1687 if (remove_empty_directories(ref_file)) {
1689 error("there are still refs under '%s'", orig_refname);
1692 refname = resolve_ref_unsafe(orig_refname, lock->old_sha1, mustexist, &type);
1698 error("unable to resolve reference %s: %s",
1699 orig_refname, strerror(errno));
1702 missing = is_null_sha1(lock->old_sha1);
1703 /* When the ref did not exist and we are creating it,
1704 * make sure there is no existing ref that is packed
1705 * whose name begins with our refname, nor a ref whose
1706 * name is a proper prefix of our refname.
1709 !is_refname_available(refname, NULL, get_packed_refs(get_ref_cache(NULL)))) {
1710 last_errno = ENOTDIR;
1714 lock->lk = xcalloc(1, sizeof(struct lock_file));
1716 lflags = LOCK_DIE_ON_ERROR;
1717 if (flags & REF_NODEREF) {
1718 refname = orig_refname;
1719 lflags |= LOCK_NODEREF;
1721 lock->ref_name = xstrdup(refname);
1722 lock->orig_ref_name = xstrdup(orig_refname);
1723 ref_file = git_path("%s", refname);
1725 lock->force_write = 1;
1726 if ((flags & REF_NODEREF) && (type & REF_ISSYMREF))
1727 lock->force_write = 1;
1729 if (safe_create_leading_directories(ref_file)) {
1731 error("unable to create directory for %s", ref_file);
1735 lock->lock_fd = hold_lock_file_for_update(lock->lk, ref_file, lflags);
1736 return old_sha1 ? verify_lock(lock, old_sha1, mustexist) : lock;
1744 struct ref_lock *lock_ref_sha1(const char *refname, const unsigned char *old_sha1)
1746 char refpath[PATH_MAX];
1747 if (check_refname_format(refname, 0))
1749 strcpy(refpath, mkpath("refs/%s", refname));
1750 return lock_ref_sha1_basic(refpath, old_sha1, 0, NULL);
1753 struct ref_lock *lock_any_ref_for_update(const char *refname,
1754 const unsigned char *old_sha1, int flags)
1756 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL))
1758 return lock_ref_sha1_basic(refname, old_sha1, flags, NULL);
1761 struct repack_without_ref_sb {
1762 const char *refname;
1766 static int repack_without_ref_fn(const char *refname, const unsigned char *sha1,
1767 int flags, void *cb_data)
1769 struct repack_without_ref_sb *data = cb_data;
1770 char line[PATH_MAX + 100];
1773 if (!strcmp(data->refname, refname))
1775 len = snprintf(line, sizeof(line), "%s %s\n",
1776 sha1_to_hex(sha1), refname);
1777 /* this should not happen but just being defensive */
1778 if (len > sizeof(line))
1779 die("too long a refname '%s'", refname);
1780 write_or_die(data->fd, line, len);
1784 static struct lock_file packlock;
1786 static int repack_without_ref(const char *refname)
1788 struct repack_without_ref_sb data;
1789 struct ref_cache *refs = get_ref_cache(NULL);
1790 struct ref_dir *packed = get_packed_refs(refs);
1791 if (find_ref(packed, refname) == NULL)
1793 data.refname = refname;
1794 data.fd = hold_lock_file_for_update(&packlock, git_path("packed-refs"), 0);
1796 unable_to_lock_error(git_path("packed-refs"), errno);
1797 return error("cannot delete '%s' from packed refs", refname);
1799 clear_packed_ref_cache(refs);
1800 packed = get_packed_refs(refs);
1801 do_for_each_ref_in_dir(packed, 0, "", repack_without_ref_fn, 0, 0, &data);
1802 return commit_lock_file(&packlock);
1805 int delete_ref(const char *refname, const unsigned char *sha1, int delopt)
1807 struct ref_lock *lock;
1808 int err, i = 0, ret = 0, flag = 0;
1810 lock = lock_ref_sha1_basic(refname, sha1, delopt, &flag);
1813 if (!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {
1815 i = strlen(lock->lk->filename) - 5; /* .lock */
1816 lock->lk->filename[i] = 0;
1817 err = unlink_or_warn(lock->lk->filename);
1818 if (err && errno != ENOENT)
1821 lock->lk->filename[i] = '.';
1823 /* removing the loose one could have resurrected an earlier
1824 * packed one. Also, if it was not loose we need to repack
1827 ret |= repack_without_ref(lock->ref_name);
1829 unlink_or_warn(git_path("logs/%s", lock->ref_name));
1830 invalidate_ref_cache(NULL);
1836 * People using contrib's git-new-workdir have .git/logs/refs ->
1837 * /some/other/path/.git/logs/refs, and that may live on another device.
1839 * IOW, to avoid cross device rename errors, the temporary renamed log must
1840 * live into logs/refs.
1842 #define TMP_RENAMED_LOG "logs/refs/.tmp-renamed-log"
1844 int rename_ref(const char *oldrefname, const char *newrefname, const char *logmsg)
1846 unsigned char sha1[20], orig_sha1[20];
1847 int flag = 0, logmoved = 0;
1848 struct ref_lock *lock;
1849 struct stat loginfo;
1850 int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);
1851 const char *symref = NULL;
1852 struct ref_cache *refs = get_ref_cache(NULL);
1854 if (log && S_ISLNK(loginfo.st_mode))
1855 return error("reflog for %s is a symlink", oldrefname);
1857 symref = resolve_ref_unsafe(oldrefname, orig_sha1, 1, &flag);
1858 if (flag & REF_ISSYMREF)
1859 return error("refname %s is a symbolic ref, renaming it is not supported",
1862 return error("refname %s not found", oldrefname);
1864 if (!is_refname_available(newrefname, oldrefname, get_packed_refs(refs)))
1867 if (!is_refname_available(newrefname, oldrefname, get_loose_refs(refs)))
1870 if (log && rename(git_path("logs/%s", oldrefname), git_path(TMP_RENAMED_LOG)))
1871 return error("unable to move logfile logs/%s to "TMP_RENAMED_LOG": %s",
1872 oldrefname, strerror(errno));
1874 if (delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {
1875 error("unable to delete old %s", oldrefname);
1879 if (!read_ref_full(newrefname, sha1, 1, &flag) &&
1880 delete_ref(newrefname, sha1, REF_NODEREF)) {
1881 if (errno==EISDIR) {
1882 if (remove_empty_directories(git_path("%s", newrefname))) {
1883 error("Directory not empty: %s", newrefname);
1887 error("unable to delete existing %s", newrefname);
1892 if (log && safe_create_leading_directories(git_path("logs/%s", newrefname))) {
1893 error("unable to create directory for %s", newrefname);
1898 if (log && rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", newrefname))) {
1899 if (errno==EISDIR || errno==ENOTDIR) {
1901 * rename(a, b) when b is an existing
1902 * directory ought to result in ISDIR, but
1903 * Solaris 5.8 gives ENOTDIR. Sheesh.
1905 if (remove_empty_directories(git_path("logs/%s", newrefname))) {
1906 error("Directory not empty: logs/%s", newrefname);
1911 error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s: %s",
1912 newrefname, strerror(errno));
1918 lock = lock_ref_sha1_basic(newrefname, NULL, 0, NULL);
1920 error("unable to lock %s for update", newrefname);
1923 lock->force_write = 1;
1924 hashcpy(lock->old_sha1, orig_sha1);
1925 if (write_ref_sha1(lock, orig_sha1, logmsg)) {
1926 error("unable to write current sha1 into %s", newrefname);
1933 lock = lock_ref_sha1_basic(oldrefname, NULL, 0, NULL);
1935 error("unable to lock %s for rollback", oldrefname);
1939 lock->force_write = 1;
1940 flag = log_all_ref_updates;
1941 log_all_ref_updates = 0;
1942 if (write_ref_sha1(lock, orig_sha1, NULL))
1943 error("unable to write current sha1 into %s", oldrefname);
1944 log_all_ref_updates = flag;
1947 if (logmoved && rename(git_path("logs/%s", newrefname), git_path("logs/%s", oldrefname)))
1948 error("unable to restore logfile %s from %s: %s",
1949 oldrefname, newrefname, strerror(errno));
1950 if (!logmoved && log &&
1951 rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", oldrefname)))
1952 error("unable to restore logfile %s from "TMP_RENAMED_LOG": %s",
1953 oldrefname, strerror(errno));
1958 int close_ref(struct ref_lock *lock)
1960 if (close_lock_file(lock->lk))
1966 int commit_ref(struct ref_lock *lock)
1968 if (commit_lock_file(lock->lk))
1974 void unlock_ref(struct ref_lock *lock)
1976 /* Do not free lock->lk -- atexit() still looks at them */
1978 rollback_lock_file(lock->lk);
1979 free(lock->ref_name);
1980 free(lock->orig_ref_name);
1985 * copy the reflog message msg to buf, which has been allocated sufficiently
1986 * large, while cleaning up the whitespaces. Especially, convert LF to space,
1987 * because reflog file is one line per entry.
1989 static int copy_msg(char *buf, const char *msg)
1996 while ((c = *msg++)) {
1997 if (wasspace && isspace(c))
1999 wasspace = isspace(c);
2004 while (buf < cp && isspace(cp[-1]))
2010 int log_ref_setup(const char *refname, char *logfile, int bufsize)
2012 int logfd, oflags = O_APPEND | O_WRONLY;
2014 git_snpath(logfile, bufsize, "logs/%s", refname);
2015 if (log_all_ref_updates &&
2016 (!prefixcmp(refname, "refs/heads/") ||
2017 !prefixcmp(refname, "refs/remotes/") ||
2018 !prefixcmp(refname, "refs/notes/") ||
2019 !strcmp(refname, "HEAD"))) {
2020 if (safe_create_leading_directories(logfile) < 0)
2021 return error("unable to create directory for %s",
2026 logfd = open(logfile, oflags, 0666);
2028 if (!(oflags & O_CREAT) && errno == ENOENT)
2031 if ((oflags & O_CREAT) && errno == EISDIR) {
2032 if (remove_empty_directories(logfile)) {
2033 return error("There are still logs under '%s'",
2036 logfd = open(logfile, oflags, 0666);
2040 return error("Unable to append to %s: %s",
2041 logfile, strerror(errno));
2044 adjust_shared_perm(logfile);
2049 static int log_ref_write(const char *refname, const unsigned char *old_sha1,
2050 const unsigned char *new_sha1, const char *msg)
2052 int logfd, result, written, oflags = O_APPEND | O_WRONLY;
2053 unsigned maxlen, len;
2055 char log_file[PATH_MAX];
2057 const char *committer;
2059 if (log_all_ref_updates < 0)
2060 log_all_ref_updates = !is_bare_repository();
2062 result = log_ref_setup(refname, log_file, sizeof(log_file));
2066 logfd = open(log_file, oflags);
2069 msglen = msg ? strlen(msg) : 0;
2070 committer = git_committer_info(0);
2071 maxlen = strlen(committer) + msglen + 100;
2072 logrec = xmalloc(maxlen);
2073 len = sprintf(logrec, "%s %s %s\n",
2074 sha1_to_hex(old_sha1),
2075 sha1_to_hex(new_sha1),
2078 len += copy_msg(logrec + len - 1, msg) - 1;
2079 written = len <= maxlen ? write_in_full(logfd, logrec, len) : -1;
2081 if (close(logfd) != 0 || written != len)
2082 return error("Unable to append to %s", log_file);
2086 static int is_branch(const char *refname)
2088 return !strcmp(refname, "HEAD") || !prefixcmp(refname, "refs/heads/");
2091 int write_ref_sha1(struct ref_lock *lock,
2092 const unsigned char *sha1, const char *logmsg)
2094 static char term = '\n';
2099 if (!lock->force_write && !hashcmp(lock->old_sha1, sha1)) {
2103 o = parse_object(sha1);
2105 error("Trying to write ref %s with nonexistent object %s",
2106 lock->ref_name, sha1_to_hex(sha1));
2110 if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
2111 error("Trying to write non-commit object %s to branch %s",
2112 sha1_to_hex(sha1), lock->ref_name);
2116 if (write_in_full(lock->lock_fd, sha1_to_hex(sha1), 40) != 40 ||
2117 write_in_full(lock->lock_fd, &term, 1) != 1
2118 || close_ref(lock) < 0) {
2119 error("Couldn't write %s", lock->lk->filename);
2123 clear_loose_ref_cache(get_ref_cache(NULL));
2124 if (log_ref_write(lock->ref_name, lock->old_sha1, sha1, logmsg) < 0 ||
2125 (strcmp(lock->ref_name, lock->orig_ref_name) &&
2126 log_ref_write(lock->orig_ref_name, lock->old_sha1, sha1, logmsg) < 0)) {
2130 if (strcmp(lock->orig_ref_name, "HEAD") != 0) {
2132 * Special hack: If a branch is updated directly and HEAD
2133 * points to it (may happen on the remote side of a push
2134 * for example) then logically the HEAD reflog should be
2136 * A generic solution implies reverse symref information,
2137 * but finding all symrefs pointing to the given branch
2138 * would be rather costly for this rare event (the direct
2139 * update of a branch) to be worth it. So let's cheat and
2140 * check with HEAD only which should cover 99% of all usage
2141 * scenarios (even 100% of the default ones).
2143 unsigned char head_sha1[20];
2145 const char *head_ref;
2146 head_ref = resolve_ref_unsafe("HEAD", head_sha1, 1, &head_flag);
2147 if (head_ref && (head_flag & REF_ISSYMREF) &&
2148 !strcmp(head_ref, lock->ref_name))
2149 log_ref_write("HEAD", lock->old_sha1, sha1, logmsg);
2151 if (commit_ref(lock)) {
2152 error("Couldn't set %s", lock->ref_name);
2160 int create_symref(const char *ref_target, const char *refs_heads_master,
2163 const char *lockpath;
2165 int fd, len, written;
2166 char *git_HEAD = git_pathdup("%s", ref_target);
2167 unsigned char old_sha1[20], new_sha1[20];
2169 if (logmsg && read_ref(ref_target, old_sha1))
2172 if (safe_create_leading_directories(git_HEAD) < 0)
2173 return error("unable to create directory for %s", git_HEAD);
2175 #ifndef NO_SYMLINK_HEAD
2176 if (prefer_symlink_refs) {
2178 if (!symlink(refs_heads_master, git_HEAD))
2180 fprintf(stderr, "no symlink - falling back to symbolic ref\n");
2184 len = snprintf(ref, sizeof(ref), "ref: %s\n", refs_heads_master);
2185 if (sizeof(ref) <= len) {
2186 error("refname too long: %s", refs_heads_master);
2187 goto error_free_return;
2189 lockpath = mkpath("%s.lock", git_HEAD);
2190 fd = open(lockpath, O_CREAT | O_EXCL | O_WRONLY, 0666);
2192 error("Unable to open %s for writing", lockpath);
2193 goto error_free_return;
2195 written = write_in_full(fd, ref, len);
2196 if (close(fd) != 0 || written != len) {
2197 error("Unable to write to %s", lockpath);
2198 goto error_unlink_return;
2200 if (rename(lockpath, git_HEAD) < 0) {
2201 error("Unable to create %s", git_HEAD);
2202 goto error_unlink_return;
2204 if (adjust_shared_perm(git_HEAD)) {
2205 error("Unable to fix permissions on %s", lockpath);
2206 error_unlink_return:
2207 unlink_or_warn(lockpath);
2213 #ifndef NO_SYMLINK_HEAD
2216 if (logmsg && !read_ref(refs_heads_master, new_sha1))
2217 log_ref_write(ref_target, old_sha1, new_sha1, logmsg);
2223 static char *ref_msg(const char *line, const char *endp)
2227 ep = memchr(line, '\n', endp - line);
2230 return xmemdupz(line, ep - line);
2233 int read_ref_at(const char *refname, unsigned long at_time, int cnt,
2234 unsigned char *sha1, char **msg,
2235 unsigned long *cutoff_time, int *cutoff_tz, int *cutoff_cnt)
2237 const char *logfile, *logdata, *logend, *rec, *lastgt, *lastrec;
2239 int logfd, tz, reccnt = 0;
2242 unsigned char logged_sha1[20];
2246 logfile = git_path("logs/%s", refname);
2247 logfd = open(logfile, O_RDONLY, 0);
2249 die_errno("Unable to read log '%s'", logfile);
2252 die("Log %s is empty.", logfile);
2253 mapsz = xsize_t(st.st_size);
2254 log_mapped = xmmap(NULL, mapsz, PROT_READ, MAP_PRIVATE, logfd, 0);
2255 logdata = log_mapped;
2259 rec = logend = logdata + st.st_size;
2260 while (logdata < rec) {
2262 if (logdata < rec && *(rec-1) == '\n')
2265 while (logdata < rec && *(rec-1) != '\n') {
2271 die("Log %s is corrupt.", logfile);
2272 date = strtoul(lastgt + 1, &tz_c, 10);
2273 if (date <= at_time || cnt == 0) {
2274 tz = strtoul(tz_c, NULL, 10);
2276 *msg = ref_msg(rec, logend);
2278 *cutoff_time = date;
2282 *cutoff_cnt = reccnt - 1;
2284 if (get_sha1_hex(lastrec, logged_sha1))
2285 die("Log %s is corrupt.", logfile);
2286 if (get_sha1_hex(rec + 41, sha1))
2287 die("Log %s is corrupt.", logfile);
2288 if (hashcmp(logged_sha1, sha1)) {
2289 warning("Log %s has gap after %s.",
2290 logfile, show_date(date, tz, DATE_RFC2822));
2293 else if (date == at_time) {
2294 if (get_sha1_hex(rec + 41, sha1))
2295 die("Log %s is corrupt.", logfile);
2298 if (get_sha1_hex(rec + 41, logged_sha1))
2299 die("Log %s is corrupt.", logfile);
2300 if (hashcmp(logged_sha1, sha1)) {
2301 warning("Log %s unexpectedly ended on %s.",
2302 logfile, show_date(date, tz, DATE_RFC2822));
2305 munmap(log_mapped, mapsz);
2314 while (rec < logend && *rec != '>' && *rec != '\n')
2316 if (rec == logend || *rec == '\n')
2317 die("Log %s is corrupt.", logfile);
2318 date = strtoul(rec + 1, &tz_c, 10);
2319 tz = strtoul(tz_c, NULL, 10);
2320 if (get_sha1_hex(logdata, sha1))
2321 die("Log %s is corrupt.", logfile);
2322 if (is_null_sha1(sha1)) {
2323 if (get_sha1_hex(logdata + 41, sha1))
2324 die("Log %s is corrupt.", logfile);
2327 *msg = ref_msg(logdata, logend);
2328 munmap(log_mapped, mapsz);
2331 *cutoff_time = date;
2335 *cutoff_cnt = reccnt;
2339 static int show_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn, void *cb_data)
2341 unsigned char osha1[20], nsha1[20];
2342 char *email_end, *message;
2343 unsigned long timestamp;
2346 /* old SP new SP name <email> SP time TAB msg LF */
2347 if (sb->len < 83 || sb->buf[sb->len - 1] != '\n' ||
2348 get_sha1_hex(sb->buf, osha1) || sb->buf[40] != ' ' ||
2349 get_sha1_hex(sb->buf + 41, nsha1) || sb->buf[81] != ' ' ||
2350 !(email_end = strchr(sb->buf + 82, '>')) ||
2351 email_end[1] != ' ' ||
2352 !(timestamp = strtoul(email_end + 2, &message, 10)) ||
2353 !message || message[0] != ' ' ||
2354 (message[1] != '+' && message[1] != '-') ||
2355 !isdigit(message[2]) || !isdigit(message[3]) ||
2356 !isdigit(message[4]) || !isdigit(message[5]))
2357 return 0; /* corrupt? */
2358 email_end[1] = '\0';
2359 tz = strtol(message + 1, NULL, 10);
2360 if (message[6] != '\t')
2364 return fn(osha1, nsha1, sb->buf + 82, timestamp, tz, message, cb_data);
2367 static char *find_beginning_of_line(char *bob, char *scan)
2369 while (bob < scan && *(--scan) != '\n')
2370 ; /* keep scanning backwards */
2372 * Return either beginning of the buffer, or LF at the end of
2373 * the previous line.
2378 int for_each_reflog_ent_reverse(const char *refname, each_reflog_ent_fn fn, void *cb_data)
2380 struct strbuf sb = STRBUF_INIT;
2383 int ret = 0, at_tail = 1;
2385 logfp = fopen(git_path("logs/%s", refname), "r");
2389 /* Jump to the end */
2390 if (fseek(logfp, 0, SEEK_END) < 0)
2391 return error("cannot seek back reflog for %s: %s",
2392 refname, strerror(errno));
2394 while (!ret && 0 < pos) {
2400 /* Fill next block from the end */
2401 cnt = (sizeof(buf) < pos) ? sizeof(buf) : pos;
2402 if (fseek(logfp, pos - cnt, SEEK_SET))
2403 return error("cannot seek back reflog for %s: %s",
2404 refname, strerror(errno));
2405 nread = fread(buf, cnt, 1, logfp);
2407 return error("cannot read %d bytes from reflog for %s: %s",
2408 cnt, refname, strerror(errno));
2411 scanp = endp = buf + cnt;
2412 if (at_tail && scanp[-1] == '\n')
2413 /* Looking at the final LF at the end of the file */
2417 while (buf < scanp) {
2419 * terminating LF of the previous line, or the beginning
2424 bp = find_beginning_of_line(buf, scanp);
2427 strbuf_splice(&sb, 0, 0, buf, endp - buf);
2429 break; /* need to fill another block */
2430 scanp = buf - 1; /* leave loop */
2433 * (bp + 1) thru endp is the beginning of the
2434 * current line we have in sb
2436 strbuf_splice(&sb, 0, 0, bp + 1, endp - (bp + 1));
2440 ret = show_one_reflog_ent(&sb, fn, cb_data);
2448 ret = show_one_reflog_ent(&sb, fn, cb_data);
2451 strbuf_release(&sb);
2455 int for_each_reflog_ent(const char *refname, each_reflog_ent_fn fn, void *cb_data)
2458 struct strbuf sb = STRBUF_INIT;
2461 logfp = fopen(git_path("logs/%s", refname), "r");
2465 while (!ret && !strbuf_getwholeline(&sb, logfp, '\n'))
2466 ret = show_one_reflog_ent(&sb, fn, cb_data);
2468 strbuf_release(&sb);
2472 * Call fn for each reflog in the namespace indicated by name. name
2473 * must be empty or end with '/'. Name will be used as a scratch
2474 * space, but its contents will be restored before return.
2476 static int do_for_each_reflog(struct strbuf *name, each_ref_fn fn, void *cb_data)
2478 DIR *d = opendir(git_path("logs/%s", name->buf));
2481 int oldlen = name->len;
2484 return name->len ? errno : 0;
2486 while ((de = readdir(d)) != NULL) {
2489 if (de->d_name[0] == '.')
2491 if (has_extension(de->d_name, ".lock"))
2493 strbuf_addstr(name, de->d_name);
2494 if (stat(git_path("logs/%s", name->buf), &st) < 0) {
2495 ; /* silently ignore */
2497 if (S_ISDIR(st.st_mode)) {
2498 strbuf_addch(name, '/');
2499 retval = do_for_each_reflog(name, fn, cb_data);
2501 unsigned char sha1[20];
2502 if (read_ref_full(name->buf, sha1, 0, NULL))
2503 retval = error("bad ref for %s", name->buf);
2505 retval = fn(name->buf, sha1, 0, cb_data);
2510 strbuf_setlen(name, oldlen);
2516 int for_each_reflog(each_ref_fn fn, void *cb_data)
2520 strbuf_init(&name, PATH_MAX);
2521 retval = do_for_each_reflog(&name, fn, cb_data);
2522 strbuf_release(&name);
2526 int update_ref(const char *action, const char *refname,
2527 const unsigned char *sha1, const unsigned char *oldval,
2528 int flags, enum action_on_err onerr)
2530 static struct ref_lock *lock;
2531 lock = lock_any_ref_for_update(refname, oldval, flags);
2533 const char *str = "Cannot lock the ref '%s'.";
2535 case MSG_ON_ERR: error(str, refname); break;
2536 case DIE_ON_ERR: die(str, refname); break;
2537 case QUIET_ON_ERR: break;
2541 if (write_ref_sha1(lock, sha1, action) < 0) {
2542 const char *str = "Cannot update the ref '%s'.";
2544 case MSG_ON_ERR: error(str, refname); break;
2545 case DIE_ON_ERR: die(str, refname); break;
2546 case QUIET_ON_ERR: break;
2553 struct ref *find_ref_by_name(const struct ref *list, const char *name)
2555 for ( ; list; list = list->next)
2556 if (!strcmp(list->name, name))
2557 return (struct ref *)list;
2562 * generate a format suitable for scanf from a ref_rev_parse_rules
2563 * rule, that is replace the "%.*s" spec with a "%s" spec
2565 static void gen_scanf_fmt(char *scanf_fmt, const char *rule)
2569 spec = strstr(rule, "%.*s");
2570 if (!spec || strstr(spec + 4, "%.*s"))
2571 die("invalid rule in ref_rev_parse_rules: %s", rule);
2573 /* copy all until spec */
2574 strncpy(scanf_fmt, rule, spec - rule);
2575 scanf_fmt[spec - rule] = '\0';
2577 strcat(scanf_fmt, "%s");
2578 /* copy remaining rule */
2579 strcat(scanf_fmt, spec + 4);
2584 char *shorten_unambiguous_ref(const char *refname, int strict)
2587 static char **scanf_fmts;
2588 static int nr_rules;
2591 /* pre generate scanf formats from ref_rev_parse_rules[] */
2593 size_t total_len = 0;
2595 /* the rule list is NULL terminated, count them first */
2596 for (; ref_rev_parse_rules[nr_rules]; nr_rules++)
2597 /* no +1 because strlen("%s") < strlen("%.*s") */
2598 total_len += strlen(ref_rev_parse_rules[nr_rules]);
2600 scanf_fmts = xmalloc(nr_rules * sizeof(char *) + total_len);
2603 for (i = 0; i < nr_rules; i++) {
2604 scanf_fmts[i] = (char *)&scanf_fmts[nr_rules]
2606 gen_scanf_fmt(scanf_fmts[i], ref_rev_parse_rules[i]);
2607 total_len += strlen(ref_rev_parse_rules[i]);
2611 /* bail out if there are no rules */
2613 return xstrdup(refname);
2615 /* buffer for scanf result, at most refname must fit */
2616 short_name = xstrdup(refname);
2618 /* skip first rule, it will always match */
2619 for (i = nr_rules - 1; i > 0 ; --i) {
2621 int rules_to_fail = i;
2624 if (1 != sscanf(refname, scanf_fmts[i], short_name))
2627 short_name_len = strlen(short_name);
2630 * in strict mode, all (except the matched one) rules
2631 * must fail to resolve to a valid non-ambiguous ref
2634 rules_to_fail = nr_rules;
2637 * check if the short name resolves to a valid ref,
2638 * but use only rules prior to the matched one
2640 for (j = 0; j < rules_to_fail; j++) {
2641 const char *rule = ref_rev_parse_rules[j];
2642 char refname[PATH_MAX];
2644 /* skip matched rule */
2649 * the short name is ambiguous, if it resolves
2650 * (with this previous rule) to a valid ref
2651 * read_ref() returns 0 on success
2653 mksnpath(refname, sizeof(refname),
2654 rule, short_name_len, short_name);
2655 if (ref_exists(refname))
2660 * short name is non-ambiguous if all previous rules
2661 * haven't resolved to a valid ref
2663 if (j == rules_to_fail)
2668 return xstrdup(refname);
2671 static struct string_list *hide_refs;
2673 int parse_hide_refs_config(const char *var, const char *value, const char *section)
2675 if (!strcmp("transfer.hiderefs", var) ||
2676 /* NEEDSWORK: use parse_config_key() once both are merged */
2677 (!prefixcmp(var, section) && var[strlen(section)] == '.' &&
2678 !strcmp(var + strlen(section), ".hiderefs"))) {
2683 return config_error_nonbool(var);
2684 ref = xstrdup(value);
2686 while (len && ref[len - 1] == '/')
2689 hide_refs = xcalloc(1, sizeof(*hide_refs));
2690 hide_refs->strdup_strings = 1;
2692 string_list_append(hide_refs, ref);
2697 int ref_is_hidden(const char *refname)
2699 struct string_list_item *item;
2703 for_each_string_list_item(item, hide_refs) {
2705 if (prefixcmp(refname, item->string))
2707 len = strlen(item->string);
2708 if (!refname[len] || refname[len] == '/')