refs: use strncmp() instead of strlen() and memcmp()
[alt-git.git] / refs.c
blob257472f8e4449911e462e241a515c2e8241ee860
1 #include "cache.h"
2 #include "refs.h"
3 #include "object.h"
4 #include "tag.h"
5 #include "dir.h"
7 /*
8 * Make sure "ref" is something reasonable to have under ".git/refs/";
9 * We do not like it if:
11 * - any path component of it begins with ".", or
12 * - it has double dots "..", or
13 * - it has ASCII control character, "~", "^", ":" or SP, anywhere, or
14 * - it ends with a "/".
15 * - it ends with ".lock"
16 * - it contains a "\" (backslash)
19 /* Return true iff ch is not allowed in reference names. */
20 static inline int bad_ref_char(int ch)
22 if (((unsigned) ch) <= ' ' || ch == 0x7f ||
23 ch == '~' || ch == '^' || ch == ':' || ch == '\\')
24 return 1;
25 /* 2.13 Pattern Matching Notation */
26 if (ch == '*' || ch == '?' || ch == '[') /* Unsupported */
27 return 1;
28 return 0;
32 * Try to read one refname component from the front of refname. Return
33 * the length of the component found, or -1 if the component is not
34 * legal.
36 static int check_refname_component(const char *refname, int flags)
38 const char *cp;
39 char last = '\0';
41 for (cp = refname; ; cp++) {
42 char ch = *cp;
43 if (ch == '\0' || ch == '/')
44 break;
45 if (bad_ref_char(ch))
46 return -1; /* Illegal character in refname. */
47 if (last == '.' && ch == '.')
48 return -1; /* Refname contains "..". */
49 if (last == '@' && ch == '{')
50 return -1; /* Refname contains "@{". */
51 last = ch;
53 if (cp == refname)
54 return 0; /* Component has zero length. */
55 if (refname[0] == '.') {
56 if (!(flags & REFNAME_DOT_COMPONENT))
57 return -1; /* Component starts with '.'. */
59 * Even if leading dots are allowed, don't allow "."
60 * as a component (".." is prevented by a rule above).
62 if (refname[1] == '\0')
63 return -1; /* Component equals ".". */
65 if (cp - refname >= 5 && !memcmp(cp - 5, ".lock", 5))
66 return -1; /* Refname ends with ".lock". */
67 return cp - refname;
70 int check_refname_format(const char *refname, int flags)
72 int component_len, component_count = 0;
74 while (1) {
75 /* We are at the start of a path component. */
76 component_len = check_refname_component(refname, flags);
77 if (component_len <= 0) {
78 if ((flags & REFNAME_REFSPEC_PATTERN) &&
79 refname[0] == '*' &&
80 (refname[1] == '\0' || refname[1] == '/')) {
81 /* Accept one wildcard as a full refname component. */
82 flags &= ~REFNAME_REFSPEC_PATTERN;
83 component_len = 1;
84 } else {
85 return -1;
88 component_count++;
89 if (refname[component_len] == '\0')
90 break;
91 /* Skip to next component. */
92 refname += component_len + 1;
95 if (refname[component_len - 1] == '.')
96 return -1; /* Refname ends with '.'. */
97 if (!(flags & REFNAME_ALLOW_ONELEVEL) && component_count < 2)
98 return -1; /* Refname has only one component. */
99 return 0;
102 struct ref_entry;
105 * Information used (along with the information in ref_entry) to
106 * describe a single cached reference. This data structure only
107 * occurs embedded in a union in struct ref_entry, and only when
108 * (ref_entry->flag & REF_DIR) is zero.
110 struct ref_value {
111 unsigned char sha1[20];
112 unsigned char peeled[20];
115 struct ref_cache;
118 * Information used (along with the information in ref_entry) to
119 * describe a level in the hierarchy of references. This data
120 * structure only occurs embedded in a union in struct ref_entry, and
121 * only when (ref_entry.flag & REF_DIR) is set. In that case,
122 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references
123 * in the directory have already been read:
125 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose
126 * or packed references, already read.
128 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose
129 * references that hasn't been read yet (nor has any of its
130 * subdirectories).
132 * Entries within a directory are stored within a growable array of
133 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i <
134 * sorted are sorted by their component name in strcmp() order and the
135 * remaining entries are unsorted.
137 * Loose references are read lazily, one directory at a time. When a
138 * directory of loose references is read, then all of the references
139 * in that directory are stored, and REF_INCOMPLETE stubs are created
140 * for any subdirectories, but the subdirectories themselves are not
141 * read. The reading is triggered by get_ref_dir().
143 struct ref_dir {
144 int nr, alloc;
147 * Entries with index 0 <= i < sorted are sorted by name. New
148 * entries are appended to the list unsorted, and are sorted
149 * only when required; thus we avoid the need to sort the list
150 * after the addition of every reference.
152 int sorted;
154 /* A pointer to the ref_cache that contains this ref_dir. */
155 struct ref_cache *ref_cache;
157 struct ref_entry **entries;
160 /* ISSYMREF=0x01, ISPACKED=0x02, and ISBROKEN=0x04 are public interfaces */
161 #define REF_KNOWS_PEELED 0x08
163 /* ref_entry represents a directory of references */
164 #define REF_DIR 0x10
167 * Entry has not yet been read from disk (used only for REF_DIR
168 * entries representing loose references)
170 #define REF_INCOMPLETE 0x20
173 * A ref_entry represents either a reference or a "subdirectory" of
174 * references.
176 * Each directory in the reference namespace is represented by a
177 * ref_entry with (flags & REF_DIR) set and containing a subdir member
178 * that holds the entries in that directory that have been read so
179 * far. If (flags & REF_INCOMPLETE) is set, then the directory and
180 * its subdirectories haven't been read yet. REF_INCOMPLETE is only
181 * used for loose reference directories.
183 * References are represented by a ref_entry with (flags & REF_DIR)
184 * unset and a value member that describes the reference's value. The
185 * flag member is at the ref_entry level, but it is also needed to
186 * interpret the contents of the value field (in other words, a
187 * ref_value object is not very much use without the enclosing
188 * ref_entry).
190 * Reference names cannot end with slash and directories' names are
191 * always stored with a trailing slash (except for the top-level
192 * directory, which is always denoted by ""). This has two nice
193 * consequences: (1) when the entries in each subdir are sorted
194 * lexicographically by name (as they usually are), the references in
195 * a whole tree can be generated in lexicographic order by traversing
196 * the tree in left-to-right, depth-first order; (2) the names of
197 * references and subdirectories cannot conflict, and therefore the
198 * presence of an empty subdirectory does not block the creation of a
199 * similarly-named reference. (The fact that reference names with the
200 * same leading components can conflict *with each other* is a
201 * separate issue that is regulated by is_refname_available().)
203 * Please note that the name field contains the fully-qualified
204 * reference (or subdirectory) name. Space could be saved by only
205 * storing the relative names. But that would require the full names
206 * to be generated on the fly when iterating in do_for_each_ref(), and
207 * would break callback functions, who have always been able to assume
208 * that the name strings that they are passed will not be freed during
209 * the iteration.
211 struct ref_entry {
212 unsigned char flag; /* ISSYMREF? ISPACKED? */
213 union {
214 struct ref_value value; /* if not (flags&REF_DIR) */
215 struct ref_dir subdir; /* if (flags&REF_DIR) */
216 } u;
218 * The full name of the reference (e.g., "refs/heads/master")
219 * or the full name of the directory with a trailing slash
220 * (e.g., "refs/heads/"):
222 char name[FLEX_ARRAY];
225 static void read_loose_refs(const char *dirname, struct ref_dir *dir);
227 static struct ref_dir *get_ref_dir(struct ref_entry *entry)
229 struct ref_dir *dir;
230 assert(entry->flag & REF_DIR);
231 dir = &entry->u.subdir;
232 if (entry->flag & REF_INCOMPLETE) {
233 read_loose_refs(entry->name, dir);
234 entry->flag &= ~REF_INCOMPLETE;
236 return dir;
239 static struct ref_entry *create_ref_entry(const char *refname,
240 const unsigned char *sha1, int flag,
241 int check_name)
243 int len;
244 struct ref_entry *ref;
246 if (check_name &&
247 check_refname_format(refname, REFNAME_ALLOW_ONELEVEL|REFNAME_DOT_COMPONENT))
248 die("Reference has invalid format: '%s'", refname);
249 len = strlen(refname) + 1;
250 ref = xmalloc(sizeof(struct ref_entry) + len);
251 hashcpy(ref->u.value.sha1, sha1);
252 hashclr(ref->u.value.peeled);
253 memcpy(ref->name, refname, len);
254 ref->flag = flag;
255 return ref;
258 static void clear_ref_dir(struct ref_dir *dir);
260 static void free_ref_entry(struct ref_entry *entry)
262 if (entry->flag & REF_DIR)
263 clear_ref_dir(get_ref_dir(entry));
264 free(entry);
268 * Add a ref_entry to the end of dir (unsorted). Entry is always
269 * stored directly in dir; no recursion into subdirectories is
270 * done.
272 static void add_entry_to_dir(struct ref_dir *dir, struct ref_entry *entry)
274 ALLOC_GROW(dir->entries, dir->nr + 1, dir->alloc);
275 dir->entries[dir->nr++] = entry;
279 * Clear and free all entries in dir, recursively.
281 static void clear_ref_dir(struct ref_dir *dir)
283 int i;
284 for (i = 0; i < dir->nr; i++)
285 free_ref_entry(dir->entries[i]);
286 free(dir->entries);
287 dir->sorted = dir->nr = dir->alloc = 0;
288 dir->entries = NULL;
292 * Create a struct ref_entry object for the specified dirname.
293 * dirname is the name of the directory with a trailing slash (e.g.,
294 * "refs/heads/") or "" for the top-level directory.
296 static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache,
297 const char *dirname, size_t len,
298 int incomplete)
300 struct ref_entry *direntry;
301 direntry = xcalloc(1, sizeof(struct ref_entry) + len + 1);
302 memcpy(direntry->name, dirname, len);
303 direntry->name[len] = '\0';
304 direntry->u.subdir.ref_cache = ref_cache;
305 direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE : 0);
306 return direntry;
309 static int ref_entry_cmp(const void *a, const void *b)
311 struct ref_entry *one = *(struct ref_entry **)a;
312 struct ref_entry *two = *(struct ref_entry **)b;
313 return strcmp(one->name, two->name);
316 static void sort_ref_dir(struct ref_dir *dir);
318 struct string_slice {
319 size_t len;
320 const char *str;
323 static int ref_entry_cmp_sslice(const void *key_, const void *ent_)
325 const struct string_slice *key = key_;
326 const struct ref_entry *ent = *(const struct ref_entry * const *)ent_;
327 int cmp = strncmp(key->str, ent->name, key->len);
328 if (cmp)
329 return cmp;
330 return '\0' - (unsigned char)ent->name[key->len];
334 * Return the entry with the given refname from the ref_dir
335 * (non-recursively), sorting dir if necessary. Return NULL if no
336 * such entry is found. dir must already be complete.
338 static struct ref_entry *search_ref_dir(struct ref_dir *dir,
339 const char *refname, size_t len)
341 struct ref_entry **r;
342 struct string_slice key;
344 if (refname == NULL || !dir->nr)
345 return NULL;
347 sort_ref_dir(dir);
348 key.len = len;
349 key.str = refname;
350 r = bsearch(&key, dir->entries, dir->nr, sizeof(*dir->entries),
351 ref_entry_cmp_sslice);
353 if (r == NULL)
354 return NULL;
356 return *r;
360 * Search for a directory entry directly within dir (without
361 * recursing). Sort dir if necessary. subdirname must be a directory
362 * name (i.e., end in '/'). If mkdir is set, then create the
363 * directory if it is missing; otherwise, return NULL if the desired
364 * directory cannot be found. dir must already be complete.
366 static struct ref_dir *search_for_subdir(struct ref_dir *dir,
367 const char *subdirname, size_t len,
368 int mkdir)
370 struct ref_entry *entry = search_ref_dir(dir, subdirname, len);
371 if (!entry) {
372 if (!mkdir)
373 return NULL;
375 * Since dir is complete, the absence of a subdir
376 * means that the subdir really doesn't exist;
377 * therefore, create an empty record for it but mark
378 * the record complete.
380 entry = create_dir_entry(dir->ref_cache, subdirname, len, 0);
381 add_entry_to_dir(dir, entry);
383 return get_ref_dir(entry);
387 * If refname is a reference name, find the ref_dir within the dir
388 * tree that should hold refname. If refname is a directory name
389 * (i.e., ends in '/'), then return that ref_dir itself. dir must
390 * represent the top-level directory and must already be complete.
391 * Sort ref_dirs and recurse into subdirectories as necessary. If
392 * mkdir is set, then create any missing directories; otherwise,
393 * return NULL if the desired directory cannot be found.
395 static struct ref_dir *find_containing_dir(struct ref_dir *dir,
396 const char *refname, int mkdir)
398 const char *slash;
399 for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) {
400 size_t dirnamelen = slash - refname + 1;
401 struct ref_dir *subdir;
402 subdir = search_for_subdir(dir, refname, dirnamelen, mkdir);
403 if (!subdir) {
404 dir = NULL;
405 break;
407 dir = subdir;
410 return dir;
414 * Find the value entry with the given name in dir, sorting ref_dirs
415 * and recursing into subdirectories as necessary. If the name is not
416 * found or it corresponds to a directory entry, return NULL.
418 static struct ref_entry *find_ref(struct ref_dir *dir, const char *refname)
420 struct ref_entry *entry;
421 dir = find_containing_dir(dir, refname, 0);
422 if (!dir)
423 return NULL;
424 entry = search_ref_dir(dir, refname, strlen(refname));
425 return (entry && !(entry->flag & REF_DIR)) ? entry : NULL;
429 * Add a ref_entry to the ref_dir (unsorted), recursing into
430 * subdirectories as necessary. dir must represent the top-level
431 * directory. Return 0 on success.
433 static int add_ref(struct ref_dir *dir, struct ref_entry *ref)
435 dir = find_containing_dir(dir, ref->name, 1);
436 if (!dir)
437 return -1;
438 add_entry_to_dir(dir, ref);
439 return 0;
443 * Emit a warning and return true iff ref1 and ref2 have the same name
444 * and the same sha1. Die if they have the same name but different
445 * sha1s.
447 static int is_dup_ref(const struct ref_entry *ref1, const struct ref_entry *ref2)
449 if (strcmp(ref1->name, ref2->name))
450 return 0;
452 /* Duplicate name; make sure that they don't conflict: */
454 if ((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR))
455 /* This is impossible by construction */
456 die("Reference directory conflict: %s", ref1->name);
458 if (hashcmp(ref1->u.value.sha1, ref2->u.value.sha1))
459 die("Duplicated ref, and SHA1s don't match: %s", ref1->name);
461 warning("Duplicated ref: %s", ref1->name);
462 return 1;
466 * Sort the entries in dir non-recursively (if they are not already
467 * sorted) and remove any duplicate entries.
469 static void sort_ref_dir(struct ref_dir *dir)
471 int i, j;
472 struct ref_entry *last = NULL;
475 * This check also prevents passing a zero-length array to qsort(),
476 * which is a problem on some platforms.
478 if (dir->sorted == dir->nr)
479 return;
481 qsort(dir->entries, dir->nr, sizeof(*dir->entries), ref_entry_cmp);
483 /* Remove any duplicates: */
484 for (i = 0, j = 0; j < dir->nr; j++) {
485 struct ref_entry *entry = dir->entries[j];
486 if (last && is_dup_ref(last, entry))
487 free_ref_entry(entry);
488 else
489 last = dir->entries[i++] = entry;
491 dir->sorted = dir->nr = i;
494 #define DO_FOR_EACH_INCLUDE_BROKEN 01
496 static struct ref_entry *current_ref;
498 static int do_one_ref(const char *base, each_ref_fn fn, int trim,
499 int flags, void *cb_data, struct ref_entry *entry)
501 int retval;
502 if (prefixcmp(entry->name, base))
503 return 0;
505 if (!(flags & DO_FOR_EACH_INCLUDE_BROKEN)) {
506 if (entry->flag & REF_ISBROKEN)
507 return 0; /* ignore broken refs e.g. dangling symref */
508 if (!has_sha1_file(entry->u.value.sha1)) {
509 error("%s does not point to a valid object!", entry->name);
510 return 0;
513 current_ref = entry;
514 retval = fn(entry->name + trim, entry->u.value.sha1, entry->flag, cb_data);
515 current_ref = NULL;
516 return retval;
520 * Call fn for each reference in dir that has index in the range
521 * offset <= index < dir->nr. Recurse into subdirectories that are in
522 * that index range, sorting them before iterating. This function
523 * does not sort dir itself; it should be sorted beforehand.
525 static int do_for_each_ref_in_dir(struct ref_dir *dir, int offset,
526 const char *base,
527 each_ref_fn fn, int trim, int flags, void *cb_data)
529 int i;
530 assert(dir->sorted == dir->nr);
531 for (i = offset; i < dir->nr; i++) {
532 struct ref_entry *entry = dir->entries[i];
533 int retval;
534 if (entry->flag & REF_DIR) {
535 struct ref_dir *subdir = get_ref_dir(entry);
536 sort_ref_dir(subdir);
537 retval = do_for_each_ref_in_dir(subdir, 0,
538 base, fn, trim, flags, cb_data);
539 } else {
540 retval = do_one_ref(base, fn, trim, flags, cb_data, entry);
542 if (retval)
543 return retval;
545 return 0;
549 * Call fn for each reference in the union of dir1 and dir2, in order
550 * by refname. Recurse into subdirectories. If a value entry appears
551 * in both dir1 and dir2, then only process the version that is in
552 * dir2. The input dirs must already be sorted, but subdirs will be
553 * sorted as needed.
555 static int do_for_each_ref_in_dirs(struct ref_dir *dir1,
556 struct ref_dir *dir2,
557 const char *base, each_ref_fn fn, int trim,
558 int flags, void *cb_data)
560 int retval;
561 int i1 = 0, i2 = 0;
563 assert(dir1->sorted == dir1->nr);
564 assert(dir2->sorted == dir2->nr);
565 while (1) {
566 struct ref_entry *e1, *e2;
567 int cmp;
568 if (i1 == dir1->nr) {
569 return do_for_each_ref_in_dir(dir2, i2,
570 base, fn, trim, flags, cb_data);
572 if (i2 == dir2->nr) {
573 return do_for_each_ref_in_dir(dir1, i1,
574 base, fn, trim, flags, cb_data);
576 e1 = dir1->entries[i1];
577 e2 = dir2->entries[i2];
578 cmp = strcmp(e1->name, e2->name);
579 if (cmp == 0) {
580 if ((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) {
581 /* Both are directories; descend them in parallel. */
582 struct ref_dir *subdir1 = get_ref_dir(e1);
583 struct ref_dir *subdir2 = get_ref_dir(e2);
584 sort_ref_dir(subdir1);
585 sort_ref_dir(subdir2);
586 retval = do_for_each_ref_in_dirs(
587 subdir1, subdir2,
588 base, fn, trim, flags, cb_data);
589 i1++;
590 i2++;
591 } else if (!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) {
592 /* Both are references; ignore the one from dir1. */
593 retval = do_one_ref(base, fn, trim, flags, cb_data, e2);
594 i1++;
595 i2++;
596 } else {
597 die("conflict between reference and directory: %s",
598 e1->name);
600 } else {
601 struct ref_entry *e;
602 if (cmp < 0) {
603 e = e1;
604 i1++;
605 } else {
606 e = e2;
607 i2++;
609 if (e->flag & REF_DIR) {
610 struct ref_dir *subdir = get_ref_dir(e);
611 sort_ref_dir(subdir);
612 retval = do_for_each_ref_in_dir(
613 subdir, 0,
614 base, fn, trim, flags, cb_data);
615 } else {
616 retval = do_one_ref(base, fn, trim, flags, cb_data, e);
619 if (retval)
620 return retval;
622 if (i1 < dir1->nr)
623 return do_for_each_ref_in_dir(dir1, i1,
624 base, fn, trim, flags, cb_data);
625 if (i2 < dir2->nr)
626 return do_for_each_ref_in_dir(dir2, i2,
627 base, fn, trim, flags, cb_data);
628 return 0;
632 * Return true iff refname1 and refname2 conflict with each other.
633 * Two reference names conflict if one of them exactly matches the
634 * leading components of the other; e.g., "foo/bar" conflicts with
635 * both "foo" and with "foo/bar/baz" but not with "foo/bar" or
636 * "foo/barbados".
638 static int names_conflict(const char *refname1, const char *refname2)
640 for (; *refname1 && *refname1 == *refname2; refname1++, refname2++)
642 return (*refname1 == '\0' && *refname2 == '/')
643 || (*refname1 == '/' && *refname2 == '\0');
646 struct name_conflict_cb {
647 const char *refname;
648 const char *oldrefname;
649 const char *conflicting_refname;
652 static int name_conflict_fn(const char *existingrefname, const unsigned char *sha1,
653 int flags, void *cb_data)
655 struct name_conflict_cb *data = (struct name_conflict_cb *)cb_data;
656 if (data->oldrefname && !strcmp(data->oldrefname, existingrefname))
657 return 0;
658 if (names_conflict(data->refname, existingrefname)) {
659 data->conflicting_refname = existingrefname;
660 return 1;
662 return 0;
666 * Return true iff a reference named refname could be created without
667 * conflicting with the name of an existing reference in array. If
668 * oldrefname is non-NULL, ignore potential conflicts with oldrefname
669 * (e.g., because oldrefname is scheduled for deletion in the same
670 * operation).
672 static int is_refname_available(const char *refname, const char *oldrefname,
673 struct ref_dir *dir)
675 struct name_conflict_cb data;
676 data.refname = refname;
677 data.oldrefname = oldrefname;
678 data.conflicting_refname = NULL;
680 sort_ref_dir(dir);
681 if (do_for_each_ref_in_dir(dir, 0, "", name_conflict_fn,
682 0, DO_FOR_EACH_INCLUDE_BROKEN,
683 &data)) {
684 error("'%s' exists; cannot create '%s'",
685 data.conflicting_refname, refname);
686 return 0;
688 return 1;
692 * Future: need to be in "struct repository"
693 * when doing a full libification.
695 static struct ref_cache {
696 struct ref_cache *next;
697 struct ref_entry *loose;
698 struct ref_entry *packed;
699 /* The submodule name, or "" for the main repo. */
700 char name[FLEX_ARRAY];
701 } *ref_cache;
703 static void clear_packed_ref_cache(struct ref_cache *refs)
705 if (refs->packed) {
706 free_ref_entry(refs->packed);
707 refs->packed = NULL;
711 static void clear_loose_ref_cache(struct ref_cache *refs)
713 if (refs->loose) {
714 free_ref_entry(refs->loose);
715 refs->loose = NULL;
719 static struct ref_cache *create_ref_cache(const char *submodule)
721 int len;
722 struct ref_cache *refs;
723 if (!submodule)
724 submodule = "";
725 len = strlen(submodule) + 1;
726 refs = xcalloc(1, sizeof(struct ref_cache) + len);
727 memcpy(refs->name, submodule, len);
728 return refs;
732 * Return a pointer to a ref_cache for the specified submodule. For
733 * the main repository, use submodule==NULL. The returned structure
734 * will be allocated and initialized but not necessarily populated; it
735 * should not be freed.
737 static struct ref_cache *get_ref_cache(const char *submodule)
739 struct ref_cache *refs = ref_cache;
740 if (!submodule)
741 submodule = "";
742 while (refs) {
743 if (!strcmp(submodule, refs->name))
744 return refs;
745 refs = refs->next;
748 refs = create_ref_cache(submodule);
749 refs->next = ref_cache;
750 ref_cache = refs;
751 return refs;
754 void invalidate_ref_cache(const char *submodule)
756 struct ref_cache *refs = get_ref_cache(submodule);
757 clear_packed_ref_cache(refs);
758 clear_loose_ref_cache(refs);
762 * Parse one line from a packed-refs file. Write the SHA1 to sha1.
763 * Return a pointer to the refname within the line (null-terminated),
764 * or NULL if there was a problem.
766 static const char *parse_ref_line(char *line, unsigned char *sha1)
769 * 42: the answer to everything.
771 * In this case, it happens to be the answer to
772 * 40 (length of sha1 hex representation)
773 * +1 (space in between hex and name)
774 * +1 (newline at the end of the line)
776 int len = strlen(line) - 42;
778 if (len <= 0)
779 return NULL;
780 if (get_sha1_hex(line, sha1) < 0)
781 return NULL;
782 if (!isspace(line[40]))
783 return NULL;
784 line += 41;
785 if (isspace(*line))
786 return NULL;
787 if (line[len] != '\n')
788 return NULL;
789 line[len] = 0;
791 return line;
794 static void read_packed_refs(FILE *f, struct ref_dir *dir)
796 struct ref_entry *last = NULL;
797 char refline[PATH_MAX];
798 int flag = REF_ISPACKED;
800 while (fgets(refline, sizeof(refline), f)) {
801 unsigned char sha1[20];
802 const char *refname;
803 static const char header[] = "# pack-refs with:";
805 if (!strncmp(refline, header, sizeof(header)-1)) {
806 const char *traits = refline + sizeof(header) - 1;
807 if (strstr(traits, " peeled "))
808 flag |= REF_KNOWS_PEELED;
809 /* perhaps other traits later as well */
810 continue;
813 refname = parse_ref_line(refline, sha1);
814 if (refname) {
815 last = create_ref_entry(refname, sha1, flag, 1);
816 add_ref(dir, last);
817 continue;
819 if (last &&
820 refline[0] == '^' &&
821 strlen(refline) == 42 &&
822 refline[41] == '\n' &&
823 !get_sha1_hex(refline + 1, sha1))
824 hashcpy(last->u.value.peeled, sha1);
828 static struct ref_dir *get_packed_refs(struct ref_cache *refs)
830 if (!refs->packed) {
831 const char *packed_refs_file;
832 FILE *f;
834 refs->packed = create_dir_entry(refs, "", 0, 0);
835 if (*refs->name)
836 packed_refs_file = git_path_submodule(refs->name, "packed-refs");
837 else
838 packed_refs_file = git_path("packed-refs");
839 f = fopen(packed_refs_file, "r");
840 if (f) {
841 read_packed_refs(f, get_ref_dir(refs->packed));
842 fclose(f);
845 return get_ref_dir(refs->packed);
848 void add_packed_ref(const char *refname, const unsigned char *sha1)
850 add_ref(get_packed_refs(get_ref_cache(NULL)),
851 create_ref_entry(refname, sha1, REF_ISPACKED, 1));
855 * Read the loose references from the namespace dirname into dir
856 * (without recursing). dirname must end with '/'. dir must be the
857 * directory entry corresponding to dirname.
859 static void read_loose_refs(const char *dirname, struct ref_dir *dir)
861 struct ref_cache *refs = dir->ref_cache;
862 DIR *d;
863 const char *path;
864 struct dirent *de;
865 int dirnamelen = strlen(dirname);
866 struct strbuf refname;
868 if (*refs->name)
869 path = git_path_submodule(refs->name, "%s", dirname);
870 else
871 path = git_path("%s", dirname);
873 d = opendir(path);
874 if (!d)
875 return;
877 strbuf_init(&refname, dirnamelen + 257);
878 strbuf_add(&refname, dirname, dirnamelen);
880 while ((de = readdir(d)) != NULL) {
881 unsigned char sha1[20];
882 struct stat st;
883 int flag;
884 const char *refdir;
886 if (de->d_name[0] == '.')
887 continue;
888 if (has_extension(de->d_name, ".lock"))
889 continue;
890 strbuf_addstr(&refname, de->d_name);
891 refdir = *refs->name
892 ? git_path_submodule(refs->name, "%s", refname.buf)
893 : git_path("%s", refname.buf);
894 if (stat(refdir, &st) < 0) {
895 ; /* silently ignore */
896 } else if (S_ISDIR(st.st_mode)) {
897 strbuf_addch(&refname, '/');
898 add_entry_to_dir(dir,
899 create_dir_entry(refs, refname.buf,
900 refname.len, 1));
901 } else {
902 if (*refs->name) {
903 hashclr(sha1);
904 flag = 0;
905 if (resolve_gitlink_ref(refs->name, refname.buf, sha1) < 0) {
906 hashclr(sha1);
907 flag |= REF_ISBROKEN;
909 } else if (read_ref_full(refname.buf, sha1, 1, &flag)) {
910 hashclr(sha1);
911 flag |= REF_ISBROKEN;
913 add_entry_to_dir(dir,
914 create_ref_entry(refname.buf, sha1, flag, 1));
916 strbuf_setlen(&refname, dirnamelen);
918 strbuf_release(&refname);
919 closedir(d);
922 static struct ref_dir *get_loose_refs(struct ref_cache *refs)
924 if (!refs->loose) {
926 * Mark the top-level directory complete because we
927 * are about to read the only subdirectory that can
928 * hold references:
930 refs->loose = create_dir_entry(refs, "", 0, 0);
932 * Create an incomplete entry for "refs/":
934 add_entry_to_dir(get_ref_dir(refs->loose),
935 create_dir_entry(refs, "refs/", 5, 1));
937 return get_ref_dir(refs->loose);
940 /* We allow "recursive" symbolic refs. Only within reason, though */
941 #define MAXDEPTH 5
942 #define MAXREFLEN (1024)
945 * Called by resolve_gitlink_ref_recursive() after it failed to read
946 * from the loose refs in ref_cache refs. Find <refname> in the
947 * packed-refs file for the submodule.
949 static int resolve_gitlink_packed_ref(struct ref_cache *refs,
950 const char *refname, unsigned char *sha1)
952 struct ref_entry *ref;
953 struct ref_dir *dir = get_packed_refs(refs);
955 ref = find_ref(dir, refname);
956 if (ref == NULL)
957 return -1;
959 memcpy(sha1, ref->u.value.sha1, 20);
960 return 0;
963 static int resolve_gitlink_ref_recursive(struct ref_cache *refs,
964 const char *refname, unsigned char *sha1,
965 int recursion)
967 int fd, len;
968 char buffer[128], *p;
969 char *path;
971 if (recursion > MAXDEPTH || strlen(refname) > MAXREFLEN)
972 return -1;
973 path = *refs->name
974 ? git_path_submodule(refs->name, "%s", refname)
975 : git_path("%s", refname);
976 fd = open(path, O_RDONLY);
977 if (fd < 0)
978 return resolve_gitlink_packed_ref(refs, refname, sha1);
980 len = read(fd, buffer, sizeof(buffer)-1);
981 close(fd);
982 if (len < 0)
983 return -1;
984 while (len && isspace(buffer[len-1]))
985 len--;
986 buffer[len] = 0;
988 /* Was it a detached head or an old-fashioned symlink? */
989 if (!get_sha1_hex(buffer, sha1))
990 return 0;
992 /* Symref? */
993 if (strncmp(buffer, "ref:", 4))
994 return -1;
995 p = buffer + 4;
996 while (isspace(*p))
997 p++;
999 return resolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);
1002 int resolve_gitlink_ref(const char *path, const char *refname, unsigned char *sha1)
1004 int len = strlen(path), retval;
1005 char *submodule;
1006 struct ref_cache *refs;
1008 while (len && path[len-1] == '/')
1009 len--;
1010 if (!len)
1011 return -1;
1012 submodule = xstrndup(path, len);
1013 refs = get_ref_cache(submodule);
1014 free(submodule);
1016 retval = resolve_gitlink_ref_recursive(refs, refname, sha1, 0);
1017 return retval;
1021 * Try to read ref from the packed references. On success, set sha1
1022 * and return 0; otherwise, return -1.
1024 static int get_packed_ref(const char *refname, unsigned char *sha1)
1026 struct ref_dir *packed = get_packed_refs(get_ref_cache(NULL));
1027 struct ref_entry *entry = find_ref(packed, refname);
1028 if (entry) {
1029 hashcpy(sha1, entry->u.value.sha1);
1030 return 0;
1032 return -1;
1035 const char *resolve_ref_unsafe(const char *refname, unsigned char *sha1, int reading, int *flag)
1037 int depth = MAXDEPTH;
1038 ssize_t len;
1039 char buffer[256];
1040 static char refname_buffer[256];
1042 if (flag)
1043 *flag = 0;
1045 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL))
1046 return NULL;
1048 for (;;) {
1049 char path[PATH_MAX];
1050 struct stat st;
1051 char *buf;
1052 int fd;
1054 if (--depth < 0)
1055 return NULL;
1057 git_snpath(path, sizeof(path), "%s", refname);
1059 if (lstat(path, &st) < 0) {
1060 if (errno != ENOENT)
1061 return NULL;
1063 * The loose reference file does not exist;
1064 * check for a packed reference.
1066 if (!get_packed_ref(refname, sha1)) {
1067 if (flag)
1068 *flag |= REF_ISPACKED;
1069 return refname;
1071 /* The reference is not a packed reference, either. */
1072 if (reading) {
1073 return NULL;
1074 } else {
1075 hashclr(sha1);
1076 return refname;
1080 /* Follow "normalized" - ie "refs/.." symlinks by hand */
1081 if (S_ISLNK(st.st_mode)) {
1082 len = readlink(path, buffer, sizeof(buffer)-1);
1083 if (len < 0)
1084 return NULL;
1085 buffer[len] = 0;
1086 if (!prefixcmp(buffer, "refs/") &&
1087 !check_refname_format(buffer, 0)) {
1088 strcpy(refname_buffer, buffer);
1089 refname = refname_buffer;
1090 if (flag)
1091 *flag |= REF_ISSYMREF;
1092 continue;
1096 /* Is it a directory? */
1097 if (S_ISDIR(st.st_mode)) {
1098 errno = EISDIR;
1099 return NULL;
1103 * Anything else, just open it and try to use it as
1104 * a ref
1106 fd = open(path, O_RDONLY);
1107 if (fd < 0)
1108 return NULL;
1109 len = read_in_full(fd, buffer, sizeof(buffer)-1);
1110 close(fd);
1111 if (len < 0)
1112 return NULL;
1113 while (len && isspace(buffer[len-1]))
1114 len--;
1115 buffer[len] = '\0';
1118 * Is it a symbolic ref?
1120 if (prefixcmp(buffer, "ref:"))
1121 break;
1122 if (flag)
1123 *flag |= REF_ISSYMREF;
1124 buf = buffer + 4;
1125 while (isspace(*buf))
1126 buf++;
1127 if (check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {
1128 if (flag)
1129 *flag |= REF_ISBROKEN;
1130 return NULL;
1132 refname = strcpy(refname_buffer, buf);
1134 /* Please note that FETCH_HEAD has a second line containing other data. */
1135 if (get_sha1_hex(buffer, sha1) || (buffer[40] != '\0' && !isspace(buffer[40]))) {
1136 if (flag)
1137 *flag |= REF_ISBROKEN;
1138 return NULL;
1140 return refname;
1143 char *resolve_refdup(const char *ref, unsigned char *sha1, int reading, int *flag)
1145 const char *ret = resolve_ref_unsafe(ref, sha1, reading, flag);
1146 return ret ? xstrdup(ret) : NULL;
1149 /* The argument to filter_refs */
1150 struct ref_filter {
1151 const char *pattern;
1152 each_ref_fn *fn;
1153 void *cb_data;
1156 int read_ref_full(const char *refname, unsigned char *sha1, int reading, int *flags)
1158 if (resolve_ref_unsafe(refname, sha1, reading, flags))
1159 return 0;
1160 return -1;
1163 int read_ref(const char *refname, unsigned char *sha1)
1165 return read_ref_full(refname, sha1, 1, NULL);
1168 int ref_exists(const char *refname)
1170 unsigned char sha1[20];
1171 return !!resolve_ref_unsafe(refname, sha1, 1, NULL);
1174 static int filter_refs(const char *refname, const unsigned char *sha1, int flags,
1175 void *data)
1177 struct ref_filter *filter = (struct ref_filter *)data;
1178 if (fnmatch(filter->pattern, refname, 0))
1179 return 0;
1180 return filter->fn(refname, sha1, flags, filter->cb_data);
1183 int peel_ref(const char *refname, unsigned char *sha1)
1185 int flag;
1186 unsigned char base[20];
1187 struct object *o;
1189 if (current_ref && (current_ref->name == refname
1190 || !strcmp(current_ref->name, refname))) {
1191 if (current_ref->flag & REF_KNOWS_PEELED) {
1192 hashcpy(sha1, current_ref->u.value.peeled);
1193 return 0;
1195 hashcpy(base, current_ref->u.value.sha1);
1196 goto fallback;
1199 if (read_ref_full(refname, base, 1, &flag))
1200 return -1;
1202 if ((flag & REF_ISPACKED)) {
1203 struct ref_dir *dir = get_packed_refs(get_ref_cache(NULL));
1204 struct ref_entry *r = find_ref(dir, refname);
1206 if (r != NULL && r->flag & REF_KNOWS_PEELED) {
1207 hashcpy(sha1, r->u.value.peeled);
1208 return 0;
1212 fallback:
1213 o = parse_object(base);
1214 if (o && o->type == OBJ_TAG) {
1215 o = deref_tag(o, refname, 0);
1216 if (o) {
1217 hashcpy(sha1, o->sha1);
1218 return 0;
1221 return -1;
1224 struct warn_if_dangling_data {
1225 FILE *fp;
1226 const char *refname;
1227 const char *msg_fmt;
1230 static int warn_if_dangling_symref(const char *refname, const unsigned char *sha1,
1231 int flags, void *cb_data)
1233 struct warn_if_dangling_data *d = cb_data;
1234 const char *resolves_to;
1235 unsigned char junk[20];
1237 if (!(flags & REF_ISSYMREF))
1238 return 0;
1240 resolves_to = resolve_ref_unsafe(refname, junk, 0, NULL);
1241 if (!resolves_to || strcmp(resolves_to, d->refname))
1242 return 0;
1244 fprintf(d->fp, d->msg_fmt, refname);
1245 fputc('\n', d->fp);
1246 return 0;
1249 void warn_dangling_symref(FILE *fp, const char *msg_fmt, const char *refname)
1251 struct warn_if_dangling_data data;
1253 data.fp = fp;
1254 data.refname = refname;
1255 data.msg_fmt = msg_fmt;
1256 for_each_rawref(warn_if_dangling_symref, &data);
1259 static int do_for_each_ref(const char *submodule, const char *base, each_ref_fn fn,
1260 int trim, int flags, void *cb_data)
1262 struct ref_cache *refs = get_ref_cache(submodule);
1263 struct ref_dir *packed_dir = get_packed_refs(refs);
1264 struct ref_dir *loose_dir = get_loose_refs(refs);
1265 int retval = 0;
1267 if (base && *base) {
1268 packed_dir = find_containing_dir(packed_dir, base, 0);
1269 loose_dir = find_containing_dir(loose_dir, base, 0);
1272 if (packed_dir && loose_dir) {
1273 sort_ref_dir(packed_dir);
1274 sort_ref_dir(loose_dir);
1275 retval = do_for_each_ref_in_dirs(
1276 packed_dir, loose_dir,
1277 base, fn, trim, flags, cb_data);
1278 } else if (packed_dir) {
1279 sort_ref_dir(packed_dir);
1280 retval = do_for_each_ref_in_dir(
1281 packed_dir, 0,
1282 base, fn, trim, flags, cb_data);
1283 } else if (loose_dir) {
1284 sort_ref_dir(loose_dir);
1285 retval = do_for_each_ref_in_dir(
1286 loose_dir, 0,
1287 base, fn, trim, flags, cb_data);
1290 return retval;
1293 static int do_head_ref(const char *submodule, each_ref_fn fn, void *cb_data)
1295 unsigned char sha1[20];
1296 int flag;
1298 if (submodule) {
1299 if (resolve_gitlink_ref(submodule, "HEAD", sha1) == 0)
1300 return fn("HEAD", sha1, 0, cb_data);
1302 return 0;
1305 if (!read_ref_full("HEAD", sha1, 1, &flag))
1306 return fn("HEAD", sha1, flag, cb_data);
1308 return 0;
1311 int head_ref(each_ref_fn fn, void *cb_data)
1313 return do_head_ref(NULL, fn, cb_data);
1316 int head_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1318 return do_head_ref(submodule, fn, cb_data);
1321 int for_each_ref(each_ref_fn fn, void *cb_data)
1323 return do_for_each_ref(NULL, "", fn, 0, 0, cb_data);
1326 int for_each_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1328 return do_for_each_ref(submodule, "", fn, 0, 0, cb_data);
1331 int for_each_ref_in(const char *prefix, each_ref_fn fn, void *cb_data)
1333 return do_for_each_ref(NULL, prefix, fn, strlen(prefix), 0, cb_data);
1336 int for_each_ref_in_submodule(const char *submodule, const char *prefix,
1337 each_ref_fn fn, void *cb_data)
1339 return do_for_each_ref(submodule, prefix, fn, strlen(prefix), 0, cb_data);
1342 int for_each_tag_ref(each_ref_fn fn, void *cb_data)
1344 return for_each_ref_in("refs/tags/", fn, cb_data);
1347 int for_each_tag_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1349 return for_each_ref_in_submodule(submodule, "refs/tags/", fn, cb_data);
1352 int for_each_branch_ref(each_ref_fn fn, void *cb_data)
1354 return for_each_ref_in("refs/heads/", fn, cb_data);
1357 int for_each_branch_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1359 return for_each_ref_in_submodule(submodule, "refs/heads/", fn, cb_data);
1362 int for_each_remote_ref(each_ref_fn fn, void *cb_data)
1364 return for_each_ref_in("refs/remotes/", fn, cb_data);
1367 int for_each_remote_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1369 return for_each_ref_in_submodule(submodule, "refs/remotes/", fn, cb_data);
1372 int for_each_replace_ref(each_ref_fn fn, void *cb_data)
1374 return do_for_each_ref(NULL, "refs/replace/", fn, 13, 0, cb_data);
1377 int head_ref_namespaced(each_ref_fn fn, void *cb_data)
1379 struct strbuf buf = STRBUF_INIT;
1380 int ret = 0;
1381 unsigned char sha1[20];
1382 int flag;
1384 strbuf_addf(&buf, "%sHEAD", get_git_namespace());
1385 if (!read_ref_full(buf.buf, sha1, 1, &flag))
1386 ret = fn(buf.buf, sha1, flag, cb_data);
1387 strbuf_release(&buf);
1389 return ret;
1392 int for_each_namespaced_ref(each_ref_fn fn, void *cb_data)
1394 struct strbuf buf = STRBUF_INIT;
1395 int ret;
1396 strbuf_addf(&buf, "%srefs/", get_git_namespace());
1397 ret = do_for_each_ref(NULL, buf.buf, fn, 0, 0, cb_data);
1398 strbuf_release(&buf);
1399 return ret;
1402 int for_each_glob_ref_in(each_ref_fn fn, const char *pattern,
1403 const char *prefix, void *cb_data)
1405 struct strbuf real_pattern = STRBUF_INIT;
1406 struct ref_filter filter;
1407 int ret;
1409 if (!prefix && prefixcmp(pattern, "refs/"))
1410 strbuf_addstr(&real_pattern, "refs/");
1411 else if (prefix)
1412 strbuf_addstr(&real_pattern, prefix);
1413 strbuf_addstr(&real_pattern, pattern);
1415 if (!has_glob_specials(pattern)) {
1416 /* Append implied '/' '*' if not present. */
1417 if (real_pattern.buf[real_pattern.len - 1] != '/')
1418 strbuf_addch(&real_pattern, '/');
1419 /* No need to check for '*', there is none. */
1420 strbuf_addch(&real_pattern, '*');
1423 filter.pattern = real_pattern.buf;
1424 filter.fn = fn;
1425 filter.cb_data = cb_data;
1426 ret = for_each_ref(filter_refs, &filter);
1428 strbuf_release(&real_pattern);
1429 return ret;
1432 int for_each_glob_ref(each_ref_fn fn, const char *pattern, void *cb_data)
1434 return for_each_glob_ref_in(fn, pattern, NULL, cb_data);
1437 int for_each_rawref(each_ref_fn fn, void *cb_data)
1439 return do_for_each_ref(NULL, "", fn, 0,
1440 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);
1443 const char *prettify_refname(const char *name)
1445 return name + (
1446 !prefixcmp(name, "refs/heads/") ? 11 :
1447 !prefixcmp(name, "refs/tags/") ? 10 :
1448 !prefixcmp(name, "refs/remotes/") ? 13 :
1452 const char *ref_rev_parse_rules[] = {
1453 "%.*s",
1454 "refs/%.*s",
1455 "refs/tags/%.*s",
1456 "refs/heads/%.*s",
1457 "refs/remotes/%.*s",
1458 "refs/remotes/%.*s/HEAD",
1459 NULL
1462 int refname_match(const char *abbrev_name, const char *full_name, const char **rules)
1464 const char **p;
1465 const int abbrev_name_len = strlen(abbrev_name);
1467 for (p = rules; *p; p++) {
1468 if (!strcmp(full_name, mkpath(*p, abbrev_name_len, abbrev_name))) {
1469 return 1;
1473 return 0;
1476 static struct ref_lock *verify_lock(struct ref_lock *lock,
1477 const unsigned char *old_sha1, int mustexist)
1479 if (read_ref_full(lock->ref_name, lock->old_sha1, mustexist, NULL)) {
1480 error("Can't verify ref %s", lock->ref_name);
1481 unlock_ref(lock);
1482 return NULL;
1484 if (hashcmp(lock->old_sha1, old_sha1)) {
1485 error("Ref %s is at %s but expected %s", lock->ref_name,
1486 sha1_to_hex(lock->old_sha1), sha1_to_hex(old_sha1));
1487 unlock_ref(lock);
1488 return NULL;
1490 return lock;
1493 static int remove_empty_directories(const char *file)
1495 /* we want to create a file but there is a directory there;
1496 * if that is an empty directory (or a directory that contains
1497 * only empty directories), remove them.
1499 struct strbuf path;
1500 int result;
1502 strbuf_init(&path, 20);
1503 strbuf_addstr(&path, file);
1505 result = remove_dir_recursively(&path, REMOVE_DIR_EMPTY_ONLY);
1507 strbuf_release(&path);
1509 return result;
1513 * *string and *len will only be substituted, and *string returned (for
1514 * later free()ing) if the string passed in is a magic short-hand form
1515 * to name a branch.
1517 static char *substitute_branch_name(const char **string, int *len)
1519 struct strbuf buf = STRBUF_INIT;
1520 int ret = interpret_branch_name(*string, &buf);
1522 if (ret == *len) {
1523 size_t size;
1524 *string = strbuf_detach(&buf, &size);
1525 *len = size;
1526 return (char *)*string;
1529 return NULL;
1532 int dwim_ref(const char *str, int len, unsigned char *sha1, char **ref)
1534 char *last_branch = substitute_branch_name(&str, &len);
1535 const char **p, *r;
1536 int refs_found = 0;
1538 *ref = NULL;
1539 for (p = ref_rev_parse_rules; *p; p++) {
1540 char fullref[PATH_MAX];
1541 unsigned char sha1_from_ref[20];
1542 unsigned char *this_result;
1543 int flag;
1545 this_result = refs_found ? sha1_from_ref : sha1;
1546 mksnpath(fullref, sizeof(fullref), *p, len, str);
1547 r = resolve_ref_unsafe(fullref, this_result, 1, &flag);
1548 if (r) {
1549 if (!refs_found++)
1550 *ref = xstrdup(r);
1551 if (!warn_ambiguous_refs)
1552 break;
1553 } else if ((flag & REF_ISSYMREF) && strcmp(fullref, "HEAD")) {
1554 warning("ignoring dangling symref %s.", fullref);
1555 } else if ((flag & REF_ISBROKEN) && strchr(fullref, '/')) {
1556 warning("ignoring broken ref %s.", fullref);
1559 free(last_branch);
1560 return refs_found;
1563 int dwim_log(const char *str, int len, unsigned char *sha1, char **log)
1565 char *last_branch = substitute_branch_name(&str, &len);
1566 const char **p;
1567 int logs_found = 0;
1569 *log = NULL;
1570 for (p = ref_rev_parse_rules; *p; p++) {
1571 struct stat st;
1572 unsigned char hash[20];
1573 char path[PATH_MAX];
1574 const char *ref, *it;
1576 mksnpath(path, sizeof(path), *p, len, str);
1577 ref = resolve_ref_unsafe(path, hash, 1, NULL);
1578 if (!ref)
1579 continue;
1580 if (!stat(git_path("logs/%s", path), &st) &&
1581 S_ISREG(st.st_mode))
1582 it = path;
1583 else if (strcmp(ref, path) &&
1584 !stat(git_path("logs/%s", ref), &st) &&
1585 S_ISREG(st.st_mode))
1586 it = ref;
1587 else
1588 continue;
1589 if (!logs_found++) {
1590 *log = xstrdup(it);
1591 hashcpy(sha1, hash);
1593 if (!warn_ambiguous_refs)
1594 break;
1596 free(last_branch);
1597 return logs_found;
1600 static struct ref_lock *lock_ref_sha1_basic(const char *refname,
1601 const unsigned char *old_sha1,
1602 int flags, int *type_p)
1604 char *ref_file;
1605 const char *orig_refname = refname;
1606 struct ref_lock *lock;
1607 int last_errno = 0;
1608 int type, lflags;
1609 int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
1610 int missing = 0;
1612 lock = xcalloc(1, sizeof(struct ref_lock));
1613 lock->lock_fd = -1;
1615 refname = resolve_ref_unsafe(refname, lock->old_sha1, mustexist, &type);
1616 if (!refname && errno == EISDIR) {
1617 /* we are trying to lock foo but we used to
1618 * have foo/bar which now does not exist;
1619 * it is normal for the empty directory 'foo'
1620 * to remain.
1622 ref_file = git_path("%s", orig_refname);
1623 if (remove_empty_directories(ref_file)) {
1624 last_errno = errno;
1625 error("there are still refs under '%s'", orig_refname);
1626 goto error_return;
1628 refname = resolve_ref_unsafe(orig_refname, lock->old_sha1, mustexist, &type);
1630 if (type_p)
1631 *type_p = type;
1632 if (!refname) {
1633 last_errno = errno;
1634 error("unable to resolve reference %s: %s",
1635 orig_refname, strerror(errno));
1636 goto error_return;
1638 missing = is_null_sha1(lock->old_sha1);
1639 /* When the ref did not exist and we are creating it,
1640 * make sure there is no existing ref that is packed
1641 * whose name begins with our refname, nor a ref whose
1642 * name is a proper prefix of our refname.
1644 if (missing &&
1645 !is_refname_available(refname, NULL, get_packed_refs(get_ref_cache(NULL)))) {
1646 last_errno = ENOTDIR;
1647 goto error_return;
1650 lock->lk = xcalloc(1, sizeof(struct lock_file));
1652 lflags = LOCK_DIE_ON_ERROR;
1653 if (flags & REF_NODEREF) {
1654 refname = orig_refname;
1655 lflags |= LOCK_NODEREF;
1657 lock->ref_name = xstrdup(refname);
1658 lock->orig_ref_name = xstrdup(orig_refname);
1659 ref_file = git_path("%s", refname);
1660 if (missing)
1661 lock->force_write = 1;
1662 if ((flags & REF_NODEREF) && (type & REF_ISSYMREF))
1663 lock->force_write = 1;
1665 if (safe_create_leading_directories(ref_file)) {
1666 last_errno = errno;
1667 error("unable to create directory for %s", ref_file);
1668 goto error_return;
1671 lock->lock_fd = hold_lock_file_for_update(lock->lk, ref_file, lflags);
1672 return old_sha1 ? verify_lock(lock, old_sha1, mustexist) : lock;
1674 error_return:
1675 unlock_ref(lock);
1676 errno = last_errno;
1677 return NULL;
1680 struct ref_lock *lock_ref_sha1(const char *refname, const unsigned char *old_sha1)
1682 char refpath[PATH_MAX];
1683 if (check_refname_format(refname, 0))
1684 return NULL;
1685 strcpy(refpath, mkpath("refs/%s", refname));
1686 return lock_ref_sha1_basic(refpath, old_sha1, 0, NULL);
1689 struct ref_lock *lock_any_ref_for_update(const char *refname,
1690 const unsigned char *old_sha1, int flags)
1692 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL))
1693 return NULL;
1694 return lock_ref_sha1_basic(refname, old_sha1, flags, NULL);
1697 struct repack_without_ref_sb {
1698 const char *refname;
1699 int fd;
1702 static int repack_without_ref_fn(const char *refname, const unsigned char *sha1,
1703 int flags, void *cb_data)
1705 struct repack_without_ref_sb *data = cb_data;
1706 char line[PATH_MAX + 100];
1707 int len;
1709 if (!strcmp(data->refname, refname))
1710 return 0;
1711 len = snprintf(line, sizeof(line), "%s %s\n",
1712 sha1_to_hex(sha1), refname);
1713 /* this should not happen but just being defensive */
1714 if (len > sizeof(line))
1715 die("too long a refname '%s'", refname);
1716 write_or_die(data->fd, line, len);
1717 return 0;
1720 static struct lock_file packlock;
1722 static int repack_without_ref(const char *refname)
1724 struct repack_without_ref_sb data;
1725 struct ref_dir *packed = get_packed_refs(get_ref_cache(NULL));
1726 if (find_ref(packed, refname) == NULL)
1727 return 0;
1728 data.refname = refname;
1729 data.fd = hold_lock_file_for_update(&packlock, git_path("packed-refs"), 0);
1730 if (data.fd < 0) {
1731 unable_to_lock_error(git_path("packed-refs"), errno);
1732 return error("cannot delete '%s' from packed refs", refname);
1734 do_for_each_ref_in_dir(packed, 0, "", repack_without_ref_fn, 0, 0, &data);
1735 return commit_lock_file(&packlock);
1738 int delete_ref(const char *refname, const unsigned char *sha1, int delopt)
1740 struct ref_lock *lock;
1741 int err, i = 0, ret = 0, flag = 0;
1743 lock = lock_ref_sha1_basic(refname, sha1, 0, &flag);
1744 if (!lock)
1745 return 1;
1746 if (!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {
1747 /* loose */
1748 const char *path;
1750 if (!(delopt & REF_NODEREF)) {
1751 i = strlen(lock->lk->filename) - 5; /* .lock */
1752 lock->lk->filename[i] = 0;
1753 path = lock->lk->filename;
1754 } else {
1755 path = git_path("%s", refname);
1757 err = unlink_or_warn(path);
1758 if (err && errno != ENOENT)
1759 ret = 1;
1761 if (!(delopt & REF_NODEREF))
1762 lock->lk->filename[i] = '.';
1764 /* removing the loose one could have resurrected an earlier
1765 * packed one. Also, if it was not loose we need to repack
1766 * without it.
1768 ret |= repack_without_ref(refname);
1770 unlink_or_warn(git_path("logs/%s", lock->ref_name));
1771 invalidate_ref_cache(NULL);
1772 unlock_ref(lock);
1773 return ret;
1777 * People using contrib's git-new-workdir have .git/logs/refs ->
1778 * /some/other/path/.git/logs/refs, and that may live on another device.
1780 * IOW, to avoid cross device rename errors, the temporary renamed log must
1781 * live into logs/refs.
1783 #define TMP_RENAMED_LOG "logs/refs/.tmp-renamed-log"
1785 int rename_ref(const char *oldrefname, const char *newrefname, const char *logmsg)
1787 unsigned char sha1[20], orig_sha1[20];
1788 int flag = 0, logmoved = 0;
1789 struct ref_lock *lock;
1790 struct stat loginfo;
1791 int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);
1792 const char *symref = NULL;
1793 struct ref_cache *refs = get_ref_cache(NULL);
1795 if (log && S_ISLNK(loginfo.st_mode))
1796 return error("reflog for %s is a symlink", oldrefname);
1798 symref = resolve_ref_unsafe(oldrefname, orig_sha1, 1, &flag);
1799 if (flag & REF_ISSYMREF)
1800 return error("refname %s is a symbolic ref, renaming it is not supported",
1801 oldrefname);
1802 if (!symref)
1803 return error("refname %s not found", oldrefname);
1805 if (!is_refname_available(newrefname, oldrefname, get_packed_refs(refs)))
1806 return 1;
1808 if (!is_refname_available(newrefname, oldrefname, get_loose_refs(refs)))
1809 return 1;
1811 if (log && rename(git_path("logs/%s", oldrefname), git_path(TMP_RENAMED_LOG)))
1812 return error("unable to move logfile logs/%s to "TMP_RENAMED_LOG": %s",
1813 oldrefname, strerror(errno));
1815 if (delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {
1816 error("unable to delete old %s", oldrefname);
1817 goto rollback;
1820 if (!read_ref_full(newrefname, sha1, 1, &flag) &&
1821 delete_ref(newrefname, sha1, REF_NODEREF)) {
1822 if (errno==EISDIR) {
1823 if (remove_empty_directories(git_path("%s", newrefname))) {
1824 error("Directory not empty: %s", newrefname);
1825 goto rollback;
1827 } else {
1828 error("unable to delete existing %s", newrefname);
1829 goto rollback;
1833 if (log && safe_create_leading_directories(git_path("logs/%s", newrefname))) {
1834 error("unable to create directory for %s", newrefname);
1835 goto rollback;
1838 retry:
1839 if (log && rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", newrefname))) {
1840 if (errno==EISDIR || errno==ENOTDIR) {
1842 * rename(a, b) when b is an existing
1843 * directory ought to result in ISDIR, but
1844 * Solaris 5.8 gives ENOTDIR. Sheesh.
1846 if (remove_empty_directories(git_path("logs/%s", newrefname))) {
1847 error("Directory not empty: logs/%s", newrefname);
1848 goto rollback;
1850 goto retry;
1851 } else {
1852 error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s: %s",
1853 newrefname, strerror(errno));
1854 goto rollback;
1857 logmoved = log;
1859 lock = lock_ref_sha1_basic(newrefname, NULL, 0, NULL);
1860 if (!lock) {
1861 error("unable to lock %s for update", newrefname);
1862 goto rollback;
1864 lock->force_write = 1;
1865 hashcpy(lock->old_sha1, orig_sha1);
1866 if (write_ref_sha1(lock, orig_sha1, logmsg)) {
1867 error("unable to write current sha1 into %s", newrefname);
1868 goto rollback;
1871 return 0;
1873 rollback:
1874 lock = lock_ref_sha1_basic(oldrefname, NULL, 0, NULL);
1875 if (!lock) {
1876 error("unable to lock %s for rollback", oldrefname);
1877 goto rollbacklog;
1880 lock->force_write = 1;
1881 flag = log_all_ref_updates;
1882 log_all_ref_updates = 0;
1883 if (write_ref_sha1(lock, orig_sha1, NULL))
1884 error("unable to write current sha1 into %s", oldrefname);
1885 log_all_ref_updates = flag;
1887 rollbacklog:
1888 if (logmoved && rename(git_path("logs/%s", newrefname), git_path("logs/%s", oldrefname)))
1889 error("unable to restore logfile %s from %s: %s",
1890 oldrefname, newrefname, strerror(errno));
1891 if (!logmoved && log &&
1892 rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", oldrefname)))
1893 error("unable to restore logfile %s from "TMP_RENAMED_LOG": %s",
1894 oldrefname, strerror(errno));
1896 return 1;
1899 int close_ref(struct ref_lock *lock)
1901 if (close_lock_file(lock->lk))
1902 return -1;
1903 lock->lock_fd = -1;
1904 return 0;
1907 int commit_ref(struct ref_lock *lock)
1909 if (commit_lock_file(lock->lk))
1910 return -1;
1911 lock->lock_fd = -1;
1912 return 0;
1915 void unlock_ref(struct ref_lock *lock)
1917 /* Do not free lock->lk -- atexit() still looks at them */
1918 if (lock->lk)
1919 rollback_lock_file(lock->lk);
1920 free(lock->ref_name);
1921 free(lock->orig_ref_name);
1922 free(lock);
1926 * copy the reflog message msg to buf, which has been allocated sufficiently
1927 * large, while cleaning up the whitespaces. Especially, convert LF to space,
1928 * because reflog file is one line per entry.
1930 static int copy_msg(char *buf, const char *msg)
1932 char *cp = buf;
1933 char c;
1934 int wasspace = 1;
1936 *cp++ = '\t';
1937 while ((c = *msg++)) {
1938 if (wasspace && isspace(c))
1939 continue;
1940 wasspace = isspace(c);
1941 if (wasspace)
1942 c = ' ';
1943 *cp++ = c;
1945 while (buf < cp && isspace(cp[-1]))
1946 cp--;
1947 *cp++ = '\n';
1948 return cp - buf;
1951 int log_ref_setup(const char *refname, char *logfile, int bufsize)
1953 int logfd, oflags = O_APPEND | O_WRONLY;
1955 git_snpath(logfile, bufsize, "logs/%s", refname);
1956 if (log_all_ref_updates &&
1957 (!prefixcmp(refname, "refs/heads/") ||
1958 !prefixcmp(refname, "refs/remotes/") ||
1959 !prefixcmp(refname, "refs/notes/") ||
1960 !strcmp(refname, "HEAD"))) {
1961 if (safe_create_leading_directories(logfile) < 0)
1962 return error("unable to create directory for %s",
1963 logfile);
1964 oflags |= O_CREAT;
1967 logfd = open(logfile, oflags, 0666);
1968 if (logfd < 0) {
1969 if (!(oflags & O_CREAT) && errno == ENOENT)
1970 return 0;
1972 if ((oflags & O_CREAT) && errno == EISDIR) {
1973 if (remove_empty_directories(logfile)) {
1974 return error("There are still logs under '%s'",
1975 logfile);
1977 logfd = open(logfile, oflags, 0666);
1980 if (logfd < 0)
1981 return error("Unable to append to %s: %s",
1982 logfile, strerror(errno));
1985 adjust_shared_perm(logfile);
1986 close(logfd);
1987 return 0;
1990 static int log_ref_write(const char *refname, const unsigned char *old_sha1,
1991 const unsigned char *new_sha1, const char *msg)
1993 int logfd, result, written, oflags = O_APPEND | O_WRONLY;
1994 unsigned maxlen, len;
1995 int msglen;
1996 char log_file[PATH_MAX];
1997 char *logrec;
1998 const char *committer;
2000 if (log_all_ref_updates < 0)
2001 log_all_ref_updates = !is_bare_repository();
2003 result = log_ref_setup(refname, log_file, sizeof(log_file));
2004 if (result)
2005 return result;
2007 logfd = open(log_file, oflags);
2008 if (logfd < 0)
2009 return 0;
2010 msglen = msg ? strlen(msg) : 0;
2011 committer = git_committer_info(0);
2012 maxlen = strlen(committer) + msglen + 100;
2013 logrec = xmalloc(maxlen);
2014 len = sprintf(logrec, "%s %s %s\n",
2015 sha1_to_hex(old_sha1),
2016 sha1_to_hex(new_sha1),
2017 committer);
2018 if (msglen)
2019 len += copy_msg(logrec + len - 1, msg) - 1;
2020 written = len <= maxlen ? write_in_full(logfd, logrec, len) : -1;
2021 free(logrec);
2022 if (close(logfd) != 0 || written != len)
2023 return error("Unable to append to %s", log_file);
2024 return 0;
2027 static int is_branch(const char *refname)
2029 return !strcmp(refname, "HEAD") || !prefixcmp(refname, "refs/heads/");
2032 int write_ref_sha1(struct ref_lock *lock,
2033 const unsigned char *sha1, const char *logmsg)
2035 static char term = '\n';
2036 struct object *o;
2038 if (!lock)
2039 return -1;
2040 if (!lock->force_write && !hashcmp(lock->old_sha1, sha1)) {
2041 unlock_ref(lock);
2042 return 0;
2044 o = parse_object(sha1);
2045 if (!o) {
2046 error("Trying to write ref %s with nonexistent object %s",
2047 lock->ref_name, sha1_to_hex(sha1));
2048 unlock_ref(lock);
2049 return -1;
2051 if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
2052 error("Trying to write non-commit object %s to branch %s",
2053 sha1_to_hex(sha1), lock->ref_name);
2054 unlock_ref(lock);
2055 return -1;
2057 if (write_in_full(lock->lock_fd, sha1_to_hex(sha1), 40) != 40 ||
2058 write_in_full(lock->lock_fd, &term, 1) != 1
2059 || close_ref(lock) < 0) {
2060 error("Couldn't write %s", lock->lk->filename);
2061 unlock_ref(lock);
2062 return -1;
2064 clear_loose_ref_cache(get_ref_cache(NULL));
2065 if (log_ref_write(lock->ref_name, lock->old_sha1, sha1, logmsg) < 0 ||
2066 (strcmp(lock->ref_name, lock->orig_ref_name) &&
2067 log_ref_write(lock->orig_ref_name, lock->old_sha1, sha1, logmsg) < 0)) {
2068 unlock_ref(lock);
2069 return -1;
2071 if (strcmp(lock->orig_ref_name, "HEAD") != 0) {
2073 * Special hack: If a branch is updated directly and HEAD
2074 * points to it (may happen on the remote side of a push
2075 * for example) then logically the HEAD reflog should be
2076 * updated too.
2077 * A generic solution implies reverse symref information,
2078 * but finding all symrefs pointing to the given branch
2079 * would be rather costly for this rare event (the direct
2080 * update of a branch) to be worth it. So let's cheat and
2081 * check with HEAD only which should cover 99% of all usage
2082 * scenarios (even 100% of the default ones).
2084 unsigned char head_sha1[20];
2085 int head_flag;
2086 const char *head_ref;
2087 head_ref = resolve_ref_unsafe("HEAD", head_sha1, 1, &head_flag);
2088 if (head_ref && (head_flag & REF_ISSYMREF) &&
2089 !strcmp(head_ref, lock->ref_name))
2090 log_ref_write("HEAD", lock->old_sha1, sha1, logmsg);
2092 if (commit_ref(lock)) {
2093 error("Couldn't set %s", lock->ref_name);
2094 unlock_ref(lock);
2095 return -1;
2097 unlock_ref(lock);
2098 return 0;
2101 int create_symref(const char *ref_target, const char *refs_heads_master,
2102 const char *logmsg)
2104 const char *lockpath;
2105 char ref[1000];
2106 int fd, len, written;
2107 char *git_HEAD = git_pathdup("%s", ref_target);
2108 unsigned char old_sha1[20], new_sha1[20];
2110 if (logmsg && read_ref(ref_target, old_sha1))
2111 hashclr(old_sha1);
2113 if (safe_create_leading_directories(git_HEAD) < 0)
2114 return error("unable to create directory for %s", git_HEAD);
2116 #ifndef NO_SYMLINK_HEAD
2117 if (prefer_symlink_refs) {
2118 unlink(git_HEAD);
2119 if (!symlink(refs_heads_master, git_HEAD))
2120 goto done;
2121 fprintf(stderr, "no symlink - falling back to symbolic ref\n");
2123 #endif
2125 len = snprintf(ref, sizeof(ref), "ref: %s\n", refs_heads_master);
2126 if (sizeof(ref) <= len) {
2127 error("refname too long: %s", refs_heads_master);
2128 goto error_free_return;
2130 lockpath = mkpath("%s.lock", git_HEAD);
2131 fd = open(lockpath, O_CREAT | O_EXCL | O_WRONLY, 0666);
2132 if (fd < 0) {
2133 error("Unable to open %s for writing", lockpath);
2134 goto error_free_return;
2136 written = write_in_full(fd, ref, len);
2137 if (close(fd) != 0 || written != len) {
2138 error("Unable to write to %s", lockpath);
2139 goto error_unlink_return;
2141 if (rename(lockpath, git_HEAD) < 0) {
2142 error("Unable to create %s", git_HEAD);
2143 goto error_unlink_return;
2145 if (adjust_shared_perm(git_HEAD)) {
2146 error("Unable to fix permissions on %s", lockpath);
2147 error_unlink_return:
2148 unlink_or_warn(lockpath);
2149 error_free_return:
2150 free(git_HEAD);
2151 return -1;
2154 #ifndef NO_SYMLINK_HEAD
2155 done:
2156 #endif
2157 if (logmsg && !read_ref(refs_heads_master, new_sha1))
2158 log_ref_write(ref_target, old_sha1, new_sha1, logmsg);
2160 free(git_HEAD);
2161 return 0;
2164 static char *ref_msg(const char *line, const char *endp)
2166 const char *ep;
2167 line += 82;
2168 ep = memchr(line, '\n', endp - line);
2169 if (!ep)
2170 ep = endp;
2171 return xmemdupz(line, ep - line);
2174 int read_ref_at(const char *refname, unsigned long at_time, int cnt,
2175 unsigned char *sha1, char **msg,
2176 unsigned long *cutoff_time, int *cutoff_tz, int *cutoff_cnt)
2178 const char *logfile, *logdata, *logend, *rec, *lastgt, *lastrec;
2179 char *tz_c;
2180 int logfd, tz, reccnt = 0;
2181 struct stat st;
2182 unsigned long date;
2183 unsigned char logged_sha1[20];
2184 void *log_mapped;
2185 size_t mapsz;
2187 logfile = git_path("logs/%s", refname);
2188 logfd = open(logfile, O_RDONLY, 0);
2189 if (logfd < 0)
2190 die_errno("Unable to read log '%s'", logfile);
2191 fstat(logfd, &st);
2192 if (!st.st_size)
2193 die("Log %s is empty.", logfile);
2194 mapsz = xsize_t(st.st_size);
2195 log_mapped = xmmap(NULL, mapsz, PROT_READ, MAP_PRIVATE, logfd, 0);
2196 logdata = log_mapped;
2197 close(logfd);
2199 lastrec = NULL;
2200 rec = logend = logdata + st.st_size;
2201 while (logdata < rec) {
2202 reccnt++;
2203 if (logdata < rec && *(rec-1) == '\n')
2204 rec--;
2205 lastgt = NULL;
2206 while (logdata < rec && *(rec-1) != '\n') {
2207 rec--;
2208 if (*rec == '>')
2209 lastgt = rec;
2211 if (!lastgt)
2212 die("Log %s is corrupt.", logfile);
2213 date = strtoul(lastgt + 1, &tz_c, 10);
2214 if (date <= at_time || cnt == 0) {
2215 tz = strtoul(tz_c, NULL, 10);
2216 if (msg)
2217 *msg = ref_msg(rec, logend);
2218 if (cutoff_time)
2219 *cutoff_time = date;
2220 if (cutoff_tz)
2221 *cutoff_tz = tz;
2222 if (cutoff_cnt)
2223 *cutoff_cnt = reccnt - 1;
2224 if (lastrec) {
2225 if (get_sha1_hex(lastrec, logged_sha1))
2226 die("Log %s is corrupt.", logfile);
2227 if (get_sha1_hex(rec + 41, sha1))
2228 die("Log %s is corrupt.", logfile);
2229 if (hashcmp(logged_sha1, sha1)) {
2230 warning("Log %s has gap after %s.",
2231 logfile, show_date(date, tz, DATE_RFC2822));
2234 else if (date == at_time) {
2235 if (get_sha1_hex(rec + 41, sha1))
2236 die("Log %s is corrupt.", logfile);
2238 else {
2239 if (get_sha1_hex(rec + 41, logged_sha1))
2240 die("Log %s is corrupt.", logfile);
2241 if (hashcmp(logged_sha1, sha1)) {
2242 warning("Log %s unexpectedly ended on %s.",
2243 logfile, show_date(date, tz, DATE_RFC2822));
2246 munmap(log_mapped, mapsz);
2247 return 0;
2249 lastrec = rec;
2250 if (cnt > 0)
2251 cnt--;
2254 rec = logdata;
2255 while (rec < logend && *rec != '>' && *rec != '\n')
2256 rec++;
2257 if (rec == logend || *rec == '\n')
2258 die("Log %s is corrupt.", logfile);
2259 date = strtoul(rec + 1, &tz_c, 10);
2260 tz = strtoul(tz_c, NULL, 10);
2261 if (get_sha1_hex(logdata, sha1))
2262 die("Log %s is corrupt.", logfile);
2263 if (is_null_sha1(sha1)) {
2264 if (get_sha1_hex(logdata + 41, sha1))
2265 die("Log %s is corrupt.", logfile);
2267 if (msg)
2268 *msg = ref_msg(logdata, logend);
2269 munmap(log_mapped, mapsz);
2271 if (cutoff_time)
2272 *cutoff_time = date;
2273 if (cutoff_tz)
2274 *cutoff_tz = tz;
2275 if (cutoff_cnt)
2276 *cutoff_cnt = reccnt;
2277 return 1;
2280 int for_each_recent_reflog_ent(const char *refname, each_reflog_ent_fn fn, long ofs, void *cb_data)
2282 const char *logfile;
2283 FILE *logfp;
2284 struct strbuf sb = STRBUF_INIT;
2285 int ret = 0;
2287 logfile = git_path("logs/%s", refname);
2288 logfp = fopen(logfile, "r");
2289 if (!logfp)
2290 return -1;
2292 if (ofs) {
2293 struct stat statbuf;
2294 if (fstat(fileno(logfp), &statbuf) ||
2295 statbuf.st_size < ofs ||
2296 fseek(logfp, -ofs, SEEK_END) ||
2297 strbuf_getwholeline(&sb, logfp, '\n')) {
2298 fclose(logfp);
2299 strbuf_release(&sb);
2300 return -1;
2304 while (!strbuf_getwholeline(&sb, logfp, '\n')) {
2305 unsigned char osha1[20], nsha1[20];
2306 char *email_end, *message;
2307 unsigned long timestamp;
2308 int tz;
2310 /* old SP new SP name <email> SP time TAB msg LF */
2311 if (sb.len < 83 || sb.buf[sb.len - 1] != '\n' ||
2312 get_sha1_hex(sb.buf, osha1) || sb.buf[40] != ' ' ||
2313 get_sha1_hex(sb.buf + 41, nsha1) || sb.buf[81] != ' ' ||
2314 !(email_end = strchr(sb.buf + 82, '>')) ||
2315 email_end[1] != ' ' ||
2316 !(timestamp = strtoul(email_end + 2, &message, 10)) ||
2317 !message || message[0] != ' ' ||
2318 (message[1] != '+' && message[1] != '-') ||
2319 !isdigit(message[2]) || !isdigit(message[3]) ||
2320 !isdigit(message[4]) || !isdigit(message[5]))
2321 continue; /* corrupt? */
2322 email_end[1] = '\0';
2323 tz = strtol(message + 1, NULL, 10);
2324 if (message[6] != '\t')
2325 message += 6;
2326 else
2327 message += 7;
2328 ret = fn(osha1, nsha1, sb.buf + 82, timestamp, tz, message,
2329 cb_data);
2330 if (ret)
2331 break;
2333 fclose(logfp);
2334 strbuf_release(&sb);
2335 return ret;
2338 int for_each_reflog_ent(const char *refname, each_reflog_ent_fn fn, void *cb_data)
2340 return for_each_recent_reflog_ent(refname, fn, 0, cb_data);
2344 * Call fn for each reflog in the namespace indicated by name. name
2345 * must be empty or end with '/'. Name will be used as a scratch
2346 * space, but its contents will be restored before return.
2348 static int do_for_each_reflog(struct strbuf *name, each_ref_fn fn, void *cb_data)
2350 DIR *d = opendir(git_path("logs/%s", name->buf));
2351 int retval = 0;
2352 struct dirent *de;
2353 int oldlen = name->len;
2355 if (!d)
2356 return name->len ? errno : 0;
2358 while ((de = readdir(d)) != NULL) {
2359 struct stat st;
2361 if (de->d_name[0] == '.')
2362 continue;
2363 if (has_extension(de->d_name, ".lock"))
2364 continue;
2365 strbuf_addstr(name, de->d_name);
2366 if (stat(git_path("logs/%s", name->buf), &st) < 0) {
2367 ; /* silently ignore */
2368 } else {
2369 if (S_ISDIR(st.st_mode)) {
2370 strbuf_addch(name, '/');
2371 retval = do_for_each_reflog(name, fn, cb_data);
2372 } else {
2373 unsigned char sha1[20];
2374 if (read_ref_full(name->buf, sha1, 0, NULL))
2375 retval = error("bad ref for %s", name->buf);
2376 else
2377 retval = fn(name->buf, sha1, 0, cb_data);
2379 if (retval)
2380 break;
2382 strbuf_setlen(name, oldlen);
2384 closedir(d);
2385 return retval;
2388 int for_each_reflog(each_ref_fn fn, void *cb_data)
2390 int retval;
2391 struct strbuf name;
2392 strbuf_init(&name, PATH_MAX);
2393 retval = do_for_each_reflog(&name, fn, cb_data);
2394 strbuf_release(&name);
2395 return retval;
2398 int update_ref(const char *action, const char *refname,
2399 const unsigned char *sha1, const unsigned char *oldval,
2400 int flags, enum action_on_err onerr)
2402 static struct ref_lock *lock;
2403 lock = lock_any_ref_for_update(refname, oldval, flags);
2404 if (!lock) {
2405 const char *str = "Cannot lock the ref '%s'.";
2406 switch (onerr) {
2407 case MSG_ON_ERR: error(str, refname); break;
2408 case DIE_ON_ERR: die(str, refname); break;
2409 case QUIET_ON_ERR: break;
2411 return 1;
2413 if (write_ref_sha1(lock, sha1, action) < 0) {
2414 const char *str = "Cannot update the ref '%s'.";
2415 switch (onerr) {
2416 case MSG_ON_ERR: error(str, refname); break;
2417 case DIE_ON_ERR: die(str, refname); break;
2418 case QUIET_ON_ERR: break;
2420 return 1;
2422 return 0;
2425 struct ref *find_ref_by_name(const struct ref *list, const char *name)
2427 for ( ; list; list = list->next)
2428 if (!strcmp(list->name, name))
2429 return (struct ref *)list;
2430 return NULL;
2434 * generate a format suitable for scanf from a ref_rev_parse_rules
2435 * rule, that is replace the "%.*s" spec with a "%s" spec
2437 static void gen_scanf_fmt(char *scanf_fmt, const char *rule)
2439 char *spec;
2441 spec = strstr(rule, "%.*s");
2442 if (!spec || strstr(spec + 4, "%.*s"))
2443 die("invalid rule in ref_rev_parse_rules: %s", rule);
2445 /* copy all until spec */
2446 strncpy(scanf_fmt, rule, spec - rule);
2447 scanf_fmt[spec - rule] = '\0';
2448 /* copy new spec */
2449 strcat(scanf_fmt, "%s");
2450 /* copy remaining rule */
2451 strcat(scanf_fmt, spec + 4);
2453 return;
2456 char *shorten_unambiguous_ref(const char *refname, int strict)
2458 int i;
2459 static char **scanf_fmts;
2460 static int nr_rules;
2461 char *short_name;
2463 /* pre generate scanf formats from ref_rev_parse_rules[] */
2464 if (!nr_rules) {
2465 size_t total_len = 0;
2467 /* the rule list is NULL terminated, count them first */
2468 for (; ref_rev_parse_rules[nr_rules]; nr_rules++)
2469 /* no +1 because strlen("%s") < strlen("%.*s") */
2470 total_len += strlen(ref_rev_parse_rules[nr_rules]);
2472 scanf_fmts = xmalloc(nr_rules * sizeof(char *) + total_len);
2474 total_len = 0;
2475 for (i = 0; i < nr_rules; i++) {
2476 scanf_fmts[i] = (char *)&scanf_fmts[nr_rules]
2477 + total_len;
2478 gen_scanf_fmt(scanf_fmts[i], ref_rev_parse_rules[i]);
2479 total_len += strlen(ref_rev_parse_rules[i]);
2483 /* bail out if there are no rules */
2484 if (!nr_rules)
2485 return xstrdup(refname);
2487 /* buffer for scanf result, at most refname must fit */
2488 short_name = xstrdup(refname);
2490 /* skip first rule, it will always match */
2491 for (i = nr_rules - 1; i > 0 ; --i) {
2492 int j;
2493 int rules_to_fail = i;
2494 int short_name_len;
2496 if (1 != sscanf(refname, scanf_fmts[i], short_name))
2497 continue;
2499 short_name_len = strlen(short_name);
2502 * in strict mode, all (except the matched one) rules
2503 * must fail to resolve to a valid non-ambiguous ref
2505 if (strict)
2506 rules_to_fail = nr_rules;
2509 * check if the short name resolves to a valid ref,
2510 * but use only rules prior to the matched one
2512 for (j = 0; j < rules_to_fail; j++) {
2513 const char *rule = ref_rev_parse_rules[j];
2514 char refname[PATH_MAX];
2516 /* skip matched rule */
2517 if (i == j)
2518 continue;
2521 * the short name is ambiguous, if it resolves
2522 * (with this previous rule) to a valid ref
2523 * read_ref() returns 0 on success
2525 mksnpath(refname, sizeof(refname),
2526 rule, short_name_len, short_name);
2527 if (ref_exists(refname))
2528 break;
2532 * short name is non-ambiguous if all previous rules
2533 * haven't resolved to a valid ref
2535 if (j == rules_to_fail)
2536 return short_name;
2539 free(short_name);
2540 return xstrdup(refname);