remote-hg: get the correct refs
[git/dscho.git] / remote.c
blob0d51007c1009455636081e261720589298a8f6a2
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;
31 struct rewrites {
32 struct rewrite **rewrite;
33 int rewrite_alloc;
34 int rewrite_nr;
37 static struct remote **remotes;
38 static int remotes_alloc;
39 static int remotes_nr;
41 static struct branch **branches;
42 static int branches_alloc;
43 static int branches_nr;
45 static struct branch *current_branch;
46 static const char *default_remote_name;
47 static int explicit_default_remote_name;
49 static struct rewrites rewrites;
50 static struct rewrites rewrites_push;
52 #define BUF_SIZE (2048)
53 static char buffer[BUF_SIZE];
56 static int valid_remote(const struct remote *remote)
58 return !remote->url != !remote->foreign_vcs;
61 static const char *alias_url(const char *url, struct rewrites *r)
63 int i, j;
64 char *ret;
65 struct counted_string *longest;
66 int longest_i;
68 longest = NULL;
69 longest_i = -1;
70 for (i = 0; i < r->rewrite_nr; i++) {
71 if (!r->rewrite[i])
72 continue;
73 for (j = 0; j < r->rewrite[i]->instead_of_nr; j++) {
74 if (!prefixcmp(url, r->rewrite[i]->instead_of[j].s) &&
75 (!longest ||
76 longest->len < r->rewrite[i]->instead_of[j].len)) {
77 longest = &(r->rewrite[i]->instead_of[j]);
78 longest_i = i;
82 if (!longest)
83 return url;
85 ret = xmalloc(r->rewrite[longest_i]->baselen +
86 (strlen(url) - longest->len) + 1);
87 strcpy(ret, r->rewrite[longest_i]->base);
88 strcpy(ret + r->rewrite[longest_i]->baselen, url + longest->len);
89 return ret;
92 static void add_push_refspec(struct remote *remote, const char *ref)
94 ALLOC_GROW(remote->push_refspec,
95 remote->push_refspec_nr + 1,
96 remote->push_refspec_alloc);
97 remote->push_refspec[remote->push_refspec_nr++] = ref;
100 static void add_fetch_refspec(struct remote *remote, const char *ref)
102 ALLOC_GROW(remote->fetch_refspec,
103 remote->fetch_refspec_nr + 1,
104 remote->fetch_refspec_alloc);
105 remote->fetch_refspec[remote->fetch_refspec_nr++] = ref;
108 static void add_url(struct remote *remote, const char *url)
110 ALLOC_GROW(remote->url, remote->url_nr + 1, remote->url_alloc);
111 remote->url[remote->url_nr++] = url;
114 static void add_pushurl(struct remote *remote, const char *pushurl)
116 ALLOC_GROW(remote->pushurl, remote->pushurl_nr + 1, remote->pushurl_alloc);
117 remote->pushurl[remote->pushurl_nr++] = pushurl;
120 static void add_pushurl_alias(struct remote *remote, const char *url)
122 const char *pushurl = alias_url(url, &rewrites_push);
123 if (pushurl != url)
124 add_pushurl(remote, pushurl);
127 static void add_url_alias(struct remote *remote, const char *url)
129 add_url(remote, alias_url(url, &rewrites));
130 add_pushurl_alias(remote, url);
133 static struct remote *make_remote(const char *name, int len)
135 struct remote *ret;
136 int i;
138 for (i = 0; i < remotes_nr; i++) {
139 if (len ? (!strncmp(name, remotes[i]->name, len) &&
140 !remotes[i]->name[len]) :
141 !strcmp(name, remotes[i]->name))
142 return remotes[i];
145 ret = xcalloc(1, sizeof(struct remote));
146 ALLOC_GROW(remotes, remotes_nr + 1, remotes_alloc);
147 remotes[remotes_nr++] = ret;
148 if (len)
149 ret->name = xstrndup(name, len);
150 else
151 ret->name = xstrdup(name);
152 return ret;
155 static void add_merge(struct branch *branch, const char *name)
157 ALLOC_GROW(branch->merge_name, branch->merge_nr + 1,
158 branch->merge_alloc);
159 branch->merge_name[branch->merge_nr++] = name;
162 static struct branch *make_branch(const char *name, int len)
164 struct branch *ret;
165 int i;
166 char *refname;
168 for (i = 0; i < branches_nr; i++) {
169 if (len ? (!strncmp(name, branches[i]->name, len) &&
170 !branches[i]->name[len]) :
171 !strcmp(name, branches[i]->name))
172 return branches[i];
175 ALLOC_GROW(branches, branches_nr + 1, branches_alloc);
176 ret = xcalloc(1, sizeof(struct branch));
177 branches[branches_nr++] = ret;
178 if (len)
179 ret->name = xstrndup(name, len);
180 else
181 ret->name = xstrdup(name);
182 refname = xmalloc(strlen(name) + strlen("refs/heads/") + 1);
183 strcpy(refname, "refs/heads/");
184 strcpy(refname + strlen("refs/heads/"), ret->name);
185 ret->refname = refname;
187 return ret;
190 static struct rewrite *make_rewrite(struct rewrites *r, const char *base, int len)
192 struct rewrite *ret;
193 int i;
195 for (i = 0; i < r->rewrite_nr; i++) {
196 if (len
197 ? (len == r->rewrite[i]->baselen &&
198 !strncmp(base, r->rewrite[i]->base, len))
199 : !strcmp(base, r->rewrite[i]->base))
200 return r->rewrite[i];
203 ALLOC_GROW(r->rewrite, r->rewrite_nr + 1, r->rewrite_alloc);
204 ret = xcalloc(1, sizeof(struct rewrite));
205 r->rewrite[r->rewrite_nr++] = ret;
206 if (len) {
207 ret->base = xstrndup(base, len);
208 ret->baselen = len;
210 else {
211 ret->base = xstrdup(base);
212 ret->baselen = strlen(base);
214 return ret;
217 static void add_instead_of(struct rewrite *rewrite, const char *instead_of)
219 ALLOC_GROW(rewrite->instead_of, rewrite->instead_of_nr + 1, rewrite->instead_of_alloc);
220 rewrite->instead_of[rewrite->instead_of_nr].s = instead_of;
221 rewrite->instead_of[rewrite->instead_of_nr].len = strlen(instead_of);
222 rewrite->instead_of_nr++;
225 static void read_remotes_file(struct remote *remote)
227 FILE *f = fopen(git_path("remotes/%s", remote->name), "r");
229 if (!f)
230 return;
231 remote->origin = REMOTE_REMOTES;
232 while (fgets(buffer, BUF_SIZE, f)) {
233 int value_list;
234 char *s, *p;
236 if (!prefixcmp(buffer, "URL:")) {
237 value_list = 0;
238 s = buffer + 4;
239 } else if (!prefixcmp(buffer, "Push:")) {
240 value_list = 1;
241 s = buffer + 5;
242 } else if (!prefixcmp(buffer, "Pull:")) {
243 value_list = 2;
244 s = buffer + 5;
245 } else
246 continue;
248 while (isspace(*s))
249 s++;
250 if (!*s)
251 continue;
253 p = s + strlen(s);
254 while (isspace(p[-1]))
255 *--p = 0;
257 switch (value_list) {
258 case 0:
259 add_url_alias(remote, xstrdup(s));
260 break;
261 case 1:
262 add_push_refspec(remote, xstrdup(s));
263 break;
264 case 2:
265 add_fetch_refspec(remote, xstrdup(s));
266 break;
269 fclose(f);
272 static void read_branches_file(struct remote *remote)
274 const char *slash = strchr(remote->name, '/');
275 char *frag;
276 struct strbuf branch = STRBUF_INIT;
277 int n = slash ? slash - remote->name : 1000;
278 FILE *f = fopen(git_path("branches/%.*s", n, remote->name), "r");
279 char *s, *p;
280 int len;
282 if (!f)
283 return;
284 s = fgets(buffer, BUF_SIZE, f);
285 fclose(f);
286 if (!s)
287 return;
288 while (isspace(*s))
289 s++;
290 if (!*s)
291 return;
292 remote->origin = REMOTE_BRANCHES;
293 p = s + strlen(s);
294 while (isspace(p[-1]))
295 *--p = 0;
296 len = p - s;
297 if (slash)
298 len += strlen(slash);
299 p = xmalloc(len + 1);
300 strcpy(p, s);
301 if (slash)
302 strcat(p, slash);
305 * With "slash", e.g. "git fetch jgarzik/netdev-2.6" when
306 * reading from $GIT_DIR/branches/jgarzik fetches "HEAD" from
307 * the partial URL obtained from the branches file plus
308 * "/netdev-2.6" and does not store it in any tracking ref.
309 * #branch specifier in the file is ignored.
311 * Otherwise, the branches file would have URL and optionally
312 * #branch specified. The "master" (or specified) branch is
313 * fetched and stored in the local branch of the same name.
315 frag = strchr(p, '#');
316 if (frag) {
317 *(frag++) = '\0';
318 strbuf_addf(&branch, "refs/heads/%s", frag);
319 } else
320 strbuf_addstr(&branch, "refs/heads/master");
321 if (!slash) {
322 strbuf_addf(&branch, ":refs/heads/%s", remote->name);
323 } else {
324 strbuf_reset(&branch);
325 strbuf_addstr(&branch, "HEAD:");
327 add_url_alias(remote, p);
328 add_fetch_refspec(remote, strbuf_detach(&branch, NULL));
330 * Cogito compatible push: push current HEAD to remote #branch
331 * (master if missing)
333 strbuf_init(&branch, 0);
334 strbuf_addstr(&branch, "HEAD");
335 if (frag)
336 strbuf_addf(&branch, ":refs/heads/%s", frag);
337 else
338 strbuf_addstr(&branch, ":refs/heads/master");
339 add_push_refspec(remote, strbuf_detach(&branch, NULL));
340 remote->fetch_tags = 1; /* always auto-follow */
343 static int handle_config(const char *key, const char *value, void *cb)
345 const char *name;
346 const char *subkey;
347 struct remote *remote;
348 struct branch *branch;
349 if (!prefixcmp(key, "branch.")) {
350 name = key + 7;
351 subkey = strrchr(name, '.');
352 if (!subkey)
353 return 0;
354 branch = make_branch(name, subkey - name);
355 if (!strcmp(subkey, ".remote")) {
356 if (!value)
357 return config_error_nonbool(key);
358 branch->remote_name = xstrdup(value);
359 if (branch == current_branch) {
360 default_remote_name = branch->remote_name;
361 explicit_default_remote_name = 1;
363 } else if (!strcmp(subkey, ".merge")) {
364 if (!value)
365 return config_error_nonbool(key);
366 add_merge(branch, xstrdup(value));
368 return 0;
370 if (!prefixcmp(key, "url.")) {
371 struct rewrite *rewrite;
372 name = key + 4;
373 subkey = strrchr(name, '.');
374 if (!subkey)
375 return 0;
376 if (!strcmp(subkey, ".insteadof")) {
377 rewrite = make_rewrite(&rewrites, name, subkey - name);
378 if (!value)
379 return config_error_nonbool(key);
380 add_instead_of(rewrite, xstrdup(value));
381 } else if (!strcmp(subkey, ".pushinsteadof")) {
382 rewrite = make_rewrite(&rewrites_push, name, subkey - name);
383 if (!value)
384 return config_error_nonbool(key);
385 add_instead_of(rewrite, xstrdup(value));
388 if (prefixcmp(key, "remote."))
389 return 0;
390 name = key + 7;
391 if (*name == '/') {
392 warning("Config remote shorthand cannot begin with '/': %s",
393 name);
394 return 0;
396 subkey = strrchr(name, '.');
397 if (!subkey)
398 return 0;
399 remote = make_remote(name, subkey - name);
400 remote->origin = REMOTE_CONFIG;
401 if (!strcmp(subkey, ".mirror"))
402 remote->mirror = git_config_bool(key, value);
403 else if (!strcmp(subkey, ".skipdefaultupdate"))
404 remote->skip_default_update = git_config_bool(key, value);
406 else if (!strcmp(subkey, ".url")) {
407 const char *v;
408 if (git_config_string(&v, key, value))
409 return -1;
410 add_url(remote, v);
411 } else if (!strcmp(subkey, ".pushurl")) {
412 const char *v;
413 if (git_config_string(&v, key, value))
414 return -1;
415 add_pushurl(remote, v);
416 } else if (!strcmp(subkey, ".push")) {
417 const char *v;
418 if (git_config_string(&v, key, value))
419 return -1;
420 add_push_refspec(remote, v);
421 } else if (!strcmp(subkey, ".fetch")) {
422 const char *v;
423 if (git_config_string(&v, key, value))
424 return -1;
425 add_fetch_refspec(remote, v);
426 } else if (!strcmp(subkey, ".receivepack")) {
427 const char *v;
428 if (git_config_string(&v, key, value))
429 return -1;
430 if (!remote->receivepack)
431 remote->receivepack = v;
432 else
433 error("more than one receivepack given, using the first");
434 } else if (!strcmp(subkey, ".uploadpack")) {
435 const char *v;
436 if (git_config_string(&v, key, value))
437 return -1;
438 if (!remote->uploadpack)
439 remote->uploadpack = v;
440 else
441 error("more than one uploadpack given, using the first");
442 } else if (!strcmp(subkey, ".tagopt")) {
443 if (!strcmp(value, "--no-tags"))
444 remote->fetch_tags = -1;
445 } else if (!strcmp(subkey, ".proxy")) {
446 return git_config_string((const char **)&remote->http_proxy,
447 key, value);
448 } else if (!strcmp(subkey, ".vcs")) {
449 return git_config_string(&remote->foreign_vcs, key, value);
451 return 0;
454 static void alias_all_urls(void)
456 int i, j;
457 for (i = 0; i < remotes_nr; i++) {
458 int add_pushurl_aliases;
459 if (!remotes[i])
460 continue;
461 for (j = 0; j < remotes[i]->pushurl_nr; j++) {
462 remotes[i]->pushurl[j] = alias_url(remotes[i]->pushurl[j], &rewrites);
464 add_pushurl_aliases = remotes[i]->pushurl_nr == 0;
465 for (j = 0; j < remotes[i]->url_nr; j++) {
466 if (add_pushurl_aliases)
467 add_pushurl_alias(remotes[i], remotes[i]->url[j]);
468 remotes[i]->url[j] = alias_url(remotes[i]->url[j], &rewrites);
473 static void read_config(void)
475 unsigned char sha1[20];
476 const char *head_ref;
477 int flag;
478 if (default_remote_name) // did this already
479 return;
480 default_remote_name = xstrdup("origin");
481 current_branch = NULL;
482 head_ref = resolve_ref("HEAD", sha1, 0, &flag);
483 if (head_ref && (flag & REF_ISSYMREF) &&
484 !prefixcmp(head_ref, "refs/heads/")) {
485 current_branch =
486 make_branch(head_ref + strlen("refs/heads/"), 0);
488 git_config(handle_config, NULL);
489 alias_all_urls();
493 * We need to make sure the tracking branches are well formed, but a
494 * wildcard refspec in "struct refspec" must have a trailing slash. We
495 * temporarily drop the trailing '/' while calling check_ref_format(),
496 * and put it back. The caller knows that a CHECK_REF_FORMAT_ONELEVEL
497 * error return is Ok for a wildcard refspec.
499 static int verify_refname(char *name, int is_glob)
501 int result;
503 result = check_ref_format(name);
504 if (is_glob && result == CHECK_REF_FORMAT_WILDCARD)
505 result = CHECK_REF_FORMAT_OK;
506 return result;
510 * This function frees a refspec array.
511 * Warning: code paths should be checked to ensure that the src
512 * and dst pointers are always freeable pointers as well
513 * as the refspec pointer itself.
515 static void free_refspecs(struct refspec *refspec, int nr_refspec)
517 int i;
519 if (!refspec)
520 return;
522 for (i = 0; i < nr_refspec; i++) {
523 free(refspec[i].src);
524 free(refspec[i].dst);
526 free(refspec);
529 static struct refspec *parse_refspec_internal(int nr_refspec, const char **refspec, int fetch, int verify)
531 int i;
532 int st;
533 struct refspec *rs = xcalloc(sizeof(*rs), nr_refspec);
535 for (i = 0; i < nr_refspec; i++) {
536 size_t llen;
537 int is_glob;
538 const char *lhs, *rhs;
540 is_glob = 0;
542 lhs = refspec[i];
543 if (*lhs == '+') {
544 rs[i].force = 1;
545 lhs++;
548 rhs = strrchr(lhs, ':');
551 * Before going on, special case ":" (or "+:") as a refspec
552 * for matching refs.
554 if (!fetch && rhs == lhs && rhs[1] == '\0') {
555 rs[i].matching = 1;
556 continue;
559 if (rhs) {
560 size_t rlen = strlen(++rhs);
561 is_glob = (1 <= rlen && strchr(rhs, '*'));
562 rs[i].dst = xstrndup(rhs, rlen);
565 llen = (rhs ? (rhs - lhs - 1) : strlen(lhs));
566 if (1 <= llen && memchr(lhs, '*', llen)) {
567 if ((rhs && !is_glob) || (!rhs && fetch))
568 goto invalid;
569 is_glob = 1;
570 } else if (rhs && is_glob) {
571 goto invalid;
574 rs[i].pattern = is_glob;
575 rs[i].src = xstrndup(lhs, llen);
577 if (fetch) {
579 * LHS
580 * - empty is allowed; it means HEAD.
581 * - otherwise it must be a valid looking ref.
583 if (!*rs[i].src)
584 ; /* empty is ok */
585 else {
586 st = verify_refname(rs[i].src, is_glob);
587 if (st && st != CHECK_REF_FORMAT_ONELEVEL)
588 goto invalid;
591 * RHS
592 * - missing is ok, and is same as empty.
593 * - empty is ok; it means not to store.
594 * - otherwise it must be a valid looking ref.
596 if (!rs[i].dst) {
597 ; /* ok */
598 } else if (!*rs[i].dst) {
599 ; /* ok */
600 } else {
601 st = verify_refname(rs[i].dst, is_glob);
602 if (st && st != CHECK_REF_FORMAT_ONELEVEL)
603 goto invalid;
605 } else {
607 * LHS
608 * - empty is allowed; it means delete.
609 * - when wildcarded, it must be a valid looking ref.
610 * - otherwise, it must be an extended SHA-1, but
611 * there is no existing way to validate this.
613 if (!*rs[i].src)
614 ; /* empty is ok */
615 else if (is_glob) {
616 st = verify_refname(rs[i].src, is_glob);
617 if (st && st != CHECK_REF_FORMAT_ONELEVEL)
618 goto invalid;
620 else
621 ; /* anything goes, for now */
623 * RHS
624 * - missing is allowed, but LHS then must be a
625 * valid looking ref.
626 * - empty is not allowed.
627 * - otherwise it must be a valid looking ref.
629 if (!rs[i].dst) {
630 st = verify_refname(rs[i].src, is_glob);
631 if (st && st != CHECK_REF_FORMAT_ONELEVEL)
632 goto invalid;
633 } else if (!*rs[i].dst) {
634 goto invalid;
635 } else {
636 st = verify_refname(rs[i].dst, is_glob);
637 if (st && st != CHECK_REF_FORMAT_ONELEVEL)
638 goto invalid;
642 return rs;
644 invalid:
645 if (verify) {
647 * nr_refspec must be greater than zero and i must be valid
648 * since it is only possible to reach this point from within
649 * the for loop above.
651 free_refspecs(rs, i+1);
652 return NULL;
654 die("Invalid refspec '%s'", refspec[i]);
657 int valid_fetch_refspec(const char *fetch_refspec_str)
659 const char *fetch_refspec[] = { fetch_refspec_str };
660 struct refspec *refspec;
662 refspec = parse_refspec_internal(1, fetch_refspec, 1, 1);
663 free_refspecs(refspec, 1);
664 return !!refspec;
667 struct refspec *parse_fetch_refspec(int nr_refspec, const char **refspec)
669 return parse_refspec_internal(nr_refspec, refspec, 1, 0);
672 static struct refspec *parse_push_refspec(int nr_refspec, const char **refspec)
674 return parse_refspec_internal(nr_refspec, refspec, 0, 0);
677 static int valid_remote_nick(const char *name)
679 if (!name[0] || is_dot_or_dotdot(name))
680 return 0;
681 return !strchr(name, '/'); /* no slash */
684 struct remote *remote_get(const char *name)
686 struct remote *ret;
687 int name_given = 0;
689 read_config();
690 if (name)
691 name_given = 1;
692 else {
693 name = default_remote_name;
694 name_given = explicit_default_remote_name;
697 ret = make_remote(name, 0);
698 if (valid_remote_nick(name)) {
699 if (!valid_remote(ret))
700 read_remotes_file(ret);
701 if (!valid_remote(ret))
702 read_branches_file(ret);
704 if (name_given && !valid_remote(ret))
705 add_url_alias(ret, name);
706 if (!valid_remote(ret))
707 return NULL;
708 ret->fetch = parse_fetch_refspec(ret->fetch_refspec_nr, ret->fetch_refspec);
709 ret->push = parse_push_refspec(ret->push_refspec_nr, ret->push_refspec);
710 return ret;
713 int remote_is_configured(const char *name)
715 int i;
716 read_config();
718 for (i = 0; i < remotes_nr; i++)
719 if (!strcmp(name, remotes[i]->name))
720 return 1;
721 return 0;
724 int for_each_remote(each_remote_fn fn, void *priv)
726 int i, result = 0;
727 read_config();
728 for (i = 0; i < remotes_nr && !result; i++) {
729 struct remote *r = remotes[i];
730 if (!r)
731 continue;
732 if (!r->fetch)
733 r->fetch = parse_fetch_refspec(r->fetch_refspec_nr,
734 r->fetch_refspec);
735 if (!r->push)
736 r->push = parse_push_refspec(r->push_refspec_nr,
737 r->push_refspec);
738 result = fn(r, priv);
740 return result;
743 void ref_remove_duplicates(struct ref *ref_map)
745 struct ref **posn;
746 struct ref *next;
747 for (; ref_map; ref_map = ref_map->next) {
748 if (!ref_map->peer_ref)
749 continue;
750 posn = &ref_map->next;
751 while (*posn) {
752 if ((*posn)->peer_ref &&
753 !strcmp((*posn)->peer_ref->name,
754 ref_map->peer_ref->name)) {
755 if (strcmp((*posn)->name, ref_map->name))
756 die("%s tracks both %s and %s",
757 ref_map->peer_ref->name,
758 (*posn)->name, ref_map->name);
759 next = (*posn)->next;
760 free((*posn)->peer_ref);
761 free(*posn);
762 *posn = next;
763 } else {
764 posn = &(*posn)->next;
770 int remote_has_url(struct remote *remote, const char *url)
772 int i;
773 for (i = 0; i < remote->url_nr; i++) {
774 if (!strcmp(remote->url[i], url))
775 return 1;
777 return 0;
780 static int match_name_with_pattern(const char *key, const char *name,
781 const char *value, char **result)
783 const char *kstar = strchr(key, '*');
784 size_t klen;
785 size_t ksuffixlen;
786 size_t namelen;
787 int ret;
788 if (!kstar)
789 die("Key '%s' of pattern had no '*'", key);
790 klen = kstar - key;
791 ksuffixlen = strlen(kstar + 1);
792 namelen = strlen(name);
793 ret = !strncmp(name, key, klen) && namelen >= klen + ksuffixlen &&
794 !memcmp(name + namelen - ksuffixlen, kstar + 1, ksuffixlen);
795 if (ret && value) {
796 const char *vstar = strchr(value, '*');
797 size_t vlen;
798 size_t vsuffixlen;
799 if (!vstar)
800 die("Value '%s' of pattern has no '*'", value);
801 vlen = vstar - value;
802 vsuffixlen = strlen(vstar + 1);
803 *result = xmalloc(vlen + vsuffixlen +
804 strlen(name) -
805 klen - ksuffixlen + 1);
806 strncpy(*result, value, vlen);
807 strncpy(*result + vlen,
808 name + klen, namelen - klen - ksuffixlen);
809 strcpy(*result + vlen + namelen - klen - ksuffixlen,
810 vstar + 1);
812 return ret;
815 int remote_find_tracking(struct remote *remote, struct refspec *refspec)
817 int find_src = refspec->src == NULL;
818 char *needle, **result;
819 int i;
821 if (find_src) {
822 if (!refspec->dst)
823 return error("find_tracking: need either src or dst");
824 needle = refspec->dst;
825 result = &refspec->src;
826 } else {
827 needle = refspec->src;
828 result = &refspec->dst;
831 for (i = 0; i < remote->fetch_refspec_nr; i++) {
832 struct refspec *fetch = &remote->fetch[i];
833 const char *key = find_src ? fetch->dst : fetch->src;
834 const char *value = find_src ? fetch->src : fetch->dst;
835 if (!fetch->dst)
836 continue;
837 if (fetch->pattern) {
838 if (match_name_with_pattern(key, needle, value, result)) {
839 refspec->force = fetch->force;
840 return 0;
842 } else if (!strcmp(needle, key)) {
843 *result = xstrdup(value);
844 refspec->force = fetch->force;
845 return 0;
848 return -1;
851 static struct ref *alloc_ref_with_prefix(const char *prefix, size_t prefixlen,
852 const char *name)
854 size_t len = strlen(name);
855 struct ref *ref = xcalloc(1, sizeof(struct ref) + prefixlen + len + 1);
856 memcpy(ref->name, prefix, prefixlen);
857 memcpy(ref->name + prefixlen, name, len);
858 return ref;
861 struct ref *alloc_ref(const char *name)
863 return alloc_ref_with_prefix("", 0, name);
866 static struct ref *copy_ref(const struct ref *ref)
868 struct ref *cpy;
869 size_t len;
870 if (!ref)
871 return NULL;
872 len = strlen(ref->name);
873 cpy = xmalloc(sizeof(struct ref) + len + 1);
874 memcpy(cpy, ref, sizeof(struct ref) + len + 1);
875 cpy->next = NULL;
876 cpy->symref = ref->symref ? xstrdup(ref->symref) : NULL;
877 cpy->remote_status = ref->remote_status ? xstrdup(ref->remote_status) : NULL;
878 cpy->peer_ref = copy_ref(ref->peer_ref);
879 return cpy;
882 struct ref *copy_ref_list(const struct ref *ref)
884 struct ref *ret = NULL;
885 struct ref **tail = &ret;
886 while (ref) {
887 *tail = copy_ref(ref);
888 ref = ref->next;
889 tail = &((*tail)->next);
891 return ret;
894 static void free_ref(struct ref *ref)
896 if (!ref)
897 return;
898 free_ref(ref->peer_ref);
899 free(ref->remote_status);
900 free(ref->symref);
901 free(ref);
904 void free_refs(struct ref *ref)
906 struct ref *next;
907 while (ref) {
908 next = ref->next;
909 free_ref(ref);
910 ref = next;
914 static int count_refspec_match(const char *pattern,
915 struct ref *refs,
916 struct ref **matched_ref)
918 int patlen = strlen(pattern);
919 struct ref *matched_weak = NULL;
920 struct ref *matched = NULL;
921 int weak_match = 0;
922 int match = 0;
924 for (weak_match = match = 0; refs; refs = refs->next) {
925 char *name = refs->name;
926 int namelen = strlen(name);
928 if (!refname_match(pattern, name, ref_rev_parse_rules))
929 continue;
931 /* A match is "weak" if it is with refs outside
932 * heads or tags, and did not specify the pattern
933 * in full (e.g. "refs/remotes/origin/master") or at
934 * least from the toplevel (e.g. "remotes/origin/master");
935 * otherwise "git push $URL master" would result in
936 * ambiguity between remotes/origin/master and heads/master
937 * at the remote site.
939 if (namelen != patlen &&
940 patlen != namelen - 5 &&
941 prefixcmp(name, "refs/heads/") &&
942 prefixcmp(name, "refs/tags/")) {
943 /* We want to catch the case where only weak
944 * matches are found and there are multiple
945 * matches, and where more than one strong
946 * matches are found, as ambiguous. One
947 * strong match with zero or more weak matches
948 * are acceptable as a unique match.
950 matched_weak = refs;
951 weak_match++;
953 else {
954 matched = refs;
955 match++;
958 if (!matched) {
959 *matched_ref = matched_weak;
960 return weak_match;
962 else {
963 *matched_ref = matched;
964 return match;
968 static void tail_link_ref(struct ref *ref, struct ref ***tail)
970 **tail = ref;
971 while (ref->next)
972 ref = ref->next;
973 *tail = &ref->next;
976 static struct ref *try_explicit_object_name(const char *name)
978 unsigned char sha1[20];
979 struct ref *ref;
981 if (!*name) {
982 ref = alloc_ref("(delete)");
983 hashclr(ref->new_sha1);
984 return ref;
986 if (get_sha1(name, sha1))
987 return NULL;
988 ref = alloc_ref(name);
989 hashcpy(ref->new_sha1, sha1);
990 return ref;
993 static struct ref *make_linked_ref(const char *name, struct ref ***tail)
995 struct ref *ret = alloc_ref(name);
996 tail_link_ref(ret, tail);
997 return ret;
1000 static char *guess_ref(const char *name, struct ref *peer)
1002 struct strbuf buf = STRBUF_INIT;
1003 unsigned char sha1[20];
1005 const char *r = resolve_ref(peer->name, sha1, 1, NULL);
1006 if (!r)
1007 return NULL;
1009 if (!prefixcmp(r, "refs/heads/"))
1010 strbuf_addstr(&buf, "refs/heads/");
1011 else if (!prefixcmp(r, "refs/tags/"))
1012 strbuf_addstr(&buf, "refs/tags/");
1013 else
1014 return NULL;
1016 strbuf_addstr(&buf, name);
1017 return strbuf_detach(&buf, NULL);
1020 static int match_explicit(struct ref *src, struct ref *dst,
1021 struct ref ***dst_tail,
1022 struct refspec *rs)
1024 struct ref *matched_src, *matched_dst;
1025 int copy_src;
1027 const char *dst_value = rs->dst;
1028 char *dst_guess;
1030 if (rs->pattern || rs->matching)
1031 return 0;
1033 matched_src = matched_dst = NULL;
1034 switch (count_refspec_match(rs->src, src, &matched_src)) {
1035 case 1:
1036 copy_src = 1;
1037 break;
1038 case 0:
1039 /* The source could be in the get_sha1() format
1040 * not a reference name. :refs/other is a
1041 * way to delete 'other' ref at the remote end.
1043 matched_src = try_explicit_object_name(rs->src);
1044 if (!matched_src)
1045 return error("src refspec %s does not match any.", rs->src);
1046 copy_src = 0;
1047 break;
1048 default:
1049 return error("src refspec %s matches more than one.", rs->src);
1052 if (!dst_value) {
1053 unsigned char sha1[20];
1054 int flag;
1056 dst_value = resolve_ref(matched_src->name, sha1, 1, &flag);
1057 if (!dst_value ||
1058 ((flag & REF_ISSYMREF) &&
1059 prefixcmp(dst_value, "refs/heads/")))
1060 die("%s cannot be resolved to branch.",
1061 matched_src->name);
1064 switch (count_refspec_match(dst_value, dst, &matched_dst)) {
1065 case 1:
1066 break;
1067 case 0:
1068 if (!memcmp(dst_value, "refs/", 5))
1069 matched_dst = make_linked_ref(dst_value, dst_tail);
1070 else if ((dst_guess = guess_ref(dst_value, matched_src)))
1071 matched_dst = make_linked_ref(dst_guess, dst_tail);
1072 else
1073 error("unable to push to unqualified destination: %s\n"
1074 "The destination refspec neither matches an "
1075 "existing ref on the remote nor\n"
1076 "begins with refs/, and we are unable to "
1077 "guess a prefix based on the source ref.",
1078 dst_value);
1079 break;
1080 default:
1081 matched_dst = NULL;
1082 error("dst refspec %s matches more than one.",
1083 dst_value);
1084 break;
1086 if (!matched_dst)
1087 return -1;
1088 if (matched_dst->peer_ref)
1089 return error("dst ref %s receives from more than one src.",
1090 matched_dst->name);
1091 else {
1092 matched_dst->peer_ref = copy_src ? copy_ref(matched_src) : matched_src;
1093 matched_dst->force = rs->force;
1095 return 0;
1098 static int match_explicit_refs(struct ref *src, struct ref *dst,
1099 struct ref ***dst_tail, struct refspec *rs,
1100 int rs_nr)
1102 int i, errs;
1103 for (i = errs = 0; i < rs_nr; i++)
1104 errs += match_explicit(src, dst, dst_tail, &rs[i]);
1105 return errs;
1108 static const struct refspec *check_pattern_match(const struct refspec *rs,
1109 int rs_nr,
1110 const struct ref *src)
1112 int i;
1113 int matching_refs = -1;
1114 for (i = 0; i < rs_nr; i++) {
1115 if (rs[i].matching &&
1116 (matching_refs == -1 || rs[i].force)) {
1117 matching_refs = i;
1118 continue;
1121 if (rs[i].pattern && match_name_with_pattern(rs[i].src, src->name,
1122 NULL, NULL))
1123 return rs + i;
1125 if (matching_refs != -1)
1126 return rs + matching_refs;
1127 else
1128 return NULL;
1131 static struct ref **tail_ref(struct ref **head)
1133 struct ref **tail = head;
1134 while (*tail)
1135 tail = &((*tail)->next);
1136 return tail;
1140 * Note. This is used only by "push"; refspec matching rules for
1141 * push and fetch are subtly different, so do not try to reuse it
1142 * without thinking.
1144 int match_refs(struct ref *src, struct ref **dst,
1145 int nr_refspec, const char **refspec, int flags)
1147 struct refspec *rs;
1148 int send_all = flags & MATCH_REFS_ALL;
1149 int send_mirror = flags & MATCH_REFS_MIRROR;
1150 int errs;
1151 static const char *default_refspec[] = { ":", NULL };
1152 struct ref **dst_tail = tail_ref(dst);
1154 if (!nr_refspec) {
1155 nr_refspec = 1;
1156 refspec = default_refspec;
1158 rs = parse_push_refspec(nr_refspec, (const char **) refspec);
1159 errs = match_explicit_refs(src, *dst, &dst_tail, rs, nr_refspec);
1161 /* pick the remainder */
1162 for ( ; src; src = src->next) {
1163 struct ref *dst_peer;
1164 const struct refspec *pat = NULL;
1165 char *dst_name;
1166 if (src->peer_ref)
1167 continue;
1169 pat = check_pattern_match(rs, nr_refspec, src);
1170 if (!pat)
1171 continue;
1173 if (pat->matching) {
1175 * "matching refs"; traditionally we pushed everything
1176 * including refs outside refs/heads/ hierarchy, but
1177 * that does not make much sense these days.
1179 if (!send_mirror && prefixcmp(src->name, "refs/heads/"))
1180 continue;
1181 dst_name = xstrdup(src->name);
1183 } else {
1184 const char *dst_side = pat->dst ? pat->dst : pat->src;
1185 if (!match_name_with_pattern(pat->src, src->name,
1186 dst_side, &dst_name))
1187 die("Didn't think it matches any more");
1189 dst_peer = find_ref_by_name(*dst, dst_name);
1190 if (dst_peer) {
1191 if (dst_peer->peer_ref)
1192 /* We're already sending something to this ref. */
1193 goto free_name;
1195 } else {
1196 if (pat->matching && !(send_all || send_mirror))
1198 * Remote doesn't have it, and we have no
1199 * explicit pattern, and we don't have
1200 * --all nor --mirror.
1202 goto free_name;
1204 /* Create a new one and link it */
1205 dst_peer = make_linked_ref(dst_name, &dst_tail);
1206 hashcpy(dst_peer->new_sha1, src->new_sha1);
1208 dst_peer->peer_ref = copy_ref(src);
1209 dst_peer->force = pat->force;
1210 free_name:
1211 free(dst_name);
1213 if (errs)
1214 return -1;
1215 return 0;
1218 struct branch *branch_get(const char *name)
1220 struct branch *ret;
1222 read_config();
1223 if (!name || !*name || !strcmp(name, "HEAD"))
1224 ret = current_branch;
1225 else
1226 ret = make_branch(name, 0);
1227 if (ret && ret->remote_name) {
1228 ret->remote = remote_get(ret->remote_name);
1229 if (ret->merge_nr) {
1230 int i;
1231 ret->merge = xcalloc(sizeof(*ret->merge),
1232 ret->merge_nr);
1233 for (i = 0; i < ret->merge_nr; i++) {
1234 ret->merge[i] = xcalloc(1, sizeof(**ret->merge));
1235 ret->merge[i]->src = xstrdup(ret->merge_name[i]);
1236 if (remote_find_tracking(ret->remote, ret->merge[i])
1237 && !strcmp(ret->remote_name, "."))
1238 ret->merge[i]->dst = xstrdup(ret->merge_name[i]);
1242 return ret;
1245 int branch_has_merge_config(struct branch *branch)
1247 return branch && !!branch->merge;
1250 int branch_merge_matches(struct branch *branch,
1251 int i,
1252 const char *refname)
1254 if (!branch || i < 0 || i >= branch->merge_nr)
1255 return 0;
1256 return refname_match(branch->merge[i]->src, refname, ref_fetch_rules);
1259 static struct ref *get_expanded_map(const struct ref *remote_refs,
1260 const struct refspec *refspec)
1262 const struct ref *ref;
1263 struct ref *ret = NULL;
1264 struct ref **tail = &ret;
1266 char *expn_name;
1268 for (ref = remote_refs; ref; ref = ref->next) {
1269 if (strchr(ref->name, '^'))
1270 continue; /* a dereference item */
1271 if (match_name_with_pattern(refspec->src, ref->name,
1272 refspec->dst, &expn_name)) {
1273 struct ref *cpy = copy_ref(ref);
1275 cpy->peer_ref = alloc_ref(expn_name);
1276 free(expn_name);
1277 if (refspec->force)
1278 cpy->peer_ref->force = 1;
1279 *tail = cpy;
1280 tail = &cpy->next;
1284 return ret;
1287 static const struct ref *find_ref_by_name_abbrev(const struct ref *refs, const char *name)
1289 const struct ref *ref;
1290 for (ref = refs; ref; ref = ref->next) {
1291 if (refname_match(name, ref->name, ref_fetch_rules))
1292 return ref;
1294 return NULL;
1297 struct ref *get_remote_ref(const struct ref *remote_refs, const char *name)
1299 const struct ref *ref = find_ref_by_name_abbrev(remote_refs, name);
1301 if (!ref)
1302 return NULL;
1304 return copy_ref(ref);
1307 static struct ref *get_local_ref(const char *name)
1309 if (!name || name[0] == '\0')
1310 return NULL;
1312 if (!prefixcmp(name, "refs/"))
1313 return alloc_ref(name);
1315 if (!prefixcmp(name, "heads/") ||
1316 !prefixcmp(name, "tags/") ||
1317 !prefixcmp(name, "remotes/"))
1318 return alloc_ref_with_prefix("refs/", 5, name);
1320 return alloc_ref_with_prefix("refs/heads/", 11, name);
1323 int get_fetch_map(const struct ref *remote_refs,
1324 const struct refspec *refspec,
1325 struct ref ***tail,
1326 int missing_ok)
1328 struct ref *ref_map, **rmp;
1330 if (refspec->pattern) {
1331 ref_map = get_expanded_map(remote_refs, refspec);
1332 } else {
1333 const char *name = refspec->src[0] ? refspec->src : "HEAD";
1335 ref_map = get_remote_ref(remote_refs, name);
1336 if (!missing_ok && !ref_map)
1337 die("Couldn't find remote ref %s", name);
1338 if (ref_map) {
1339 ref_map->peer_ref = get_local_ref(refspec->dst);
1340 if (ref_map->peer_ref && refspec->force)
1341 ref_map->peer_ref->force = 1;
1345 for (rmp = &ref_map; *rmp; ) {
1346 if ((*rmp)->peer_ref) {
1347 int st = check_ref_format((*rmp)->peer_ref->name + 5);
1348 if (st && st != CHECK_REF_FORMAT_ONELEVEL) {
1349 struct ref *ignore = *rmp;
1350 error("* Ignoring funny ref '%s' locally",
1351 (*rmp)->peer_ref->name);
1352 *rmp = (*rmp)->next;
1353 free(ignore->peer_ref);
1354 free(ignore);
1355 continue;
1358 rmp = &((*rmp)->next);
1361 if (ref_map)
1362 tail_link_ref(ref_map, tail);
1364 return 0;
1367 int resolve_remote_symref(struct ref *ref, struct ref *list)
1369 if (!ref->symref)
1370 return 0;
1371 for (; list; list = list->next)
1372 if (!strcmp(ref->symref, list->name)) {
1373 hashcpy(ref->old_sha1, list->old_sha1);
1374 return 0;
1376 return 1;
1379 static void unmark_and_free(struct commit_list *list, unsigned int mark)
1381 while (list) {
1382 struct commit_list *temp = list;
1383 temp->item->object.flags &= ~mark;
1384 list = temp->next;
1385 free(temp);
1389 int ref_newer(const unsigned char *new_sha1, const unsigned char *old_sha1)
1391 struct object *o;
1392 struct commit *old, *new;
1393 struct commit_list *list, *used;
1394 int found = 0;
1396 /* Both new and old must be commit-ish and new is descendant of
1397 * old. Otherwise we require --force.
1399 o = deref_tag(parse_object(old_sha1), NULL, 0);
1400 if (!o || o->type != OBJ_COMMIT)
1401 return 0;
1402 old = (struct commit *) o;
1404 o = deref_tag(parse_object(new_sha1), NULL, 0);
1405 if (!o || o->type != OBJ_COMMIT)
1406 return 0;
1407 new = (struct commit *) o;
1409 if (parse_commit(new) < 0)
1410 return 0;
1412 used = list = NULL;
1413 commit_list_insert(new, &list);
1414 while (list) {
1415 new = pop_most_recent_commit(&list, TMP_MARK);
1416 commit_list_insert(new, &used);
1417 if (new == old) {
1418 found = 1;
1419 break;
1422 unmark_and_free(list, TMP_MARK);
1423 unmark_and_free(used, TMP_MARK);
1424 return found;
1428 * Return true if there is anything to report, otherwise false.
1430 int stat_tracking_info(struct branch *branch, int *num_ours, int *num_theirs)
1432 unsigned char sha1[20];
1433 struct commit *ours, *theirs;
1434 char symmetric[84];
1435 struct rev_info revs;
1436 const char *rev_argv[10], *base;
1437 int rev_argc;
1440 * Nothing to report unless we are marked to build on top of
1441 * somebody else.
1443 if (!branch ||
1444 !branch->merge || !branch->merge[0] || !branch->merge[0]->dst)
1445 return 0;
1448 * If what we used to build on no longer exists, there is
1449 * nothing to report.
1451 base = branch->merge[0]->dst;
1452 if (!resolve_ref(base, sha1, 1, NULL))
1453 return 0;
1454 theirs = lookup_commit_reference(sha1);
1455 if (!theirs)
1456 return 0;
1458 if (!resolve_ref(branch->refname, sha1, 1, NULL))
1459 return 0;
1460 ours = lookup_commit_reference(sha1);
1461 if (!ours)
1462 return 0;
1464 /* are we the same? */
1465 if (theirs == ours)
1466 return 0;
1468 /* Run "rev-list --left-right ours...theirs" internally... */
1469 rev_argc = 0;
1470 rev_argv[rev_argc++] = NULL;
1471 rev_argv[rev_argc++] = "--left-right";
1472 rev_argv[rev_argc++] = symmetric;
1473 rev_argv[rev_argc++] = "--";
1474 rev_argv[rev_argc] = NULL;
1476 strcpy(symmetric, sha1_to_hex(ours->object.sha1));
1477 strcpy(symmetric + 40, "...");
1478 strcpy(symmetric + 43, sha1_to_hex(theirs->object.sha1));
1480 init_revisions(&revs, NULL);
1481 setup_revisions(rev_argc, rev_argv, &revs, NULL);
1482 prepare_revision_walk(&revs);
1484 /* ... and count the commits on each side. */
1485 *num_ours = 0;
1486 *num_theirs = 0;
1487 while (1) {
1488 struct commit *c = get_revision(&revs);
1489 if (!c)
1490 break;
1491 if (c->object.flags & SYMMETRIC_LEFT)
1492 (*num_ours)++;
1493 else
1494 (*num_theirs)++;
1497 /* clear object flags smudged by the above traversal */
1498 clear_commit_marks(ours, ALL_REV_FLAGS);
1499 clear_commit_marks(theirs, ALL_REV_FLAGS);
1500 return 1;
1504 * Return true when there is anything to report, otherwise false.
1506 int format_tracking_info(struct branch *branch, struct strbuf *sb)
1508 int num_ours, num_theirs;
1509 const char *base;
1511 if (!stat_tracking_info(branch, &num_ours, &num_theirs))
1512 return 0;
1514 base = branch->merge[0]->dst;
1515 base = shorten_unambiguous_ref(base, 0);
1516 if (!num_theirs)
1517 strbuf_addf(sb, "Your branch is ahead of '%s' "
1518 "by %d commit%s.\n",
1519 base, num_ours, (num_ours == 1) ? "" : "s");
1520 else if (!num_ours)
1521 strbuf_addf(sb, "Your branch is behind '%s' "
1522 "by %d commit%s, "
1523 "and can be fast-forwarded.\n",
1524 base, num_theirs, (num_theirs == 1) ? "" : "s");
1525 else
1526 strbuf_addf(sb, "Your branch and '%s' have diverged,\n"
1527 "and have %d and %d different commit(s) each, "
1528 "respectively.\n",
1529 base, num_ours, num_theirs);
1530 return 1;
1533 static int one_local_ref(const char *refname, const unsigned char *sha1, int flag, void *cb_data)
1535 struct ref ***local_tail = cb_data;
1536 struct ref *ref;
1537 int len;
1539 /* we already know it starts with refs/ to get here */
1540 if (check_ref_format(refname + 5))
1541 return 0;
1543 len = strlen(refname) + 1;
1544 ref = xcalloc(1, sizeof(*ref) + len);
1545 hashcpy(ref->new_sha1, sha1);
1546 memcpy(ref->name, refname, len);
1547 **local_tail = ref;
1548 *local_tail = &ref->next;
1549 return 0;
1552 struct ref *get_local_heads(void)
1554 struct ref *local_refs = NULL, **local_tail = &local_refs;
1555 for_each_ref(one_local_ref, &local_tail);
1556 return local_refs;
1559 struct ref *guess_remote_head(const struct ref *head,
1560 const struct ref *refs,
1561 int all)
1563 const struct ref *r;
1564 struct ref *list = NULL;
1565 struct ref **tail = &list;
1567 if (!head)
1568 return NULL;
1571 * Some transports support directly peeking at
1572 * where HEAD points; if that is the case, then
1573 * we don't have to guess.
1575 if (head->symref)
1576 return copy_ref(find_ref_by_name(refs, head->symref));
1578 /* If refs/heads/master could be right, it is. */
1579 if (!all) {
1580 r = find_ref_by_name(refs, "refs/heads/master");
1581 if (r && !hashcmp(r->old_sha1, head->old_sha1))
1582 return copy_ref(r);
1585 /* Look for another ref that points there */
1586 for (r = refs; r; r = r->next) {
1587 if (r != head && !hashcmp(r->old_sha1, head->old_sha1)) {
1588 *tail = copy_ref(r);
1589 tail = &((*tail)->next);
1590 if (!all)
1591 break;
1595 return list;