Allow helper to map private ref names into normal names
[git/dscho.git] / remote.c
blob1f7870d107371af9dd4db1fb6e2e777138d682b3
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];
55 static int valid_remote(const struct remote *remote)
57 return (!!remote->url) || (!!remote->foreign_vcs);
60 static const char *alias_url(const char *url, struct rewrites *r)
62 int i, j;
63 char *ret;
64 struct counted_string *longest;
65 int longest_i;
67 longest = NULL;
68 longest_i = -1;
69 for (i = 0; i < r->rewrite_nr; i++) {
70 if (!r->rewrite[i])
71 continue;
72 for (j = 0; j < r->rewrite[i]->instead_of_nr; j++) {
73 if (!prefixcmp(url, r->rewrite[i]->instead_of[j].s) &&
74 (!longest ||
75 longest->len < r->rewrite[i]->instead_of[j].len)) {
76 longest = &(r->rewrite[i]->instead_of[j]);
77 longest_i = i;
81 if (!longest)
82 return url;
84 ret = xmalloc(r->rewrite[longest_i]->baselen +
85 (strlen(url) - longest->len) + 1);
86 strcpy(ret, r->rewrite[longest_i]->base);
87 strcpy(ret + r->rewrite[longest_i]->baselen, url + longest->len);
88 return ret;
91 static void add_push_refspec(struct remote *remote, const char *ref)
93 ALLOC_GROW(remote->push_refspec,
94 remote->push_refspec_nr + 1,
95 remote->push_refspec_alloc);
96 remote->push_refspec[remote->push_refspec_nr++] = ref;
99 static void add_fetch_refspec(struct remote *remote, const char *ref)
101 ALLOC_GROW(remote->fetch_refspec,
102 remote->fetch_refspec_nr + 1,
103 remote->fetch_refspec_alloc);
104 remote->fetch_refspec[remote->fetch_refspec_nr++] = ref;
107 static void add_url(struct remote *remote, const char *url)
109 ALLOC_GROW(remote->url, remote->url_nr + 1, remote->url_alloc);
110 remote->url[remote->url_nr++] = url;
113 static void add_pushurl(struct remote *remote, const char *pushurl)
115 ALLOC_GROW(remote->pushurl, remote->pushurl_nr + 1, remote->pushurl_alloc);
116 remote->pushurl[remote->pushurl_nr++] = pushurl;
119 static void add_pushurl_alias(struct remote *remote, const char *url)
121 const char *pushurl = alias_url(url, &rewrites_push);
122 if (pushurl != url)
123 add_pushurl(remote, pushurl);
126 static void add_url_alias(struct remote *remote, const char *url)
128 add_url(remote, alias_url(url, &rewrites));
129 add_pushurl_alias(remote, url);
132 static struct remote *make_remote(const char *name, int len)
134 struct remote *ret;
135 int i;
137 for (i = 0; i < remotes_nr; i++) {
138 if (len ? (!strncmp(name, remotes[i]->name, len) &&
139 !remotes[i]->name[len]) :
140 !strcmp(name, remotes[i]->name))
141 return remotes[i];
144 ret = xcalloc(1, sizeof(struct remote));
145 ALLOC_GROW(remotes, remotes_nr + 1, remotes_alloc);
146 remotes[remotes_nr++] = ret;
147 if (len)
148 ret->name = xstrndup(name, len);
149 else
150 ret->name = xstrdup(name);
151 return ret;
154 static void add_merge(struct branch *branch, const char *name)
156 ALLOC_GROW(branch->merge_name, branch->merge_nr + 1,
157 branch->merge_alloc);
158 branch->merge_name[branch->merge_nr++] = name;
161 static struct branch *make_branch(const char *name, int len)
163 struct branch *ret;
164 int i;
165 char *refname;
167 for (i = 0; i < branches_nr; i++) {
168 if (len ? (!strncmp(name, branches[i]->name, len) &&
169 !branches[i]->name[len]) :
170 !strcmp(name, branches[i]->name))
171 return branches[i];
174 ALLOC_GROW(branches, branches_nr + 1, branches_alloc);
175 ret = xcalloc(1, sizeof(struct branch));
176 branches[branches_nr++] = ret;
177 if (len)
178 ret->name = xstrndup(name, len);
179 else
180 ret->name = xstrdup(name);
181 refname = xmalloc(strlen(name) + strlen("refs/heads/") + 1);
182 strcpy(refname, "refs/heads/");
183 strcpy(refname + strlen("refs/heads/"), ret->name);
184 ret->refname = refname;
186 return ret;
189 static struct rewrite *make_rewrite(struct rewrites *r, const char *base, int len)
191 struct rewrite *ret;
192 int i;
194 for (i = 0; i < r->rewrite_nr; i++) {
195 if (len
196 ? (len == r->rewrite[i]->baselen &&
197 !strncmp(base, r->rewrite[i]->base, len))
198 : !strcmp(base, r->rewrite[i]->base))
199 return r->rewrite[i];
202 ALLOC_GROW(r->rewrite, r->rewrite_nr + 1, r->rewrite_alloc);
203 ret = xcalloc(1, sizeof(struct rewrite));
204 r->rewrite[r->rewrite_nr++] = ret;
205 if (len) {
206 ret->base = xstrndup(base, len);
207 ret->baselen = len;
209 else {
210 ret->base = xstrdup(base);
211 ret->baselen = strlen(base);
213 return ret;
216 static void add_instead_of(struct rewrite *rewrite, const char *instead_of)
218 ALLOC_GROW(rewrite->instead_of, rewrite->instead_of_nr + 1, rewrite->instead_of_alloc);
219 rewrite->instead_of[rewrite->instead_of_nr].s = instead_of;
220 rewrite->instead_of[rewrite->instead_of_nr].len = strlen(instead_of);
221 rewrite->instead_of_nr++;
224 static void read_remotes_file(struct remote *remote)
226 FILE *f = fopen(git_path("remotes/%s", remote->name), "r");
228 if (!f)
229 return;
230 remote->origin = REMOTE_REMOTES;
231 while (fgets(buffer, BUF_SIZE, f)) {
232 int value_list;
233 char *s, *p;
235 if (!prefixcmp(buffer, "URL:")) {
236 value_list = 0;
237 s = buffer + 4;
238 } else if (!prefixcmp(buffer, "Push:")) {
239 value_list = 1;
240 s = buffer + 5;
241 } else if (!prefixcmp(buffer, "Pull:")) {
242 value_list = 2;
243 s = buffer + 5;
244 } else
245 continue;
247 while (isspace(*s))
248 s++;
249 if (!*s)
250 continue;
252 p = s + strlen(s);
253 while (isspace(p[-1]))
254 *--p = 0;
256 switch (value_list) {
257 case 0:
258 add_url_alias(remote, xstrdup(s));
259 break;
260 case 1:
261 add_push_refspec(remote, xstrdup(s));
262 break;
263 case 2:
264 add_fetch_refspec(remote, xstrdup(s));
265 break;
268 fclose(f);
271 static void read_branches_file(struct remote *remote)
273 const char *slash = strchr(remote->name, '/');
274 char *frag;
275 struct strbuf branch = STRBUF_INIT;
276 int n = slash ? slash - remote->name : 1000;
277 FILE *f = fopen(git_path("branches/%.*s", n, remote->name), "r");
278 char *s, *p;
279 int len;
281 if (!f)
282 return;
283 s = fgets(buffer, BUF_SIZE, f);
284 fclose(f);
285 if (!s)
286 return;
287 while (isspace(*s))
288 s++;
289 if (!*s)
290 return;
291 remote->origin = REMOTE_BRANCHES;
292 p = s + strlen(s);
293 while (isspace(p[-1]))
294 *--p = 0;
295 len = p - s;
296 if (slash)
297 len += strlen(slash);
298 p = xmalloc(len + 1);
299 strcpy(p, s);
300 if (slash)
301 strcat(p, slash);
304 * With "slash", e.g. "git fetch jgarzik/netdev-2.6" when
305 * reading from $GIT_DIR/branches/jgarzik fetches "HEAD" from
306 * the partial URL obtained from the branches file plus
307 * "/netdev-2.6" and does not store it in any tracking ref.
308 * #branch specifier in the file is ignored.
310 * Otherwise, the branches file would have URL and optionally
311 * #branch specified. The "master" (or specified) branch is
312 * fetched and stored in the local branch of the same name.
314 frag = strchr(p, '#');
315 if (frag) {
316 *(frag++) = '\0';
317 strbuf_addf(&branch, "refs/heads/%s", frag);
318 } else
319 strbuf_addstr(&branch, "refs/heads/master");
320 if (!slash) {
321 strbuf_addf(&branch, ":refs/heads/%s", remote->name);
322 } else {
323 strbuf_reset(&branch);
324 strbuf_addstr(&branch, "HEAD:");
326 add_url_alias(remote, p);
327 add_fetch_refspec(remote, strbuf_detach(&branch, NULL));
329 * Cogito compatible push: push current HEAD to remote #branch
330 * (master if missing)
332 strbuf_init(&branch, 0);
333 strbuf_addstr(&branch, "HEAD");
334 if (frag)
335 strbuf_addf(&branch, ":refs/heads/%s", frag);
336 else
337 strbuf_addstr(&branch, ":refs/heads/master");
338 add_push_refspec(remote, strbuf_detach(&branch, NULL));
339 remote->fetch_tags = 1; /* always auto-follow */
342 static int handle_config(const char *key, const char *value, void *cb)
344 const char *name;
345 const char *subkey;
346 struct remote *remote;
347 struct branch *branch;
348 if (!prefixcmp(key, "branch.")) {
349 name = key + 7;
350 subkey = strrchr(name, '.');
351 if (!subkey)
352 return 0;
353 branch = make_branch(name, subkey - name);
354 if (!strcmp(subkey, ".remote")) {
355 if (!value)
356 return config_error_nonbool(key);
357 branch->remote_name = xstrdup(value);
358 if (branch == current_branch) {
359 default_remote_name = branch->remote_name;
360 explicit_default_remote_name = 1;
362 } else if (!strcmp(subkey, ".merge")) {
363 if (!value)
364 return config_error_nonbool(key);
365 add_merge(branch, xstrdup(value));
367 return 0;
369 if (!prefixcmp(key, "url.")) {
370 struct rewrite *rewrite;
371 name = key + 4;
372 subkey = strrchr(name, '.');
373 if (!subkey)
374 return 0;
375 if (!strcmp(subkey, ".insteadof")) {
376 rewrite = make_rewrite(&rewrites, name, subkey - name);
377 if (!value)
378 return config_error_nonbool(key);
379 add_instead_of(rewrite, xstrdup(value));
380 } else if (!strcmp(subkey, ".pushinsteadof")) {
381 rewrite = make_rewrite(&rewrites_push, name, subkey - name);
382 if (!value)
383 return config_error_nonbool(key);
384 add_instead_of(rewrite, xstrdup(value));
387 if (prefixcmp(key, "remote."))
388 return 0;
389 name = key + 7;
390 if (*name == '/') {
391 warning("Config remote shorthand cannot begin with '/': %s",
392 name);
393 return 0;
395 subkey = strrchr(name, '.');
396 if (!subkey)
397 return 0;
398 remote = make_remote(name, subkey - name);
399 remote->origin = REMOTE_CONFIG;
400 if (!strcmp(subkey, ".mirror"))
401 remote->mirror = git_config_bool(key, value);
402 else if (!strcmp(subkey, ".skipdefaultupdate"))
403 remote->skip_default_update = git_config_bool(key, value);
405 else if (!strcmp(subkey, ".url")) {
406 const char *v;
407 if (git_config_string(&v, key, value))
408 return -1;
409 add_url(remote, v);
410 } else if (!strcmp(subkey, ".pushurl")) {
411 const char *v;
412 if (git_config_string(&v, key, value))
413 return -1;
414 add_pushurl(remote, v);
415 } else if (!strcmp(subkey, ".push")) {
416 const char *v;
417 if (git_config_string(&v, key, value))
418 return -1;
419 add_push_refspec(remote, v);
420 } else if (!strcmp(subkey, ".fetch")) {
421 const char *v;
422 if (git_config_string(&v, key, value))
423 return -1;
424 add_fetch_refspec(remote, v);
425 } else if (!strcmp(subkey, ".receivepack")) {
426 const char *v;
427 if (git_config_string(&v, key, value))
428 return -1;
429 if (!remote->receivepack)
430 remote->receivepack = v;
431 else
432 error("more than one receivepack given, using the first");
433 } else if (!strcmp(subkey, ".uploadpack")) {
434 const char *v;
435 if (git_config_string(&v, key, value))
436 return -1;
437 if (!remote->uploadpack)
438 remote->uploadpack = v;
439 else
440 error("more than one uploadpack given, using the first");
441 } else if (!strcmp(subkey, ".tagopt")) {
442 if (!strcmp(value, "--no-tags"))
443 remote->fetch_tags = -1;
444 } else if (!strcmp(subkey, ".proxy")) {
445 return git_config_string((const char **)&remote->http_proxy,
446 key, value);
447 } else if (!strcmp(subkey, ".vcs")) {
448 return git_config_string(&remote->foreign_vcs, key, value);
450 return 0;
453 static void alias_all_urls(void)
455 int i, j;
456 for (i = 0; i < remotes_nr; i++) {
457 int add_pushurl_aliases;
458 if (!remotes[i])
459 continue;
460 for (j = 0; j < remotes[i]->pushurl_nr; j++) {
461 remotes[i]->pushurl[j] = alias_url(remotes[i]->pushurl[j], &rewrites);
463 add_pushurl_aliases = remotes[i]->pushurl_nr == 0;
464 for (j = 0; j < remotes[i]->url_nr; j++) {
465 if (add_pushurl_aliases)
466 add_pushurl_alias(remotes[i], remotes[i]->url[j]);
467 remotes[i]->url[j] = alias_url(remotes[i]->url[j], &rewrites);
472 static void read_config(void)
474 unsigned char sha1[20];
475 const char *head_ref;
476 int flag;
477 if (default_remote_name) // did this already
478 return;
479 default_remote_name = xstrdup("origin");
480 current_branch = NULL;
481 head_ref = resolve_ref("HEAD", sha1, 0, &flag);
482 if (head_ref && (flag & REF_ISSYMREF) &&
483 !prefixcmp(head_ref, "refs/heads/")) {
484 current_branch =
485 make_branch(head_ref + strlen("refs/heads/"), 0);
487 git_config(handle_config, NULL);
488 alias_all_urls();
492 * We need to make sure the tracking branches are well formed, but a
493 * wildcard refspec in "struct refspec" must have a trailing slash. We
494 * temporarily drop the trailing '/' while calling check_ref_format(),
495 * and put it back. The caller knows that a CHECK_REF_FORMAT_ONELEVEL
496 * error return is Ok for a wildcard refspec.
498 static int verify_refname(char *name, int is_glob)
500 int result;
502 result = check_ref_format(name);
503 if (is_glob && result == CHECK_REF_FORMAT_WILDCARD)
504 result = CHECK_REF_FORMAT_OK;
505 return result;
509 * This function frees a refspec array.
510 * Warning: code paths should be checked to ensure that the src
511 * and dst pointers are always freeable pointers as well
512 * as the refspec pointer itself.
514 static void free_refspecs(struct refspec *refspec, int nr_refspec)
516 int i;
518 if (!refspec)
519 return;
521 for (i = 0; i < nr_refspec; i++) {
522 free(refspec[i].src);
523 free(refspec[i].dst);
525 free(refspec);
528 static struct refspec *parse_refspec_internal(int nr_refspec, const char **refspec, int fetch, int verify)
530 int i;
531 int st;
532 struct refspec *rs = xcalloc(sizeof(*rs), nr_refspec);
534 for (i = 0; i < nr_refspec; i++) {
535 size_t llen;
536 int is_glob;
537 const char *lhs, *rhs;
539 is_glob = 0;
541 lhs = refspec[i];
542 if (*lhs == '+') {
543 rs[i].force = 1;
544 lhs++;
547 rhs = strrchr(lhs, ':');
550 * Before going on, special case ":" (or "+:") as a refspec
551 * for matching refs.
553 if (!fetch && rhs == lhs && rhs[1] == '\0') {
554 rs[i].matching = 1;
555 continue;
558 if (rhs) {
559 size_t rlen = strlen(++rhs);
560 is_glob = (1 <= rlen && strchr(rhs, '*'));
561 rs[i].dst = xstrndup(rhs, rlen);
564 llen = (rhs ? (rhs - lhs - 1) : strlen(lhs));
565 if (1 <= llen && memchr(lhs, '*', llen)) {
566 if ((rhs && !is_glob) || (!rhs && fetch))
567 goto invalid;
568 is_glob = 1;
569 } else if (rhs && is_glob) {
570 goto invalid;
573 rs[i].pattern = is_glob;
574 rs[i].src = xstrndup(lhs, llen);
576 if (fetch) {
578 * LHS
579 * - empty is allowed; it means HEAD.
580 * - otherwise it must be a valid looking ref.
582 if (!*rs[i].src)
583 ; /* empty is ok */
584 else {
585 st = verify_refname(rs[i].src, is_glob);
586 if (st && st != CHECK_REF_FORMAT_ONELEVEL)
587 goto invalid;
590 * RHS
591 * - missing is ok, and is same as empty.
592 * - empty is ok; it means not to store.
593 * - otherwise it must be a valid looking ref.
595 if (!rs[i].dst) {
596 ; /* ok */
597 } else if (!*rs[i].dst) {
598 ; /* ok */
599 } else {
600 st = verify_refname(rs[i].dst, is_glob);
601 if (st && st != CHECK_REF_FORMAT_ONELEVEL)
602 goto invalid;
604 } else {
606 * LHS
607 * - empty is allowed; it means delete.
608 * - when wildcarded, it must be a valid looking ref.
609 * - otherwise, it must be an extended SHA-1, but
610 * there is no existing way to validate this.
612 if (!*rs[i].src)
613 ; /* empty is ok */
614 else if (is_glob) {
615 st = verify_refname(rs[i].src, is_glob);
616 if (st && st != CHECK_REF_FORMAT_ONELEVEL)
617 goto invalid;
619 else
620 ; /* anything goes, for now */
622 * RHS
623 * - missing is allowed, but LHS then must be a
624 * valid looking ref.
625 * - empty is not allowed.
626 * - otherwise it must be a valid looking ref.
628 if (!rs[i].dst) {
629 st = verify_refname(rs[i].src, is_glob);
630 if (st && st != CHECK_REF_FORMAT_ONELEVEL)
631 goto invalid;
632 } else if (!*rs[i].dst) {
633 goto invalid;
634 } else {
635 st = verify_refname(rs[i].dst, is_glob);
636 if (st && st != CHECK_REF_FORMAT_ONELEVEL)
637 goto invalid;
641 return rs;
643 invalid:
644 if (verify) {
646 * nr_refspec must be greater than zero and i must be valid
647 * since it is only possible to reach this point from within
648 * the for loop above.
650 free_refspecs(rs, i+1);
651 return NULL;
653 die("Invalid refspec '%s'", refspec[i]);
656 int valid_fetch_refspec(const char *fetch_refspec_str)
658 const char *fetch_refspec[] = { fetch_refspec_str };
659 struct refspec *refspec;
661 refspec = parse_refspec_internal(1, fetch_refspec, 1, 1);
662 free_refspecs(refspec, 1);
663 return !!refspec;
666 struct refspec *parse_fetch_refspec(int nr_refspec, const char **refspec)
668 return parse_refspec_internal(nr_refspec, refspec, 1, 0);
671 static struct refspec *parse_push_refspec(int nr_refspec, const char **refspec)
673 return parse_refspec_internal(nr_refspec, refspec, 0, 0);
676 void free_refspec(int nr_refspec, struct refspec *refspec)
678 int i;
679 for (i = 0; i < nr_refspec; i++) {
680 free(refspec[i].src);
681 free(refspec[i].dst);
683 free(refspec);
686 static int valid_remote_nick(const char *name)
688 if (!name[0] || is_dot_or_dotdot(name))
689 return 0;
690 return !strchr(name, '/'); /* no slash */
693 struct remote *remote_get(const char *name)
695 struct remote *ret;
696 int name_given = 0;
698 read_config();
699 if (name)
700 name_given = 1;
701 else {
702 name = default_remote_name;
703 name_given = explicit_default_remote_name;
706 ret = make_remote(name, 0);
707 if (valid_remote_nick(name)) {
708 if (!valid_remote(ret))
709 read_remotes_file(ret);
710 if (!valid_remote(ret))
711 read_branches_file(ret);
713 if (name_given && !valid_remote(ret))
714 add_url_alias(ret, name);
715 if (!valid_remote(ret))
716 return NULL;
717 ret->fetch = parse_fetch_refspec(ret->fetch_refspec_nr, ret->fetch_refspec);
718 ret->push = parse_push_refspec(ret->push_refspec_nr, ret->push_refspec);
719 return ret;
722 int remote_is_configured(const char *name)
724 int i;
725 read_config();
727 for (i = 0; i < remotes_nr; i++)
728 if (!strcmp(name, remotes[i]->name))
729 return 1;
730 return 0;
733 int for_each_remote(each_remote_fn fn, void *priv)
735 int i, result = 0;
736 read_config();
737 for (i = 0; i < remotes_nr && !result; i++) {
738 struct remote *r = remotes[i];
739 if (!r)
740 continue;
741 if (!r->fetch)
742 r->fetch = parse_fetch_refspec(r->fetch_refspec_nr,
743 r->fetch_refspec);
744 if (!r->push)
745 r->push = parse_push_refspec(r->push_refspec_nr,
746 r->push_refspec);
747 result = fn(r, priv);
749 return result;
752 void ref_remove_duplicates(struct ref *ref_map)
754 struct ref **posn;
755 struct ref *next;
756 for (; ref_map; ref_map = ref_map->next) {
757 if (!ref_map->peer_ref)
758 continue;
759 posn = &ref_map->next;
760 while (*posn) {
761 if ((*posn)->peer_ref &&
762 !strcmp((*posn)->peer_ref->name,
763 ref_map->peer_ref->name)) {
764 if (strcmp((*posn)->name, ref_map->name))
765 die("%s tracks both %s and %s",
766 ref_map->peer_ref->name,
767 (*posn)->name, ref_map->name);
768 next = (*posn)->next;
769 free((*posn)->peer_ref);
770 free(*posn);
771 *posn = next;
772 } else {
773 posn = &(*posn)->next;
779 int remote_has_url(struct remote *remote, const char *url)
781 int i;
782 for (i = 0; i < remote->url_nr; i++) {
783 if (!strcmp(remote->url[i], url))
784 return 1;
786 return 0;
789 static int match_name_with_pattern(const char *key, const char *name,
790 const char *value, char **result)
792 const char *kstar = strchr(key, '*');
793 size_t klen;
794 size_t ksuffixlen;
795 size_t namelen;
796 int ret;
797 if (!kstar)
798 die("Key '%s' of pattern had no '*'", key);
799 klen = kstar - key;
800 ksuffixlen = strlen(kstar + 1);
801 namelen = strlen(name);
802 ret = !strncmp(name, key, klen) && namelen >= klen + ksuffixlen &&
803 !memcmp(name + namelen - ksuffixlen, kstar + 1, ksuffixlen);
804 if (ret && value) {
805 const char *vstar = strchr(value, '*');
806 size_t vlen;
807 size_t vsuffixlen;
808 if (!vstar)
809 die("Value '%s' of pattern has no '*'", value);
810 vlen = vstar - value;
811 vsuffixlen = strlen(vstar + 1);
812 *result = xmalloc(vlen + vsuffixlen +
813 strlen(name) -
814 klen - ksuffixlen + 1);
815 strncpy(*result, value, vlen);
816 strncpy(*result + vlen,
817 name + klen, namelen - klen - ksuffixlen);
818 strcpy(*result + vlen + namelen - klen - ksuffixlen,
819 vstar + 1);
821 return ret;
824 char *apply_refspecs(struct refspec *refspecs, int nr_refspec,
825 const char *name)
827 int i;
828 char *ret = NULL;
829 for (i = 0; i < nr_refspec; i++) {
830 struct refspec *refspec = refspecs + i;
831 if (refspec->pattern) {
832 if (match_name_with_pattern(refspec->src, name,
833 refspec->dst, &ret))
834 return ret;
835 } else if (!strcmp(refspec->src, name))
836 return strdup(refspec->dst);
838 return NULL;
841 int remote_find_tracking(struct remote *remote, struct refspec *refspec)
843 int find_src = refspec->src == NULL;
844 char *needle, **result;
845 int i;
847 if (find_src) {
848 if (!refspec->dst)
849 return error("find_tracking: need either src or dst");
850 needle = refspec->dst;
851 result = &refspec->src;
852 } else {
853 needle = refspec->src;
854 result = &refspec->dst;
857 for (i = 0; i < remote->fetch_refspec_nr; i++) {
858 struct refspec *fetch = &remote->fetch[i];
859 const char *key = find_src ? fetch->dst : fetch->src;
860 const char *value = find_src ? fetch->src : fetch->dst;
861 if (!fetch->dst)
862 continue;
863 if (fetch->pattern) {
864 if (match_name_with_pattern(key, needle, value, result)) {
865 refspec->force = fetch->force;
866 return 0;
868 } else if (!strcmp(needle, key)) {
869 *result = xstrdup(value);
870 refspec->force = fetch->force;
871 return 0;
874 return -1;
877 static struct ref *alloc_ref_with_prefix(const char *prefix, size_t prefixlen,
878 const char *name)
880 size_t len = strlen(name);
881 struct ref *ref = xcalloc(1, sizeof(struct ref) + prefixlen + len + 1);
882 memcpy(ref->name, prefix, prefixlen);
883 memcpy(ref->name + prefixlen, name, len);
884 return ref;
887 struct ref *alloc_ref(const char *name)
889 return alloc_ref_with_prefix("", 0, name);
892 static struct ref *copy_ref(const struct ref *ref)
894 struct ref *cpy;
895 size_t len;
896 if (!ref)
897 return NULL;
898 len = strlen(ref->name);
899 cpy = xmalloc(sizeof(struct ref) + len + 1);
900 memcpy(cpy, ref, sizeof(struct ref) + len + 1);
901 cpy->next = NULL;
902 cpy->symref = ref->symref ? xstrdup(ref->symref) : NULL;
903 cpy->remote_status = ref->remote_status ? xstrdup(ref->remote_status) : NULL;
904 cpy->peer_ref = copy_ref(ref->peer_ref);
905 return cpy;
908 struct ref *copy_ref_list(const struct ref *ref)
910 struct ref *ret = NULL;
911 struct ref **tail = &ret;
912 while (ref) {
913 *tail = copy_ref(ref);
914 ref = ref->next;
915 tail = &((*tail)->next);
917 return ret;
920 static void free_ref(struct ref *ref)
922 if (!ref)
923 return;
924 free_ref(ref->peer_ref);
925 free(ref->remote_status);
926 free(ref->symref);
927 free(ref);
930 void free_refs(struct ref *ref)
932 struct ref *next;
933 while (ref) {
934 next = ref->next;
935 free_ref(ref);
936 ref = next;
940 static int count_refspec_match(const char *pattern,
941 struct ref *refs,
942 struct ref **matched_ref)
944 int patlen = strlen(pattern);
945 struct ref *matched_weak = NULL;
946 struct ref *matched = NULL;
947 int weak_match = 0;
948 int match = 0;
950 for (weak_match = match = 0; refs; refs = refs->next) {
951 char *name = refs->name;
952 int namelen = strlen(name);
954 if (!refname_match(pattern, name, ref_rev_parse_rules))
955 continue;
957 /* A match is "weak" if it is with refs outside
958 * heads or tags, and did not specify the pattern
959 * in full (e.g. "refs/remotes/origin/master") or at
960 * least from the toplevel (e.g. "remotes/origin/master");
961 * otherwise "git push $URL master" would result in
962 * ambiguity between remotes/origin/master and heads/master
963 * at the remote site.
965 if (namelen != patlen &&
966 patlen != namelen - 5 &&
967 prefixcmp(name, "refs/heads/") &&
968 prefixcmp(name, "refs/tags/")) {
969 /* We want to catch the case where only weak
970 * matches are found and there are multiple
971 * matches, and where more than one strong
972 * matches are found, as ambiguous. One
973 * strong match with zero or more weak matches
974 * are acceptable as a unique match.
976 matched_weak = refs;
977 weak_match++;
979 else {
980 matched = refs;
981 match++;
984 if (!matched) {
985 *matched_ref = matched_weak;
986 return weak_match;
988 else {
989 *matched_ref = matched;
990 return match;
994 static void tail_link_ref(struct ref *ref, struct ref ***tail)
996 **tail = ref;
997 while (ref->next)
998 ref = ref->next;
999 *tail = &ref->next;
1002 static struct ref *try_explicit_object_name(const char *name)
1004 unsigned char sha1[20];
1005 struct ref *ref;
1007 if (!*name) {
1008 ref = alloc_ref("(delete)");
1009 hashclr(ref->new_sha1);
1010 return ref;
1012 if (get_sha1(name, sha1))
1013 return NULL;
1014 ref = alloc_ref(name);
1015 hashcpy(ref->new_sha1, sha1);
1016 return ref;
1019 static struct ref *make_linked_ref(const char *name, struct ref ***tail)
1021 struct ref *ret = alloc_ref(name);
1022 tail_link_ref(ret, tail);
1023 return ret;
1026 static char *guess_ref(const char *name, struct ref *peer)
1028 struct strbuf buf = STRBUF_INIT;
1029 unsigned char sha1[20];
1031 const char *r = resolve_ref(peer->name, sha1, 1, NULL);
1032 if (!r)
1033 return NULL;
1035 if (!prefixcmp(r, "refs/heads/"))
1036 strbuf_addstr(&buf, "refs/heads/");
1037 else if (!prefixcmp(r, "refs/tags/"))
1038 strbuf_addstr(&buf, "refs/tags/");
1039 else
1040 return NULL;
1042 strbuf_addstr(&buf, name);
1043 return strbuf_detach(&buf, NULL);
1046 static int match_explicit(struct ref *src, struct ref *dst,
1047 struct ref ***dst_tail,
1048 struct refspec *rs)
1050 struct ref *matched_src, *matched_dst;
1051 int copy_src;
1053 const char *dst_value = rs->dst;
1054 char *dst_guess;
1056 if (rs->pattern || rs->matching)
1057 return 0;
1059 matched_src = matched_dst = NULL;
1060 switch (count_refspec_match(rs->src, src, &matched_src)) {
1061 case 1:
1062 copy_src = 1;
1063 break;
1064 case 0:
1065 /* The source could be in the get_sha1() format
1066 * not a reference name. :refs/other is a
1067 * way to delete 'other' ref at the remote end.
1069 matched_src = try_explicit_object_name(rs->src);
1070 if (!matched_src)
1071 return error("src refspec %s does not match any.", rs->src);
1072 copy_src = 0;
1073 break;
1074 default:
1075 return error("src refspec %s matches more than one.", rs->src);
1078 if (!dst_value) {
1079 unsigned char sha1[20];
1080 int flag;
1082 dst_value = resolve_ref(matched_src->name, sha1, 1, &flag);
1083 if (!dst_value ||
1084 ((flag & REF_ISSYMREF) &&
1085 prefixcmp(dst_value, "refs/heads/")))
1086 die("%s cannot be resolved to branch.",
1087 matched_src->name);
1090 switch (count_refspec_match(dst_value, dst, &matched_dst)) {
1091 case 1:
1092 break;
1093 case 0:
1094 if (!memcmp(dst_value, "refs/", 5))
1095 matched_dst = make_linked_ref(dst_value, dst_tail);
1096 else if ((dst_guess = guess_ref(dst_value, matched_src)))
1097 matched_dst = make_linked_ref(dst_guess, dst_tail);
1098 else
1099 error("unable to push to unqualified destination: %s\n"
1100 "The destination refspec neither matches an "
1101 "existing ref on the remote nor\n"
1102 "begins with refs/, and we are unable to "
1103 "guess a prefix based on the source ref.",
1104 dst_value);
1105 break;
1106 default:
1107 matched_dst = NULL;
1108 error("dst refspec %s matches more than one.",
1109 dst_value);
1110 break;
1112 if (!matched_dst)
1113 return -1;
1114 if (matched_dst->peer_ref)
1115 return error("dst ref %s receives from more than one src.",
1116 matched_dst->name);
1117 else {
1118 matched_dst->peer_ref = copy_src ? copy_ref(matched_src) : matched_src;
1119 matched_dst->force = rs->force;
1121 return 0;
1124 static int match_explicit_refs(struct ref *src, struct ref *dst,
1125 struct ref ***dst_tail, struct refspec *rs,
1126 int rs_nr)
1128 int i, errs;
1129 for (i = errs = 0; i < rs_nr; i++)
1130 errs += match_explicit(src, dst, dst_tail, &rs[i]);
1131 return errs;
1134 static const struct refspec *check_pattern_match(const struct refspec *rs,
1135 int rs_nr,
1136 const struct ref *src)
1138 int i;
1139 int matching_refs = -1;
1140 for (i = 0; i < rs_nr; i++) {
1141 if (rs[i].matching &&
1142 (matching_refs == -1 || rs[i].force)) {
1143 matching_refs = i;
1144 continue;
1147 if (rs[i].pattern && match_name_with_pattern(rs[i].src, src->name,
1148 NULL, NULL))
1149 return rs + i;
1151 if (matching_refs != -1)
1152 return rs + matching_refs;
1153 else
1154 return NULL;
1157 static struct ref **tail_ref(struct ref **head)
1159 struct ref **tail = head;
1160 while (*tail)
1161 tail = &((*tail)->next);
1162 return tail;
1166 * Note. This is used only by "push"; refspec matching rules for
1167 * push and fetch are subtly different, so do not try to reuse it
1168 * without thinking.
1170 int match_refs(struct ref *src, struct ref **dst,
1171 int nr_refspec, const char **refspec, int flags)
1173 struct refspec *rs;
1174 int send_all = flags & MATCH_REFS_ALL;
1175 int send_mirror = flags & MATCH_REFS_MIRROR;
1176 int errs;
1177 static const char *default_refspec[] = { ":", NULL };
1178 struct ref **dst_tail = tail_ref(dst);
1180 if (!nr_refspec) {
1181 nr_refspec = 1;
1182 refspec = default_refspec;
1184 rs = parse_push_refspec(nr_refspec, (const char **) refspec);
1185 errs = match_explicit_refs(src, *dst, &dst_tail, rs, nr_refspec);
1187 /* pick the remainder */
1188 for ( ; src; src = src->next) {
1189 struct ref *dst_peer;
1190 const struct refspec *pat = NULL;
1191 char *dst_name;
1192 if (src->peer_ref)
1193 continue;
1195 pat = check_pattern_match(rs, nr_refspec, src);
1196 if (!pat)
1197 continue;
1199 if (pat->matching) {
1201 * "matching refs"; traditionally we pushed everything
1202 * including refs outside refs/heads/ hierarchy, but
1203 * that does not make much sense these days.
1205 if (!send_mirror && prefixcmp(src->name, "refs/heads/"))
1206 continue;
1207 dst_name = xstrdup(src->name);
1209 } else {
1210 const char *dst_side = pat->dst ? pat->dst : pat->src;
1211 if (!match_name_with_pattern(pat->src, src->name,
1212 dst_side, &dst_name))
1213 die("Didn't think it matches any more");
1215 dst_peer = find_ref_by_name(*dst, dst_name);
1216 if (dst_peer) {
1217 if (dst_peer->peer_ref)
1218 /* We're already sending something to this ref. */
1219 goto free_name;
1221 } else {
1222 if (pat->matching && !(send_all || send_mirror))
1224 * Remote doesn't have it, and we have no
1225 * explicit pattern, and we don't have
1226 * --all nor --mirror.
1228 goto free_name;
1230 /* Create a new one and link it */
1231 dst_peer = make_linked_ref(dst_name, &dst_tail);
1232 hashcpy(dst_peer->new_sha1, src->new_sha1);
1234 dst_peer->peer_ref = copy_ref(src);
1235 dst_peer->force = pat->force;
1236 free_name:
1237 free(dst_name);
1239 if (errs)
1240 return -1;
1241 return 0;
1244 struct branch *branch_get(const char *name)
1246 struct branch *ret;
1248 read_config();
1249 if (!name || !*name || !strcmp(name, "HEAD"))
1250 ret = current_branch;
1251 else
1252 ret = make_branch(name, 0);
1253 if (ret && ret->remote_name) {
1254 ret->remote = remote_get(ret->remote_name);
1255 if (ret->merge_nr) {
1256 int i;
1257 ret->merge = xcalloc(sizeof(*ret->merge),
1258 ret->merge_nr);
1259 for (i = 0; i < ret->merge_nr; i++) {
1260 ret->merge[i] = xcalloc(1, sizeof(**ret->merge));
1261 ret->merge[i]->src = xstrdup(ret->merge_name[i]);
1262 if (remote_find_tracking(ret->remote, ret->merge[i])
1263 && !strcmp(ret->remote_name, "."))
1264 ret->merge[i]->dst = xstrdup(ret->merge_name[i]);
1268 return ret;
1271 int branch_has_merge_config(struct branch *branch)
1273 return branch && !!branch->merge;
1276 int branch_merge_matches(struct branch *branch,
1277 int i,
1278 const char *refname)
1280 if (!branch || i < 0 || i >= branch->merge_nr)
1281 return 0;
1282 return refname_match(branch->merge[i]->src, refname, ref_fetch_rules);
1285 static struct ref *get_expanded_map(const struct ref *remote_refs,
1286 const struct refspec *refspec)
1288 const struct ref *ref;
1289 struct ref *ret = NULL;
1290 struct ref **tail = &ret;
1292 char *expn_name;
1294 for (ref = remote_refs; ref; ref = ref->next) {
1295 if (strchr(ref->name, '^'))
1296 continue; /* a dereference item */
1297 if (match_name_with_pattern(refspec->src, ref->name,
1298 refspec->dst, &expn_name)) {
1299 struct ref *cpy = copy_ref(ref);
1301 cpy->peer_ref = alloc_ref(expn_name);
1302 free(expn_name);
1303 if (refspec->force)
1304 cpy->peer_ref->force = 1;
1305 *tail = cpy;
1306 tail = &cpy->next;
1310 return ret;
1313 static const struct ref *find_ref_by_name_abbrev(const struct ref *refs, const char *name)
1315 const struct ref *ref;
1316 for (ref = refs; ref; ref = ref->next) {
1317 if (refname_match(name, ref->name, ref_fetch_rules))
1318 return ref;
1320 return NULL;
1323 struct ref *get_remote_ref(const struct ref *remote_refs, const char *name)
1325 const struct ref *ref = find_ref_by_name_abbrev(remote_refs, name);
1327 if (!ref)
1328 return NULL;
1330 return copy_ref(ref);
1333 static struct ref *get_local_ref(const char *name)
1335 if (!name || name[0] == '\0')
1336 return NULL;
1338 if (!prefixcmp(name, "refs/"))
1339 return alloc_ref(name);
1341 if (!prefixcmp(name, "heads/") ||
1342 !prefixcmp(name, "tags/") ||
1343 !prefixcmp(name, "remotes/"))
1344 return alloc_ref_with_prefix("refs/", 5, name);
1346 return alloc_ref_with_prefix("refs/heads/", 11, name);
1349 int get_fetch_map(const struct ref *remote_refs,
1350 const struct refspec *refspec,
1351 struct ref ***tail,
1352 int missing_ok)
1354 struct ref *ref_map, **rmp;
1356 if (refspec->pattern) {
1357 ref_map = get_expanded_map(remote_refs, refspec);
1358 } else {
1359 const char *name = refspec->src[0] ? refspec->src : "HEAD";
1361 ref_map = get_remote_ref(remote_refs, name);
1362 if (!missing_ok && !ref_map)
1363 die("Couldn't find remote ref %s", name);
1364 if (ref_map) {
1365 ref_map->peer_ref = get_local_ref(refspec->dst);
1366 if (ref_map->peer_ref && refspec->force)
1367 ref_map->peer_ref->force = 1;
1371 for (rmp = &ref_map; *rmp; ) {
1372 if ((*rmp)->peer_ref) {
1373 int st = check_ref_format((*rmp)->peer_ref->name + 5);
1374 if (st && st != CHECK_REF_FORMAT_ONELEVEL) {
1375 struct ref *ignore = *rmp;
1376 error("* Ignoring funny ref '%s' locally",
1377 (*rmp)->peer_ref->name);
1378 *rmp = (*rmp)->next;
1379 free(ignore->peer_ref);
1380 free(ignore);
1381 continue;
1384 rmp = &((*rmp)->next);
1387 if (ref_map)
1388 tail_link_ref(ref_map, tail);
1390 return 0;
1393 int resolve_remote_symref(struct ref *ref, struct ref *list)
1395 if (!ref->symref)
1396 return 0;
1397 for (; list; list = list->next)
1398 if (!strcmp(ref->symref, list->name)) {
1399 hashcpy(ref->old_sha1, list->old_sha1);
1400 return 0;
1402 return 1;
1405 static void unmark_and_free(struct commit_list *list, unsigned int mark)
1407 while (list) {
1408 struct commit_list *temp = list;
1409 temp->item->object.flags &= ~mark;
1410 list = temp->next;
1411 free(temp);
1415 int ref_newer(const unsigned char *new_sha1, const unsigned char *old_sha1)
1417 struct object *o;
1418 struct commit *old, *new;
1419 struct commit_list *list, *used;
1420 int found = 0;
1422 /* Both new and old must be commit-ish and new is descendant of
1423 * old. Otherwise we require --force.
1425 o = deref_tag(parse_object(old_sha1), NULL, 0);
1426 if (!o || o->type != OBJ_COMMIT)
1427 return 0;
1428 old = (struct commit *) o;
1430 o = deref_tag(parse_object(new_sha1), NULL, 0);
1431 if (!o || o->type != OBJ_COMMIT)
1432 return 0;
1433 new = (struct commit *) o;
1435 if (parse_commit(new) < 0)
1436 return 0;
1438 used = list = NULL;
1439 commit_list_insert(new, &list);
1440 while (list) {
1441 new = pop_most_recent_commit(&list, TMP_MARK);
1442 commit_list_insert(new, &used);
1443 if (new == old) {
1444 found = 1;
1445 break;
1448 unmark_and_free(list, TMP_MARK);
1449 unmark_and_free(used, TMP_MARK);
1450 return found;
1454 * Return true if there is anything to report, otherwise false.
1456 int stat_tracking_info(struct branch *branch, int *num_ours, int *num_theirs)
1458 unsigned char sha1[20];
1459 struct commit *ours, *theirs;
1460 char symmetric[84];
1461 struct rev_info revs;
1462 const char *rev_argv[10], *base;
1463 int rev_argc;
1466 * Nothing to report unless we are marked to build on top of
1467 * somebody else.
1469 if (!branch ||
1470 !branch->merge || !branch->merge[0] || !branch->merge[0]->dst)
1471 return 0;
1474 * If what we used to build on no longer exists, there is
1475 * nothing to report.
1477 base = branch->merge[0]->dst;
1478 if (!resolve_ref(base, sha1, 1, NULL))
1479 return 0;
1480 theirs = lookup_commit_reference(sha1);
1481 if (!theirs)
1482 return 0;
1484 if (!resolve_ref(branch->refname, sha1, 1, NULL))
1485 return 0;
1486 ours = lookup_commit_reference(sha1);
1487 if (!ours)
1488 return 0;
1490 /* are we the same? */
1491 if (theirs == ours)
1492 return 0;
1494 /* Run "rev-list --left-right ours...theirs" internally... */
1495 rev_argc = 0;
1496 rev_argv[rev_argc++] = NULL;
1497 rev_argv[rev_argc++] = "--left-right";
1498 rev_argv[rev_argc++] = symmetric;
1499 rev_argv[rev_argc++] = "--";
1500 rev_argv[rev_argc] = NULL;
1502 strcpy(symmetric, sha1_to_hex(ours->object.sha1));
1503 strcpy(symmetric + 40, "...");
1504 strcpy(symmetric + 43, sha1_to_hex(theirs->object.sha1));
1506 init_revisions(&revs, NULL);
1507 setup_revisions(rev_argc, rev_argv, &revs, NULL);
1508 prepare_revision_walk(&revs);
1510 /* ... and count the commits on each side. */
1511 *num_ours = 0;
1512 *num_theirs = 0;
1513 while (1) {
1514 struct commit *c = get_revision(&revs);
1515 if (!c)
1516 break;
1517 if (c->object.flags & SYMMETRIC_LEFT)
1518 (*num_ours)++;
1519 else
1520 (*num_theirs)++;
1523 /* clear object flags smudged by the above traversal */
1524 clear_commit_marks(ours, ALL_REV_FLAGS);
1525 clear_commit_marks(theirs, ALL_REV_FLAGS);
1526 return 1;
1530 * Return true when there is anything to report, otherwise false.
1532 int format_tracking_info(struct branch *branch, struct strbuf *sb)
1534 int num_ours, num_theirs;
1535 const char *base;
1537 if (!stat_tracking_info(branch, &num_ours, &num_theirs))
1538 return 0;
1540 base = branch->merge[0]->dst;
1541 base = shorten_unambiguous_ref(base, 0);
1542 if (!num_theirs)
1543 strbuf_addf(sb, "Your branch is ahead of '%s' "
1544 "by %d commit%s.\n",
1545 base, num_ours, (num_ours == 1) ? "" : "s");
1546 else if (!num_ours)
1547 strbuf_addf(sb, "Your branch is behind '%s' "
1548 "by %d commit%s, "
1549 "and can be fast-forwarded.\n",
1550 base, num_theirs, (num_theirs == 1) ? "" : "s");
1551 else
1552 strbuf_addf(sb, "Your branch and '%s' have diverged,\n"
1553 "and have %d and %d different commit(s) each, "
1554 "respectively.\n",
1555 base, num_ours, num_theirs);
1556 return 1;
1559 static int one_local_ref(const char *refname, const unsigned char *sha1, int flag, void *cb_data)
1561 struct ref ***local_tail = cb_data;
1562 struct ref *ref;
1563 int len;
1565 /* we already know it starts with refs/ to get here */
1566 if (check_ref_format(refname + 5))
1567 return 0;
1569 len = strlen(refname) + 1;
1570 ref = xcalloc(1, sizeof(*ref) + len);
1571 hashcpy(ref->new_sha1, sha1);
1572 memcpy(ref->name, refname, len);
1573 **local_tail = ref;
1574 *local_tail = &ref->next;
1575 return 0;
1578 struct ref *get_local_heads(void)
1580 struct ref *local_refs = NULL, **local_tail = &local_refs;
1581 for_each_ref(one_local_ref, &local_tail);
1582 return local_refs;
1585 struct ref *guess_remote_head(const struct ref *head,
1586 const struct ref *refs,
1587 int all)
1589 const struct ref *r;
1590 struct ref *list = NULL;
1591 struct ref **tail = &list;
1593 if (!head)
1594 return NULL;
1597 * Some transports support directly peeking at
1598 * where HEAD points; if that is the case, then
1599 * we don't have to guess.
1601 if (head->symref)
1602 return copy_ref(find_ref_by_name(refs, head->symref));
1604 /* If refs/heads/master could be right, it is. */
1605 if (!all) {
1606 r = find_ref_by_name(refs, "refs/heads/master");
1607 if (r && !hashcmp(r->old_sha1, head->old_sha1))
1608 return copy_ref(r);
1611 /* Look for another ref that points there */
1612 for (r = refs; r; r = r->next) {
1613 if (r != head && !hashcmp(r->old_sha1, head->old_sha1)) {
1614 *tail = copy_ref(r);
1615 tail = &((*tail)->next);
1616 if (!all)
1617 break;
1621 return list;