resolve_gitlink_ref_recursive(): change to work with struct ref_cache
[git/dscho.git] / refs.c
blob7e6cea54588c6b77bc92e346079359b125de741e
1 #include "cache.h"
2 #include "refs.h"
3 #include "object.h"
4 #include "tag.h"
5 #include "dir.h"
7 /* ISSYMREF=01 and ISPACKED=02 are public interfaces */
8 #define REF_KNOWS_PEELED 04
9 #define REF_BROKEN 010
11 struct ref_entry {
12 unsigned char flag; /* ISSYMREF? ISPACKED? */
13 unsigned char sha1[20];
14 unsigned char peeled[20];
15 /* The full name of the reference (e.g., "refs/heads/master"): */
16 char name[FLEX_ARRAY];
19 struct ref_array {
20 int nr, alloc;
21 struct ref_entry **refs;
25 * Parse one line from a packed-refs file. Write the SHA1 to sha1.
26 * Return a pointer to the refname within the line (null-terminated),
27 * or NULL if there was a problem.
29 static const char *parse_ref_line(char *line, unsigned char *sha1)
32 * 42: the answer to everything.
34 * In this case, it happens to be the answer to
35 * 40 (length of sha1 hex representation)
36 * +1 (space in between hex and name)
37 * +1 (newline at the end of the line)
39 int len = strlen(line) - 42;
41 if (len <= 0)
42 return NULL;
43 if (get_sha1_hex(line, sha1) < 0)
44 return NULL;
45 if (!isspace(line[40]))
46 return NULL;
47 line += 41;
48 if (isspace(*line))
49 return NULL;
50 if (line[len] != '\n')
51 return NULL;
52 line[len] = 0;
54 return line;
57 /* Add a ref_entry to the end of the ref_array (unsorted). */
58 static void add_ref(const char *refname, const unsigned char *sha1,
59 int flag, struct ref_array *refs,
60 struct ref_entry **new_entry)
62 int len;
63 struct ref_entry *entry;
65 /* Allocate it and add it in.. */
66 len = strlen(refname) + 1;
67 entry = xmalloc(sizeof(struct ref_entry) + len);
68 hashcpy(entry->sha1, sha1);
69 hashclr(entry->peeled);
70 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL|REFNAME_DOT_COMPONENT))
71 die("Reference has invalid format: '%s'", refname);
72 memcpy(entry->name, refname, len);
73 entry->flag = flag;
74 if (new_entry)
75 *new_entry = entry;
76 ALLOC_GROW(refs->refs, refs->nr + 1, refs->alloc);
77 refs->refs[refs->nr++] = entry;
80 static int ref_entry_cmp(const void *a, const void *b)
82 struct ref_entry *one = *(struct ref_entry **)a;
83 struct ref_entry *two = *(struct ref_entry **)b;
84 return strcmp(one->name, two->name);
88 * Emit a warning and return true iff ref1 and ref2 have the same name
89 * and the same sha1. Die if they have the same name but different
90 * sha1s.
92 static int is_dup_ref(const struct ref_entry *ref1, const struct ref_entry *ref2)
94 if (!strcmp(ref1->name, ref2->name)) {
95 /* Duplicate name; make sure that the SHA1s match: */
96 if (hashcmp(ref1->sha1, ref2->sha1))
97 die("Duplicated ref, and SHA1s don't match: %s",
98 ref1->name);
99 warning("Duplicated ref: %s", ref1->name);
100 return 1;
101 } else {
102 return 0;
106 static void sort_ref_array(struct ref_array *array)
108 int i = 0, j = 1;
110 /* Nothing to sort unless there are at least two entries */
111 if (array->nr < 2)
112 return;
114 qsort(array->refs, array->nr, sizeof(*array->refs), ref_entry_cmp);
116 /* Remove any duplicates from the ref_array */
117 for (; j < array->nr; j++) {
118 struct ref_entry *a = array->refs[i];
119 struct ref_entry *b = array->refs[j];
120 if (is_dup_ref(a, b)) {
121 free(b);
122 continue;
124 i++;
125 array->refs[i] = array->refs[j];
127 array->nr = i + 1;
130 static struct ref_entry *search_ref_array(struct ref_array *array, const char *refname)
132 struct ref_entry *e, **r;
133 int len;
135 if (refname == NULL)
136 return NULL;
138 if (!array->nr)
139 return NULL;
141 len = strlen(refname) + 1;
142 e = xmalloc(sizeof(struct ref_entry) + len);
143 memcpy(e->name, refname, len);
145 r = bsearch(&e, array->refs, array->nr, sizeof(*array->refs), ref_entry_cmp);
147 free(e);
149 if (r == NULL)
150 return NULL;
152 return *r;
156 * Future: need to be in "struct repository"
157 * when doing a full libification.
159 static struct ref_cache {
160 struct ref_cache *next;
161 char did_loose;
162 char did_packed;
163 struct ref_array loose;
164 struct ref_array packed;
165 /* The submodule name, or "" for the main repo. */
166 char name[FLEX_ARRAY];
167 } *ref_cache;
169 static struct ref_entry *current_ref;
171 static struct ref_array extra_refs;
173 static void clear_ref_array(struct ref_array *array)
175 int i;
176 for (i = 0; i < array->nr; i++)
177 free(array->refs[i]);
178 free(array->refs);
179 array->nr = array->alloc = 0;
180 array->refs = NULL;
183 static void clear_packed_ref_cache(struct ref_cache *refs)
185 if (refs->did_packed)
186 clear_ref_array(&refs->packed);
187 refs->did_packed = 0;
190 static void clear_loose_ref_cache(struct ref_cache *refs)
192 if (refs->did_loose)
193 clear_ref_array(&refs->loose);
194 refs->did_loose = 0;
197 static struct ref_cache *create_ref_cache(const char *submodule)
199 int len;
200 struct ref_cache *refs;
201 if (!submodule)
202 submodule = "";
203 len = strlen(submodule) + 1;
204 refs = xcalloc(1, sizeof(struct ref_cache) + len);
205 memcpy(refs->name, submodule, len);
206 return refs;
210 * Return a pointer to a ref_cache for the specified submodule. For
211 * the main repository, use submodule==NULL. The returned structure
212 * will be allocated and initialized but not necessarily populated; it
213 * should not be freed.
215 static struct ref_cache *get_ref_cache(const char *submodule)
217 struct ref_cache *refs = ref_cache;
218 if (!submodule)
219 submodule = "";
220 while (refs) {
221 if (!strcmp(submodule, refs->name))
222 return refs;
223 refs = refs->next;
226 refs = create_ref_cache(submodule);
227 refs->next = ref_cache;
228 ref_cache = refs;
229 return refs;
232 void invalidate_ref_cache(const char *submodule)
234 struct ref_cache *refs = get_ref_cache(submodule);
235 clear_packed_ref_cache(refs);
236 clear_loose_ref_cache(refs);
239 static void read_packed_refs(FILE *f, struct ref_array *array)
241 struct ref_entry *last = NULL;
242 char refline[PATH_MAX];
243 int flag = REF_ISPACKED;
245 while (fgets(refline, sizeof(refline), f)) {
246 unsigned char sha1[20];
247 const char *refname;
248 static const char header[] = "# pack-refs with:";
250 if (!strncmp(refline, header, sizeof(header)-1)) {
251 const char *traits = refline + sizeof(header) - 1;
252 if (strstr(traits, " peeled "))
253 flag |= REF_KNOWS_PEELED;
254 /* perhaps other traits later as well */
255 continue;
258 refname = parse_ref_line(refline, sha1);
259 if (refname) {
260 add_ref(refname, sha1, flag, array, &last);
261 continue;
263 if (last &&
264 refline[0] == '^' &&
265 strlen(refline) == 42 &&
266 refline[41] == '\n' &&
267 !get_sha1_hex(refline + 1, sha1))
268 hashcpy(last->peeled, sha1);
270 sort_ref_array(array);
273 void add_extra_ref(const char *refname, const unsigned char *sha1, int flag)
275 add_ref(refname, sha1, flag, &extra_refs, NULL);
278 void clear_extra_refs(void)
280 clear_ref_array(&extra_refs);
283 static struct ref_array *get_packed_refs(struct ref_cache *refs)
285 if (!refs->did_packed) {
286 const char *packed_refs_file;
287 FILE *f;
289 if (*refs->name)
290 packed_refs_file = git_path_submodule(refs->name, "packed-refs");
291 else
292 packed_refs_file = git_path("packed-refs");
293 f = fopen(packed_refs_file, "r");
294 if (f) {
295 read_packed_refs(f, &refs->packed);
296 fclose(f);
298 refs->did_packed = 1;
300 return &refs->packed;
303 static void get_ref_dir(struct ref_cache *refs, const char *base,
304 struct ref_array *array)
306 DIR *dir;
307 const char *path;
309 if (*refs->name)
310 path = git_path_submodule(refs->name, "%s", base);
311 else
312 path = git_path("%s", base);
315 dir = opendir(path);
317 if (dir) {
318 struct dirent *de;
319 int baselen = strlen(base);
320 char *ref = xmalloc(baselen + 257);
322 memcpy(ref, base, baselen);
323 if (baselen && base[baselen-1] != '/')
324 ref[baselen++] = '/';
326 while ((de = readdir(dir)) != NULL) {
327 unsigned char sha1[20];
328 struct stat st;
329 int flag;
330 int namelen;
331 const char *refdir;
333 if (de->d_name[0] == '.')
334 continue;
335 namelen = strlen(de->d_name);
336 if (namelen > 255)
337 continue;
338 if (has_extension(de->d_name, ".lock"))
339 continue;
340 memcpy(ref + baselen, de->d_name, namelen+1);
341 refdir = *refs->name
342 ? git_path_submodule(refs->name, "%s", ref)
343 : git_path("%s", ref);
344 if (stat(refdir, &st) < 0)
345 continue;
346 if (S_ISDIR(st.st_mode)) {
347 get_ref_dir(refs, ref, array);
348 continue;
350 if (*refs->name) {
351 hashclr(sha1);
352 flag = 0;
353 if (resolve_gitlink_ref(refs->name, ref, sha1) < 0) {
354 hashclr(sha1);
355 flag |= REF_BROKEN;
357 } else
358 if (!resolve_ref(ref, sha1, 1, &flag)) {
359 hashclr(sha1);
360 flag |= REF_BROKEN;
362 add_ref(ref, sha1, flag, array, NULL);
364 free(ref);
365 closedir(dir);
369 struct warn_if_dangling_data {
370 FILE *fp;
371 const char *refname;
372 const char *msg_fmt;
375 static int warn_if_dangling_symref(const char *refname, const unsigned char *sha1,
376 int flags, void *cb_data)
378 struct warn_if_dangling_data *d = cb_data;
379 const char *resolves_to;
380 unsigned char junk[20];
382 if (!(flags & REF_ISSYMREF))
383 return 0;
385 resolves_to = resolve_ref(refname, junk, 0, NULL);
386 if (!resolves_to || strcmp(resolves_to, d->refname))
387 return 0;
389 fprintf(d->fp, d->msg_fmt, refname);
390 return 0;
393 void warn_dangling_symref(FILE *fp, const char *msg_fmt, const char *refname)
395 struct warn_if_dangling_data data;
397 data.fp = fp;
398 data.refname = refname;
399 data.msg_fmt = msg_fmt;
400 for_each_rawref(warn_if_dangling_symref, &data);
403 static struct ref_array *get_loose_refs(struct ref_cache *refs)
405 if (!refs->did_loose) {
406 get_ref_dir(refs, "refs", &refs->loose);
407 sort_ref_array(&refs->loose);
408 refs->did_loose = 1;
410 return &refs->loose;
413 /* We allow "recursive" symbolic refs. Only within reason, though */
414 #define MAXDEPTH 5
415 #define MAXREFLEN (1024)
417 static int resolve_gitlink_packed_ref(struct ref_cache *refs,
418 const char *refname, unsigned char *sha1)
420 int retval = -1;
421 struct ref_entry *ref;
422 struct ref_array *array = get_packed_refs(refs);
424 ref = search_ref_array(array, refname);
425 if (ref != NULL) {
426 memcpy(sha1, ref->sha1, 20);
427 retval = 0;
429 return retval;
432 static int resolve_gitlink_ref_recursive(struct ref_cache *refs,
433 const char *refname, unsigned char *sha1,
434 int recursion)
436 int fd, len;
437 char buffer[128], *p;
438 char *path;
440 if (recursion > MAXDEPTH || strlen(refname) > MAXREFLEN)
441 return -1;
442 path = *refs->name
443 ? git_path_submodule(refs->name, "%s", refname)
444 : git_path("%s", refname);
445 fd = open(path, O_RDONLY);
446 if (fd < 0)
447 return resolve_gitlink_packed_ref(refs, refname, sha1);
449 len = read(fd, buffer, sizeof(buffer)-1);
450 close(fd);
451 if (len < 0)
452 return -1;
453 while (len && isspace(buffer[len-1]))
454 len--;
455 buffer[len] = 0;
457 /* Was it a detached head or an old-fashioned symlink? */
458 if (!get_sha1_hex(buffer, sha1))
459 return 0;
461 /* Symref? */
462 if (strncmp(buffer, "ref:", 4))
463 return -1;
464 p = buffer + 4;
465 while (isspace(*p))
466 p++;
468 return resolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);
471 int resolve_gitlink_ref(const char *path, const char *refname, unsigned char *sha1)
473 int len = strlen(path), retval;
474 char *submodule;
475 struct ref_cache *refs;
477 while (len && path[len-1] == '/')
478 len--;
479 if (!len)
480 return -1;
481 submodule = xstrndup(path, len);
482 refs = get_ref_cache(submodule);
483 free(submodule);
485 retval = resolve_gitlink_ref_recursive(refs, refname, sha1, 0);
486 return retval;
490 * Try to read ref from the packed references. On success, set sha1
491 * and return 0; otherwise, return -1.
493 static int get_packed_ref(const char *refname, unsigned char *sha1)
495 struct ref_array *packed = get_packed_refs(get_ref_cache(NULL));
496 struct ref_entry *entry = search_ref_array(packed, refname);
497 if (entry) {
498 hashcpy(sha1, entry->sha1);
499 return 0;
501 return -1;
504 const char *resolve_ref(const char *refname, unsigned char *sha1, int reading, int *flag)
506 int depth = MAXDEPTH;
507 ssize_t len;
508 char buffer[256];
509 static char refname_buffer[256];
510 char path[PATH_MAX];
512 if (flag)
513 *flag = 0;
515 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL))
516 return NULL;
518 for (;;) {
519 struct stat st;
520 char *buf;
521 int fd;
523 if (--depth < 0)
524 return NULL;
526 git_snpath(path, sizeof(path), "%s", refname);
528 if (lstat(path, &st) < 0) {
529 if (errno != ENOENT)
530 return NULL;
532 * The loose reference file does not exist;
533 * check for a packed reference.
535 if (!get_packed_ref(refname, sha1)) {
536 if (flag)
537 *flag |= REF_ISPACKED;
538 return refname;
540 /* The reference is not a packed reference, either. */
541 if (reading) {
542 return NULL;
543 } else {
544 hashclr(sha1);
545 return refname;
549 /* Follow "normalized" - ie "refs/.." symlinks by hand */
550 if (S_ISLNK(st.st_mode)) {
551 len = readlink(path, buffer, sizeof(buffer)-1);
552 if (len < 0)
553 return NULL;
554 buffer[len] = 0;
555 if (!prefixcmp(buffer, "refs/") &&
556 !check_refname_format(buffer, 0)) {
557 strcpy(refname_buffer, buffer);
558 refname = refname_buffer;
559 if (flag)
560 *flag |= REF_ISSYMREF;
561 continue;
565 /* Is it a directory? */
566 if (S_ISDIR(st.st_mode)) {
567 errno = EISDIR;
568 return NULL;
572 * Anything else, just open it and try to use it as
573 * a ref
575 fd = open(path, O_RDONLY);
576 if (fd < 0)
577 return NULL;
578 len = read_in_full(fd, buffer, sizeof(buffer)-1);
579 close(fd);
580 if (len < 0)
581 return NULL;
582 while (len && isspace(buffer[len-1]))
583 len--;
584 buffer[len] = '\0';
587 * Is it a symbolic ref?
589 if (prefixcmp(buffer, "ref:"))
590 break;
591 buf = buffer + 4;
592 while (isspace(*buf))
593 buf++;
594 if (check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {
595 warning("symbolic reference in %s is formatted incorrectly",
596 path);
597 return NULL;
599 refname = strcpy(refname_buffer, buf);
600 if (flag)
601 *flag |= REF_ISSYMREF;
603 /* Please note that FETCH_HEAD has a second line containing other data. */
604 if (get_sha1_hex(buffer, sha1) || (buffer[40] != '\0' && !isspace(buffer[40]))) {
605 warning("reference in %s is formatted incorrectly", path);
606 return NULL;
608 return refname;
611 /* The argument to filter_refs */
612 struct ref_filter {
613 const char *pattern;
614 each_ref_fn *fn;
615 void *cb_data;
618 int read_ref(const char *refname, unsigned char *sha1)
620 if (resolve_ref(refname, sha1, 1, NULL))
621 return 0;
622 return -1;
625 #define DO_FOR_EACH_INCLUDE_BROKEN 01
626 static int do_one_ref(const char *base, each_ref_fn fn, int trim,
627 int flags, void *cb_data, struct ref_entry *entry)
629 if (prefixcmp(entry->name, base))
630 return 0;
632 if (!(flags & DO_FOR_EACH_INCLUDE_BROKEN)) {
633 if (entry->flag & REF_BROKEN)
634 return 0; /* ignore dangling symref */
635 if (!has_sha1_file(entry->sha1)) {
636 error("%s does not point to a valid object!", entry->name);
637 return 0;
640 current_ref = entry;
641 return fn(entry->name + trim, entry->sha1, entry->flag, cb_data);
644 static int filter_refs(const char *refname, const unsigned char *sha, int flags,
645 void *data)
647 struct ref_filter *filter = (struct ref_filter *)data;
648 if (fnmatch(filter->pattern, refname, 0))
649 return 0;
650 return filter->fn(refname, sha, flags, filter->cb_data);
653 int peel_ref(const char *refname, unsigned char *sha1)
655 int flag;
656 unsigned char base[20];
657 struct object *o;
659 if (current_ref && (current_ref->name == refname
660 || !strcmp(current_ref->name, refname))) {
661 if (current_ref->flag & REF_KNOWS_PEELED) {
662 hashcpy(sha1, current_ref->peeled);
663 return 0;
665 hashcpy(base, current_ref->sha1);
666 goto fallback;
669 if (!resolve_ref(refname, base, 1, &flag))
670 return -1;
672 if ((flag & REF_ISPACKED)) {
673 struct ref_array *array = get_packed_refs(get_ref_cache(NULL));
674 struct ref_entry *r = search_ref_array(array, refname);
676 if (r != NULL && r->flag & REF_KNOWS_PEELED) {
677 hashcpy(sha1, r->peeled);
678 return 0;
682 fallback:
683 o = parse_object(base);
684 if (o && o->type == OBJ_TAG) {
685 o = deref_tag(o, refname, 0);
686 if (o) {
687 hashcpy(sha1, o->sha1);
688 return 0;
691 return -1;
694 static int do_for_each_ref(const char *submodule, const char *base, each_ref_fn fn,
695 int trim, int flags, void *cb_data)
697 int retval = 0, i, p = 0, l = 0;
698 struct ref_cache *refs = get_ref_cache(submodule);
699 struct ref_array *packed = get_packed_refs(refs);
700 struct ref_array *loose = get_loose_refs(refs);
702 struct ref_array *extra = &extra_refs;
704 for (i = 0; i < extra->nr; i++)
705 retval = do_one_ref(base, fn, trim, flags, cb_data, extra->refs[i]);
707 while (p < packed->nr && l < loose->nr) {
708 struct ref_entry *entry;
709 int cmp = strcmp(packed->refs[p]->name, loose->refs[l]->name);
710 if (!cmp) {
711 p++;
712 continue;
714 if (cmp > 0) {
715 entry = loose->refs[l++];
716 } else {
717 entry = packed->refs[p++];
719 retval = do_one_ref(base, fn, trim, flags, cb_data, entry);
720 if (retval)
721 goto end_each;
724 if (l < loose->nr) {
725 p = l;
726 packed = loose;
729 for (; p < packed->nr; p++) {
730 retval = do_one_ref(base, fn, trim, flags, cb_data, packed->refs[p]);
731 if (retval)
732 goto end_each;
735 end_each:
736 current_ref = NULL;
737 return retval;
741 static int do_head_ref(const char *submodule, each_ref_fn fn, void *cb_data)
743 unsigned char sha1[20];
744 int flag;
746 if (submodule) {
747 if (resolve_gitlink_ref(submodule, "HEAD", sha1) == 0)
748 return fn("HEAD", sha1, 0, cb_data);
750 return 0;
753 if (resolve_ref("HEAD", sha1, 1, &flag))
754 return fn("HEAD", sha1, flag, cb_data);
756 return 0;
759 int head_ref(each_ref_fn fn, void *cb_data)
761 return do_head_ref(NULL, fn, cb_data);
764 int head_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
766 return do_head_ref(submodule, fn, cb_data);
769 int for_each_ref(each_ref_fn fn, void *cb_data)
771 return do_for_each_ref(NULL, "", fn, 0, 0, cb_data);
774 int for_each_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
776 return do_for_each_ref(submodule, "", fn, 0, 0, cb_data);
779 int for_each_ref_in(const char *prefix, each_ref_fn fn, void *cb_data)
781 return do_for_each_ref(NULL, prefix, fn, strlen(prefix), 0, cb_data);
784 int for_each_ref_in_submodule(const char *submodule, const char *prefix,
785 each_ref_fn fn, void *cb_data)
787 return do_for_each_ref(submodule, prefix, fn, strlen(prefix), 0, cb_data);
790 int for_each_tag_ref(each_ref_fn fn, void *cb_data)
792 return for_each_ref_in("refs/tags/", fn, cb_data);
795 int for_each_tag_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
797 return for_each_ref_in_submodule(submodule, "refs/tags/", fn, cb_data);
800 int for_each_branch_ref(each_ref_fn fn, void *cb_data)
802 return for_each_ref_in("refs/heads/", fn, cb_data);
805 int for_each_branch_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
807 return for_each_ref_in_submodule(submodule, "refs/heads/", fn, cb_data);
810 int for_each_remote_ref(each_ref_fn fn, void *cb_data)
812 return for_each_ref_in("refs/remotes/", fn, cb_data);
815 int for_each_remote_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
817 return for_each_ref_in_submodule(submodule, "refs/remotes/", fn, cb_data);
820 int for_each_replace_ref(each_ref_fn fn, void *cb_data)
822 return do_for_each_ref(NULL, "refs/replace/", fn, 13, 0, cb_data);
825 int head_ref_namespaced(each_ref_fn fn, void *cb_data)
827 struct strbuf buf = STRBUF_INIT;
828 int ret = 0;
829 unsigned char sha1[20];
830 int flag;
832 strbuf_addf(&buf, "%sHEAD", get_git_namespace());
833 if (resolve_ref(buf.buf, sha1, 1, &flag))
834 ret = fn(buf.buf, sha1, flag, cb_data);
835 strbuf_release(&buf);
837 return ret;
840 int for_each_namespaced_ref(each_ref_fn fn, void *cb_data)
842 struct strbuf buf = STRBUF_INIT;
843 int ret;
844 strbuf_addf(&buf, "%srefs/", get_git_namespace());
845 ret = do_for_each_ref(NULL, buf.buf, fn, 0, 0, cb_data);
846 strbuf_release(&buf);
847 return ret;
850 int for_each_glob_ref_in(each_ref_fn fn, const char *pattern,
851 const char *prefix, void *cb_data)
853 struct strbuf real_pattern = STRBUF_INIT;
854 struct ref_filter filter;
855 int ret;
857 if (!prefix && prefixcmp(pattern, "refs/"))
858 strbuf_addstr(&real_pattern, "refs/");
859 else if (prefix)
860 strbuf_addstr(&real_pattern, prefix);
861 strbuf_addstr(&real_pattern, pattern);
863 if (!has_glob_specials(pattern)) {
864 /* Append implied '/' '*' if not present. */
865 if (real_pattern.buf[real_pattern.len - 1] != '/')
866 strbuf_addch(&real_pattern, '/');
867 /* No need to check for '*', there is none. */
868 strbuf_addch(&real_pattern, '*');
871 filter.pattern = real_pattern.buf;
872 filter.fn = fn;
873 filter.cb_data = cb_data;
874 ret = for_each_ref(filter_refs, &filter);
876 strbuf_release(&real_pattern);
877 return ret;
880 int for_each_glob_ref(each_ref_fn fn, const char *pattern, void *cb_data)
882 return for_each_glob_ref_in(fn, pattern, NULL, cb_data);
885 int for_each_rawref(each_ref_fn fn, void *cb_data)
887 return do_for_each_ref(NULL, "", fn, 0,
888 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);
892 * Make sure "ref" is something reasonable to have under ".git/refs/";
893 * We do not like it if:
895 * - any path component of it begins with ".", or
896 * - it has double dots "..", or
897 * - it has ASCII control character, "~", "^", ":" or SP, anywhere, or
898 * - it ends with a "/".
899 * - it ends with ".lock"
900 * - it contains a "\" (backslash)
903 /* Return true iff ch is not allowed in reference names. */
904 static inline int bad_ref_char(int ch)
906 if (((unsigned) ch) <= ' ' || ch == 0x7f ||
907 ch == '~' || ch == '^' || ch == ':' || ch == '\\')
908 return 1;
909 /* 2.13 Pattern Matching Notation */
910 if (ch == '*' || ch == '?' || ch == '[') /* Unsupported */
911 return 1;
912 return 0;
916 * Try to read one refname component from the front of refname. Return
917 * the length of the component found, or -1 if the component is not
918 * legal.
920 static int check_refname_component(const char *refname, int flags)
922 const char *cp;
923 char last = '\0';
925 for (cp = refname; ; cp++) {
926 char ch = *cp;
927 if (ch == '\0' || ch == '/')
928 break;
929 if (bad_ref_char(ch))
930 return -1; /* Illegal character in refname. */
931 if (last == '.' && ch == '.')
932 return -1; /* Refname contains "..". */
933 if (last == '@' && ch == '{')
934 return -1; /* Refname contains "@{". */
935 last = ch;
937 if (cp == refname)
938 return -1; /* Component has zero length. */
939 if (refname[0] == '.') {
940 if (!(flags & REFNAME_DOT_COMPONENT))
941 return -1; /* Component starts with '.'. */
943 * Even if leading dots are allowed, don't allow "."
944 * as a component (".." is prevented by a rule above).
946 if (refname[1] == '\0')
947 return -1; /* Component equals ".". */
949 if (cp - refname >= 5 && !memcmp(cp - 5, ".lock", 5))
950 return -1; /* Refname ends with ".lock". */
951 return cp - refname;
954 int check_refname_format(const char *refname, int flags)
956 int component_len, component_count = 0;
958 while (1) {
959 /* We are at the start of a path component. */
960 component_len = check_refname_component(refname, flags);
961 if (component_len < 0) {
962 if ((flags & REFNAME_REFSPEC_PATTERN) &&
963 refname[0] == '*' &&
964 (refname[1] == '\0' || refname[1] == '/')) {
965 /* Accept one wildcard as a full refname component. */
966 flags &= ~REFNAME_REFSPEC_PATTERN;
967 component_len = 1;
968 } else {
969 return -1;
972 component_count++;
973 if (refname[component_len] == '\0')
974 break;
975 /* Skip to next component. */
976 refname += component_len + 1;
979 if (refname[component_len - 1] == '.')
980 return -1; /* Refname ends with '.'. */
981 if (!(flags & REFNAME_ALLOW_ONELEVEL) && component_count < 2)
982 return -1; /* Refname has only one component. */
983 return 0;
986 const char *prettify_refname(const char *name)
988 return name + (
989 !prefixcmp(name, "refs/heads/") ? 11 :
990 !prefixcmp(name, "refs/tags/") ? 10 :
991 !prefixcmp(name, "refs/remotes/") ? 13 :
995 const char *ref_rev_parse_rules[] = {
996 "%.*s",
997 "refs/%.*s",
998 "refs/tags/%.*s",
999 "refs/heads/%.*s",
1000 "refs/remotes/%.*s",
1001 "refs/remotes/%.*s/HEAD",
1002 NULL
1005 const char *ref_fetch_rules[] = {
1006 "%.*s",
1007 "refs/%.*s",
1008 "refs/heads/%.*s",
1009 NULL
1012 int refname_match(const char *abbrev_name, const char *full_name, const char **rules)
1014 const char **p;
1015 const int abbrev_name_len = strlen(abbrev_name);
1017 for (p = rules; *p; p++) {
1018 if (!strcmp(full_name, mkpath(*p, abbrev_name_len, abbrev_name))) {
1019 return 1;
1023 return 0;
1026 static struct ref_lock *verify_lock(struct ref_lock *lock,
1027 const unsigned char *old_sha1, int mustexist)
1029 if (!resolve_ref(lock->ref_name, lock->old_sha1, mustexist, NULL)) {
1030 error("Can't verify ref %s", lock->ref_name);
1031 unlock_ref(lock);
1032 return NULL;
1034 if (hashcmp(lock->old_sha1, old_sha1)) {
1035 error("Ref %s is at %s but expected %s", lock->ref_name,
1036 sha1_to_hex(lock->old_sha1), sha1_to_hex(old_sha1));
1037 unlock_ref(lock);
1038 return NULL;
1040 return lock;
1043 static int remove_empty_directories(const char *file)
1045 /* we want to create a file but there is a directory there;
1046 * if that is an empty directory (or a directory that contains
1047 * only empty directories), remove them.
1049 struct strbuf path;
1050 int result;
1052 strbuf_init(&path, 20);
1053 strbuf_addstr(&path, file);
1055 result = remove_dir_recursively(&path, REMOVE_DIR_EMPTY_ONLY);
1057 strbuf_release(&path);
1059 return result;
1063 * Return true iff a reference named refname could be created without
1064 * conflicting with the name of an existing reference. If oldrefname
1065 * is non-NULL, ignore potential conflicts with oldrefname (e.g.,
1066 * because oldrefname is scheduled for deletion in the same
1067 * operation).
1069 static int is_refname_available(const char *refname, const char *oldrefname,
1070 struct ref_array *array)
1072 int i, namlen = strlen(refname); /* e.g. 'foo/bar' */
1073 for (i = 0; i < array->nr; i++ ) {
1074 struct ref_entry *entry = array->refs[i];
1075 /* entry->name could be 'foo' or 'foo/bar/baz' */
1076 if (!oldrefname || strcmp(oldrefname, entry->name)) {
1077 int len = strlen(entry->name);
1078 int cmplen = (namlen < len) ? namlen : len;
1079 const char *lead = (namlen < len) ? entry->name : refname;
1080 if (!strncmp(refname, entry->name, cmplen) &&
1081 lead[cmplen] == '/') {
1082 error("'%s' exists; cannot create '%s'",
1083 entry->name, refname);
1084 return 0;
1088 return 1;
1091 static struct ref_lock *lock_ref_sha1_basic(const char *refname,
1092 const unsigned char *old_sha1,
1093 int flags, int *type_p)
1095 char *ref_file;
1096 const char *orig_refname = refname;
1097 struct ref_lock *lock;
1098 int last_errno = 0;
1099 int type, lflags;
1100 int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
1101 int missing = 0;
1103 lock = xcalloc(1, sizeof(struct ref_lock));
1104 lock->lock_fd = -1;
1106 refname = resolve_ref(refname, lock->old_sha1, mustexist, &type);
1107 if (!refname && errno == EISDIR) {
1108 /* we are trying to lock foo but we used to
1109 * have foo/bar which now does not exist;
1110 * it is normal for the empty directory 'foo'
1111 * to remain.
1113 ref_file = git_path("%s", orig_refname);
1114 if (remove_empty_directories(ref_file)) {
1115 last_errno = errno;
1116 error("there are still refs under '%s'", orig_refname);
1117 goto error_return;
1119 refname = resolve_ref(orig_refname, lock->old_sha1, mustexist, &type);
1121 if (type_p)
1122 *type_p = type;
1123 if (!refname) {
1124 last_errno = errno;
1125 error("unable to resolve reference %s: %s",
1126 orig_refname, strerror(errno));
1127 goto error_return;
1129 missing = is_null_sha1(lock->old_sha1);
1130 /* When the ref did not exist and we are creating it,
1131 * make sure there is no existing ref that is packed
1132 * whose name begins with our refname, nor a ref whose
1133 * name is a proper prefix of our refname.
1135 if (missing &&
1136 !is_refname_available(refname, NULL, get_packed_refs(get_ref_cache(NULL)))) {
1137 last_errno = ENOTDIR;
1138 goto error_return;
1141 lock->lk = xcalloc(1, sizeof(struct lock_file));
1143 lflags = LOCK_DIE_ON_ERROR;
1144 if (flags & REF_NODEREF) {
1145 refname = orig_refname;
1146 lflags |= LOCK_NODEREF;
1148 lock->ref_name = xstrdup(refname);
1149 lock->orig_ref_name = xstrdup(orig_refname);
1150 ref_file = git_path("%s", refname);
1151 if (missing)
1152 lock->force_write = 1;
1153 if ((flags & REF_NODEREF) && (type & REF_ISSYMREF))
1154 lock->force_write = 1;
1156 if (safe_create_leading_directories(ref_file)) {
1157 last_errno = errno;
1158 error("unable to create directory for %s", ref_file);
1159 goto error_return;
1162 lock->lock_fd = hold_lock_file_for_update(lock->lk, ref_file, lflags);
1163 return old_sha1 ? verify_lock(lock, old_sha1, mustexist) : lock;
1165 error_return:
1166 unlock_ref(lock);
1167 errno = last_errno;
1168 return NULL;
1171 struct ref_lock *lock_ref_sha1(const char *refname, const unsigned char *old_sha1)
1173 char refpath[PATH_MAX];
1174 if (check_refname_format(refname, 0))
1175 return NULL;
1176 strcpy(refpath, mkpath("refs/%s", refname));
1177 return lock_ref_sha1_basic(refpath, old_sha1, 0, NULL);
1180 struct ref_lock *lock_any_ref_for_update(const char *refname,
1181 const unsigned char *old_sha1, int flags)
1183 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL))
1184 return NULL;
1185 return lock_ref_sha1_basic(refname, old_sha1, flags, NULL);
1188 static struct lock_file packlock;
1190 static int repack_without_ref(const char *refname)
1192 struct ref_array *packed;
1193 struct ref_entry *ref;
1194 int fd, i;
1196 packed = get_packed_refs(get_ref_cache(NULL));
1197 ref = search_ref_array(packed, refname);
1198 if (ref == NULL)
1199 return 0;
1200 fd = hold_lock_file_for_update(&packlock, git_path("packed-refs"), 0);
1201 if (fd < 0) {
1202 unable_to_lock_error(git_path("packed-refs"), errno);
1203 return error("cannot delete '%s' from packed refs", refname);
1206 for (i = 0; i < packed->nr; i++) {
1207 char line[PATH_MAX + 100];
1208 int len;
1210 ref = packed->refs[i];
1212 if (!strcmp(refname, ref->name))
1213 continue;
1214 len = snprintf(line, sizeof(line), "%s %s\n",
1215 sha1_to_hex(ref->sha1), ref->name);
1216 /* this should not happen but just being defensive */
1217 if (len > sizeof(line))
1218 die("too long a refname '%s'", ref->name);
1219 write_or_die(fd, line, len);
1221 return commit_lock_file(&packlock);
1224 int delete_ref(const char *refname, const unsigned char *sha1, int delopt)
1226 struct ref_lock *lock;
1227 int err, i = 0, ret = 0, flag = 0;
1229 lock = lock_ref_sha1_basic(refname, sha1, 0, &flag);
1230 if (!lock)
1231 return 1;
1232 if (!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {
1233 /* loose */
1234 const char *path;
1236 if (!(delopt & REF_NODEREF)) {
1237 i = strlen(lock->lk->filename) - 5; /* .lock */
1238 lock->lk->filename[i] = 0;
1239 path = lock->lk->filename;
1240 } else {
1241 path = git_path("%s", refname);
1243 err = unlink_or_warn(path);
1244 if (err && errno != ENOENT)
1245 ret = 1;
1247 if (!(delopt & REF_NODEREF))
1248 lock->lk->filename[i] = '.';
1250 /* removing the loose one could have resurrected an earlier
1251 * packed one. Also, if it was not loose we need to repack
1252 * without it.
1254 ret |= repack_without_ref(refname);
1256 unlink_or_warn(git_path("logs/%s", lock->ref_name));
1257 invalidate_ref_cache(NULL);
1258 unlock_ref(lock);
1259 return ret;
1263 * People using contrib's git-new-workdir have .git/logs/refs ->
1264 * /some/other/path/.git/logs/refs, and that may live on another device.
1266 * IOW, to avoid cross device rename errors, the temporary renamed log must
1267 * live into logs/refs.
1269 #define TMP_RENAMED_LOG "logs/refs/.tmp-renamed-log"
1271 int rename_ref(const char *oldrefname, const char *newrefname, const char *logmsg)
1273 static const char renamed_ref[] = "RENAMED-REF";
1274 unsigned char sha1[20], orig_sha1[20];
1275 int flag = 0, logmoved = 0;
1276 struct ref_lock *lock;
1277 struct stat loginfo;
1278 int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);
1279 const char *symref = NULL;
1280 struct ref_cache *refs = get_ref_cache(NULL);
1282 if (log && S_ISLNK(loginfo.st_mode))
1283 return error("reflog for %s is a symlink", oldrefname);
1285 symref = resolve_ref(oldrefname, orig_sha1, 1, &flag);
1286 if (flag & REF_ISSYMREF)
1287 return error("refname %s is a symbolic ref, renaming it is not supported",
1288 oldrefname);
1289 if (!symref)
1290 return error("refname %s not found", oldrefname);
1292 if (!is_refname_available(newrefname, oldrefname, get_packed_refs(refs)))
1293 return 1;
1295 if (!is_refname_available(newrefname, oldrefname, get_loose_refs(refs)))
1296 return 1;
1298 lock = lock_ref_sha1_basic(renamed_ref, NULL, 0, NULL);
1299 if (!lock)
1300 return error("unable to lock %s", renamed_ref);
1301 lock->force_write = 1;
1302 if (write_ref_sha1(lock, orig_sha1, logmsg))
1303 return error("unable to save current sha1 in %s", renamed_ref);
1305 if (log && rename(git_path("logs/%s", oldrefname), git_path(TMP_RENAMED_LOG)))
1306 return error("unable to move logfile logs/%s to "TMP_RENAMED_LOG": %s",
1307 oldrefname, strerror(errno));
1309 if (delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {
1310 error("unable to delete old %s", oldrefname);
1311 goto rollback;
1314 if (resolve_ref(newrefname, sha1, 1, &flag) && delete_ref(newrefname, sha1, REF_NODEREF)) {
1315 if (errno==EISDIR) {
1316 if (remove_empty_directories(git_path("%s", newrefname))) {
1317 error("Directory not empty: %s", newrefname);
1318 goto rollback;
1320 } else {
1321 error("unable to delete existing %s", newrefname);
1322 goto rollback;
1326 if (log && safe_create_leading_directories(git_path("logs/%s", newrefname))) {
1327 error("unable to create directory for %s", newrefname);
1328 goto rollback;
1331 retry:
1332 if (log && rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", newrefname))) {
1333 if (errno==EISDIR || errno==ENOTDIR) {
1335 * rename(a, b) when b is an existing
1336 * directory ought to result in ISDIR, but
1337 * Solaris 5.8 gives ENOTDIR. Sheesh.
1339 if (remove_empty_directories(git_path("logs/%s", newrefname))) {
1340 error("Directory not empty: logs/%s", newrefname);
1341 goto rollback;
1343 goto retry;
1344 } else {
1345 error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s: %s",
1346 newrefname, strerror(errno));
1347 goto rollback;
1350 logmoved = log;
1352 lock = lock_ref_sha1_basic(newrefname, NULL, 0, NULL);
1353 if (!lock) {
1354 error("unable to lock %s for update", newrefname);
1355 goto rollback;
1357 lock->force_write = 1;
1358 hashcpy(lock->old_sha1, orig_sha1);
1359 if (write_ref_sha1(lock, orig_sha1, logmsg)) {
1360 error("unable to write current sha1 into %s", newrefname);
1361 goto rollback;
1364 return 0;
1366 rollback:
1367 lock = lock_ref_sha1_basic(oldrefname, NULL, 0, NULL);
1368 if (!lock) {
1369 error("unable to lock %s for rollback", oldrefname);
1370 goto rollbacklog;
1373 lock->force_write = 1;
1374 flag = log_all_ref_updates;
1375 log_all_ref_updates = 0;
1376 if (write_ref_sha1(lock, orig_sha1, NULL))
1377 error("unable to write current sha1 into %s", oldrefname);
1378 log_all_ref_updates = flag;
1380 rollbacklog:
1381 if (logmoved && rename(git_path("logs/%s", newrefname), git_path("logs/%s", oldrefname)))
1382 error("unable to restore logfile %s from %s: %s",
1383 oldrefname, newrefname, strerror(errno));
1384 if (!logmoved && log &&
1385 rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", oldrefname)))
1386 error("unable to restore logfile %s from "TMP_RENAMED_LOG": %s",
1387 oldrefname, strerror(errno));
1389 return 1;
1392 int close_ref(struct ref_lock *lock)
1394 if (close_lock_file(lock->lk))
1395 return -1;
1396 lock->lock_fd = -1;
1397 return 0;
1400 int commit_ref(struct ref_lock *lock)
1402 if (commit_lock_file(lock->lk))
1403 return -1;
1404 lock->lock_fd = -1;
1405 return 0;
1408 void unlock_ref(struct ref_lock *lock)
1410 /* Do not free lock->lk -- atexit() still looks at them */
1411 if (lock->lk)
1412 rollback_lock_file(lock->lk);
1413 free(lock->ref_name);
1414 free(lock->orig_ref_name);
1415 free(lock);
1419 * copy the reflog message msg to buf, which has been allocated sufficiently
1420 * large, while cleaning up the whitespaces. Especially, convert LF to space,
1421 * because reflog file is one line per entry.
1423 static int copy_msg(char *buf, const char *msg)
1425 char *cp = buf;
1426 char c;
1427 int wasspace = 1;
1429 *cp++ = '\t';
1430 while ((c = *msg++)) {
1431 if (wasspace && isspace(c))
1432 continue;
1433 wasspace = isspace(c);
1434 if (wasspace)
1435 c = ' ';
1436 *cp++ = c;
1438 while (buf < cp && isspace(cp[-1]))
1439 cp--;
1440 *cp++ = '\n';
1441 return cp - buf;
1444 int log_ref_setup(const char *refname, char *logfile, int bufsize)
1446 int logfd, oflags = O_APPEND | O_WRONLY;
1448 git_snpath(logfile, bufsize, "logs/%s", refname);
1449 if (log_all_ref_updates &&
1450 (!prefixcmp(refname, "refs/heads/") ||
1451 !prefixcmp(refname, "refs/remotes/") ||
1452 !prefixcmp(refname, "refs/notes/") ||
1453 !strcmp(refname, "HEAD"))) {
1454 if (safe_create_leading_directories(logfile) < 0)
1455 return error("unable to create directory for %s",
1456 logfile);
1457 oflags |= O_CREAT;
1460 logfd = open(logfile, oflags, 0666);
1461 if (logfd < 0) {
1462 if (!(oflags & O_CREAT) && errno == ENOENT)
1463 return 0;
1465 if ((oflags & O_CREAT) && errno == EISDIR) {
1466 if (remove_empty_directories(logfile)) {
1467 return error("There are still logs under '%s'",
1468 logfile);
1470 logfd = open(logfile, oflags, 0666);
1473 if (logfd < 0)
1474 return error("Unable to append to %s: %s",
1475 logfile, strerror(errno));
1478 adjust_shared_perm(logfile);
1479 close(logfd);
1480 return 0;
1483 static int log_ref_write(const char *refname, const unsigned char *old_sha1,
1484 const unsigned char *new_sha1, const char *msg)
1486 int logfd, result, written, oflags = O_APPEND | O_WRONLY;
1487 unsigned maxlen, len;
1488 int msglen;
1489 char log_file[PATH_MAX];
1490 char *logrec;
1491 const char *committer;
1493 if (log_all_ref_updates < 0)
1494 log_all_ref_updates = !is_bare_repository();
1496 result = log_ref_setup(refname, log_file, sizeof(log_file));
1497 if (result)
1498 return result;
1500 logfd = open(log_file, oflags);
1501 if (logfd < 0)
1502 return 0;
1503 msglen = msg ? strlen(msg) : 0;
1504 committer = git_committer_info(0);
1505 maxlen = strlen(committer) + msglen + 100;
1506 logrec = xmalloc(maxlen);
1507 len = sprintf(logrec, "%s %s %s\n",
1508 sha1_to_hex(old_sha1),
1509 sha1_to_hex(new_sha1),
1510 committer);
1511 if (msglen)
1512 len += copy_msg(logrec + len - 1, msg) - 1;
1513 written = len <= maxlen ? write_in_full(logfd, logrec, len) : -1;
1514 free(logrec);
1515 if (close(logfd) != 0 || written != len)
1516 return error("Unable to append to %s", log_file);
1517 return 0;
1520 static int is_branch(const char *refname)
1522 return !strcmp(refname, "HEAD") || !prefixcmp(refname, "refs/heads/");
1525 int write_ref_sha1(struct ref_lock *lock,
1526 const unsigned char *sha1, const char *logmsg)
1528 static char term = '\n';
1529 struct object *o;
1531 if (!lock)
1532 return -1;
1533 if (!lock->force_write && !hashcmp(lock->old_sha1, sha1)) {
1534 unlock_ref(lock);
1535 return 0;
1537 o = parse_object(sha1);
1538 if (!o) {
1539 error("Trying to write ref %s with nonexistent object %s",
1540 lock->ref_name, sha1_to_hex(sha1));
1541 unlock_ref(lock);
1542 return -1;
1544 if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
1545 error("Trying to write non-commit object %s to branch %s",
1546 sha1_to_hex(sha1), lock->ref_name);
1547 unlock_ref(lock);
1548 return -1;
1550 if (write_in_full(lock->lock_fd, sha1_to_hex(sha1), 40) != 40 ||
1551 write_in_full(lock->lock_fd, &term, 1) != 1
1552 || close_ref(lock) < 0) {
1553 error("Couldn't write %s", lock->lk->filename);
1554 unlock_ref(lock);
1555 return -1;
1557 clear_loose_ref_cache(get_ref_cache(NULL));
1558 if (log_ref_write(lock->ref_name, lock->old_sha1, sha1, logmsg) < 0 ||
1559 (strcmp(lock->ref_name, lock->orig_ref_name) &&
1560 log_ref_write(lock->orig_ref_name, lock->old_sha1, sha1, logmsg) < 0)) {
1561 unlock_ref(lock);
1562 return -1;
1564 if (strcmp(lock->orig_ref_name, "HEAD") != 0) {
1566 * Special hack: If a branch is updated directly and HEAD
1567 * points to it (may happen on the remote side of a push
1568 * for example) then logically the HEAD reflog should be
1569 * updated too.
1570 * A generic solution implies reverse symref information,
1571 * but finding all symrefs pointing to the given branch
1572 * would be rather costly for this rare event (the direct
1573 * update of a branch) to be worth it. So let's cheat and
1574 * check with HEAD only which should cover 99% of all usage
1575 * scenarios (even 100% of the default ones).
1577 unsigned char head_sha1[20];
1578 int head_flag;
1579 const char *head_ref;
1580 head_ref = resolve_ref("HEAD", head_sha1, 1, &head_flag);
1581 if (head_ref && (head_flag & REF_ISSYMREF) &&
1582 !strcmp(head_ref, lock->ref_name))
1583 log_ref_write("HEAD", lock->old_sha1, sha1, logmsg);
1585 if (commit_ref(lock)) {
1586 error("Couldn't set %s", lock->ref_name);
1587 unlock_ref(lock);
1588 return -1;
1590 unlock_ref(lock);
1591 return 0;
1594 int create_symref(const char *ref_target, const char *refs_heads_master,
1595 const char *logmsg)
1597 const char *lockpath;
1598 char ref[1000];
1599 int fd, len, written;
1600 char *git_HEAD = git_pathdup("%s", ref_target);
1601 unsigned char old_sha1[20], new_sha1[20];
1603 if (logmsg && read_ref(ref_target, old_sha1))
1604 hashclr(old_sha1);
1606 if (safe_create_leading_directories(git_HEAD) < 0)
1607 return error("unable to create directory for %s", git_HEAD);
1609 #ifndef NO_SYMLINK_HEAD
1610 if (prefer_symlink_refs) {
1611 unlink(git_HEAD);
1612 if (!symlink(refs_heads_master, git_HEAD))
1613 goto done;
1614 fprintf(stderr, "no symlink - falling back to symbolic ref\n");
1616 #endif
1618 len = snprintf(ref, sizeof(ref), "ref: %s\n", refs_heads_master);
1619 if (sizeof(ref) <= len) {
1620 error("refname too long: %s", refs_heads_master);
1621 goto error_free_return;
1623 lockpath = mkpath("%s.lock", git_HEAD);
1624 fd = open(lockpath, O_CREAT | O_EXCL | O_WRONLY, 0666);
1625 if (fd < 0) {
1626 error("Unable to open %s for writing", lockpath);
1627 goto error_free_return;
1629 written = write_in_full(fd, ref, len);
1630 if (close(fd) != 0 || written != len) {
1631 error("Unable to write to %s", lockpath);
1632 goto error_unlink_return;
1634 if (rename(lockpath, git_HEAD) < 0) {
1635 error("Unable to create %s", git_HEAD);
1636 goto error_unlink_return;
1638 if (adjust_shared_perm(git_HEAD)) {
1639 error("Unable to fix permissions on %s", lockpath);
1640 error_unlink_return:
1641 unlink_or_warn(lockpath);
1642 error_free_return:
1643 free(git_HEAD);
1644 return -1;
1647 #ifndef NO_SYMLINK_HEAD
1648 done:
1649 #endif
1650 if (logmsg && !read_ref(refs_heads_master, new_sha1))
1651 log_ref_write(ref_target, old_sha1, new_sha1, logmsg);
1653 free(git_HEAD);
1654 return 0;
1657 static char *ref_msg(const char *line, const char *endp)
1659 const char *ep;
1660 line += 82;
1661 ep = memchr(line, '\n', endp - line);
1662 if (!ep)
1663 ep = endp;
1664 return xmemdupz(line, ep - line);
1667 int read_ref_at(const char *refname, unsigned long at_time, int cnt,
1668 unsigned char *sha1, char **msg,
1669 unsigned long *cutoff_time, int *cutoff_tz, int *cutoff_cnt)
1671 const char *logfile, *logdata, *logend, *rec, *lastgt, *lastrec;
1672 char *tz_c;
1673 int logfd, tz, reccnt = 0;
1674 struct stat st;
1675 unsigned long date;
1676 unsigned char logged_sha1[20];
1677 void *log_mapped;
1678 size_t mapsz;
1680 logfile = git_path("logs/%s", refname);
1681 logfd = open(logfile, O_RDONLY, 0);
1682 if (logfd < 0)
1683 die_errno("Unable to read log '%s'", logfile);
1684 fstat(logfd, &st);
1685 if (!st.st_size)
1686 die("Log %s is empty.", logfile);
1687 mapsz = xsize_t(st.st_size);
1688 log_mapped = xmmap(NULL, mapsz, PROT_READ, MAP_PRIVATE, logfd, 0);
1689 logdata = log_mapped;
1690 close(logfd);
1692 lastrec = NULL;
1693 rec = logend = logdata + st.st_size;
1694 while (logdata < rec) {
1695 reccnt++;
1696 if (logdata < rec && *(rec-1) == '\n')
1697 rec--;
1698 lastgt = NULL;
1699 while (logdata < rec && *(rec-1) != '\n') {
1700 rec--;
1701 if (*rec == '>')
1702 lastgt = rec;
1704 if (!lastgt)
1705 die("Log %s is corrupt.", logfile);
1706 date = strtoul(lastgt + 1, &tz_c, 10);
1707 if (date <= at_time || cnt == 0) {
1708 tz = strtoul(tz_c, NULL, 10);
1709 if (msg)
1710 *msg = ref_msg(rec, logend);
1711 if (cutoff_time)
1712 *cutoff_time = date;
1713 if (cutoff_tz)
1714 *cutoff_tz = tz;
1715 if (cutoff_cnt)
1716 *cutoff_cnt = reccnt - 1;
1717 if (lastrec) {
1718 if (get_sha1_hex(lastrec, logged_sha1))
1719 die("Log %s is corrupt.", logfile);
1720 if (get_sha1_hex(rec + 41, sha1))
1721 die("Log %s is corrupt.", logfile);
1722 if (hashcmp(logged_sha1, sha1)) {
1723 warning("Log %s has gap after %s.",
1724 logfile, show_date(date, tz, DATE_RFC2822));
1727 else if (date == at_time) {
1728 if (get_sha1_hex(rec + 41, sha1))
1729 die("Log %s is corrupt.", logfile);
1731 else {
1732 if (get_sha1_hex(rec + 41, logged_sha1))
1733 die("Log %s is corrupt.", logfile);
1734 if (hashcmp(logged_sha1, sha1)) {
1735 warning("Log %s unexpectedly ended on %s.",
1736 logfile, show_date(date, tz, DATE_RFC2822));
1739 munmap(log_mapped, mapsz);
1740 return 0;
1742 lastrec = rec;
1743 if (cnt > 0)
1744 cnt--;
1747 rec = logdata;
1748 while (rec < logend && *rec != '>' && *rec != '\n')
1749 rec++;
1750 if (rec == logend || *rec == '\n')
1751 die("Log %s is corrupt.", logfile);
1752 date = strtoul(rec + 1, &tz_c, 10);
1753 tz = strtoul(tz_c, NULL, 10);
1754 if (get_sha1_hex(logdata, sha1))
1755 die("Log %s is corrupt.", logfile);
1756 if (is_null_sha1(sha1)) {
1757 if (get_sha1_hex(logdata + 41, sha1))
1758 die("Log %s is corrupt.", logfile);
1760 if (msg)
1761 *msg = ref_msg(logdata, logend);
1762 munmap(log_mapped, mapsz);
1764 if (cutoff_time)
1765 *cutoff_time = date;
1766 if (cutoff_tz)
1767 *cutoff_tz = tz;
1768 if (cutoff_cnt)
1769 *cutoff_cnt = reccnt;
1770 return 1;
1773 int for_each_recent_reflog_ent(const char *refname, each_reflog_ent_fn fn, long ofs, void *cb_data)
1775 const char *logfile;
1776 FILE *logfp;
1777 struct strbuf sb = STRBUF_INIT;
1778 int ret = 0;
1780 logfile = git_path("logs/%s", refname);
1781 logfp = fopen(logfile, "r");
1782 if (!logfp)
1783 return -1;
1785 if (ofs) {
1786 struct stat statbuf;
1787 if (fstat(fileno(logfp), &statbuf) ||
1788 statbuf.st_size < ofs ||
1789 fseek(logfp, -ofs, SEEK_END) ||
1790 strbuf_getwholeline(&sb, logfp, '\n')) {
1791 fclose(logfp);
1792 strbuf_release(&sb);
1793 return -1;
1797 while (!strbuf_getwholeline(&sb, logfp, '\n')) {
1798 unsigned char osha1[20], nsha1[20];
1799 char *email_end, *message;
1800 unsigned long timestamp;
1801 int tz;
1803 /* old SP new SP name <email> SP time TAB msg LF */
1804 if (sb.len < 83 || sb.buf[sb.len - 1] != '\n' ||
1805 get_sha1_hex(sb.buf, osha1) || sb.buf[40] != ' ' ||
1806 get_sha1_hex(sb.buf + 41, nsha1) || sb.buf[81] != ' ' ||
1807 !(email_end = strchr(sb.buf + 82, '>')) ||
1808 email_end[1] != ' ' ||
1809 !(timestamp = strtoul(email_end + 2, &message, 10)) ||
1810 !message || message[0] != ' ' ||
1811 (message[1] != '+' && message[1] != '-') ||
1812 !isdigit(message[2]) || !isdigit(message[3]) ||
1813 !isdigit(message[4]) || !isdigit(message[5]))
1814 continue; /* corrupt? */
1815 email_end[1] = '\0';
1816 tz = strtol(message + 1, NULL, 10);
1817 if (message[6] != '\t')
1818 message += 6;
1819 else
1820 message += 7;
1821 ret = fn(osha1, nsha1, sb.buf + 82, timestamp, tz, message,
1822 cb_data);
1823 if (ret)
1824 break;
1826 fclose(logfp);
1827 strbuf_release(&sb);
1828 return ret;
1831 int for_each_reflog_ent(const char *refname, each_reflog_ent_fn fn, void *cb_data)
1833 return for_each_recent_reflog_ent(refname, fn, 0, cb_data);
1836 static int do_for_each_reflog(const char *base, each_ref_fn fn, void *cb_data)
1838 DIR *dir = opendir(git_path("logs/%s", base));
1839 int retval = 0;
1841 if (dir) {
1842 struct dirent *de;
1843 int baselen = strlen(base);
1844 char *log = xmalloc(baselen + 257);
1846 memcpy(log, base, baselen);
1847 if (baselen && base[baselen-1] != '/')
1848 log[baselen++] = '/';
1850 while ((de = readdir(dir)) != NULL) {
1851 struct stat st;
1852 int namelen;
1854 if (de->d_name[0] == '.')
1855 continue;
1856 namelen = strlen(de->d_name);
1857 if (namelen > 255)
1858 continue;
1859 if (has_extension(de->d_name, ".lock"))
1860 continue;
1861 memcpy(log + baselen, de->d_name, namelen+1);
1862 if (stat(git_path("logs/%s", log), &st) < 0)
1863 continue;
1864 if (S_ISDIR(st.st_mode)) {
1865 retval = do_for_each_reflog(log, fn, cb_data);
1866 } else {
1867 unsigned char sha1[20];
1868 if (!resolve_ref(log, sha1, 0, NULL))
1869 retval = error("bad ref for %s", log);
1870 else
1871 retval = fn(log, sha1, 0, cb_data);
1873 if (retval)
1874 break;
1876 free(log);
1877 closedir(dir);
1879 else if (*base)
1880 return errno;
1881 return retval;
1884 int for_each_reflog(each_ref_fn fn, void *cb_data)
1886 return do_for_each_reflog("", fn, cb_data);
1889 int update_ref(const char *action, const char *refname,
1890 const unsigned char *sha1, const unsigned char *oldval,
1891 int flags, enum action_on_err onerr)
1893 static struct ref_lock *lock;
1894 lock = lock_any_ref_for_update(refname, oldval, flags);
1895 if (!lock) {
1896 const char *str = "Cannot lock the ref '%s'.";
1897 switch (onerr) {
1898 case MSG_ON_ERR: error(str, refname); break;
1899 case DIE_ON_ERR: die(str, refname); break;
1900 case QUIET_ON_ERR: break;
1902 return 1;
1904 if (write_ref_sha1(lock, sha1, action) < 0) {
1905 const char *str = "Cannot update the ref '%s'.";
1906 switch (onerr) {
1907 case MSG_ON_ERR: error(str, refname); break;
1908 case DIE_ON_ERR: die(str, refname); break;
1909 case QUIET_ON_ERR: break;
1911 return 1;
1913 return 0;
1916 int ref_exists(const char *refname)
1918 unsigned char sha1[20];
1919 return !!resolve_ref(refname, sha1, 1, NULL);
1922 struct ref *find_ref_by_name(const struct ref *list, const char *name)
1924 for ( ; list; list = list->next)
1925 if (!strcmp(list->name, name))
1926 return (struct ref *)list;
1927 return NULL;
1931 * generate a format suitable for scanf from a ref_rev_parse_rules
1932 * rule, that is replace the "%.*s" spec with a "%s" spec
1934 static void gen_scanf_fmt(char *scanf_fmt, const char *rule)
1936 char *spec;
1938 spec = strstr(rule, "%.*s");
1939 if (!spec || strstr(spec + 4, "%.*s"))
1940 die("invalid rule in ref_rev_parse_rules: %s", rule);
1942 /* copy all until spec */
1943 strncpy(scanf_fmt, rule, spec - rule);
1944 scanf_fmt[spec - rule] = '\0';
1945 /* copy new spec */
1946 strcat(scanf_fmt, "%s");
1947 /* copy remaining rule */
1948 strcat(scanf_fmt, spec + 4);
1950 return;
1953 char *shorten_unambiguous_ref(const char *refname, int strict)
1955 int i;
1956 static char **scanf_fmts;
1957 static int nr_rules;
1958 char *short_name;
1960 /* pre generate scanf formats from ref_rev_parse_rules[] */
1961 if (!nr_rules) {
1962 size_t total_len = 0;
1964 /* the rule list is NULL terminated, count them first */
1965 for (; ref_rev_parse_rules[nr_rules]; nr_rules++)
1966 /* no +1 because strlen("%s") < strlen("%.*s") */
1967 total_len += strlen(ref_rev_parse_rules[nr_rules]);
1969 scanf_fmts = xmalloc(nr_rules * sizeof(char *) + total_len);
1971 total_len = 0;
1972 for (i = 0; i < nr_rules; i++) {
1973 scanf_fmts[i] = (char *)&scanf_fmts[nr_rules]
1974 + total_len;
1975 gen_scanf_fmt(scanf_fmts[i], ref_rev_parse_rules[i]);
1976 total_len += strlen(ref_rev_parse_rules[i]);
1980 /* bail out if there are no rules */
1981 if (!nr_rules)
1982 return xstrdup(refname);
1984 /* buffer for scanf result, at most refname must fit */
1985 short_name = xstrdup(refname);
1987 /* skip first rule, it will always match */
1988 for (i = nr_rules - 1; i > 0 ; --i) {
1989 int j;
1990 int rules_to_fail = i;
1991 int short_name_len;
1993 if (1 != sscanf(refname, scanf_fmts[i], short_name))
1994 continue;
1996 short_name_len = strlen(short_name);
1999 * in strict mode, all (except the matched one) rules
2000 * must fail to resolve to a valid non-ambiguous ref
2002 if (strict)
2003 rules_to_fail = nr_rules;
2006 * check if the short name resolves to a valid ref,
2007 * but use only rules prior to the matched one
2009 for (j = 0; j < rules_to_fail; j++) {
2010 const char *rule = ref_rev_parse_rules[j];
2011 unsigned char short_objectname[20];
2012 char refname[PATH_MAX];
2014 /* skip matched rule */
2015 if (i == j)
2016 continue;
2019 * the short name is ambiguous, if it resolves
2020 * (with this previous rule) to a valid ref
2021 * read_ref() returns 0 on success
2023 mksnpath(refname, sizeof(refname),
2024 rule, short_name_len, short_name);
2025 if (!read_ref(refname, short_objectname))
2026 break;
2030 * short name is non-ambiguous if all previous rules
2031 * haven't resolved to a valid ref
2033 if (j == rules_to_fail)
2034 return short_name;
2037 free(short_name);
2038 return xstrdup(refname);