add_ref(): add docstring
[git/jnareb-git.git] / refs.c
blob2252c663b95a04ce930d23c42b0a7f04ad27852c
1 #include "cache.h"
2 #include "refs.h"
3 #include "object.h"
4 #include "tag.h"
5 #include "dir.h"
7 /* ISSYMREF=0x01, ISPACKED=0x02 and ISBROKEN=0x04 are public interfaces */
8 #define REF_KNOWS_PEELED 0x10
10 struct ref_entry {
11 unsigned char flag; /* ISSYMREF? ISPACKED? */
12 unsigned char sha1[20];
13 unsigned char peeled[20];
14 /* The full name of the reference (e.g., "refs/heads/master"): */
15 char name[FLEX_ARRAY];
18 struct ref_array {
19 int nr, alloc;
20 struct ref_entry **refs;
24 * Parse one line from a packed-refs file. Write the SHA1 to sha1.
25 * Return a pointer to the refname within the line (null-terminated),
26 * or NULL if there was a problem.
28 static const char *parse_ref_line(char *line, unsigned char *sha1)
31 * 42: the answer to everything.
33 * In this case, it happens to be the answer to
34 * 40 (length of sha1 hex representation)
35 * +1 (space in between hex and name)
36 * +1 (newline at the end of the line)
38 int len = strlen(line) - 42;
40 if (len <= 0)
41 return NULL;
42 if (get_sha1_hex(line, sha1) < 0)
43 return NULL;
44 if (!isspace(line[40]))
45 return NULL;
46 line += 41;
47 if (isspace(*line))
48 return NULL;
49 if (line[len] != '\n')
50 return NULL;
51 line[len] = 0;
53 return line;
56 /* Add a ref_entry to the end of the ref_array (unsorted). */
57 static void add_ref(const char *refname, const unsigned char *sha1,
58 int flag, int check_name, struct ref_array *refs,
59 struct ref_entry **new_entry)
61 int len;
62 struct ref_entry *entry;
64 /* Allocate it and add it in.. */
65 len = strlen(refname) + 1;
66 entry = xmalloc(sizeof(struct ref_entry) + len);
67 hashcpy(entry->sha1, sha1);
68 hashclr(entry->peeled);
69 if (check_name &&
70 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);
87 static void sort_ref_array(struct ref_array *array)
89 int i = 0, j = 1;
91 /* Nothing to sort unless there are at least two entries */
92 if (array->nr < 2)
93 return;
95 qsort(array->refs, array->nr, sizeof(*array->refs), ref_entry_cmp);
97 /* Remove any duplicates from the ref_array */
98 for (; j < array->nr; j++) {
99 struct ref_entry *a = array->refs[i];
100 struct ref_entry *b = array->refs[j];
101 if (!strcmp(a->name, b->name)) {
102 if (hashcmp(a->sha1, b->sha1))
103 die("Duplicated ref, and SHA1s don't match: %s",
104 a->name);
105 warning("Duplicated ref: %s", a->name);
106 free(b);
107 continue;
109 i++;
110 array->refs[i] = array->refs[j];
112 array->nr = i + 1;
115 static struct ref_entry *search_ref_array(struct ref_array *array, const char *refname)
117 struct ref_entry *e, **r;
118 int len;
120 if (refname == NULL)
121 return NULL;
123 if (!array->nr)
124 return NULL;
126 len = strlen(refname) + 1;
127 e = xmalloc(sizeof(struct ref_entry) + len);
128 memcpy(e->name, refname, len);
130 r = bsearch(&e, array->refs, array->nr, sizeof(*array->refs), ref_entry_cmp);
132 free(e);
134 if (r == NULL)
135 return NULL;
137 return *r;
141 * Future: need to be in "struct repository"
142 * when doing a full libification.
144 static struct ref_cache {
145 struct ref_cache *next;
146 char did_loose;
147 char did_packed;
148 struct ref_array loose;
149 struct ref_array packed;
150 /* The submodule name, or "" for the main repo. */
151 char name[FLEX_ARRAY];
152 } *ref_cache;
154 static struct ref_entry *current_ref;
156 static struct ref_array extra_refs;
158 static void clear_ref_array(struct ref_array *array)
160 int i;
161 for (i = 0; i < array->nr; i++)
162 free(array->refs[i]);
163 free(array->refs);
164 array->nr = array->alloc = 0;
165 array->refs = NULL;
168 static void clear_packed_ref_cache(struct ref_cache *refs)
170 if (refs->did_packed)
171 clear_ref_array(&refs->packed);
172 refs->did_packed = 0;
175 static void clear_loose_ref_cache(struct ref_cache *refs)
177 if (refs->did_loose)
178 clear_ref_array(&refs->loose);
179 refs->did_loose = 0;
182 static struct ref_cache *create_ref_cache(const char *submodule)
184 int len;
185 struct ref_cache *refs;
186 if (!submodule)
187 submodule = "";
188 len = strlen(submodule) + 1;
189 refs = xcalloc(1, sizeof(struct ref_cache) + len);
190 memcpy(refs->name, submodule, len);
191 return refs;
195 * Return a pointer to a ref_cache for the specified submodule. For
196 * the main repository, use submodule==NULL. The returned structure
197 * will be allocated and initialized but not necessarily populated; it
198 * should not be freed.
200 static struct ref_cache *get_ref_cache(const char *submodule)
202 struct ref_cache *refs = ref_cache;
203 if (!submodule)
204 submodule = "";
205 while (refs) {
206 if (!strcmp(submodule, refs->name))
207 return refs;
208 refs = refs->next;
211 refs = create_ref_cache(submodule);
212 refs->next = ref_cache;
213 ref_cache = refs;
214 return refs;
217 void invalidate_ref_cache(const char *submodule)
219 struct ref_cache *refs = get_ref_cache(submodule);
220 clear_packed_ref_cache(refs);
221 clear_loose_ref_cache(refs);
224 static void read_packed_refs(FILE *f, struct ref_array *array)
226 struct ref_entry *last = NULL;
227 char refline[PATH_MAX];
228 int flag = REF_ISPACKED;
230 while (fgets(refline, sizeof(refline), f)) {
231 unsigned char sha1[20];
232 const char *refname;
233 static const char header[] = "# pack-refs with:";
235 if (!strncmp(refline, header, sizeof(header)-1)) {
236 const char *traits = refline + sizeof(header) - 1;
237 if (strstr(traits, " peeled "))
238 flag |= REF_KNOWS_PEELED;
239 /* perhaps other traits later as well */
240 continue;
243 refname = parse_ref_line(refline, sha1);
244 if (refname) {
245 add_ref(refname, sha1, flag, 1, array, &last);
246 continue;
248 if (last &&
249 refline[0] == '^' &&
250 strlen(refline) == 42 &&
251 refline[41] == '\n' &&
252 !get_sha1_hex(refline + 1, sha1))
253 hashcpy(last->peeled, sha1);
255 sort_ref_array(array);
258 void add_extra_ref(const char *refname, const unsigned char *sha1, int flag)
260 add_ref(refname, sha1, flag, 0, &extra_refs, NULL);
263 void clear_extra_refs(void)
265 clear_ref_array(&extra_refs);
268 static struct ref_array *get_packed_refs(const char *submodule)
270 struct ref_cache *refs = get_ref_cache(submodule);
272 if (!refs->did_packed) {
273 const char *packed_refs_file;
274 FILE *f;
276 if (submodule)
277 packed_refs_file = git_path_submodule(submodule, "packed-refs");
278 else
279 packed_refs_file = git_path("packed-refs");
280 f = fopen(packed_refs_file, "r");
281 if (f) {
282 read_packed_refs(f, &refs->packed);
283 fclose(f);
285 refs->did_packed = 1;
287 return &refs->packed;
290 static void get_ref_dir(const char *submodule, const char *base,
291 struct ref_array *array)
293 DIR *dir;
294 const char *path;
296 if (submodule)
297 path = git_path_submodule(submodule, "%s", base);
298 else
299 path = git_path("%s", base);
302 dir = opendir(path);
304 if (dir) {
305 struct dirent *de;
306 int baselen = strlen(base);
307 char *refname = xmalloc(baselen + 257);
309 memcpy(refname, base, baselen);
310 if (baselen && base[baselen-1] != '/')
311 refname[baselen++] = '/';
313 while ((de = readdir(dir)) != NULL) {
314 unsigned char sha1[20];
315 struct stat st;
316 int flag;
317 int namelen;
318 const char *refdir;
320 if (de->d_name[0] == '.')
321 continue;
322 namelen = strlen(de->d_name);
323 if (namelen > 255)
324 continue;
325 if (has_extension(de->d_name, ".lock"))
326 continue;
327 memcpy(refname + baselen, de->d_name, namelen+1);
328 refdir = submodule
329 ? git_path_submodule(submodule, "%s", refname)
330 : git_path("%s", refname);
331 if (stat(refdir, &st) < 0)
332 continue;
333 if (S_ISDIR(st.st_mode)) {
334 get_ref_dir(submodule, refname, array);
335 continue;
337 if (submodule) {
338 hashclr(sha1);
339 flag = 0;
340 if (resolve_gitlink_ref(submodule, refname, sha1) < 0) {
341 hashclr(sha1);
342 flag |= REF_ISBROKEN;
344 } else if (read_ref_full(refname, sha1, 1, &flag)) {
345 hashclr(sha1);
346 flag |= REF_ISBROKEN;
348 add_ref(refname, sha1, flag, 1, array, NULL);
350 free(refname);
351 closedir(dir);
355 struct warn_if_dangling_data {
356 FILE *fp;
357 const char *refname;
358 const char *msg_fmt;
361 static int warn_if_dangling_symref(const char *refname, const unsigned char *sha1,
362 int flags, void *cb_data)
364 struct warn_if_dangling_data *d = cb_data;
365 const char *resolves_to;
366 unsigned char junk[20];
368 if (!(flags & REF_ISSYMREF))
369 return 0;
371 resolves_to = resolve_ref(refname, junk, 0, NULL);
372 if (!resolves_to || strcmp(resolves_to, d->refname))
373 return 0;
375 fprintf(d->fp, d->msg_fmt, refname);
376 return 0;
379 void warn_dangling_symref(FILE *fp, const char *msg_fmt, const char *refname)
381 struct warn_if_dangling_data data;
383 data.fp = fp;
384 data.refname = refname;
385 data.msg_fmt = msg_fmt;
386 for_each_rawref(warn_if_dangling_symref, &data);
389 static struct ref_array *get_loose_refs(const char *submodule)
391 struct ref_cache *refs = get_ref_cache(submodule);
393 if (!refs->did_loose) {
394 get_ref_dir(submodule, "refs", &refs->loose);
395 sort_ref_array(&refs->loose);
396 refs->did_loose = 1;
398 return &refs->loose;
401 /* We allow "recursive" symbolic refs. Only within reason, though */
402 #define MAXDEPTH 5
403 #define MAXREFLEN (1024)
406 * Called by resolve_gitlink_ref_recursive() after it failed to read
407 * from "name", which is "module/.git/<refname>". Find <refname> in
408 * the packed-refs file for the submodule.
410 static int resolve_gitlink_packed_ref(char *name, int pathlen,
411 const char *refname, unsigned char *sha1)
413 int retval = -1;
414 struct ref_entry *ref;
415 struct ref_array *array;
417 /* being defensive: resolve_gitlink_ref() did this for us */
418 if (pathlen < 6 || memcmp(name + pathlen - 6, "/.git/", 6))
419 die("Oops");
420 name[pathlen - 6] = '\0'; /* make it path to the submodule */
421 array = get_packed_refs(name);
422 ref = search_ref_array(array, refname);
423 if (ref != NULL) {
424 memcpy(sha1, ref->sha1, 20);
425 retval = 0;
427 return retval;
430 static int resolve_gitlink_ref_recursive(char *name, int pathlen,
431 const char *refname, unsigned char *sha1,
432 int recursion)
434 int fd, len = strlen(refname);
435 char buffer[128], *p;
437 if (recursion > MAXDEPTH || len > MAXREFLEN)
438 return -1;
439 memcpy(name + pathlen, refname, len+1);
440 fd = open(name, O_RDONLY);
441 if (fd < 0)
442 return resolve_gitlink_packed_ref(name, pathlen, refname, sha1);
444 len = read(fd, buffer, sizeof(buffer)-1);
445 close(fd);
446 if (len < 0)
447 return -1;
448 while (len && isspace(buffer[len-1]))
449 len--;
450 buffer[len] = 0;
452 /* Was it a detached head or an old-fashioned symlink? */
453 if (!get_sha1_hex(buffer, sha1))
454 return 0;
456 /* Symref? */
457 if (strncmp(buffer, "ref:", 4))
458 return -1;
459 p = buffer + 4;
460 while (isspace(*p))
461 p++;
463 return resolve_gitlink_ref_recursive(name, pathlen, p, sha1, recursion+1);
466 int resolve_gitlink_ref(const char *path, const char *refname, unsigned char *sha1)
468 int len = strlen(path), retval;
469 char *gitdir;
470 const char *tmp;
472 while (len && path[len-1] == '/')
473 len--;
474 if (!len)
475 return -1;
476 gitdir = xmalloc(len + MAXREFLEN + 8);
477 memcpy(gitdir, path, len);
478 memcpy(gitdir + len, "/.git", 6);
479 len += 5;
481 tmp = read_gitfile(gitdir);
482 if (tmp) {
483 free(gitdir);
484 len = strlen(tmp);
485 gitdir = xmalloc(len + MAXREFLEN + 3);
486 memcpy(gitdir, tmp, len);
488 gitdir[len] = '/';
489 gitdir[++len] = '\0';
490 retval = resolve_gitlink_ref_recursive(gitdir, len, refname, sha1, 0);
491 free(gitdir);
492 return retval;
496 * Try to read ref from the packed references. On success, set sha1
497 * and return 0; otherwise, return -1.
499 static int get_packed_ref(const char *refname, unsigned char *sha1)
501 struct ref_array *packed = get_packed_refs(NULL);
502 struct ref_entry *entry = search_ref_array(packed, refname);
503 if (entry) {
504 hashcpy(sha1, entry->sha1);
505 return 0;
507 return -1;
510 const char *resolve_ref(const char *refname, unsigned char *sha1, int reading, int *flag)
512 int depth = MAXDEPTH;
513 ssize_t len;
514 char buffer[256];
515 static char refname_buffer[256];
517 if (flag)
518 *flag = 0;
520 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL))
521 return NULL;
523 for (;;) {
524 char path[PATH_MAX];
525 struct stat st;
526 char *buf;
527 int fd;
529 if (--depth < 0)
530 return NULL;
532 git_snpath(path, sizeof(path), "%s", refname);
534 if (lstat(path, &st) < 0) {
535 if (errno != ENOENT)
536 return NULL;
538 * The loose reference file does not exist;
539 * check for a packed reference.
541 if (!get_packed_ref(refname, sha1)) {
542 if (flag)
543 *flag |= REF_ISPACKED;
544 return refname;
546 /* The reference is not a packed reference, either. */
547 if (reading) {
548 return NULL;
549 } else {
550 hashclr(sha1);
551 return refname;
555 /* Follow "normalized" - ie "refs/.." symlinks by hand */
556 if (S_ISLNK(st.st_mode)) {
557 len = readlink(path, buffer, sizeof(buffer)-1);
558 if (len < 0)
559 return NULL;
560 buffer[len] = 0;
561 if (!prefixcmp(buffer, "refs/") &&
562 !check_refname_format(buffer, 0)) {
563 strcpy(refname_buffer, buffer);
564 refname = refname_buffer;
565 if (flag)
566 *flag |= REF_ISSYMREF;
567 continue;
571 /* Is it a directory? */
572 if (S_ISDIR(st.st_mode)) {
573 errno = EISDIR;
574 return NULL;
578 * Anything else, just open it and try to use it as
579 * a ref
581 fd = open(path, O_RDONLY);
582 if (fd < 0)
583 return NULL;
584 len = read_in_full(fd, buffer, sizeof(buffer)-1);
585 close(fd);
586 if (len < 0)
587 return NULL;
588 while (len && isspace(buffer[len-1]))
589 len--;
590 buffer[len] = '\0';
593 * Is it a symbolic ref?
595 if (prefixcmp(buffer, "ref:"))
596 break;
597 if (flag)
598 *flag |= REF_ISSYMREF;
599 buf = buffer + 4;
600 while (isspace(*buf))
601 buf++;
602 if (check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {
603 if (flag)
604 *flag |= REF_ISBROKEN;
605 return NULL;
607 refname = strcpy(refname_buffer, buf);
609 /* Please note that FETCH_HEAD has a second line containing other data. */
610 if (get_sha1_hex(buffer, sha1) || (buffer[40] != '\0' && !isspace(buffer[40]))) {
611 if (flag)
612 *flag |= REF_ISBROKEN;
613 return NULL;
615 return refname;
618 /* The argument to filter_refs */
619 struct ref_filter {
620 const char *pattern;
621 each_ref_fn *fn;
622 void *cb_data;
625 int read_ref_full(const char *refname, unsigned char *sha1, int reading, int *flags)
627 if (resolve_ref(refname, sha1, reading, flags))
628 return 0;
629 return -1;
632 int read_ref(const char *refname, unsigned char *sha1)
634 return read_ref_full(refname, sha1, 1, NULL);
637 #define DO_FOR_EACH_INCLUDE_BROKEN 01
638 static int do_one_ref(const char *base, each_ref_fn fn, int trim,
639 int flags, void *cb_data, struct ref_entry *entry)
641 if (prefixcmp(entry->name, base))
642 return 0;
644 if (!(flags & DO_FOR_EACH_INCLUDE_BROKEN)) {
645 if (entry->flag & REF_ISBROKEN)
646 return 0; /* ignore broken refs e.g. dangling symref */
647 if (!has_sha1_file(entry->sha1)) {
648 error("%s does not point to a valid object!", entry->name);
649 return 0;
652 current_ref = entry;
653 return fn(entry->name + trim, entry->sha1, entry->flag, cb_data);
656 static int filter_refs(const char *refname, const unsigned char *sha1, int flags,
657 void *data)
659 struct ref_filter *filter = (struct ref_filter *)data;
660 if (fnmatch(filter->pattern, refname, 0))
661 return 0;
662 return filter->fn(refname, sha1, flags, filter->cb_data);
665 int peel_ref(const char *refname, unsigned char *sha1)
667 int flag;
668 unsigned char base[20];
669 struct object *o;
671 if (current_ref && (current_ref->name == refname
672 || !strcmp(current_ref->name, refname))) {
673 if (current_ref->flag & REF_KNOWS_PEELED) {
674 hashcpy(sha1, current_ref->peeled);
675 return 0;
677 hashcpy(base, current_ref->sha1);
678 goto fallback;
681 if (read_ref_full(refname, base, 1, &flag))
682 return -1;
684 if ((flag & REF_ISPACKED)) {
685 struct ref_array *array = get_packed_refs(NULL);
686 struct ref_entry *r = search_ref_array(array, refname);
688 if (r != NULL && r->flag & REF_KNOWS_PEELED) {
689 hashcpy(sha1, r->peeled);
690 return 0;
694 fallback:
695 o = parse_object(base);
696 if (o && o->type == OBJ_TAG) {
697 o = deref_tag(o, refname, 0);
698 if (o) {
699 hashcpy(sha1, o->sha1);
700 return 0;
703 return -1;
706 static int do_for_each_ref(const char *submodule, const char *base, each_ref_fn fn,
707 int trim, int flags, void *cb_data)
709 int retval = 0, i, p = 0, l = 0;
710 struct ref_array *packed = get_packed_refs(submodule);
711 struct ref_array *loose = get_loose_refs(submodule);
713 struct ref_array *extra = &extra_refs;
715 for (i = 0; i < extra->nr; i++)
716 retval = do_one_ref(base, fn, trim, flags, cb_data, extra->refs[i]);
718 while (p < packed->nr && l < loose->nr) {
719 struct ref_entry *entry;
720 int cmp = strcmp(packed->refs[p]->name, loose->refs[l]->name);
721 if (!cmp) {
722 p++;
723 continue;
725 if (cmp > 0) {
726 entry = loose->refs[l++];
727 } else {
728 entry = packed->refs[p++];
730 retval = do_one_ref(base, fn, trim, flags, cb_data, entry);
731 if (retval)
732 goto end_each;
735 if (l < loose->nr) {
736 p = l;
737 packed = loose;
740 for (; p < packed->nr; p++) {
741 retval = do_one_ref(base, fn, trim, flags, cb_data, packed->refs[p]);
742 if (retval)
743 goto end_each;
746 end_each:
747 current_ref = NULL;
748 return retval;
752 static int do_head_ref(const char *submodule, each_ref_fn fn, void *cb_data)
754 unsigned char sha1[20];
755 int flag;
757 if (submodule) {
758 if (resolve_gitlink_ref(submodule, "HEAD", sha1) == 0)
759 return fn("HEAD", sha1, 0, cb_data);
761 return 0;
764 if (!read_ref_full("HEAD", sha1, 1, &flag))
765 return fn("HEAD", sha1, flag, cb_data);
767 return 0;
770 int head_ref(each_ref_fn fn, void *cb_data)
772 return do_head_ref(NULL, fn, cb_data);
775 int head_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
777 return do_head_ref(submodule, fn, cb_data);
780 int for_each_ref(each_ref_fn fn, void *cb_data)
782 return do_for_each_ref(NULL, "", fn, 0, 0, cb_data);
785 int for_each_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
787 return do_for_each_ref(submodule, "", fn, 0, 0, cb_data);
790 int for_each_ref_in(const char *prefix, each_ref_fn fn, void *cb_data)
792 return do_for_each_ref(NULL, prefix, fn, strlen(prefix), 0, cb_data);
795 int for_each_ref_in_submodule(const char *submodule, const char *prefix,
796 each_ref_fn fn, void *cb_data)
798 return do_for_each_ref(submodule, prefix, fn, strlen(prefix), 0, cb_data);
801 int for_each_tag_ref(each_ref_fn fn, void *cb_data)
803 return for_each_ref_in("refs/tags/", fn, cb_data);
806 int for_each_tag_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
808 return for_each_ref_in_submodule(submodule, "refs/tags/", fn, cb_data);
811 int for_each_branch_ref(each_ref_fn fn, void *cb_data)
813 return for_each_ref_in("refs/heads/", fn, cb_data);
816 int for_each_branch_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
818 return for_each_ref_in_submodule(submodule, "refs/heads/", fn, cb_data);
821 int for_each_remote_ref(each_ref_fn fn, void *cb_data)
823 return for_each_ref_in("refs/remotes/", fn, cb_data);
826 int for_each_remote_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
828 return for_each_ref_in_submodule(submodule, "refs/remotes/", fn, cb_data);
831 int for_each_replace_ref(each_ref_fn fn, void *cb_data)
833 return do_for_each_ref(NULL, "refs/replace/", fn, 13, 0, cb_data);
836 int head_ref_namespaced(each_ref_fn fn, void *cb_data)
838 struct strbuf buf = STRBUF_INIT;
839 int ret = 0;
840 unsigned char sha1[20];
841 int flag;
843 strbuf_addf(&buf, "%sHEAD", get_git_namespace());
844 if (!read_ref_full(buf.buf, sha1, 1, &flag))
845 ret = fn(buf.buf, sha1, flag, cb_data);
846 strbuf_release(&buf);
848 return ret;
851 int for_each_namespaced_ref(each_ref_fn fn, void *cb_data)
853 struct strbuf buf = STRBUF_INIT;
854 int ret;
855 strbuf_addf(&buf, "%srefs/", get_git_namespace());
856 ret = do_for_each_ref(NULL, buf.buf, fn, 0, 0, cb_data);
857 strbuf_release(&buf);
858 return ret;
861 int for_each_glob_ref_in(each_ref_fn fn, const char *pattern,
862 const char *prefix, void *cb_data)
864 struct strbuf real_pattern = STRBUF_INIT;
865 struct ref_filter filter;
866 int ret;
868 if (!prefix && prefixcmp(pattern, "refs/"))
869 strbuf_addstr(&real_pattern, "refs/");
870 else if (prefix)
871 strbuf_addstr(&real_pattern, prefix);
872 strbuf_addstr(&real_pattern, pattern);
874 if (!has_glob_specials(pattern)) {
875 /* Append implied '/' '*' if not present. */
876 if (real_pattern.buf[real_pattern.len - 1] != '/')
877 strbuf_addch(&real_pattern, '/');
878 /* No need to check for '*', there is none. */
879 strbuf_addch(&real_pattern, '*');
882 filter.pattern = real_pattern.buf;
883 filter.fn = fn;
884 filter.cb_data = cb_data;
885 ret = for_each_ref(filter_refs, &filter);
887 strbuf_release(&real_pattern);
888 return ret;
891 int for_each_glob_ref(each_ref_fn fn, const char *pattern, void *cb_data)
893 return for_each_glob_ref_in(fn, pattern, NULL, cb_data);
896 int for_each_rawref(each_ref_fn fn, void *cb_data)
898 return do_for_each_ref(NULL, "", fn, 0,
899 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);
903 * Make sure "ref" is something reasonable to have under ".git/refs/";
904 * We do not like it if:
906 * - any path component of it begins with ".", or
907 * - it has double dots "..", or
908 * - it has ASCII control character, "~", "^", ":" or SP, anywhere, or
909 * - it ends with a "/".
910 * - it ends with ".lock"
911 * - it contains a "\" (backslash)
914 /* Return true iff ch is not allowed in reference names. */
915 static inline int bad_ref_char(int ch)
917 if (((unsigned) ch) <= ' ' || ch == 0x7f ||
918 ch == '~' || ch == '^' || ch == ':' || ch == '\\')
919 return 1;
920 /* 2.13 Pattern Matching Notation */
921 if (ch == '*' || ch == '?' || ch == '[') /* Unsupported */
922 return 1;
923 return 0;
927 * Try to read one refname component from the front of refname. Return
928 * the length of the component found, or -1 if the component is not
929 * legal.
931 static int check_refname_component(const char *refname, int flags)
933 const char *cp;
934 char last = '\0';
936 for (cp = refname; ; cp++) {
937 char ch = *cp;
938 if (ch == '\0' || ch == '/')
939 break;
940 if (bad_ref_char(ch))
941 return -1; /* Illegal character in refname. */
942 if (last == '.' && ch == '.')
943 return -1; /* Refname contains "..". */
944 if (last == '@' && ch == '{')
945 return -1; /* Refname contains "@{". */
946 last = ch;
948 if (cp == refname)
949 return -1; /* Component has zero length. */
950 if (refname[0] == '.') {
951 if (!(flags & REFNAME_DOT_COMPONENT))
952 return -1; /* Component starts with '.'. */
954 * Even if leading dots are allowed, don't allow "."
955 * as a component (".." is prevented by a rule above).
957 if (refname[1] == '\0')
958 return -1; /* Component equals ".". */
960 if (cp - refname >= 5 && !memcmp(cp - 5, ".lock", 5))
961 return -1; /* Refname ends with ".lock". */
962 return cp - refname;
965 int check_refname_format(const char *refname, int flags)
967 int component_len, component_count = 0;
969 while (1) {
970 /* We are at the start of a path component. */
971 component_len = check_refname_component(refname, flags);
972 if (component_len < 0) {
973 if ((flags & REFNAME_REFSPEC_PATTERN) &&
974 refname[0] == '*' &&
975 (refname[1] == '\0' || refname[1] == '/')) {
976 /* Accept one wildcard as a full refname component. */
977 flags &= ~REFNAME_REFSPEC_PATTERN;
978 component_len = 1;
979 } else {
980 return -1;
983 component_count++;
984 if (refname[component_len] == '\0')
985 break;
986 /* Skip to next component. */
987 refname += component_len + 1;
990 if (refname[component_len - 1] == '.')
991 return -1; /* Refname ends with '.'. */
992 if (!(flags & REFNAME_ALLOW_ONELEVEL) && component_count < 2)
993 return -1; /* Refname has only one component. */
994 return 0;
997 const char *prettify_refname(const char *name)
999 return name + (
1000 !prefixcmp(name, "refs/heads/") ? 11 :
1001 !prefixcmp(name, "refs/tags/") ? 10 :
1002 !prefixcmp(name, "refs/remotes/") ? 13 :
1006 const char *ref_rev_parse_rules[] = {
1007 "%.*s",
1008 "refs/%.*s",
1009 "refs/tags/%.*s",
1010 "refs/heads/%.*s",
1011 "refs/remotes/%.*s",
1012 "refs/remotes/%.*s/HEAD",
1013 NULL
1016 int refname_match(const char *abbrev_name, const char *full_name, const char **rules)
1018 const char **p;
1019 const int abbrev_name_len = strlen(abbrev_name);
1021 for (p = rules; *p; p++) {
1022 if (!strcmp(full_name, mkpath(*p, abbrev_name_len, abbrev_name))) {
1023 return 1;
1027 return 0;
1030 static struct ref_lock *verify_lock(struct ref_lock *lock,
1031 const unsigned char *old_sha1, int mustexist)
1033 if (read_ref_full(lock->ref_name, lock->old_sha1, mustexist, NULL)) {
1034 error("Can't verify ref %s", lock->ref_name);
1035 unlock_ref(lock);
1036 return NULL;
1038 if (hashcmp(lock->old_sha1, old_sha1)) {
1039 error("Ref %s is at %s but expected %s", lock->ref_name,
1040 sha1_to_hex(lock->old_sha1), sha1_to_hex(old_sha1));
1041 unlock_ref(lock);
1042 return NULL;
1044 return lock;
1047 static int remove_empty_directories(const char *file)
1049 /* we want to create a file but there is a directory there;
1050 * if that is an empty directory (or a directory that contains
1051 * only empty directories), remove them.
1053 struct strbuf path;
1054 int result;
1056 strbuf_init(&path, 20);
1057 strbuf_addstr(&path, file);
1059 result = remove_dir_recursively(&path, REMOVE_DIR_EMPTY_ONLY);
1061 strbuf_release(&path);
1063 return result;
1067 * Return true iff a reference named refname could be created without
1068 * conflicting with the name of an existing reference. If oldrefname
1069 * is non-NULL, ignore potential conflicts with oldrefname (e.g.,
1070 * because oldrefname is scheduled for deletion in the same
1071 * operation).
1073 static int is_refname_available(const char *refname, const char *oldrefname,
1074 struct ref_array *array)
1076 int i, namlen = strlen(refname); /* e.g. 'foo/bar' */
1077 for (i = 0; i < array->nr; i++ ) {
1078 struct ref_entry *entry = array->refs[i];
1079 /* entry->name could be 'foo' or 'foo/bar/baz' */
1080 if (!oldrefname || strcmp(oldrefname, entry->name)) {
1081 int len = strlen(entry->name);
1082 int cmplen = (namlen < len) ? namlen : len;
1083 const char *lead = (namlen < len) ? entry->name : refname;
1084 if (!strncmp(refname, entry->name, cmplen) &&
1085 lead[cmplen] == '/') {
1086 error("'%s' exists; cannot create '%s'",
1087 entry->name, refname);
1088 return 0;
1092 return 1;
1096 * *string and *len will only be substituted, and *string returned (for
1097 * later free()ing) if the string passed in is a magic short-hand form
1098 * to name a branch.
1100 static char *substitute_branch_name(const char **string, int *len)
1102 struct strbuf buf = STRBUF_INIT;
1103 int ret = interpret_branch_name(*string, &buf);
1105 if (ret == *len) {
1106 size_t size;
1107 *string = strbuf_detach(&buf, &size);
1108 *len = size;
1109 return (char *)*string;
1112 return NULL;
1115 int dwim_ref(const char *str, int len, unsigned char *sha1, char **ref)
1117 char *last_branch = substitute_branch_name(&str, &len);
1118 const char **p, *r;
1119 int refs_found = 0;
1121 *ref = NULL;
1122 for (p = ref_rev_parse_rules; *p; p++) {
1123 char fullref[PATH_MAX];
1124 unsigned char sha1_from_ref[20];
1125 unsigned char *this_result;
1126 int flag;
1128 this_result = refs_found ? sha1_from_ref : sha1;
1129 mksnpath(fullref, sizeof(fullref), *p, len, str);
1130 r = resolve_ref(fullref, this_result, 1, &flag);
1131 if (r) {
1132 if (!refs_found++)
1133 *ref = xstrdup(r);
1134 if (!warn_ambiguous_refs)
1135 break;
1136 } else if ((flag & REF_ISSYMREF) && strcmp(fullref, "HEAD")) {
1137 warning("ignoring dangling symref %s.", fullref);
1138 } else if ((flag & REF_ISBROKEN) && strchr(fullref, '/')) {
1139 warning("ignoring broken ref %s.", fullref);
1142 free(last_branch);
1143 return refs_found;
1146 int dwim_log(const char *str, int len, unsigned char *sha1, char **log)
1148 char *last_branch = substitute_branch_name(&str, &len);
1149 const char **p;
1150 int logs_found = 0;
1152 *log = NULL;
1153 for (p = ref_rev_parse_rules; *p; p++) {
1154 struct stat st;
1155 unsigned char hash[20];
1156 char path[PATH_MAX];
1157 const char *ref, *it;
1159 mksnpath(path, sizeof(path), *p, len, str);
1160 ref = resolve_ref(path, hash, 1, NULL);
1161 if (!ref)
1162 continue;
1163 if (!stat(git_path("logs/%s", path), &st) &&
1164 S_ISREG(st.st_mode))
1165 it = path;
1166 else if (strcmp(ref, path) &&
1167 !stat(git_path("logs/%s", ref), &st) &&
1168 S_ISREG(st.st_mode))
1169 it = ref;
1170 else
1171 continue;
1172 if (!logs_found++) {
1173 *log = xstrdup(it);
1174 hashcpy(sha1, hash);
1176 if (!warn_ambiguous_refs)
1177 break;
1179 free(last_branch);
1180 return logs_found;
1183 static struct ref_lock *lock_ref_sha1_basic(const char *refname,
1184 const unsigned char *old_sha1,
1185 int flags, int *type_p)
1187 char *ref_file;
1188 const char *orig_refname = refname;
1189 struct ref_lock *lock;
1190 int last_errno = 0;
1191 int type, lflags;
1192 int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
1193 int missing = 0;
1195 lock = xcalloc(1, sizeof(struct ref_lock));
1196 lock->lock_fd = -1;
1198 refname = resolve_ref(refname, lock->old_sha1, mustexist, &type);
1199 if (!refname && errno == EISDIR) {
1200 /* we are trying to lock foo but we used to
1201 * have foo/bar which now does not exist;
1202 * it is normal for the empty directory 'foo'
1203 * to remain.
1205 ref_file = git_path("%s", orig_refname);
1206 if (remove_empty_directories(ref_file)) {
1207 last_errno = errno;
1208 error("there are still refs under '%s'", orig_refname);
1209 goto error_return;
1211 refname = resolve_ref(orig_refname, lock->old_sha1, mustexist, &type);
1213 if (type_p)
1214 *type_p = type;
1215 if (!refname) {
1216 last_errno = errno;
1217 error("unable to resolve reference %s: %s",
1218 orig_refname, strerror(errno));
1219 goto error_return;
1221 missing = is_null_sha1(lock->old_sha1);
1222 /* When the ref did not exist and we are creating it,
1223 * make sure there is no existing ref that is packed
1224 * whose name begins with our refname, nor a ref whose
1225 * name is a proper prefix of our refname.
1227 if (missing &&
1228 !is_refname_available(refname, NULL, get_packed_refs(NULL))) {
1229 last_errno = ENOTDIR;
1230 goto error_return;
1233 lock->lk = xcalloc(1, sizeof(struct lock_file));
1235 lflags = LOCK_DIE_ON_ERROR;
1236 if (flags & REF_NODEREF) {
1237 refname = orig_refname;
1238 lflags |= LOCK_NODEREF;
1240 lock->ref_name = xstrdup(refname);
1241 lock->orig_ref_name = xstrdup(orig_refname);
1242 ref_file = git_path("%s", refname);
1243 if (missing)
1244 lock->force_write = 1;
1245 if ((flags & REF_NODEREF) && (type & REF_ISSYMREF))
1246 lock->force_write = 1;
1248 if (safe_create_leading_directories(ref_file)) {
1249 last_errno = errno;
1250 error("unable to create directory for %s", ref_file);
1251 goto error_return;
1254 lock->lock_fd = hold_lock_file_for_update(lock->lk, ref_file, lflags);
1255 return old_sha1 ? verify_lock(lock, old_sha1, mustexist) : lock;
1257 error_return:
1258 unlock_ref(lock);
1259 errno = last_errno;
1260 return NULL;
1263 struct ref_lock *lock_ref_sha1(const char *refname, const unsigned char *old_sha1)
1265 char refpath[PATH_MAX];
1266 if (check_refname_format(refname, 0))
1267 return NULL;
1268 strcpy(refpath, mkpath("refs/%s", refname));
1269 return lock_ref_sha1_basic(refpath, old_sha1, 0, NULL);
1272 struct ref_lock *lock_any_ref_for_update(const char *refname,
1273 const unsigned char *old_sha1, int flags)
1275 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL))
1276 return NULL;
1277 return lock_ref_sha1_basic(refname, old_sha1, flags, NULL);
1280 static struct lock_file packlock;
1282 static int repack_without_ref(const char *refname)
1284 struct ref_array *packed;
1285 struct ref_entry *ref;
1286 int fd, i;
1288 packed = get_packed_refs(NULL);
1289 ref = search_ref_array(packed, refname);
1290 if (ref == NULL)
1291 return 0;
1292 fd = hold_lock_file_for_update(&packlock, git_path("packed-refs"), 0);
1293 if (fd < 0) {
1294 unable_to_lock_error(git_path("packed-refs"), errno);
1295 return error("cannot delete '%s' from packed refs", refname);
1298 for (i = 0; i < packed->nr; i++) {
1299 char line[PATH_MAX + 100];
1300 int len;
1302 ref = packed->refs[i];
1304 if (!strcmp(refname, ref->name))
1305 continue;
1306 len = snprintf(line, sizeof(line), "%s %s\n",
1307 sha1_to_hex(ref->sha1), ref->name);
1308 /* this should not happen but just being defensive */
1309 if (len > sizeof(line))
1310 die("too long a refname '%s'", ref->name);
1311 write_or_die(fd, line, len);
1313 return commit_lock_file(&packlock);
1316 int delete_ref(const char *refname, const unsigned char *sha1, int delopt)
1318 struct ref_lock *lock;
1319 int err, i = 0, ret = 0, flag = 0;
1321 lock = lock_ref_sha1_basic(refname, sha1, 0, &flag);
1322 if (!lock)
1323 return 1;
1324 if (!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {
1325 /* loose */
1326 const char *path;
1328 if (!(delopt & REF_NODEREF)) {
1329 i = strlen(lock->lk->filename) - 5; /* .lock */
1330 lock->lk->filename[i] = 0;
1331 path = lock->lk->filename;
1332 } else {
1333 path = git_path("%s", refname);
1335 err = unlink_or_warn(path);
1336 if (err && errno != ENOENT)
1337 ret = 1;
1339 if (!(delopt & REF_NODEREF))
1340 lock->lk->filename[i] = '.';
1342 /* removing the loose one could have resurrected an earlier
1343 * packed one. Also, if it was not loose we need to repack
1344 * without it.
1346 ret |= repack_without_ref(refname);
1348 unlink_or_warn(git_path("logs/%s", lock->ref_name));
1349 invalidate_ref_cache(NULL);
1350 unlock_ref(lock);
1351 return ret;
1355 * People using contrib's git-new-workdir have .git/logs/refs ->
1356 * /some/other/path/.git/logs/refs, and that may live on another device.
1358 * IOW, to avoid cross device rename errors, the temporary renamed log must
1359 * live into logs/refs.
1361 #define TMP_RENAMED_LOG "logs/refs/.tmp-renamed-log"
1363 int rename_ref(const char *oldrefname, const char *newrefname, const char *logmsg)
1365 unsigned char sha1[20], orig_sha1[20];
1366 int flag = 0, logmoved = 0;
1367 struct ref_lock *lock;
1368 struct stat loginfo;
1369 int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);
1370 const char *symref = NULL;
1372 if (log && S_ISLNK(loginfo.st_mode))
1373 return error("reflog for %s is a symlink", oldrefname);
1375 symref = resolve_ref(oldrefname, orig_sha1, 1, &flag);
1376 if (flag & REF_ISSYMREF)
1377 return error("refname %s is a symbolic ref, renaming it is not supported",
1378 oldrefname);
1379 if (!symref)
1380 return error("refname %s not found", oldrefname);
1382 if (!is_refname_available(newrefname, oldrefname, get_packed_refs(NULL)))
1383 return 1;
1385 if (!is_refname_available(newrefname, oldrefname, get_loose_refs(NULL)))
1386 return 1;
1388 if (log && rename(git_path("logs/%s", oldrefname), git_path(TMP_RENAMED_LOG)))
1389 return error("unable to move logfile logs/%s to "TMP_RENAMED_LOG": %s",
1390 oldrefname, strerror(errno));
1392 if (delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {
1393 error("unable to delete old %s", oldrefname);
1394 goto rollback;
1397 if (!read_ref_full(newrefname, sha1, 1, &flag) &&
1398 delete_ref(newrefname, sha1, REF_NODEREF)) {
1399 if (errno==EISDIR) {
1400 if (remove_empty_directories(git_path("%s", newrefname))) {
1401 error("Directory not empty: %s", newrefname);
1402 goto rollback;
1404 } else {
1405 error("unable to delete existing %s", newrefname);
1406 goto rollback;
1410 if (log && safe_create_leading_directories(git_path("logs/%s", newrefname))) {
1411 error("unable to create directory for %s", newrefname);
1412 goto rollback;
1415 retry:
1416 if (log && rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", newrefname))) {
1417 if (errno==EISDIR || errno==ENOTDIR) {
1419 * rename(a, b) when b is an existing
1420 * directory ought to result in ISDIR, but
1421 * Solaris 5.8 gives ENOTDIR. Sheesh.
1423 if (remove_empty_directories(git_path("logs/%s", newrefname))) {
1424 error("Directory not empty: logs/%s", newrefname);
1425 goto rollback;
1427 goto retry;
1428 } else {
1429 error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s: %s",
1430 newrefname, strerror(errno));
1431 goto rollback;
1434 logmoved = log;
1436 lock = lock_ref_sha1_basic(newrefname, NULL, 0, NULL);
1437 if (!lock) {
1438 error("unable to lock %s for update", newrefname);
1439 goto rollback;
1441 lock->force_write = 1;
1442 hashcpy(lock->old_sha1, orig_sha1);
1443 if (write_ref_sha1(lock, orig_sha1, logmsg)) {
1444 error("unable to write current sha1 into %s", newrefname);
1445 goto rollback;
1448 return 0;
1450 rollback:
1451 lock = lock_ref_sha1_basic(oldrefname, NULL, 0, NULL);
1452 if (!lock) {
1453 error("unable to lock %s for rollback", oldrefname);
1454 goto rollbacklog;
1457 lock->force_write = 1;
1458 flag = log_all_ref_updates;
1459 log_all_ref_updates = 0;
1460 if (write_ref_sha1(lock, orig_sha1, NULL))
1461 error("unable to write current sha1 into %s", oldrefname);
1462 log_all_ref_updates = flag;
1464 rollbacklog:
1465 if (logmoved && rename(git_path("logs/%s", newrefname), git_path("logs/%s", oldrefname)))
1466 error("unable to restore logfile %s from %s: %s",
1467 oldrefname, newrefname, strerror(errno));
1468 if (!logmoved && log &&
1469 rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", oldrefname)))
1470 error("unable to restore logfile %s from "TMP_RENAMED_LOG": %s",
1471 oldrefname, strerror(errno));
1473 return 1;
1476 int close_ref(struct ref_lock *lock)
1478 if (close_lock_file(lock->lk))
1479 return -1;
1480 lock->lock_fd = -1;
1481 return 0;
1484 int commit_ref(struct ref_lock *lock)
1486 if (commit_lock_file(lock->lk))
1487 return -1;
1488 lock->lock_fd = -1;
1489 return 0;
1492 void unlock_ref(struct ref_lock *lock)
1494 /* Do not free lock->lk -- atexit() still looks at them */
1495 if (lock->lk)
1496 rollback_lock_file(lock->lk);
1497 free(lock->ref_name);
1498 free(lock->orig_ref_name);
1499 free(lock);
1503 * copy the reflog message msg to buf, which has been allocated sufficiently
1504 * large, while cleaning up the whitespaces. Especially, convert LF to space,
1505 * because reflog file is one line per entry.
1507 static int copy_msg(char *buf, const char *msg)
1509 char *cp = buf;
1510 char c;
1511 int wasspace = 1;
1513 *cp++ = '\t';
1514 while ((c = *msg++)) {
1515 if (wasspace && isspace(c))
1516 continue;
1517 wasspace = isspace(c);
1518 if (wasspace)
1519 c = ' ';
1520 *cp++ = c;
1522 while (buf < cp && isspace(cp[-1]))
1523 cp--;
1524 *cp++ = '\n';
1525 return cp - buf;
1528 int log_ref_setup(const char *refname, char *logfile, int bufsize)
1530 int logfd, oflags = O_APPEND | O_WRONLY;
1532 git_snpath(logfile, bufsize, "logs/%s", refname);
1533 if (log_all_ref_updates &&
1534 (!prefixcmp(refname, "refs/heads/") ||
1535 !prefixcmp(refname, "refs/remotes/") ||
1536 !prefixcmp(refname, "refs/notes/") ||
1537 !strcmp(refname, "HEAD"))) {
1538 if (safe_create_leading_directories(logfile) < 0)
1539 return error("unable to create directory for %s",
1540 logfile);
1541 oflags |= O_CREAT;
1544 logfd = open(logfile, oflags, 0666);
1545 if (logfd < 0) {
1546 if (!(oflags & O_CREAT) && errno == ENOENT)
1547 return 0;
1549 if ((oflags & O_CREAT) && errno == EISDIR) {
1550 if (remove_empty_directories(logfile)) {
1551 return error("There are still logs under '%s'",
1552 logfile);
1554 logfd = open(logfile, oflags, 0666);
1557 if (logfd < 0)
1558 return error("Unable to append to %s: %s",
1559 logfile, strerror(errno));
1562 adjust_shared_perm(logfile);
1563 close(logfd);
1564 return 0;
1567 static int log_ref_write(const char *refname, const unsigned char *old_sha1,
1568 const unsigned char *new_sha1, const char *msg)
1570 int logfd, result, written, oflags = O_APPEND | O_WRONLY;
1571 unsigned maxlen, len;
1572 int msglen;
1573 char log_file[PATH_MAX];
1574 char *logrec;
1575 const char *committer;
1577 if (log_all_ref_updates < 0)
1578 log_all_ref_updates = !is_bare_repository();
1580 result = log_ref_setup(refname, log_file, sizeof(log_file));
1581 if (result)
1582 return result;
1584 logfd = open(log_file, oflags);
1585 if (logfd < 0)
1586 return 0;
1587 msglen = msg ? strlen(msg) : 0;
1588 committer = git_committer_info(0);
1589 maxlen = strlen(committer) + msglen + 100;
1590 logrec = xmalloc(maxlen);
1591 len = sprintf(logrec, "%s %s %s\n",
1592 sha1_to_hex(old_sha1),
1593 sha1_to_hex(new_sha1),
1594 committer);
1595 if (msglen)
1596 len += copy_msg(logrec + len - 1, msg) - 1;
1597 written = len <= maxlen ? write_in_full(logfd, logrec, len) : -1;
1598 free(logrec);
1599 if (close(logfd) != 0 || written != len)
1600 return error("Unable to append to %s", log_file);
1601 return 0;
1604 static int is_branch(const char *refname)
1606 return !strcmp(refname, "HEAD") || !prefixcmp(refname, "refs/heads/");
1609 int write_ref_sha1(struct ref_lock *lock,
1610 const unsigned char *sha1, const char *logmsg)
1612 static char term = '\n';
1613 struct object *o;
1615 if (!lock)
1616 return -1;
1617 if (!lock->force_write && !hashcmp(lock->old_sha1, sha1)) {
1618 unlock_ref(lock);
1619 return 0;
1621 o = parse_object(sha1);
1622 if (!o) {
1623 error("Trying to write ref %s with nonexistent object %s",
1624 lock->ref_name, sha1_to_hex(sha1));
1625 unlock_ref(lock);
1626 return -1;
1628 if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
1629 error("Trying to write non-commit object %s to branch %s",
1630 sha1_to_hex(sha1), lock->ref_name);
1631 unlock_ref(lock);
1632 return -1;
1634 if (write_in_full(lock->lock_fd, sha1_to_hex(sha1), 40) != 40 ||
1635 write_in_full(lock->lock_fd, &term, 1) != 1
1636 || close_ref(lock) < 0) {
1637 error("Couldn't write %s", lock->lk->filename);
1638 unlock_ref(lock);
1639 return -1;
1641 clear_loose_ref_cache(get_ref_cache(NULL));
1642 if (log_ref_write(lock->ref_name, lock->old_sha1, sha1, logmsg) < 0 ||
1643 (strcmp(lock->ref_name, lock->orig_ref_name) &&
1644 log_ref_write(lock->orig_ref_name, lock->old_sha1, sha1, logmsg) < 0)) {
1645 unlock_ref(lock);
1646 return -1;
1648 if (strcmp(lock->orig_ref_name, "HEAD") != 0) {
1650 * Special hack: If a branch is updated directly and HEAD
1651 * points to it (may happen on the remote side of a push
1652 * for example) then logically the HEAD reflog should be
1653 * updated too.
1654 * A generic solution implies reverse symref information,
1655 * but finding all symrefs pointing to the given branch
1656 * would be rather costly for this rare event (the direct
1657 * update of a branch) to be worth it. So let's cheat and
1658 * check with HEAD only which should cover 99% of all usage
1659 * scenarios (even 100% of the default ones).
1661 unsigned char head_sha1[20];
1662 int head_flag;
1663 const char *head_ref;
1664 head_ref = resolve_ref("HEAD", head_sha1, 1, &head_flag);
1665 if (head_ref && (head_flag & REF_ISSYMREF) &&
1666 !strcmp(head_ref, lock->ref_name))
1667 log_ref_write("HEAD", lock->old_sha1, sha1, logmsg);
1669 if (commit_ref(lock)) {
1670 error("Couldn't set %s", lock->ref_name);
1671 unlock_ref(lock);
1672 return -1;
1674 unlock_ref(lock);
1675 return 0;
1678 int create_symref(const char *ref_target, const char *refs_heads_master,
1679 const char *logmsg)
1681 const char *lockpath;
1682 char ref[1000];
1683 int fd, len, written;
1684 char *git_HEAD = git_pathdup("%s", ref_target);
1685 unsigned char old_sha1[20], new_sha1[20];
1687 if (logmsg && read_ref(ref_target, old_sha1))
1688 hashclr(old_sha1);
1690 if (safe_create_leading_directories(git_HEAD) < 0)
1691 return error("unable to create directory for %s", git_HEAD);
1693 #ifndef NO_SYMLINK_HEAD
1694 if (prefer_symlink_refs) {
1695 unlink(git_HEAD);
1696 if (!symlink(refs_heads_master, git_HEAD))
1697 goto done;
1698 fprintf(stderr, "no symlink - falling back to symbolic ref\n");
1700 #endif
1702 len = snprintf(ref, sizeof(ref), "ref: %s\n", refs_heads_master);
1703 if (sizeof(ref) <= len) {
1704 error("refname too long: %s", refs_heads_master);
1705 goto error_free_return;
1707 lockpath = mkpath("%s.lock", git_HEAD);
1708 fd = open(lockpath, O_CREAT | O_EXCL | O_WRONLY, 0666);
1709 if (fd < 0) {
1710 error("Unable to open %s for writing", lockpath);
1711 goto error_free_return;
1713 written = write_in_full(fd, ref, len);
1714 if (close(fd) != 0 || written != len) {
1715 error("Unable to write to %s", lockpath);
1716 goto error_unlink_return;
1718 if (rename(lockpath, git_HEAD) < 0) {
1719 error("Unable to create %s", git_HEAD);
1720 goto error_unlink_return;
1722 if (adjust_shared_perm(git_HEAD)) {
1723 error("Unable to fix permissions on %s", lockpath);
1724 error_unlink_return:
1725 unlink_or_warn(lockpath);
1726 error_free_return:
1727 free(git_HEAD);
1728 return -1;
1731 #ifndef NO_SYMLINK_HEAD
1732 done:
1733 #endif
1734 if (logmsg && !read_ref(refs_heads_master, new_sha1))
1735 log_ref_write(ref_target, old_sha1, new_sha1, logmsg);
1737 free(git_HEAD);
1738 return 0;
1741 static char *ref_msg(const char *line, const char *endp)
1743 const char *ep;
1744 line += 82;
1745 ep = memchr(line, '\n', endp - line);
1746 if (!ep)
1747 ep = endp;
1748 return xmemdupz(line, ep - line);
1751 int read_ref_at(const char *refname, unsigned long at_time, int cnt,
1752 unsigned char *sha1, char **msg,
1753 unsigned long *cutoff_time, int *cutoff_tz, int *cutoff_cnt)
1755 const char *logfile, *logdata, *logend, *rec, *lastgt, *lastrec;
1756 char *tz_c;
1757 int logfd, tz, reccnt = 0;
1758 struct stat st;
1759 unsigned long date;
1760 unsigned char logged_sha1[20];
1761 void *log_mapped;
1762 size_t mapsz;
1764 logfile = git_path("logs/%s", refname);
1765 logfd = open(logfile, O_RDONLY, 0);
1766 if (logfd < 0)
1767 die_errno("Unable to read log '%s'", logfile);
1768 fstat(logfd, &st);
1769 if (!st.st_size)
1770 die("Log %s is empty.", logfile);
1771 mapsz = xsize_t(st.st_size);
1772 log_mapped = xmmap(NULL, mapsz, PROT_READ, MAP_PRIVATE, logfd, 0);
1773 logdata = log_mapped;
1774 close(logfd);
1776 lastrec = NULL;
1777 rec = logend = logdata + st.st_size;
1778 while (logdata < rec) {
1779 reccnt++;
1780 if (logdata < rec && *(rec-1) == '\n')
1781 rec--;
1782 lastgt = NULL;
1783 while (logdata < rec && *(rec-1) != '\n') {
1784 rec--;
1785 if (*rec == '>')
1786 lastgt = rec;
1788 if (!lastgt)
1789 die("Log %s is corrupt.", logfile);
1790 date = strtoul(lastgt + 1, &tz_c, 10);
1791 if (date <= at_time || cnt == 0) {
1792 tz = strtoul(tz_c, NULL, 10);
1793 if (msg)
1794 *msg = ref_msg(rec, logend);
1795 if (cutoff_time)
1796 *cutoff_time = date;
1797 if (cutoff_tz)
1798 *cutoff_tz = tz;
1799 if (cutoff_cnt)
1800 *cutoff_cnt = reccnt - 1;
1801 if (lastrec) {
1802 if (get_sha1_hex(lastrec, logged_sha1))
1803 die("Log %s is corrupt.", logfile);
1804 if (get_sha1_hex(rec + 41, sha1))
1805 die("Log %s is corrupt.", logfile);
1806 if (hashcmp(logged_sha1, sha1)) {
1807 warning("Log %s has gap after %s.",
1808 logfile, show_date(date, tz, DATE_RFC2822));
1811 else if (date == at_time) {
1812 if (get_sha1_hex(rec + 41, sha1))
1813 die("Log %s is corrupt.", logfile);
1815 else {
1816 if (get_sha1_hex(rec + 41, logged_sha1))
1817 die("Log %s is corrupt.", logfile);
1818 if (hashcmp(logged_sha1, sha1)) {
1819 warning("Log %s unexpectedly ended on %s.",
1820 logfile, show_date(date, tz, DATE_RFC2822));
1823 munmap(log_mapped, mapsz);
1824 return 0;
1826 lastrec = rec;
1827 if (cnt > 0)
1828 cnt--;
1831 rec = logdata;
1832 while (rec < logend && *rec != '>' && *rec != '\n')
1833 rec++;
1834 if (rec == logend || *rec == '\n')
1835 die("Log %s is corrupt.", logfile);
1836 date = strtoul(rec + 1, &tz_c, 10);
1837 tz = strtoul(tz_c, NULL, 10);
1838 if (get_sha1_hex(logdata, sha1))
1839 die("Log %s is corrupt.", logfile);
1840 if (is_null_sha1(sha1)) {
1841 if (get_sha1_hex(logdata + 41, sha1))
1842 die("Log %s is corrupt.", logfile);
1844 if (msg)
1845 *msg = ref_msg(logdata, logend);
1846 munmap(log_mapped, mapsz);
1848 if (cutoff_time)
1849 *cutoff_time = date;
1850 if (cutoff_tz)
1851 *cutoff_tz = tz;
1852 if (cutoff_cnt)
1853 *cutoff_cnt = reccnt;
1854 return 1;
1857 int for_each_recent_reflog_ent(const char *refname, each_reflog_ent_fn fn, long ofs, void *cb_data)
1859 const char *logfile;
1860 FILE *logfp;
1861 struct strbuf sb = STRBUF_INIT;
1862 int ret = 0;
1864 logfile = git_path("logs/%s", refname);
1865 logfp = fopen(logfile, "r");
1866 if (!logfp)
1867 return -1;
1869 if (ofs) {
1870 struct stat statbuf;
1871 if (fstat(fileno(logfp), &statbuf) ||
1872 statbuf.st_size < ofs ||
1873 fseek(logfp, -ofs, SEEK_END) ||
1874 strbuf_getwholeline(&sb, logfp, '\n')) {
1875 fclose(logfp);
1876 strbuf_release(&sb);
1877 return -1;
1881 while (!strbuf_getwholeline(&sb, logfp, '\n')) {
1882 unsigned char osha1[20], nsha1[20];
1883 char *email_end, *message;
1884 unsigned long timestamp;
1885 int tz;
1887 /* old SP new SP name <email> SP time TAB msg LF */
1888 if (sb.len < 83 || sb.buf[sb.len - 1] != '\n' ||
1889 get_sha1_hex(sb.buf, osha1) || sb.buf[40] != ' ' ||
1890 get_sha1_hex(sb.buf + 41, nsha1) || sb.buf[81] != ' ' ||
1891 !(email_end = strchr(sb.buf + 82, '>')) ||
1892 email_end[1] != ' ' ||
1893 !(timestamp = strtoul(email_end + 2, &message, 10)) ||
1894 !message || message[0] != ' ' ||
1895 (message[1] != '+' && message[1] != '-') ||
1896 !isdigit(message[2]) || !isdigit(message[3]) ||
1897 !isdigit(message[4]) || !isdigit(message[5]))
1898 continue; /* corrupt? */
1899 email_end[1] = '\0';
1900 tz = strtol(message + 1, NULL, 10);
1901 if (message[6] != '\t')
1902 message += 6;
1903 else
1904 message += 7;
1905 ret = fn(osha1, nsha1, sb.buf + 82, timestamp, tz, message,
1906 cb_data);
1907 if (ret)
1908 break;
1910 fclose(logfp);
1911 strbuf_release(&sb);
1912 return ret;
1915 int for_each_reflog_ent(const char *refname, each_reflog_ent_fn fn, void *cb_data)
1917 return for_each_recent_reflog_ent(refname, fn, 0, cb_data);
1920 static int do_for_each_reflog(const char *base, each_ref_fn fn, void *cb_data)
1922 DIR *dir = opendir(git_path("logs/%s", base));
1923 int retval = 0;
1925 if (dir) {
1926 struct dirent *de;
1927 int baselen = strlen(base);
1928 char *log = xmalloc(baselen + 257);
1930 memcpy(log, base, baselen);
1931 if (baselen && base[baselen-1] != '/')
1932 log[baselen++] = '/';
1934 while ((de = readdir(dir)) != NULL) {
1935 struct stat st;
1936 int namelen;
1938 if (de->d_name[0] == '.')
1939 continue;
1940 namelen = strlen(de->d_name);
1941 if (namelen > 255)
1942 continue;
1943 if (has_extension(de->d_name, ".lock"))
1944 continue;
1945 memcpy(log + baselen, de->d_name, namelen+1);
1946 if (stat(git_path("logs/%s", log), &st) < 0)
1947 continue;
1948 if (S_ISDIR(st.st_mode)) {
1949 retval = do_for_each_reflog(log, fn, cb_data);
1950 } else {
1951 unsigned char sha1[20];
1952 if (read_ref_full(log, sha1, 0, NULL))
1953 retval = error("bad ref for %s", log);
1954 else
1955 retval = fn(log, sha1, 0, cb_data);
1957 if (retval)
1958 break;
1960 free(log);
1961 closedir(dir);
1963 else if (*base)
1964 return errno;
1965 return retval;
1968 int for_each_reflog(each_ref_fn fn, void *cb_data)
1970 return do_for_each_reflog("", fn, cb_data);
1973 int update_ref(const char *action, const char *refname,
1974 const unsigned char *sha1, const unsigned char *oldval,
1975 int flags, enum action_on_err onerr)
1977 static struct ref_lock *lock;
1978 lock = lock_any_ref_for_update(refname, oldval, flags);
1979 if (!lock) {
1980 const char *str = "Cannot lock the ref '%s'.";
1981 switch (onerr) {
1982 case MSG_ON_ERR: error(str, refname); break;
1983 case DIE_ON_ERR: die(str, refname); break;
1984 case QUIET_ON_ERR: break;
1986 return 1;
1988 if (write_ref_sha1(lock, sha1, action) < 0) {
1989 const char *str = "Cannot update the ref '%s'.";
1990 switch (onerr) {
1991 case MSG_ON_ERR: error(str, refname); break;
1992 case DIE_ON_ERR: die(str, refname); break;
1993 case QUIET_ON_ERR: break;
1995 return 1;
1997 return 0;
2000 int ref_exists(const char *refname)
2002 unsigned char sha1[20];
2003 return !!resolve_ref(refname, sha1, 1, NULL);
2006 struct ref *find_ref_by_name(const struct ref *list, const char *name)
2008 for ( ; list; list = list->next)
2009 if (!strcmp(list->name, name))
2010 return (struct ref *)list;
2011 return NULL;
2015 * generate a format suitable for scanf from a ref_rev_parse_rules
2016 * rule, that is replace the "%.*s" spec with a "%s" spec
2018 static void gen_scanf_fmt(char *scanf_fmt, const char *rule)
2020 char *spec;
2022 spec = strstr(rule, "%.*s");
2023 if (!spec || strstr(spec + 4, "%.*s"))
2024 die("invalid rule in ref_rev_parse_rules: %s", rule);
2026 /* copy all until spec */
2027 strncpy(scanf_fmt, rule, spec - rule);
2028 scanf_fmt[spec - rule] = '\0';
2029 /* copy new spec */
2030 strcat(scanf_fmt, "%s");
2031 /* copy remaining rule */
2032 strcat(scanf_fmt, spec + 4);
2034 return;
2037 char *shorten_unambiguous_ref(const char *refname, int strict)
2039 int i;
2040 static char **scanf_fmts;
2041 static int nr_rules;
2042 char *short_name;
2044 /* pre generate scanf formats from ref_rev_parse_rules[] */
2045 if (!nr_rules) {
2046 size_t total_len = 0;
2048 /* the rule list is NULL terminated, count them first */
2049 for (; ref_rev_parse_rules[nr_rules]; nr_rules++)
2050 /* no +1 because strlen("%s") < strlen("%.*s") */
2051 total_len += strlen(ref_rev_parse_rules[nr_rules]);
2053 scanf_fmts = xmalloc(nr_rules * sizeof(char *) + total_len);
2055 total_len = 0;
2056 for (i = 0; i < nr_rules; i++) {
2057 scanf_fmts[i] = (char *)&scanf_fmts[nr_rules]
2058 + total_len;
2059 gen_scanf_fmt(scanf_fmts[i], ref_rev_parse_rules[i]);
2060 total_len += strlen(ref_rev_parse_rules[i]);
2064 /* bail out if there are no rules */
2065 if (!nr_rules)
2066 return xstrdup(refname);
2068 /* buffer for scanf result, at most refname must fit */
2069 short_name = xstrdup(refname);
2071 /* skip first rule, it will always match */
2072 for (i = nr_rules - 1; i > 0 ; --i) {
2073 int j;
2074 int rules_to_fail = i;
2075 int short_name_len;
2077 if (1 != sscanf(refname, scanf_fmts[i], short_name))
2078 continue;
2080 short_name_len = strlen(short_name);
2083 * in strict mode, all (except the matched one) rules
2084 * must fail to resolve to a valid non-ambiguous ref
2086 if (strict)
2087 rules_to_fail = nr_rules;
2090 * check if the short name resolves to a valid ref,
2091 * but use only rules prior to the matched one
2093 for (j = 0; j < rules_to_fail; j++) {
2094 const char *rule = ref_rev_parse_rules[j];
2095 char refname[PATH_MAX];
2097 /* skip matched rule */
2098 if (i == j)
2099 continue;
2102 * the short name is ambiguous, if it resolves
2103 * (with this previous rule) to a valid ref
2104 * read_ref() returns 0 on success
2106 mksnpath(refname, sizeof(refname),
2107 rule, short_name_len, short_name);
2108 if (ref_exists(refname))
2109 break;
2113 * short name is non-ambiguous if all previous rules
2114 * haven't resolved to a valid ref
2116 if (j == rules_to_fail)
2117 return short_name;
2120 free(short_name);
2121 return xstrdup(refname);