Merge branch 'master' into next
[git/dscho.git] / remote.c
blob76b1bbdfe5fa63c05cc52c42d01b353c8f41a635
1 #include "cache.h"
2 #include "remote.h"
3 #include "refs.h"
4 #include "commit.h"
5 #include "diff.h"
6 #include "revision.h"
7 #include "dir.h"
8 #include "tag.h"
10 static struct refspec s_tag_refspec = {
14 "refs/tags/*",
15 "refs/tags/*"
18 const struct refspec *tag_refspec = &s_tag_refspec;
20 struct counted_string {
21 size_t len;
22 const char *s;
24 struct rewrite {
25 const char *base;
26 size_t baselen;
27 struct counted_string *instead_of;
28 int instead_of_nr;
29 int instead_of_alloc;
32 static struct remote **remotes;
33 static int remotes_alloc;
34 static int remotes_nr;
36 static struct branch **branches;
37 static int branches_alloc;
38 static int branches_nr;
40 static struct branch *current_branch;
41 static const char *default_remote_name;
42 static int explicit_default_remote_name;
44 static struct rewrite **rewrite;
45 static int rewrite_alloc;
46 static int rewrite_nr;
48 #define BUF_SIZE (2048)
49 static char buffer[BUF_SIZE];
51 static const char *alias_url(const char *url)
53 int i, j;
54 char *ret;
55 struct counted_string *longest;
56 int longest_i;
58 longest = NULL;
59 longest_i = -1;
60 for (i = 0; i < rewrite_nr; i++) {
61 if (!rewrite[i])
62 continue;
63 for (j = 0; j < rewrite[i]->instead_of_nr; j++) {
64 if (!prefixcmp(url, rewrite[i]->instead_of[j].s) &&
65 (!longest ||
66 longest->len < rewrite[i]->instead_of[j].len)) {
67 longest = &(rewrite[i]->instead_of[j]);
68 longest_i = i;
72 if (!longest)
73 return url;
75 ret = xmalloc(rewrite[longest_i]->baselen +
76 (strlen(url) - longest->len) + 1);
77 strcpy(ret, rewrite[longest_i]->base);
78 strcpy(ret + rewrite[longest_i]->baselen, url + longest->len);
79 return ret;
82 static void add_push_refspec(struct remote *remote, const char *ref)
84 ALLOC_GROW(remote->push_refspec,
85 remote->push_refspec_nr + 1,
86 remote->push_refspec_alloc);
87 remote->push_refspec[remote->push_refspec_nr++] = ref;
90 static void add_fetch_refspec(struct remote *remote, const char *ref)
92 ALLOC_GROW(remote->fetch_refspec,
93 remote->fetch_refspec_nr + 1,
94 remote->fetch_refspec_alloc);
95 remote->fetch_refspec[remote->fetch_refspec_nr++] = ref;
98 static void add_url(struct remote *remote, const char *url)
100 ALLOC_GROW(remote->url, remote->url_nr + 1, remote->url_alloc);
101 remote->url[remote->url_nr++] = url;
104 static void add_url_alias(struct remote *remote, const char *url)
106 add_url(remote, alias_url(url));
109 static struct remote *get_remote_by_name(const char *name)
111 int i;
112 for (i = 0; i < remotes_nr; i++) {
113 if (!strcmp(name, remotes[i]->name))
114 return remotes[i];
116 return NULL;
119 static struct remote *make_remote(const char *name, int len)
121 struct remote *ret;
122 int i;
124 for (i = 0; i < remotes_nr; i++) {
125 if (len ? (!strncmp(name, remotes[i]->name, len) &&
126 !remotes[i]->name[len]) :
127 !strcmp(name, remotes[i]->name))
128 return remotes[i];
131 ret = xcalloc(1, sizeof(struct remote));
132 ALLOC_GROW(remotes, remotes_nr + 1, remotes_alloc);
133 remotes[remotes_nr++] = ret;
134 if (len)
135 ret->name = xstrndup(name, len);
136 else
137 ret->name = xstrdup(name);
138 return ret;
141 static void add_merge(struct branch *branch, const char *name)
143 ALLOC_GROW(branch->merge_name, branch->merge_nr + 1,
144 branch->merge_alloc);
145 branch->merge_name[branch->merge_nr++] = name;
148 static struct branch *make_branch(const char *name, int len)
150 struct branch *ret;
151 int i;
152 char *refname;
154 for (i = 0; i < branches_nr; i++) {
155 if (len ? (!strncmp(name, branches[i]->name, len) &&
156 !branches[i]->name[len]) :
157 !strcmp(name, branches[i]->name))
158 return branches[i];
161 ALLOC_GROW(branches, branches_nr + 1, branches_alloc);
162 ret = xcalloc(1, sizeof(struct branch));
163 branches[branches_nr++] = ret;
164 if (len)
165 ret->name = xstrndup(name, len);
166 else
167 ret->name = xstrdup(name);
168 refname = xmalloc(strlen(name) + strlen("refs/heads/") + 1);
169 strcpy(refname, "refs/heads/");
170 strcpy(refname + strlen("refs/heads/"), ret->name);
171 ret->refname = refname;
173 return ret;
176 static struct rewrite *make_rewrite(const char *base, int len)
178 struct rewrite *ret;
179 int i;
181 for (i = 0; i < rewrite_nr; i++) {
182 if (len
183 ? (len == rewrite[i]->baselen &&
184 !strncmp(base, rewrite[i]->base, len))
185 : !strcmp(base, rewrite[i]->base))
186 return rewrite[i];
189 ALLOC_GROW(rewrite, rewrite_nr + 1, rewrite_alloc);
190 ret = xcalloc(1, sizeof(struct rewrite));
191 rewrite[rewrite_nr++] = ret;
192 if (len) {
193 ret->base = xstrndup(base, len);
194 ret->baselen = len;
196 else {
197 ret->base = xstrdup(base);
198 ret->baselen = strlen(base);
200 return ret;
203 static void add_instead_of(struct rewrite *rewrite, const char *instead_of)
205 ALLOC_GROW(rewrite->instead_of, rewrite->instead_of_nr + 1, rewrite->instead_of_alloc);
206 rewrite->instead_of[rewrite->instead_of_nr].s = instead_of;
207 rewrite->instead_of[rewrite->instead_of_nr].len = strlen(instead_of);
208 rewrite->instead_of_nr++;
211 static void read_remotes_file(struct remote *remote)
213 FILE *f = fopen(git_path("remotes/%s", remote->name), "r");
215 if (!f)
216 return;
217 remote->origin = REMOTE_REMOTES;
218 while (fgets(buffer, BUF_SIZE, f)) {
219 int value_list;
220 char *s, *p;
222 if (!prefixcmp(buffer, "URL:")) {
223 value_list = 0;
224 s = buffer + 4;
225 } else if (!prefixcmp(buffer, "Push:")) {
226 value_list = 1;
227 s = buffer + 5;
228 } else if (!prefixcmp(buffer, "Pull:")) {
229 value_list = 2;
230 s = buffer + 5;
231 } else
232 continue;
234 while (isspace(*s))
235 s++;
236 if (!*s)
237 continue;
239 p = s + strlen(s);
240 while (isspace(p[-1]))
241 *--p = 0;
243 switch (value_list) {
244 case 0:
245 add_url_alias(remote, xstrdup(s));
246 break;
247 case 1:
248 add_push_refspec(remote, xstrdup(s));
249 break;
250 case 2:
251 add_fetch_refspec(remote, xstrdup(s));
252 break;
255 fclose(f);
258 static void read_branches_file(struct remote *remote)
260 const char *slash = strchr(remote->name, '/');
261 char *frag;
262 struct strbuf branch = STRBUF_INIT;
263 int n = slash ? slash - remote->name : 1000;
264 FILE *f = fopen(git_path("branches/%.*s", n, remote->name), "r");
265 char *s, *p;
266 int len;
268 if (!f)
269 return;
270 s = fgets(buffer, BUF_SIZE, f);
271 fclose(f);
272 if (!s)
273 return;
274 while (isspace(*s))
275 s++;
276 if (!*s)
277 return;
278 remote->origin = REMOTE_BRANCHES;
279 p = s + strlen(s);
280 while (isspace(p[-1]))
281 *--p = 0;
282 len = p - s;
283 if (slash)
284 len += strlen(slash);
285 p = xmalloc(len + 1);
286 strcpy(p, s);
287 if (slash)
288 strcat(p, slash);
291 * With "slash", e.g. "git fetch jgarzik/netdev-2.6" when
292 * reading from $GIT_DIR/branches/jgarzik fetches "HEAD" from
293 * the partial URL obtained from the branches file plus
294 * "/netdev-2.6" and does not store it in any tracking ref.
295 * #branch specifier in the file is ignored.
297 * Otherwise, the branches file would have URL and optionally
298 * #branch specified. The "master" (or specified) branch is
299 * fetched and stored in the local branch of the same name.
301 frag = strchr(p, '#');
302 if (frag) {
303 *(frag++) = '\0';
304 strbuf_addf(&branch, "refs/heads/%s", frag);
305 } else
306 strbuf_addstr(&branch, "refs/heads/master");
307 if (!slash) {
308 strbuf_addf(&branch, ":refs/heads/%s", remote->name);
309 } else {
310 strbuf_reset(&branch);
311 strbuf_addstr(&branch, "HEAD:");
313 add_url_alias(remote, p);
314 add_fetch_refspec(remote, strbuf_detach(&branch, 0));
316 * Cogito compatible push: push current HEAD to remote #branch
317 * (master if missing)
319 strbuf_init(&branch, 0);
320 strbuf_addstr(&branch, "HEAD");
321 if (frag)
322 strbuf_addf(&branch, ":refs/heads/%s", frag);
323 else
324 strbuf_addstr(&branch, ":refs/heads/master");
325 add_push_refspec(remote, strbuf_detach(&branch, 0));
326 remote->fetch_tags = 1; /* always auto-follow */
329 static int handle_config(const char *key, const char *value, void *cb)
331 const char *name;
332 const char *subkey;
333 struct remote *remote;
334 struct branch *branch;
335 if (!prefixcmp(key, "branch.")) {
336 name = key + 7;
337 subkey = strrchr(name, '.');
338 if (!subkey)
339 return 0;
340 branch = make_branch(name, subkey - name);
341 if (!strcmp(subkey, ".remote")) {
342 if (!value)
343 return config_error_nonbool(key);
344 branch->remote_name = xstrdup(value);
345 if (branch == current_branch) {
346 default_remote_name = branch->remote_name;
347 explicit_default_remote_name = 1;
349 } else if (!strcmp(subkey, ".merge")) {
350 if (!value)
351 return config_error_nonbool(key);
352 add_merge(branch, xstrdup(value));
354 return 0;
356 if (!prefixcmp(key, "url.")) {
357 struct rewrite *rewrite;
358 name = key + 4;
359 subkey = strrchr(name, '.');
360 if (!subkey)
361 return 0;
362 rewrite = make_rewrite(name, subkey - name);
363 if (!strcmp(subkey, ".insteadof")) {
364 if (!value)
365 return config_error_nonbool(key);
366 add_instead_of(rewrite, xstrdup(value));
369 if (prefixcmp(key, "remote."))
370 return 0;
371 name = key + 7;
372 if (*name == '/') {
373 warning("Config remote shorthand cannot begin with '/': %s",
374 name);
375 return 0;
377 subkey = strrchr(name, '.');
378 if (!subkey)
379 return error("Config with no key for remote %s", name);
380 remote = make_remote(name, subkey - name);
381 remote->origin = REMOTE_CONFIG;
382 if (!strcmp(subkey, ".mirror"))
383 remote->mirror = git_config_bool(key, value);
384 else if (!strcmp(subkey, ".skipdefaultupdate"))
385 remote->skip_default_update = git_config_bool(key, value);
387 else if (!strcmp(subkey, ".url")) {
388 const char *v;
389 if (git_config_string(&v, key, value))
390 return -1;
391 add_url(remote, v);
392 } else if (!strcmp(subkey, ".push")) {
393 const char *v;
394 if (git_config_string(&v, key, value))
395 return -1;
396 add_push_refspec(remote, v);
397 } else if (!strcmp(subkey, ".fetch")) {
398 const char *v;
399 if (git_config_string(&v, key, value))
400 return -1;
401 add_fetch_refspec(remote, v);
402 } else if (!strcmp(subkey, ".receivepack")) {
403 const char *v;
404 if (git_config_string(&v, key, value))
405 return -1;
406 if (!remote->receivepack)
407 remote->receivepack = v;
408 else
409 error("more than one receivepack given, using the first");
410 } else if (!strcmp(subkey, ".uploadpack")) {
411 const char *v;
412 if (git_config_string(&v, key, value))
413 return -1;
414 if (!remote->uploadpack)
415 remote->uploadpack = v;
416 else
417 error("more than one uploadpack given, using the first");
418 } else if (!strcmp(subkey, ".tagopt")) {
419 if (!strcmp(value, "--no-tags"))
420 remote->fetch_tags = -1;
421 } else if (!strcmp(subkey, ".proxy")) {
422 return git_config_string((const char **)&remote->http_proxy,
423 key, value);
425 return 0;
428 static void alias_all_urls(void)
430 int i, j;
431 for (i = 0; i < remotes_nr; i++) {
432 if (!remotes[i])
433 continue;
434 for (j = 0; j < remotes[i]->url_nr; j++) {
435 remotes[i]->url[j] = alias_url(remotes[i]->url[j]);
440 static void read_config(void)
442 unsigned char sha1[20];
443 const char *head_ref;
444 int flag;
445 if (default_remote_name) // did this already
446 return;
447 default_remote_name = xstrdup("origin");
448 current_branch = NULL;
449 head_ref = resolve_ref("HEAD", sha1, 0, &flag);
450 if (head_ref && (flag & REF_ISSYMREF) &&
451 !prefixcmp(head_ref, "refs/heads/")) {
452 current_branch =
453 make_branch(head_ref + strlen("refs/heads/"), 0);
455 git_config(handle_config, NULL);
456 alias_all_urls();
460 * We need to make sure the tracking branches are well formed, but a
461 * wildcard refspec in "struct refspec" must have a trailing slash. We
462 * temporarily drop the trailing '/' while calling check_ref_format(),
463 * and put it back. The caller knows that a CHECK_REF_FORMAT_ONELEVEL
464 * error return is Ok for a wildcard refspec.
466 static int verify_refname(char *name, int is_glob)
468 int result;
470 result = check_ref_format(name);
471 if (is_glob && result == CHECK_REF_FORMAT_WILDCARD)
472 result = CHECK_REF_FORMAT_OK;
473 return result;
477 * This function frees a refspec array.
478 * Warning: code paths should be checked to ensure that the src
479 * and dst pointers are always freeable pointers as well
480 * as the refspec pointer itself.
482 static void free_refspecs(struct refspec *refspec, int nr_refspec)
484 int i;
486 if (!refspec)
487 return;
489 for (i = 0; i < nr_refspec; i++) {
490 free(refspec[i].src);
491 free(refspec[i].dst);
493 free(refspec);
496 static struct refspec *parse_refspec_internal(int nr_refspec, const char **refspec, int fetch, int verify)
498 int i;
499 int st;
500 struct refspec *rs = xcalloc(sizeof(*rs), nr_refspec);
502 for (i = 0; i < nr_refspec; i++) {
503 size_t llen;
504 int is_glob;
505 const char *lhs, *rhs;
507 is_glob = 0;
509 lhs = refspec[i];
510 if (*lhs == '+') {
511 rs[i].force = 1;
512 lhs++;
515 rhs = strrchr(lhs, ':');
518 * Before going on, special case ":" (or "+:") as a refspec
519 * for matching refs.
521 if (!fetch && rhs == lhs && rhs[1] == '\0') {
522 rs[i].matching = 1;
523 continue;
526 if (rhs) {
527 size_t rlen = strlen(++rhs);
528 is_glob = (1 <= rlen && strchr(rhs, '*'));
529 rs[i].dst = xstrndup(rhs, rlen);
532 llen = (rhs ? (rhs - lhs - 1) : strlen(lhs));
533 if (1 <= llen && memchr(lhs, '*', llen)) {
534 if ((rhs && !is_glob) || (!rhs && fetch))
535 goto invalid;
536 is_glob = 1;
537 } else if (rhs && is_glob) {
538 goto invalid;
541 rs[i].pattern = is_glob;
542 rs[i].src = xstrndup(lhs, llen);
544 if (fetch) {
546 * LHS
547 * - empty is allowed; it means HEAD.
548 * - otherwise it must be a valid looking ref.
550 if (!*rs[i].src)
551 ; /* empty is ok */
552 else {
553 st = verify_refname(rs[i].src, is_glob);
554 if (st && st != CHECK_REF_FORMAT_ONELEVEL)
555 goto invalid;
558 * RHS
559 * - missing is ok, and is same as empty.
560 * - empty is ok; it means not to store.
561 * - otherwise it must be a valid looking ref.
563 if (!rs[i].dst) {
564 ; /* ok */
565 } else if (!*rs[i].dst) {
566 ; /* ok */
567 } else {
568 st = verify_refname(rs[i].dst, is_glob);
569 if (st && st != CHECK_REF_FORMAT_ONELEVEL)
570 goto invalid;
572 } else {
574 * LHS
575 * - empty is allowed; it means delete.
576 * - when wildcarded, it must be a valid looking ref.
577 * - otherwise, it must be an extended SHA-1, but
578 * there is no existing way to validate this.
580 if (!*rs[i].src)
581 ; /* empty is ok */
582 else if (is_glob) {
583 st = verify_refname(rs[i].src, is_glob);
584 if (st && st != CHECK_REF_FORMAT_ONELEVEL)
585 goto invalid;
587 else
588 ; /* anything goes, for now */
590 * RHS
591 * - missing is allowed, but LHS then must be a
592 * valid looking ref.
593 * - empty is not allowed.
594 * - otherwise it must be a valid looking ref.
596 if (!rs[i].dst) {
597 st = verify_refname(rs[i].src, is_glob);
598 if (st && st != CHECK_REF_FORMAT_ONELEVEL)
599 goto invalid;
600 } else if (!*rs[i].dst) {
601 goto invalid;
602 } else {
603 st = verify_refname(rs[i].dst, is_glob);
604 if (st && st != CHECK_REF_FORMAT_ONELEVEL)
605 goto invalid;
609 return rs;
611 invalid:
612 if (verify) {
614 * nr_refspec must be greater than zero and i must be valid
615 * since it is only possible to reach this point from within
616 * the for loop above.
618 free_refspecs(rs, i+1);
619 return NULL;
621 die("Invalid refspec '%s'", refspec[i]);
624 int valid_fetch_refspec(const char *fetch_refspec_str)
626 const char *fetch_refspec[] = { fetch_refspec_str };
627 struct refspec *refspec;
629 refspec = parse_refspec_internal(1, fetch_refspec, 1, 1);
630 free_refspecs(refspec, 1);
631 return !!refspec;
634 struct refspec *parse_fetch_refspec(int nr_refspec, const char **refspec)
636 return parse_refspec_internal(nr_refspec, refspec, 1, 0);
639 static struct refspec *parse_push_refspec(int nr_refspec, const char **refspec)
641 return parse_refspec_internal(nr_refspec, refspec, 0, 0);
644 static int valid_remote_nick(const char *name)
646 if (!name[0] || is_dot_or_dotdot(name))
647 return 0;
648 return !strchr(name, '/'); /* no slash */
651 struct remote *remote_get(const char *name)
653 struct remote *ret;
654 int name_given = 0;
656 read_config();
657 if (name)
658 name_given = 1;
659 else {
660 name = default_remote_name;
661 name_given = explicit_default_remote_name;
663 if (name_given)
664 ret = make_remote(name, 0);
665 else {
666 ret = get_remote_by_name(name);
667 if (!ret)
668 return NULL;
670 if (valid_remote_nick(name)) {
671 if (!ret->url)
672 read_remotes_file(ret);
673 if (!ret->url)
674 read_branches_file(ret);
676 if (!ret->url)
677 add_url_alias(ret, name);
678 if (!ret->url)
679 return NULL;
680 ret->fetch = parse_fetch_refspec(ret->fetch_refspec_nr, ret->fetch_refspec);
681 ret->push = parse_push_refspec(ret->push_refspec_nr, ret->push_refspec);
682 return ret;
685 int for_each_remote(each_remote_fn fn, void *priv)
687 int i, result = 0;
688 read_config();
689 for (i = 0; i < remotes_nr && !result; i++) {
690 struct remote *r = remotes[i];
691 if (!r)
692 continue;
693 if (!r->fetch)
694 r->fetch = parse_fetch_refspec(r->fetch_refspec_nr,
695 r->fetch_refspec);
696 if (!r->push)
697 r->push = parse_push_refspec(r->push_refspec_nr,
698 r->push_refspec);
699 result = fn(r, priv);
701 return result;
704 void ref_remove_duplicates(struct ref *ref_map)
706 struct ref **posn;
707 struct ref *next;
708 for (; ref_map; ref_map = ref_map->next) {
709 if (!ref_map->peer_ref)
710 continue;
711 posn = &ref_map->next;
712 while (*posn) {
713 if ((*posn)->peer_ref &&
714 !strcmp((*posn)->peer_ref->name,
715 ref_map->peer_ref->name)) {
716 if (strcmp((*posn)->name, ref_map->name))
717 die("%s tracks both %s and %s",
718 ref_map->peer_ref->name,
719 (*posn)->name, ref_map->name);
720 next = (*posn)->next;
721 free((*posn)->peer_ref);
722 free(*posn);
723 *posn = next;
724 } else {
725 posn = &(*posn)->next;
731 int remote_has_url(struct remote *remote, const char *url)
733 int i;
734 for (i = 0; i < remote->url_nr; i++) {
735 if (!strcmp(remote->url[i], url))
736 return 1;
738 return 0;
741 static int match_name_with_pattern(const char *key, const char *name,
742 const char *value, char **result)
744 const char *kstar = strchr(key, '*');
745 size_t klen;
746 size_t ksuffixlen;
747 size_t namelen;
748 int ret;
749 if (!kstar)
750 die("Key '%s' of pattern had no '*'", key);
751 klen = kstar - key;
752 ksuffixlen = strlen(kstar + 1);
753 namelen = strlen(name);
754 ret = !strncmp(name, key, klen) && namelen >= klen + ksuffixlen &&
755 !memcmp(name + namelen - ksuffixlen, kstar + 1, ksuffixlen);
756 if (ret && value) {
757 const char *vstar = strchr(value, '*');
758 size_t vlen;
759 size_t vsuffixlen;
760 if (!vstar)
761 die("Value '%s' of pattern has no '*'", value);
762 vlen = vstar - value;
763 vsuffixlen = strlen(vstar + 1);
764 *result = xmalloc(vlen + vsuffixlen +
765 strlen(name) -
766 klen - ksuffixlen + 1);
767 strncpy(*result, value, vlen);
768 strncpy(*result + vlen,
769 name + klen, namelen - klen - ksuffixlen);
770 strcpy(*result + vlen + namelen - klen - ksuffixlen,
771 vstar + 1);
773 return ret;
776 int remote_find_tracking(struct remote *remote, struct refspec *refspec)
778 int find_src = refspec->src == NULL;
779 char *needle, **result;
780 int i;
782 if (find_src) {
783 if (!refspec->dst)
784 return error("find_tracking: need either src or dst");
785 needle = refspec->dst;
786 result = &refspec->src;
787 } else {
788 needle = refspec->src;
789 result = &refspec->dst;
792 for (i = 0; i < remote->fetch_refspec_nr; i++) {
793 struct refspec *fetch = &remote->fetch[i];
794 const char *key = find_src ? fetch->dst : fetch->src;
795 const char *value = find_src ? fetch->src : fetch->dst;
796 if (!fetch->dst)
797 continue;
798 if (fetch->pattern) {
799 if (match_name_with_pattern(key, needle, value, result)) {
800 refspec->force = fetch->force;
801 return 0;
803 } else if (!strcmp(needle, key)) {
804 *result = xstrdup(value);
805 refspec->force = fetch->force;
806 return 0;
809 return -1;
812 static struct ref *alloc_ref_with_prefix(const char *prefix, size_t prefixlen,
813 const char *name)
815 size_t len = strlen(name);
816 struct ref *ref = xcalloc(1, sizeof(struct ref) + prefixlen + len + 1);
817 memcpy(ref->name, prefix, prefixlen);
818 memcpy(ref->name + prefixlen, name, len);
819 return ref;
822 struct ref *alloc_ref(const char *name)
824 return alloc_ref_with_prefix("", 0, name);
827 static struct ref *copy_ref(const struct ref *ref)
829 struct ref *cpy;
830 size_t len;
831 if (!ref)
832 return NULL;
833 len = strlen(ref->name);
834 cpy = xmalloc(sizeof(struct ref) + len + 1);
835 memcpy(cpy, ref, sizeof(struct ref) + len + 1);
836 cpy->next = NULL;
837 cpy->symref = ref->symref ? xstrdup(ref->symref) : NULL;
838 cpy->remote_status = ref->remote_status ? xstrdup(ref->remote_status) : NULL;
839 cpy->peer_ref = copy_ref(ref->peer_ref);
840 return cpy;
843 struct ref *copy_ref_list(const struct ref *ref)
845 struct ref *ret = NULL;
846 struct ref **tail = &ret;
847 while (ref) {
848 *tail = copy_ref(ref);
849 ref = ref->next;
850 tail = &((*tail)->next);
852 return ret;
855 static void free_ref(struct ref *ref)
857 if (!ref)
858 return;
859 free_ref(ref->peer_ref);
860 free(ref->remote_status);
861 free(ref->symref);
862 free(ref);
865 void free_refs(struct ref *ref)
867 struct ref *next;
868 while (ref) {
869 next = ref->next;
870 free_ref(ref);
871 ref = next;
875 static int count_refspec_match(const char *pattern,
876 struct ref *refs,
877 struct ref **matched_ref)
879 int patlen = strlen(pattern);
880 struct ref *matched_weak = NULL;
881 struct ref *matched = NULL;
882 int weak_match = 0;
883 int match = 0;
885 for (weak_match = match = 0; refs; refs = refs->next) {
886 char *name = refs->name;
887 int namelen = strlen(name);
889 if (!refname_match(pattern, name, ref_rev_parse_rules))
890 continue;
892 /* A match is "weak" if it is with refs outside
893 * heads or tags, and did not specify the pattern
894 * in full (e.g. "refs/remotes/origin/master") or at
895 * least from the toplevel (e.g. "remotes/origin/master");
896 * otherwise "git push $URL master" would result in
897 * ambiguity between remotes/origin/master and heads/master
898 * at the remote site.
900 if (namelen != patlen &&
901 patlen != namelen - 5 &&
902 prefixcmp(name, "refs/heads/") &&
903 prefixcmp(name, "refs/tags/")) {
904 /* We want to catch the case where only weak
905 * matches are found and there are multiple
906 * matches, and where more than one strong
907 * matches are found, as ambiguous. One
908 * strong match with zero or more weak matches
909 * are acceptable as a unique match.
911 matched_weak = refs;
912 weak_match++;
914 else {
915 matched = refs;
916 match++;
919 if (!matched) {
920 *matched_ref = matched_weak;
921 return weak_match;
923 else {
924 *matched_ref = matched;
925 return match;
929 static void tail_link_ref(struct ref *ref, struct ref ***tail)
931 **tail = ref;
932 while (ref->next)
933 ref = ref->next;
934 *tail = &ref->next;
937 static struct ref *try_explicit_object_name(const char *name)
939 unsigned char sha1[20];
940 struct ref *ref;
942 if (!*name) {
943 ref = alloc_ref("(delete)");
944 hashclr(ref->new_sha1);
945 return ref;
947 if (get_sha1(name, sha1))
948 return NULL;
949 ref = alloc_ref(name);
950 hashcpy(ref->new_sha1, sha1);
951 return ref;
954 static struct ref *make_linked_ref(const char *name, struct ref ***tail)
956 struct ref *ret = alloc_ref(name);
957 tail_link_ref(ret, tail);
958 return ret;
961 static char *guess_ref(const char *name, struct ref *peer)
963 struct strbuf buf = STRBUF_INIT;
964 unsigned char sha1[20];
966 const char *r = resolve_ref(peer->name, sha1, 1, NULL);
967 if (!r)
968 return NULL;
970 if (!prefixcmp(r, "refs/heads/"))
971 strbuf_addstr(&buf, "refs/heads/");
972 else if (!prefixcmp(r, "refs/tags/"))
973 strbuf_addstr(&buf, "refs/tags/");
974 else
975 return NULL;
977 strbuf_addstr(&buf, name);
978 return strbuf_detach(&buf, NULL);
981 static int match_explicit(struct ref *src, struct ref *dst,
982 struct ref ***dst_tail,
983 struct refspec *rs)
985 struct ref *matched_src, *matched_dst;
986 int copy_src;
988 const char *dst_value = rs->dst;
989 char *dst_guess;
991 if (rs->pattern || rs->matching)
992 return 0;
994 matched_src = matched_dst = NULL;
995 switch (count_refspec_match(rs->src, src, &matched_src)) {
996 case 1:
997 copy_src = 1;
998 break;
999 case 0:
1000 /* The source could be in the get_sha1() format
1001 * not a reference name. :refs/other is a
1002 * way to delete 'other' ref at the remote end.
1004 matched_src = try_explicit_object_name(rs->src);
1005 if (!matched_src)
1006 return error("src refspec %s does not match any.", rs->src);
1007 copy_src = 0;
1008 break;
1009 default:
1010 return error("src refspec %s matches more than one.", rs->src);
1013 if (!dst_value) {
1014 unsigned char sha1[20];
1015 int flag;
1017 dst_value = resolve_ref(matched_src->name, sha1, 1, &flag);
1018 if (!dst_value ||
1019 ((flag & REF_ISSYMREF) &&
1020 prefixcmp(dst_value, "refs/heads/")))
1021 die("%s cannot be resolved to branch.",
1022 matched_src->name);
1025 switch (count_refspec_match(dst_value, dst, &matched_dst)) {
1026 case 1:
1027 break;
1028 case 0:
1029 if (!memcmp(dst_value, "refs/", 5))
1030 matched_dst = make_linked_ref(dst_value, dst_tail);
1031 else if((dst_guess = guess_ref(dst_value, matched_src)))
1032 matched_dst = make_linked_ref(dst_guess, dst_tail);
1033 else
1034 error("unable to push to unqualified destination: %s\n"
1035 "The destination refspec neither matches an "
1036 "existing ref on the remote nor\n"
1037 "begins with refs/, and we are unable to "
1038 "guess a prefix based on the source ref.",
1039 dst_value);
1040 break;
1041 default:
1042 matched_dst = NULL;
1043 error("dst refspec %s matches more than one.",
1044 dst_value);
1045 break;
1047 if (!matched_dst)
1048 return -1;
1049 if (matched_dst->peer_ref)
1050 return error("dst ref %s receives from more than one src.",
1051 matched_dst->name);
1052 else {
1053 matched_dst->peer_ref = copy_src ? copy_ref(matched_src) : matched_src;
1054 matched_dst->force = rs->force;
1056 return 0;
1059 static int match_explicit_refs(struct ref *src, struct ref *dst,
1060 struct ref ***dst_tail, struct refspec *rs,
1061 int rs_nr)
1063 int i, errs;
1064 for (i = errs = 0; i < rs_nr; i++)
1065 errs += match_explicit(src, dst, dst_tail, &rs[i]);
1066 return errs;
1069 static const struct refspec *check_pattern_match(const struct refspec *rs,
1070 int rs_nr,
1071 const struct ref *src)
1073 int i;
1074 int matching_refs = -1;
1075 for (i = 0; i < rs_nr; i++) {
1076 if (rs[i].matching &&
1077 (matching_refs == -1 || rs[i].force)) {
1078 matching_refs = i;
1079 continue;
1082 if (rs[i].pattern && match_name_with_pattern(rs[i].src, src->name,
1083 NULL, NULL))
1084 return rs + i;
1086 if (matching_refs != -1)
1087 return rs + matching_refs;
1088 else
1089 return NULL;
1093 * Note. This is used only by "push"; refspec matching rules for
1094 * push and fetch are subtly different, so do not try to reuse it
1095 * without thinking.
1097 int match_refs(struct ref *src, struct ref *dst, struct ref ***dst_tail,
1098 int nr_refspec, const char **refspec, int flags)
1100 struct refspec *rs;
1101 int send_all = flags & MATCH_REFS_ALL;
1102 int send_mirror = flags & MATCH_REFS_MIRROR;
1103 int errs;
1104 static const char *default_refspec[] = { ":", 0 };
1106 if (!nr_refspec) {
1107 nr_refspec = 1;
1108 refspec = default_refspec;
1110 rs = parse_push_refspec(nr_refspec, (const char **) refspec);
1111 errs = match_explicit_refs(src, dst, dst_tail, rs, nr_refspec);
1113 /* pick the remainder */
1114 for ( ; src; src = src->next) {
1115 struct ref *dst_peer;
1116 const struct refspec *pat = NULL;
1117 char *dst_name;
1118 if (src->peer_ref)
1119 continue;
1121 pat = check_pattern_match(rs, nr_refspec, src);
1122 if (!pat)
1123 continue;
1125 if (pat->matching) {
1127 * "matching refs"; traditionally we pushed everything
1128 * including refs outside refs/heads/ hierarchy, but
1129 * that does not make much sense these days.
1131 if (!send_mirror && prefixcmp(src->name, "refs/heads/"))
1132 continue;
1133 dst_name = xstrdup(src->name);
1135 } else {
1136 const char *dst_side = pat->dst ? pat->dst : pat->src;
1137 if (!match_name_with_pattern(pat->src, src->name,
1138 dst_side, &dst_name))
1139 die("Didn't think it matches any more");
1141 dst_peer = find_ref_by_name(dst, dst_name);
1142 if (dst_peer) {
1143 if (dst_peer->peer_ref)
1144 /* We're already sending something to this ref. */
1145 goto free_name;
1147 } else {
1148 if (pat->matching && !(send_all || send_mirror))
1150 * Remote doesn't have it, and we have no
1151 * explicit pattern, and we don't have
1152 * --all nor --mirror.
1154 goto free_name;
1156 /* Create a new one and link it */
1157 dst_peer = make_linked_ref(dst_name, dst_tail);
1158 hashcpy(dst_peer->new_sha1, src->new_sha1);
1160 dst_peer->peer_ref = copy_ref(src);
1161 dst_peer->force = pat->force;
1162 free_name:
1163 free(dst_name);
1165 if (errs)
1166 return -1;
1167 return 0;
1170 struct branch *branch_get(const char *name)
1172 struct branch *ret;
1174 read_config();
1175 if (!name || !*name || !strcmp(name, "HEAD"))
1176 ret = current_branch;
1177 else
1178 ret = make_branch(name, 0);
1179 if (ret && ret->remote_name) {
1180 ret->remote = remote_get(ret->remote_name);
1181 if (ret->merge_nr) {
1182 int i;
1183 ret->merge = xcalloc(sizeof(*ret->merge),
1184 ret->merge_nr);
1185 for (i = 0; i < ret->merge_nr; i++) {
1186 ret->merge[i] = xcalloc(1, sizeof(**ret->merge));
1187 ret->merge[i]->src = xstrdup(ret->merge_name[i]);
1188 remote_find_tracking(ret->remote,
1189 ret->merge[i]);
1193 return ret;
1196 int branch_has_merge_config(struct branch *branch)
1198 return branch && !!branch->merge;
1201 int branch_merge_matches(struct branch *branch,
1202 int i,
1203 const char *refname)
1205 if (!branch || i < 0 || i >= branch->merge_nr)
1206 return 0;
1207 return refname_match(branch->merge[i]->src, refname, ref_fetch_rules);
1210 static struct ref *get_expanded_map(const struct ref *remote_refs,
1211 const struct refspec *refspec)
1213 const struct ref *ref;
1214 struct ref *ret = NULL;
1215 struct ref **tail = &ret;
1217 char *expn_name;
1219 for (ref = remote_refs; ref; ref = ref->next) {
1220 if (strchr(ref->name, '^'))
1221 continue; /* a dereference item */
1222 if (match_name_with_pattern(refspec->src, ref->name,
1223 refspec->dst, &expn_name)) {
1224 struct ref *cpy = copy_ref(ref);
1226 cpy->peer_ref = alloc_ref(expn_name);
1227 free(expn_name);
1228 if (refspec->force)
1229 cpy->peer_ref->force = 1;
1230 *tail = cpy;
1231 tail = &cpy->next;
1235 return ret;
1238 static const struct ref *find_ref_by_name_abbrev(const struct ref *refs, const char *name)
1240 const struct ref *ref;
1241 for (ref = refs; ref; ref = ref->next) {
1242 if (refname_match(name, ref->name, ref_fetch_rules))
1243 return ref;
1245 return NULL;
1248 struct ref *get_remote_ref(const struct ref *remote_refs, const char *name)
1250 const struct ref *ref = find_ref_by_name_abbrev(remote_refs, name);
1252 if (!ref)
1253 return NULL;
1255 return copy_ref(ref);
1258 static struct ref *get_local_ref(const char *name)
1260 if (!name)
1261 return NULL;
1263 if (!prefixcmp(name, "refs/"))
1264 return alloc_ref(name);
1266 if (!prefixcmp(name, "heads/") ||
1267 !prefixcmp(name, "tags/") ||
1268 !prefixcmp(name, "remotes/"))
1269 return alloc_ref_with_prefix("refs/", 5, name);
1271 return alloc_ref_with_prefix("refs/heads/", 11, name);
1274 int get_fetch_map(const struct ref *remote_refs,
1275 const struct refspec *refspec,
1276 struct ref ***tail,
1277 int missing_ok)
1279 struct ref *ref_map, **rmp;
1281 if (refspec->pattern) {
1282 ref_map = get_expanded_map(remote_refs, refspec);
1283 } else {
1284 const char *name = refspec->src[0] ? refspec->src : "HEAD";
1286 ref_map = get_remote_ref(remote_refs, name);
1287 if (!missing_ok && !ref_map)
1288 die("Couldn't find remote ref %s", name);
1289 if (ref_map) {
1290 ref_map->peer_ref = get_local_ref(refspec->dst);
1291 if (ref_map->peer_ref && refspec->force)
1292 ref_map->peer_ref->force = 1;
1296 for (rmp = &ref_map; *rmp; ) {
1297 if ((*rmp)->peer_ref) {
1298 int st = check_ref_format((*rmp)->peer_ref->name + 5);
1299 if (st && st != CHECK_REF_FORMAT_ONELEVEL) {
1300 struct ref *ignore = *rmp;
1301 error("* Ignoring funny ref '%s' locally",
1302 (*rmp)->peer_ref->name);
1303 *rmp = (*rmp)->next;
1304 free(ignore->peer_ref);
1305 free(ignore);
1306 continue;
1309 rmp = &((*rmp)->next);
1312 if (ref_map)
1313 tail_link_ref(ref_map, tail);
1315 return 0;
1318 int resolve_remote_symref(struct ref *ref, struct ref *list)
1320 if (!ref->symref)
1321 return 0;
1322 for (; list; list = list->next)
1323 if (!strcmp(ref->symref, list->name)) {
1324 hashcpy(ref->old_sha1, list->old_sha1);
1325 return 0;
1327 return 1;
1330 static void unmark_and_free(struct commit_list *list, unsigned int mark)
1332 while (list) {
1333 struct commit_list *temp = list;
1334 temp->item->object.flags &= ~mark;
1335 list = temp->next;
1336 free(temp);
1340 int ref_newer(const unsigned char *new_sha1, const unsigned char *old_sha1)
1342 struct object *o;
1343 struct commit *old, *new;
1344 struct commit_list *list, *used;
1345 int found = 0;
1347 /* Both new and old must be commit-ish and new is descendant of
1348 * old. Otherwise we require --force.
1350 o = deref_tag(parse_object(old_sha1), NULL, 0);
1351 if (!o || o->type != OBJ_COMMIT)
1352 return 0;
1353 old = (struct commit *) o;
1355 o = deref_tag(parse_object(new_sha1), NULL, 0);
1356 if (!o || o->type != OBJ_COMMIT)
1357 return 0;
1358 new = (struct commit *) o;
1360 if (parse_commit(new) < 0)
1361 return 0;
1363 used = list = NULL;
1364 commit_list_insert(new, &list);
1365 while (list) {
1366 new = pop_most_recent_commit(&list, TMP_MARK);
1367 commit_list_insert(new, &used);
1368 if (new == old) {
1369 found = 1;
1370 break;
1373 unmark_and_free(list, TMP_MARK);
1374 unmark_and_free(used, TMP_MARK);
1375 return found;
1379 * Return true if there is anything to report, otherwise false.
1381 int stat_tracking_info(struct branch *branch, int *num_ours, int *num_theirs)
1383 unsigned char sha1[20];
1384 struct commit *ours, *theirs;
1385 char symmetric[84];
1386 struct rev_info revs;
1387 const char *rev_argv[10], *base;
1388 int rev_argc;
1391 * Nothing to report unless we are marked to build on top of
1392 * somebody else.
1394 if (!branch ||
1395 !branch->merge || !branch->merge[0] || !branch->merge[0]->dst)
1396 return 0;
1399 * If what we used to build on no longer exists, there is
1400 * nothing to report.
1402 base = branch->merge[0]->dst;
1403 if (!resolve_ref(base, sha1, 1, NULL))
1404 return 0;
1405 theirs = lookup_commit(sha1);
1406 if (!theirs)
1407 return 0;
1409 if (!resolve_ref(branch->refname, sha1, 1, NULL))
1410 return 0;
1411 ours = lookup_commit(sha1);
1412 if (!ours)
1413 return 0;
1415 /* are we the same? */
1416 if (theirs == ours)
1417 return 0;
1419 /* Run "rev-list --no-merges --left-right ours...theirs" internally... */
1420 rev_argc = 0;
1421 rev_argv[rev_argc++] = NULL;
1422 rev_argv[rev_argc++] = "--no-merges";
1423 rev_argv[rev_argc++] = "--left-right";
1424 rev_argv[rev_argc++] = symmetric;
1425 rev_argv[rev_argc++] = "--";
1426 rev_argv[rev_argc] = NULL;
1428 strcpy(symmetric, sha1_to_hex(ours->object.sha1));
1429 strcpy(symmetric + 40, "...");
1430 strcpy(symmetric + 43, sha1_to_hex(theirs->object.sha1));
1432 init_revisions(&revs, NULL);
1433 setup_revisions(rev_argc, rev_argv, &revs, NULL);
1434 prepare_revision_walk(&revs);
1436 /* ... and count the commits on each side. */
1437 *num_ours = 0;
1438 *num_theirs = 0;
1439 while (1) {
1440 struct commit *c = get_revision(&revs);
1441 if (!c)
1442 break;
1443 if (c->object.flags & SYMMETRIC_LEFT)
1444 (*num_ours)++;
1445 else
1446 (*num_theirs)++;
1449 /* clear object flags smudged by the above traversal */
1450 clear_commit_marks(ours, ALL_REV_FLAGS);
1451 clear_commit_marks(theirs, ALL_REV_FLAGS);
1452 return 1;
1456 * Return true when there is anything to report, otherwise false.
1458 int format_tracking_info(struct branch *branch, struct strbuf *sb)
1460 int num_ours, num_theirs;
1461 const char *base;
1463 if (!stat_tracking_info(branch, &num_ours, &num_theirs))
1464 return 0;
1466 base = branch->merge[0]->dst;
1467 if (!prefixcmp(base, "refs/remotes/")) {
1468 base += strlen("refs/remotes/");
1470 if (!num_theirs)
1471 strbuf_addf(sb, "Your branch is ahead of '%s' "
1472 "by %d commit%s.\n",
1473 base, num_ours, (num_ours == 1) ? "" : "s");
1474 else if (!num_ours)
1475 strbuf_addf(sb, "Your branch is behind '%s' "
1476 "by %d commit%s, "
1477 "and can be fast-forwarded.\n",
1478 base, num_theirs, (num_theirs == 1) ? "" : "s");
1479 else
1480 strbuf_addf(sb, "Your branch and '%s' have diverged,\n"
1481 "and have %d and %d different commit(s) each, "
1482 "respectively.\n",
1483 base, num_ours, num_theirs);
1484 return 1;
1487 static int one_local_ref(const char *refname, const unsigned char *sha1, int flag, void *cb_data)
1489 struct ref ***local_tail = cb_data;
1490 struct ref *ref;
1491 int len;
1493 /* we already know it starts with refs/ to get here */
1494 if (check_ref_format(refname + 5))
1495 return 0;
1497 len = strlen(refname) + 1;
1498 ref = xcalloc(1, sizeof(*ref) + len);
1499 hashcpy(ref->new_sha1, sha1);
1500 memcpy(ref->name, refname, len);
1501 **local_tail = ref;
1502 *local_tail = &ref->next;
1503 return 0;
1506 struct ref *get_local_heads(void)
1508 struct ref *local_refs, **local_tail = &local_refs;
1509 for_each_ref(one_local_ref, &local_tail);
1510 return local_refs;
1513 struct ref *guess_remote_head(const struct ref *head,
1514 const struct ref *refs,
1515 int all)
1517 const struct ref *r;
1518 struct ref *list = NULL;
1519 struct ref **tail = &list;
1521 if (!head)
1522 return NULL;
1525 * Some transports support directly peeking at
1526 * where HEAD points; if that is the case, then
1527 * we don't have to guess.
1529 if (head->symref)
1530 return copy_ref(find_ref_by_name(refs, head->symref));
1532 /* If refs/heads/master could be right, it is. */
1533 if (!all) {
1534 r = find_ref_by_name(refs, "refs/heads/master");
1535 if (r && !hashcmp(r->old_sha1, head->old_sha1))
1536 return copy_ref(r);
1539 /* Look for another ref that points there */
1540 for (r = refs; r; r = r->next) {
1541 if (r != head && !hashcmp(r->old_sha1, head->old_sha1)) {
1542 *tail = copy_ref(r);
1543 tail = &((*tail)->next);
1544 if (!all)
1545 break;
1549 return list;