Documentation: clarify branch creation
[alt-git.git] / remote.c
blob73d33f2584b061085fcaa0958c26b1c3d4665904
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 const char *alias_url(const char *url, struct rewrites *r)
57 int i, j;
58 char *ret;
59 struct counted_string *longest;
60 int longest_i;
62 longest = NULL;
63 longest_i = -1;
64 for (i = 0; i < r->rewrite_nr; i++) {
65 if (!r->rewrite[i])
66 continue;
67 for (j = 0; j < r->rewrite[i]->instead_of_nr; j++) {
68 if (!prefixcmp(url, r->rewrite[i]->instead_of[j].s) &&
69 (!longest ||
70 longest->len < r->rewrite[i]->instead_of[j].len)) {
71 longest = &(r->rewrite[i]->instead_of[j]);
72 longest_i = i;
76 if (!longest)
77 return url;
79 ret = xmalloc(r->rewrite[longest_i]->baselen +
80 (strlen(url) - longest->len) + 1);
81 strcpy(ret, r->rewrite[longest_i]->base);
82 strcpy(ret + r->rewrite[longest_i]->baselen, url + longest->len);
83 return ret;
86 static void add_push_refspec(struct remote *remote, const char *ref)
88 ALLOC_GROW(remote->push_refspec,
89 remote->push_refspec_nr + 1,
90 remote->push_refspec_alloc);
91 remote->push_refspec[remote->push_refspec_nr++] = ref;
94 static void add_fetch_refspec(struct remote *remote, const char *ref)
96 ALLOC_GROW(remote->fetch_refspec,
97 remote->fetch_refspec_nr + 1,
98 remote->fetch_refspec_alloc);
99 remote->fetch_refspec[remote->fetch_refspec_nr++] = ref;
102 static void add_url(struct remote *remote, const char *url)
104 ALLOC_GROW(remote->url, remote->url_nr + 1, remote->url_alloc);
105 remote->url[remote->url_nr++] = url;
108 static void add_pushurl(struct remote *remote, const char *pushurl)
110 ALLOC_GROW(remote->pushurl, remote->pushurl_nr + 1, remote->pushurl_alloc);
111 remote->pushurl[remote->pushurl_nr++] = pushurl;
114 static void add_pushurl_alias(struct remote *remote, const char *url)
116 const char *pushurl = alias_url(url, &rewrites_push);
117 if (pushurl != url)
118 add_pushurl(remote, pushurl);
121 static void add_url_alias(struct remote *remote, const char *url)
123 add_url(remote, alias_url(url, &rewrites));
124 add_pushurl_alias(remote, url);
127 static struct remote *make_remote(const char *name, int len)
129 struct remote *ret;
130 int i;
132 for (i = 0; i < remotes_nr; i++) {
133 if (len ? (!strncmp(name, remotes[i]->name, len) &&
134 !remotes[i]->name[len]) :
135 !strcmp(name, remotes[i]->name))
136 return remotes[i];
139 ret = xcalloc(1, sizeof(struct remote));
140 ALLOC_GROW(remotes, remotes_nr + 1, remotes_alloc);
141 remotes[remotes_nr++] = ret;
142 if (len)
143 ret->name = xstrndup(name, len);
144 else
145 ret->name = xstrdup(name);
146 return ret;
149 static void add_merge(struct branch *branch, const char *name)
151 ALLOC_GROW(branch->merge_name, branch->merge_nr + 1,
152 branch->merge_alloc);
153 branch->merge_name[branch->merge_nr++] = name;
156 static struct branch *make_branch(const char *name, int len)
158 struct branch *ret;
159 int i;
160 char *refname;
162 for (i = 0; i < branches_nr; i++) {
163 if (len ? (!strncmp(name, branches[i]->name, len) &&
164 !branches[i]->name[len]) :
165 !strcmp(name, branches[i]->name))
166 return branches[i];
169 ALLOC_GROW(branches, branches_nr + 1, branches_alloc);
170 ret = xcalloc(1, sizeof(struct branch));
171 branches[branches_nr++] = ret;
172 if (len)
173 ret->name = xstrndup(name, len);
174 else
175 ret->name = xstrdup(name);
176 refname = xmalloc(strlen(name) + strlen("refs/heads/") + 1);
177 strcpy(refname, "refs/heads/");
178 strcpy(refname + strlen("refs/heads/"), ret->name);
179 ret->refname = refname;
181 return ret;
184 static struct rewrite *make_rewrite(struct rewrites *r, const char *base, int len)
186 struct rewrite *ret;
187 int i;
189 for (i = 0; i < r->rewrite_nr; i++) {
190 if (len
191 ? (len == r->rewrite[i]->baselen &&
192 !strncmp(base, r->rewrite[i]->base, len))
193 : !strcmp(base, r->rewrite[i]->base))
194 return r->rewrite[i];
197 ALLOC_GROW(r->rewrite, r->rewrite_nr + 1, r->rewrite_alloc);
198 ret = xcalloc(1, sizeof(struct rewrite));
199 r->rewrite[r->rewrite_nr++] = ret;
200 if (len) {
201 ret->base = xstrndup(base, len);
202 ret->baselen = len;
204 else {
205 ret->base = xstrdup(base);
206 ret->baselen = strlen(base);
208 return ret;
211 static void add_instead_of(struct rewrite *rewrite, const char *instead_of)
213 ALLOC_GROW(rewrite->instead_of, rewrite->instead_of_nr + 1, rewrite->instead_of_alloc);
214 rewrite->instead_of[rewrite->instead_of_nr].s = instead_of;
215 rewrite->instead_of[rewrite->instead_of_nr].len = strlen(instead_of);
216 rewrite->instead_of_nr++;
219 static void read_remotes_file(struct remote *remote)
221 FILE *f = fopen(git_path("remotes/%s", remote->name), "r");
223 if (!f)
224 return;
225 remote->origin = REMOTE_REMOTES;
226 while (fgets(buffer, BUF_SIZE, f)) {
227 int value_list;
228 char *s, *p;
230 if (!prefixcmp(buffer, "URL:")) {
231 value_list = 0;
232 s = buffer + 4;
233 } else if (!prefixcmp(buffer, "Push:")) {
234 value_list = 1;
235 s = buffer + 5;
236 } else if (!prefixcmp(buffer, "Pull:")) {
237 value_list = 2;
238 s = buffer + 5;
239 } else
240 continue;
242 while (isspace(*s))
243 s++;
244 if (!*s)
245 continue;
247 p = s + strlen(s);
248 while (isspace(p[-1]))
249 *--p = 0;
251 switch (value_list) {
252 case 0:
253 add_url_alias(remote, xstrdup(s));
254 break;
255 case 1:
256 add_push_refspec(remote, xstrdup(s));
257 break;
258 case 2:
259 add_fetch_refspec(remote, xstrdup(s));
260 break;
263 fclose(f);
266 static void read_branches_file(struct remote *remote)
268 const char *slash = strchr(remote->name, '/');
269 char *frag;
270 struct strbuf branch = STRBUF_INIT;
271 int n = slash ? slash - remote->name : 1000;
272 FILE *f = fopen(git_path("branches/%.*s", n, remote->name), "r");
273 char *s, *p;
274 int len;
276 if (!f)
277 return;
278 s = fgets(buffer, BUF_SIZE, f);
279 fclose(f);
280 if (!s)
281 return;
282 while (isspace(*s))
283 s++;
284 if (!*s)
285 return;
286 remote->origin = REMOTE_BRANCHES;
287 p = s + strlen(s);
288 while (isspace(p[-1]))
289 *--p = 0;
290 len = p - s;
291 if (slash)
292 len += strlen(slash);
293 p = xmalloc(len + 1);
294 strcpy(p, s);
295 if (slash)
296 strcat(p, slash);
299 * With "slash", e.g. "git fetch jgarzik/netdev-2.6" when
300 * reading from $GIT_DIR/branches/jgarzik fetches "HEAD" from
301 * the partial URL obtained from the branches file plus
302 * "/netdev-2.6" and does not store it in any tracking ref.
303 * #branch specifier in the file is ignored.
305 * Otherwise, the branches file would have URL and optionally
306 * #branch specified. The "master" (or specified) branch is
307 * fetched and stored in the local branch of the same name.
309 frag = strchr(p, '#');
310 if (frag) {
311 *(frag++) = '\0';
312 strbuf_addf(&branch, "refs/heads/%s", frag);
313 } else
314 strbuf_addstr(&branch, "refs/heads/master");
315 if (!slash) {
316 strbuf_addf(&branch, ":refs/heads/%s", remote->name);
317 } else {
318 strbuf_reset(&branch);
319 strbuf_addstr(&branch, "HEAD:");
321 add_url_alias(remote, p);
322 add_fetch_refspec(remote, strbuf_detach(&branch, NULL));
324 * Cogito compatible push: push current HEAD to remote #branch
325 * (master if missing)
327 strbuf_init(&branch, 0);
328 strbuf_addstr(&branch, "HEAD");
329 if (frag)
330 strbuf_addf(&branch, ":refs/heads/%s", frag);
331 else
332 strbuf_addstr(&branch, ":refs/heads/master");
333 add_push_refspec(remote, strbuf_detach(&branch, NULL));
334 remote->fetch_tags = 1; /* always auto-follow */
337 static int handle_config(const char *key, const char *value, void *cb)
339 const char *name;
340 const char *subkey;
341 struct remote *remote;
342 struct branch *branch;
343 if (!prefixcmp(key, "branch.")) {
344 name = key + 7;
345 subkey = strrchr(name, '.');
346 if (!subkey)
347 return 0;
348 branch = make_branch(name, subkey - name);
349 if (!strcmp(subkey, ".remote")) {
350 if (!value)
351 return config_error_nonbool(key);
352 branch->remote_name = xstrdup(value);
353 if (branch == current_branch) {
354 default_remote_name = branch->remote_name;
355 explicit_default_remote_name = 1;
357 } else if (!strcmp(subkey, ".merge")) {
358 if (!value)
359 return config_error_nonbool(key);
360 add_merge(branch, xstrdup(value));
362 return 0;
364 if (!prefixcmp(key, "url.")) {
365 struct rewrite *rewrite;
366 name = key + 4;
367 subkey = strrchr(name, '.');
368 if (!subkey)
369 return 0;
370 if (!strcmp(subkey, ".insteadof")) {
371 rewrite = make_rewrite(&rewrites, name, subkey - name);
372 if (!value)
373 return config_error_nonbool(key);
374 add_instead_of(rewrite, xstrdup(value));
375 } else if (!strcmp(subkey, ".pushinsteadof")) {
376 rewrite = make_rewrite(&rewrites_push, name, subkey - name);
377 if (!value)
378 return config_error_nonbool(key);
379 add_instead_of(rewrite, xstrdup(value));
382 if (prefixcmp(key, "remote."))
383 return 0;
384 name = key + 7;
385 if (*name == '/') {
386 warning("Config remote shorthand cannot begin with '/': %s",
387 name);
388 return 0;
390 subkey = strrchr(name, '.');
391 if (!subkey)
392 return 0;
393 remote = make_remote(name, subkey - name);
394 remote->origin = REMOTE_CONFIG;
395 if (!strcmp(subkey, ".mirror"))
396 remote->mirror = git_config_bool(key, value);
397 else if (!strcmp(subkey, ".skipdefaultupdate"))
398 remote->skip_default_update = git_config_bool(key, value);
400 else if (!strcmp(subkey, ".url")) {
401 const char *v;
402 if (git_config_string(&v, key, value))
403 return -1;
404 add_url(remote, v);
405 } else if (!strcmp(subkey, ".pushurl")) {
406 const char *v;
407 if (git_config_string(&v, key, value))
408 return -1;
409 add_pushurl(remote, v);
410 } else if (!strcmp(subkey, ".push")) {
411 const char *v;
412 if (git_config_string(&v, key, value))
413 return -1;
414 add_push_refspec(remote, v);
415 } else if (!strcmp(subkey, ".fetch")) {
416 const char *v;
417 if (git_config_string(&v, key, value))
418 return -1;
419 add_fetch_refspec(remote, v);
420 } else if (!strcmp(subkey, ".receivepack")) {
421 const char *v;
422 if (git_config_string(&v, key, value))
423 return -1;
424 if (!remote->receivepack)
425 remote->receivepack = v;
426 else
427 error("more than one receivepack given, using the first");
428 } else if (!strcmp(subkey, ".uploadpack")) {
429 const char *v;
430 if (git_config_string(&v, key, value))
431 return -1;
432 if (!remote->uploadpack)
433 remote->uploadpack = v;
434 else
435 error("more than one uploadpack given, using the first");
436 } else if (!strcmp(subkey, ".tagopt")) {
437 if (!strcmp(value, "--no-tags"))
438 remote->fetch_tags = -1;
439 } else if (!strcmp(subkey, ".proxy")) {
440 return git_config_string((const char **)&remote->http_proxy,
441 key, value);
443 return 0;
446 static void alias_all_urls(void)
448 int i, j;
449 for (i = 0; i < remotes_nr; i++) {
450 int add_pushurl_aliases;
451 if (!remotes[i])
452 continue;
453 for (j = 0; j < remotes[i]->pushurl_nr; j++) {
454 remotes[i]->pushurl[j] = alias_url(remotes[i]->pushurl[j], &rewrites);
456 add_pushurl_aliases = remotes[i]->pushurl_nr == 0;
457 for (j = 0; j < remotes[i]->url_nr; j++) {
458 if (add_pushurl_aliases)
459 add_pushurl_alias(remotes[i], remotes[i]->url[j]);
460 remotes[i]->url[j] = alias_url(remotes[i]->url[j], &rewrites);
465 static void read_config(void)
467 unsigned char sha1[20];
468 const char *head_ref;
469 int flag;
470 if (default_remote_name) // did this already
471 return;
472 default_remote_name = xstrdup("origin");
473 current_branch = NULL;
474 head_ref = resolve_ref("HEAD", sha1, 0, &flag);
475 if (head_ref && (flag & REF_ISSYMREF) &&
476 !prefixcmp(head_ref, "refs/heads/")) {
477 current_branch =
478 make_branch(head_ref + strlen("refs/heads/"), 0);
480 git_config(handle_config, NULL);
481 alias_all_urls();
485 * We need to make sure the tracking branches are well formed, but a
486 * wildcard refspec in "struct refspec" must have a trailing slash. We
487 * temporarily drop the trailing '/' while calling check_ref_format(),
488 * and put it back. The caller knows that a CHECK_REF_FORMAT_ONELEVEL
489 * error return is Ok for a wildcard refspec.
491 static int verify_refname(char *name, int is_glob)
493 int result;
495 result = check_ref_format(name);
496 if (is_glob && result == CHECK_REF_FORMAT_WILDCARD)
497 result = CHECK_REF_FORMAT_OK;
498 return result;
502 * This function frees a refspec array.
503 * Warning: code paths should be checked to ensure that the src
504 * and dst pointers are always freeable pointers as well
505 * as the refspec pointer itself.
507 static void free_refspecs(struct refspec *refspec, int nr_refspec)
509 int i;
511 if (!refspec)
512 return;
514 for (i = 0; i < nr_refspec; i++) {
515 free(refspec[i].src);
516 free(refspec[i].dst);
518 free(refspec);
521 static struct refspec *parse_refspec_internal(int nr_refspec, const char **refspec, int fetch, int verify)
523 int i;
524 int st;
525 struct refspec *rs = xcalloc(sizeof(*rs), nr_refspec);
527 for (i = 0; i < nr_refspec; i++) {
528 size_t llen;
529 int is_glob;
530 const char *lhs, *rhs;
532 is_glob = 0;
534 lhs = refspec[i];
535 if (*lhs == '+') {
536 rs[i].force = 1;
537 lhs++;
540 rhs = strrchr(lhs, ':');
543 * Before going on, special case ":" (or "+:") as a refspec
544 * for matching refs.
546 if (!fetch && rhs == lhs && rhs[1] == '\0') {
547 rs[i].matching = 1;
548 continue;
551 if (rhs) {
552 size_t rlen = strlen(++rhs);
553 is_glob = (1 <= rlen && strchr(rhs, '*'));
554 rs[i].dst = xstrndup(rhs, rlen);
557 llen = (rhs ? (rhs - lhs - 1) : strlen(lhs));
558 if (1 <= llen && memchr(lhs, '*', llen)) {
559 if ((rhs && !is_glob) || (!rhs && fetch))
560 goto invalid;
561 is_glob = 1;
562 } else if (rhs && is_glob) {
563 goto invalid;
566 rs[i].pattern = is_glob;
567 rs[i].src = xstrndup(lhs, llen);
569 if (fetch) {
571 * LHS
572 * - empty is allowed; it means HEAD.
573 * - otherwise it must be a valid looking ref.
575 if (!*rs[i].src)
576 ; /* empty is ok */
577 else {
578 st = verify_refname(rs[i].src, is_glob);
579 if (st && st != CHECK_REF_FORMAT_ONELEVEL)
580 goto invalid;
583 * RHS
584 * - missing is ok, and is same as empty.
585 * - empty is ok; it means not to store.
586 * - otherwise it must be a valid looking ref.
588 if (!rs[i].dst) {
589 ; /* ok */
590 } else if (!*rs[i].dst) {
591 ; /* ok */
592 } else {
593 st = verify_refname(rs[i].dst, is_glob);
594 if (st && st != CHECK_REF_FORMAT_ONELEVEL)
595 goto invalid;
597 } else {
599 * LHS
600 * - empty is allowed; it means delete.
601 * - when wildcarded, it must be a valid looking ref.
602 * - otherwise, it must be an extended SHA-1, but
603 * there is no existing way to validate this.
605 if (!*rs[i].src)
606 ; /* empty is ok */
607 else if (is_glob) {
608 st = verify_refname(rs[i].src, is_glob);
609 if (st && st != CHECK_REF_FORMAT_ONELEVEL)
610 goto invalid;
612 else
613 ; /* anything goes, for now */
615 * RHS
616 * - missing is allowed, but LHS then must be a
617 * valid looking ref.
618 * - empty is not allowed.
619 * - otherwise it must be a valid looking ref.
621 if (!rs[i].dst) {
622 st = verify_refname(rs[i].src, is_glob);
623 if (st && st != CHECK_REF_FORMAT_ONELEVEL)
624 goto invalid;
625 } else if (!*rs[i].dst) {
626 goto invalid;
627 } else {
628 st = verify_refname(rs[i].dst, is_glob);
629 if (st && st != CHECK_REF_FORMAT_ONELEVEL)
630 goto invalid;
634 return rs;
636 invalid:
637 if (verify) {
639 * nr_refspec must be greater than zero and i must be valid
640 * since it is only possible to reach this point from within
641 * the for loop above.
643 free_refspecs(rs, i+1);
644 return NULL;
646 die("Invalid refspec '%s'", refspec[i]);
649 int valid_fetch_refspec(const char *fetch_refspec_str)
651 const char *fetch_refspec[] = { fetch_refspec_str };
652 struct refspec *refspec;
654 refspec = parse_refspec_internal(1, fetch_refspec, 1, 1);
655 free_refspecs(refspec, 1);
656 return !!refspec;
659 struct refspec *parse_fetch_refspec(int nr_refspec, const char **refspec)
661 return parse_refspec_internal(nr_refspec, refspec, 1, 0);
664 static struct refspec *parse_push_refspec(int nr_refspec, const char **refspec)
666 return parse_refspec_internal(nr_refspec, refspec, 0, 0);
669 static int valid_remote_nick(const char *name)
671 if (!name[0] || is_dot_or_dotdot(name))
672 return 0;
673 return !strchr(name, '/'); /* no slash */
676 struct remote *remote_get(const char *name)
678 struct remote *ret;
679 int name_given = 0;
681 read_config();
682 if (name)
683 name_given = 1;
684 else {
685 name = default_remote_name;
686 name_given = explicit_default_remote_name;
689 ret = make_remote(name, 0);
690 if (valid_remote_nick(name)) {
691 if (!ret->url)
692 read_remotes_file(ret);
693 if (!ret->url)
694 read_branches_file(ret);
696 if (name_given && !ret->url)
697 add_url_alias(ret, name);
698 if (!ret->url)
699 return NULL;
700 ret->fetch = parse_fetch_refspec(ret->fetch_refspec_nr, ret->fetch_refspec);
701 ret->push = parse_push_refspec(ret->push_refspec_nr, ret->push_refspec);
702 return ret;
705 int remote_is_configured(const char *name)
707 int i;
708 read_config();
710 for (i = 0; i < remotes_nr; i++)
711 if (!strcmp(name, remotes[i]->name))
712 return 1;
713 return 0;
716 int for_each_remote(each_remote_fn fn, void *priv)
718 int i, result = 0;
719 read_config();
720 for (i = 0; i < remotes_nr && !result; i++) {
721 struct remote *r = remotes[i];
722 if (!r)
723 continue;
724 if (!r->fetch)
725 r->fetch = parse_fetch_refspec(r->fetch_refspec_nr,
726 r->fetch_refspec);
727 if (!r->push)
728 r->push = parse_push_refspec(r->push_refspec_nr,
729 r->push_refspec);
730 result = fn(r, priv);
732 return result;
735 void ref_remove_duplicates(struct ref *ref_map)
737 struct ref **posn;
738 struct ref *next;
739 for (; ref_map; ref_map = ref_map->next) {
740 if (!ref_map->peer_ref)
741 continue;
742 posn = &ref_map->next;
743 while (*posn) {
744 if ((*posn)->peer_ref &&
745 !strcmp((*posn)->peer_ref->name,
746 ref_map->peer_ref->name)) {
747 if (strcmp((*posn)->name, ref_map->name))
748 die("%s tracks both %s and %s",
749 ref_map->peer_ref->name,
750 (*posn)->name, ref_map->name);
751 next = (*posn)->next;
752 free((*posn)->peer_ref);
753 free(*posn);
754 *posn = next;
755 } else {
756 posn = &(*posn)->next;
762 int remote_has_url(struct remote *remote, const char *url)
764 int i;
765 for (i = 0; i < remote->url_nr; i++) {
766 if (!strcmp(remote->url[i], url))
767 return 1;
769 return 0;
772 static int match_name_with_pattern(const char *key, const char *name,
773 const char *value, char **result)
775 const char *kstar = strchr(key, '*');
776 size_t klen;
777 size_t ksuffixlen;
778 size_t namelen;
779 int ret;
780 if (!kstar)
781 die("Key '%s' of pattern had no '*'", key);
782 klen = kstar - key;
783 ksuffixlen = strlen(kstar + 1);
784 namelen = strlen(name);
785 ret = !strncmp(name, key, klen) && namelen >= klen + ksuffixlen &&
786 !memcmp(name + namelen - ksuffixlen, kstar + 1, ksuffixlen);
787 if (ret && value) {
788 const char *vstar = strchr(value, '*');
789 size_t vlen;
790 size_t vsuffixlen;
791 if (!vstar)
792 die("Value '%s' of pattern has no '*'", value);
793 vlen = vstar - value;
794 vsuffixlen = strlen(vstar + 1);
795 *result = xmalloc(vlen + vsuffixlen +
796 strlen(name) -
797 klen - ksuffixlen + 1);
798 strncpy(*result, value, vlen);
799 strncpy(*result + vlen,
800 name + klen, namelen - klen - ksuffixlen);
801 strcpy(*result + vlen + namelen - klen - ksuffixlen,
802 vstar + 1);
804 return ret;
807 int remote_find_tracking(struct remote *remote, struct refspec *refspec)
809 int find_src = refspec->src == NULL;
810 char *needle, **result;
811 int i;
813 if (find_src) {
814 if (!refspec->dst)
815 return error("find_tracking: need either src or dst");
816 needle = refspec->dst;
817 result = &refspec->src;
818 } else {
819 needle = refspec->src;
820 result = &refspec->dst;
823 for (i = 0; i < remote->fetch_refspec_nr; i++) {
824 struct refspec *fetch = &remote->fetch[i];
825 const char *key = find_src ? fetch->dst : fetch->src;
826 const char *value = find_src ? fetch->src : fetch->dst;
827 if (!fetch->dst)
828 continue;
829 if (fetch->pattern) {
830 if (match_name_with_pattern(key, needle, value, result)) {
831 refspec->force = fetch->force;
832 return 0;
834 } else if (!strcmp(needle, key)) {
835 *result = xstrdup(value);
836 refspec->force = fetch->force;
837 return 0;
840 return -1;
843 static struct ref *alloc_ref_with_prefix(const char *prefix, size_t prefixlen,
844 const char *name)
846 size_t len = strlen(name);
847 struct ref *ref = xcalloc(1, sizeof(struct ref) + prefixlen + len + 1);
848 memcpy(ref->name, prefix, prefixlen);
849 memcpy(ref->name + prefixlen, name, len);
850 return ref;
853 struct ref *alloc_ref(const char *name)
855 return alloc_ref_with_prefix("", 0, name);
858 static struct ref *copy_ref(const struct ref *ref)
860 struct ref *cpy;
861 size_t len;
862 if (!ref)
863 return NULL;
864 len = strlen(ref->name);
865 cpy = xmalloc(sizeof(struct ref) + len + 1);
866 memcpy(cpy, ref, sizeof(struct ref) + len + 1);
867 cpy->next = NULL;
868 cpy->symref = ref->symref ? xstrdup(ref->symref) : NULL;
869 cpy->remote_status = ref->remote_status ? xstrdup(ref->remote_status) : NULL;
870 cpy->peer_ref = copy_ref(ref->peer_ref);
871 return cpy;
874 struct ref *copy_ref_list(const struct ref *ref)
876 struct ref *ret = NULL;
877 struct ref **tail = &ret;
878 while (ref) {
879 *tail = copy_ref(ref);
880 ref = ref->next;
881 tail = &((*tail)->next);
883 return ret;
886 static void free_ref(struct ref *ref)
888 if (!ref)
889 return;
890 free_ref(ref->peer_ref);
891 free(ref->remote_status);
892 free(ref->symref);
893 free(ref);
896 void free_refs(struct ref *ref)
898 struct ref *next;
899 while (ref) {
900 next = ref->next;
901 free_ref(ref);
902 ref = next;
906 static int count_refspec_match(const char *pattern,
907 struct ref *refs,
908 struct ref **matched_ref)
910 int patlen = strlen(pattern);
911 struct ref *matched_weak = NULL;
912 struct ref *matched = NULL;
913 int weak_match = 0;
914 int match = 0;
916 for (weak_match = match = 0; refs; refs = refs->next) {
917 char *name = refs->name;
918 int namelen = strlen(name);
920 if (!refname_match(pattern, name, ref_rev_parse_rules))
921 continue;
923 /* A match is "weak" if it is with refs outside
924 * heads or tags, and did not specify the pattern
925 * in full (e.g. "refs/remotes/origin/master") or at
926 * least from the toplevel (e.g. "remotes/origin/master");
927 * otherwise "git push $URL master" would result in
928 * ambiguity between remotes/origin/master and heads/master
929 * at the remote site.
931 if (namelen != patlen &&
932 patlen != namelen - 5 &&
933 prefixcmp(name, "refs/heads/") &&
934 prefixcmp(name, "refs/tags/")) {
935 /* We want to catch the case where only weak
936 * matches are found and there are multiple
937 * matches, and where more than one strong
938 * matches are found, as ambiguous. One
939 * strong match with zero or more weak matches
940 * are acceptable as a unique match.
942 matched_weak = refs;
943 weak_match++;
945 else {
946 matched = refs;
947 match++;
950 if (!matched) {
951 *matched_ref = matched_weak;
952 return weak_match;
954 else {
955 *matched_ref = matched;
956 return match;
960 static void tail_link_ref(struct ref *ref, struct ref ***tail)
962 **tail = ref;
963 while (ref->next)
964 ref = ref->next;
965 *tail = &ref->next;
968 static struct ref *try_explicit_object_name(const char *name)
970 unsigned char sha1[20];
971 struct ref *ref;
973 if (!*name) {
974 ref = alloc_ref("(delete)");
975 hashclr(ref->new_sha1);
976 return ref;
978 if (get_sha1(name, sha1))
979 return NULL;
980 ref = alloc_ref(name);
981 hashcpy(ref->new_sha1, sha1);
982 return ref;
985 static struct ref *make_linked_ref(const char *name, struct ref ***tail)
987 struct ref *ret = alloc_ref(name);
988 tail_link_ref(ret, tail);
989 return ret;
992 static char *guess_ref(const char *name, struct ref *peer)
994 struct strbuf buf = STRBUF_INIT;
995 unsigned char sha1[20];
997 const char *r = resolve_ref(peer->name, sha1, 1, NULL);
998 if (!r)
999 return NULL;
1001 if (!prefixcmp(r, "refs/heads/"))
1002 strbuf_addstr(&buf, "refs/heads/");
1003 else if (!prefixcmp(r, "refs/tags/"))
1004 strbuf_addstr(&buf, "refs/tags/");
1005 else
1006 return NULL;
1008 strbuf_addstr(&buf, name);
1009 return strbuf_detach(&buf, NULL);
1012 static int match_explicit(struct ref *src, struct ref *dst,
1013 struct ref ***dst_tail,
1014 struct refspec *rs)
1016 struct ref *matched_src, *matched_dst;
1017 int copy_src;
1019 const char *dst_value = rs->dst;
1020 char *dst_guess;
1022 if (rs->pattern || rs->matching)
1023 return 0;
1025 matched_src = matched_dst = NULL;
1026 switch (count_refspec_match(rs->src, src, &matched_src)) {
1027 case 1:
1028 copy_src = 1;
1029 break;
1030 case 0:
1031 /* The source could be in the get_sha1() format
1032 * not a reference name. :refs/other is a
1033 * way to delete 'other' ref at the remote end.
1035 matched_src = try_explicit_object_name(rs->src);
1036 if (!matched_src)
1037 return error("src refspec %s does not match any.", rs->src);
1038 copy_src = 0;
1039 break;
1040 default:
1041 return error("src refspec %s matches more than one.", rs->src);
1044 if (!dst_value) {
1045 unsigned char sha1[20];
1046 int flag;
1048 dst_value = resolve_ref(matched_src->name, sha1, 1, &flag);
1049 if (!dst_value ||
1050 ((flag & REF_ISSYMREF) &&
1051 prefixcmp(dst_value, "refs/heads/")))
1052 die("%s cannot be resolved to branch.",
1053 matched_src->name);
1056 switch (count_refspec_match(dst_value, dst, &matched_dst)) {
1057 case 1:
1058 break;
1059 case 0:
1060 if (!memcmp(dst_value, "refs/", 5))
1061 matched_dst = make_linked_ref(dst_value, dst_tail);
1062 else if ((dst_guess = guess_ref(dst_value, matched_src)))
1063 matched_dst = make_linked_ref(dst_guess, dst_tail);
1064 else
1065 error("unable to push to unqualified destination: %s\n"
1066 "The destination refspec neither matches an "
1067 "existing ref on the remote nor\n"
1068 "begins with refs/, and we are unable to "
1069 "guess a prefix based on the source ref.",
1070 dst_value);
1071 break;
1072 default:
1073 matched_dst = NULL;
1074 error("dst refspec %s matches more than one.",
1075 dst_value);
1076 break;
1078 if (!matched_dst)
1079 return -1;
1080 if (matched_dst->peer_ref)
1081 return error("dst ref %s receives from more than one src.",
1082 matched_dst->name);
1083 else {
1084 matched_dst->peer_ref = copy_src ? copy_ref(matched_src) : matched_src;
1085 matched_dst->force = rs->force;
1087 return 0;
1090 static int match_explicit_refs(struct ref *src, struct ref *dst,
1091 struct ref ***dst_tail, struct refspec *rs,
1092 int rs_nr)
1094 int i, errs;
1095 for (i = errs = 0; i < rs_nr; i++)
1096 errs += match_explicit(src, dst, dst_tail, &rs[i]);
1097 return errs;
1100 static const struct refspec *check_pattern_match(const struct refspec *rs,
1101 int rs_nr,
1102 const struct ref *src)
1104 int i;
1105 int matching_refs = -1;
1106 for (i = 0; i < rs_nr; i++) {
1107 if (rs[i].matching &&
1108 (matching_refs == -1 || rs[i].force)) {
1109 matching_refs = i;
1110 continue;
1113 if (rs[i].pattern && match_name_with_pattern(rs[i].src, src->name,
1114 NULL, NULL))
1115 return rs + i;
1117 if (matching_refs != -1)
1118 return rs + matching_refs;
1119 else
1120 return NULL;
1123 static struct ref **tail_ref(struct ref **head)
1125 struct ref **tail = head;
1126 while (*tail)
1127 tail = &((*tail)->next);
1128 return tail;
1132 * Note. This is used only by "push"; refspec matching rules for
1133 * push and fetch are subtly different, so do not try to reuse it
1134 * without thinking.
1136 int match_refs(struct ref *src, struct ref **dst,
1137 int nr_refspec, const char **refspec, int flags)
1139 struct refspec *rs;
1140 int send_all = flags & MATCH_REFS_ALL;
1141 int send_mirror = flags & MATCH_REFS_MIRROR;
1142 int errs;
1143 static const char *default_refspec[] = { ":", NULL };
1144 struct ref **dst_tail = tail_ref(dst);
1146 if (!nr_refspec) {
1147 nr_refspec = 1;
1148 refspec = default_refspec;
1150 rs = parse_push_refspec(nr_refspec, (const char **) refspec);
1151 errs = match_explicit_refs(src, *dst, &dst_tail, rs, nr_refspec);
1153 /* pick the remainder */
1154 for ( ; src; src = src->next) {
1155 struct ref *dst_peer;
1156 const struct refspec *pat = NULL;
1157 char *dst_name;
1158 if (src->peer_ref)
1159 continue;
1161 pat = check_pattern_match(rs, nr_refspec, src);
1162 if (!pat)
1163 continue;
1165 if (pat->matching) {
1167 * "matching refs"; traditionally we pushed everything
1168 * including refs outside refs/heads/ hierarchy, but
1169 * that does not make much sense these days.
1171 if (!send_mirror && prefixcmp(src->name, "refs/heads/"))
1172 continue;
1173 dst_name = xstrdup(src->name);
1175 } else {
1176 const char *dst_side = pat->dst ? pat->dst : pat->src;
1177 if (!match_name_with_pattern(pat->src, src->name,
1178 dst_side, &dst_name))
1179 die("Didn't think it matches any more");
1181 dst_peer = find_ref_by_name(*dst, dst_name);
1182 if (dst_peer) {
1183 if (dst_peer->peer_ref)
1184 /* We're already sending something to this ref. */
1185 goto free_name;
1187 } else {
1188 if (pat->matching && !(send_all || send_mirror))
1190 * Remote doesn't have it, and we have no
1191 * explicit pattern, and we don't have
1192 * --all nor --mirror.
1194 goto free_name;
1196 /* Create a new one and link it */
1197 dst_peer = make_linked_ref(dst_name, &dst_tail);
1198 hashcpy(dst_peer->new_sha1, src->new_sha1);
1200 dst_peer->peer_ref = copy_ref(src);
1201 dst_peer->force = pat->force;
1202 free_name:
1203 free(dst_name);
1205 if (errs)
1206 return -1;
1207 return 0;
1210 struct branch *branch_get(const char *name)
1212 struct branch *ret;
1214 read_config();
1215 if (!name || !*name || !strcmp(name, "HEAD"))
1216 ret = current_branch;
1217 else
1218 ret = make_branch(name, 0);
1219 if (ret && ret->remote_name) {
1220 ret->remote = remote_get(ret->remote_name);
1221 if (ret->merge_nr) {
1222 int i;
1223 ret->merge = xcalloc(sizeof(*ret->merge),
1224 ret->merge_nr);
1225 for (i = 0; i < ret->merge_nr; i++) {
1226 ret->merge[i] = xcalloc(1, sizeof(**ret->merge));
1227 ret->merge[i]->src = xstrdup(ret->merge_name[i]);
1228 if (remote_find_tracking(ret->remote, ret->merge[i])
1229 && !strcmp(ret->remote_name, "."))
1230 ret->merge[i]->dst = xstrdup(ret->merge_name[i]);
1234 return ret;
1237 int branch_has_merge_config(struct branch *branch)
1239 return branch && !!branch->merge;
1242 int branch_merge_matches(struct branch *branch,
1243 int i,
1244 const char *refname)
1246 if (!branch || i < 0 || i >= branch->merge_nr)
1247 return 0;
1248 return refname_match(branch->merge[i]->src, refname, ref_fetch_rules);
1251 static struct ref *get_expanded_map(const struct ref *remote_refs,
1252 const struct refspec *refspec)
1254 const struct ref *ref;
1255 struct ref *ret = NULL;
1256 struct ref **tail = &ret;
1258 char *expn_name;
1260 for (ref = remote_refs; ref; ref = ref->next) {
1261 if (strchr(ref->name, '^'))
1262 continue; /* a dereference item */
1263 if (match_name_with_pattern(refspec->src, ref->name,
1264 refspec->dst, &expn_name)) {
1265 struct ref *cpy = copy_ref(ref);
1267 cpy->peer_ref = alloc_ref(expn_name);
1268 free(expn_name);
1269 if (refspec->force)
1270 cpy->peer_ref->force = 1;
1271 *tail = cpy;
1272 tail = &cpy->next;
1276 return ret;
1279 static const struct ref *find_ref_by_name_abbrev(const struct ref *refs, const char *name)
1281 const struct ref *ref;
1282 for (ref = refs; ref; ref = ref->next) {
1283 if (refname_match(name, ref->name, ref_fetch_rules))
1284 return ref;
1286 return NULL;
1289 struct ref *get_remote_ref(const struct ref *remote_refs, const char *name)
1291 const struct ref *ref = find_ref_by_name_abbrev(remote_refs, name);
1293 if (!ref)
1294 return NULL;
1296 return copy_ref(ref);
1299 static struct ref *get_local_ref(const char *name)
1301 if (!name || name[0] == '\0')
1302 return NULL;
1304 if (!prefixcmp(name, "refs/"))
1305 return alloc_ref(name);
1307 if (!prefixcmp(name, "heads/") ||
1308 !prefixcmp(name, "tags/") ||
1309 !prefixcmp(name, "remotes/"))
1310 return alloc_ref_with_prefix("refs/", 5, name);
1312 return alloc_ref_with_prefix("refs/heads/", 11, name);
1315 int get_fetch_map(const struct ref *remote_refs,
1316 const struct refspec *refspec,
1317 struct ref ***tail,
1318 int missing_ok)
1320 struct ref *ref_map, **rmp;
1322 if (refspec->pattern) {
1323 ref_map = get_expanded_map(remote_refs, refspec);
1324 } else {
1325 const char *name = refspec->src[0] ? refspec->src : "HEAD";
1327 ref_map = get_remote_ref(remote_refs, name);
1328 if (!missing_ok && !ref_map)
1329 die("Couldn't find remote ref %s", name);
1330 if (ref_map) {
1331 ref_map->peer_ref = get_local_ref(refspec->dst);
1332 if (ref_map->peer_ref && refspec->force)
1333 ref_map->peer_ref->force = 1;
1337 for (rmp = &ref_map; *rmp; ) {
1338 if ((*rmp)->peer_ref) {
1339 int st = check_ref_format((*rmp)->peer_ref->name + 5);
1340 if (st && st != CHECK_REF_FORMAT_ONELEVEL) {
1341 struct ref *ignore = *rmp;
1342 error("* Ignoring funny ref '%s' locally",
1343 (*rmp)->peer_ref->name);
1344 *rmp = (*rmp)->next;
1345 free(ignore->peer_ref);
1346 free(ignore);
1347 continue;
1350 rmp = &((*rmp)->next);
1353 if (ref_map)
1354 tail_link_ref(ref_map, tail);
1356 return 0;
1359 int resolve_remote_symref(struct ref *ref, struct ref *list)
1361 if (!ref->symref)
1362 return 0;
1363 for (; list; list = list->next)
1364 if (!strcmp(ref->symref, list->name)) {
1365 hashcpy(ref->old_sha1, list->old_sha1);
1366 return 0;
1368 return 1;
1371 static void unmark_and_free(struct commit_list *list, unsigned int mark)
1373 while (list) {
1374 struct commit_list *temp = list;
1375 temp->item->object.flags &= ~mark;
1376 list = temp->next;
1377 free(temp);
1381 int ref_newer(const unsigned char *new_sha1, const unsigned char *old_sha1)
1383 struct object *o;
1384 struct commit *old, *new;
1385 struct commit_list *list, *used;
1386 int found = 0;
1388 /* Both new and old must be commit-ish and new is descendant of
1389 * old. Otherwise we require --force.
1391 o = deref_tag(parse_object(old_sha1), NULL, 0);
1392 if (!o || o->type != OBJ_COMMIT)
1393 return 0;
1394 old = (struct commit *) o;
1396 o = deref_tag(parse_object(new_sha1), NULL, 0);
1397 if (!o || o->type != OBJ_COMMIT)
1398 return 0;
1399 new = (struct commit *) o;
1401 if (parse_commit(new) < 0)
1402 return 0;
1404 used = list = NULL;
1405 commit_list_insert(new, &list);
1406 while (list) {
1407 new = pop_most_recent_commit(&list, TMP_MARK);
1408 commit_list_insert(new, &used);
1409 if (new == old) {
1410 found = 1;
1411 break;
1414 unmark_and_free(list, TMP_MARK);
1415 unmark_and_free(used, TMP_MARK);
1416 return found;
1420 * Return true if there is anything to report, otherwise false.
1422 int stat_tracking_info(struct branch *branch, int *num_ours, int *num_theirs)
1424 unsigned char sha1[20];
1425 struct commit *ours, *theirs;
1426 char symmetric[84];
1427 struct rev_info revs;
1428 const char *rev_argv[10], *base;
1429 int rev_argc;
1432 * Nothing to report unless we are marked to build on top of
1433 * somebody else.
1435 if (!branch ||
1436 !branch->merge || !branch->merge[0] || !branch->merge[0]->dst)
1437 return 0;
1440 * If what we used to build on no longer exists, there is
1441 * nothing to report.
1443 base = branch->merge[0]->dst;
1444 if (!resolve_ref(base, sha1, 1, NULL))
1445 return 0;
1446 theirs = lookup_commit_reference(sha1);
1447 if (!theirs)
1448 return 0;
1450 if (!resolve_ref(branch->refname, sha1, 1, NULL))
1451 return 0;
1452 ours = lookup_commit_reference(sha1);
1453 if (!ours)
1454 return 0;
1456 /* are we the same? */
1457 if (theirs == ours)
1458 return 0;
1460 /* Run "rev-list --left-right ours...theirs" internally... */
1461 rev_argc = 0;
1462 rev_argv[rev_argc++] = NULL;
1463 rev_argv[rev_argc++] = "--left-right";
1464 rev_argv[rev_argc++] = symmetric;
1465 rev_argv[rev_argc++] = "--";
1466 rev_argv[rev_argc] = NULL;
1468 strcpy(symmetric, sha1_to_hex(ours->object.sha1));
1469 strcpy(symmetric + 40, "...");
1470 strcpy(symmetric + 43, sha1_to_hex(theirs->object.sha1));
1472 init_revisions(&revs, NULL);
1473 setup_revisions(rev_argc, rev_argv, &revs, NULL);
1474 prepare_revision_walk(&revs);
1476 /* ... and count the commits on each side. */
1477 *num_ours = 0;
1478 *num_theirs = 0;
1479 while (1) {
1480 struct commit *c = get_revision(&revs);
1481 if (!c)
1482 break;
1483 if (c->object.flags & SYMMETRIC_LEFT)
1484 (*num_ours)++;
1485 else
1486 (*num_theirs)++;
1489 /* clear object flags smudged by the above traversal */
1490 clear_commit_marks(ours, ALL_REV_FLAGS);
1491 clear_commit_marks(theirs, ALL_REV_FLAGS);
1492 return 1;
1496 * Return true when there is anything to report, otherwise false.
1498 int format_tracking_info(struct branch *branch, struct strbuf *sb)
1500 int num_ours, num_theirs;
1501 const char *base;
1503 if (!stat_tracking_info(branch, &num_ours, &num_theirs))
1504 return 0;
1506 base = branch->merge[0]->dst;
1507 base = shorten_unambiguous_ref(base, 0);
1508 if (!num_theirs)
1509 strbuf_addf(sb, "Your branch is ahead of '%s' "
1510 "by %d commit%s.\n",
1511 base, num_ours, (num_ours == 1) ? "" : "s");
1512 else if (!num_ours)
1513 strbuf_addf(sb, "Your branch is behind '%s' "
1514 "by %d commit%s, "
1515 "and can be fast-forwarded.\n",
1516 base, num_theirs, (num_theirs == 1) ? "" : "s");
1517 else
1518 strbuf_addf(sb, "Your branch and '%s' have diverged,\n"
1519 "and have %d and %d different commit(s) each, "
1520 "respectively.\n",
1521 base, num_ours, num_theirs);
1522 return 1;
1525 static int one_local_ref(const char *refname, const unsigned char *sha1, int flag, void *cb_data)
1527 struct ref ***local_tail = cb_data;
1528 struct ref *ref;
1529 int len;
1531 /* we already know it starts with refs/ to get here */
1532 if (check_ref_format(refname + 5))
1533 return 0;
1535 len = strlen(refname) + 1;
1536 ref = xcalloc(1, sizeof(*ref) + len);
1537 hashcpy(ref->new_sha1, sha1);
1538 memcpy(ref->name, refname, len);
1539 **local_tail = ref;
1540 *local_tail = &ref->next;
1541 return 0;
1544 struct ref *get_local_heads(void)
1546 struct ref *local_refs = NULL, **local_tail = &local_refs;
1547 for_each_ref(one_local_ref, &local_tail);
1548 return local_refs;
1551 struct ref *guess_remote_head(const struct ref *head,
1552 const struct ref *refs,
1553 int all)
1555 const struct ref *r;
1556 struct ref *list = NULL;
1557 struct ref **tail = &list;
1559 if (!head)
1560 return NULL;
1563 * Some transports support directly peeking at
1564 * where HEAD points; if that is the case, then
1565 * we don't have to guess.
1567 if (head->symref)
1568 return copy_ref(find_ref_by_name(refs, head->symref));
1570 /* If refs/heads/master could be right, it is. */
1571 if (!all) {
1572 r = find_ref_by_name(refs, "refs/heads/master");
1573 if (r && !hashcmp(r->old_sha1, head->old_sha1))
1574 return copy_ref(r);
1577 /* Look for another ref that points there */
1578 for (r = refs; r; r = r->next) {
1579 if (r != head && !hashcmp(r->old_sha1, head->old_sha1)) {
1580 *tail = copy_ref(r);
1581 tail = &((*tail)->next);
1582 if (!all)
1583 break;
1587 return list;