Make test number t7406- unique
[git/dscho.git] / remote.c
blobc3ada2d72b9b3f7411ffe420030768e73a003923
1 #include "cache.h"
2 #include "remote.h"
3 #include "refs.h"
4 #include "commit.h"
5 #include "diff.h"
6 #include "revision.h"
7 #include "dir.h"
8 #include "tag.h"
10 static struct refspec s_tag_refspec = {
14 "refs/tags/*",
15 "refs/tags/*"
18 const struct refspec *tag_refspec = &s_tag_refspec;
20 struct counted_string {
21 size_t len;
22 const char *s;
24 struct rewrite {
25 const char *base;
26 size_t baselen;
27 struct counted_string *instead_of;
28 int instead_of_nr;
29 int instead_of_alloc;
32 static struct remote **remotes;
33 static int remotes_alloc;
34 static int remotes_nr;
36 static struct branch **branches;
37 static int branches_alloc;
38 static int branches_nr;
40 static struct branch *current_branch;
41 static const char *default_remote_name;
42 static int explicit_default_remote_name;
44 static struct rewrite **rewrite;
45 static int rewrite_alloc;
46 static int rewrite_nr;
48 #define BUF_SIZE (2048)
49 static char buffer[BUF_SIZE];
51 static const char *alias_url(const char *url)
53 int i, j;
54 char *ret;
55 struct counted_string *longest;
56 int longest_i;
58 longest = NULL;
59 longest_i = -1;
60 for (i = 0; i < rewrite_nr; i++) {
61 if (!rewrite[i])
62 continue;
63 for (j = 0; j < rewrite[i]->instead_of_nr; j++) {
64 if (!prefixcmp(url, rewrite[i]->instead_of[j].s) &&
65 (!longest ||
66 longest->len < rewrite[i]->instead_of[j].len)) {
67 longest = &(rewrite[i]->instead_of[j]);
68 longest_i = i;
72 if (!longest)
73 return url;
75 ret = xmalloc(rewrite[longest_i]->baselen +
76 (strlen(url) - longest->len) + 1);
77 strcpy(ret, rewrite[longest_i]->base);
78 strcpy(ret + rewrite[longest_i]->baselen, url + longest->len);
79 return ret;
82 static void add_push_refspec(struct remote *remote, const char *ref)
84 ALLOC_GROW(remote->push_refspec,
85 remote->push_refspec_nr + 1,
86 remote->push_refspec_alloc);
87 remote->push_refspec[remote->push_refspec_nr++] = ref;
90 static void add_fetch_refspec(struct remote *remote, const char *ref)
92 ALLOC_GROW(remote->fetch_refspec,
93 remote->fetch_refspec_nr + 1,
94 remote->fetch_refspec_alloc);
95 remote->fetch_refspec[remote->fetch_refspec_nr++] = ref;
98 static void add_url(struct remote *remote, const char *url)
100 ALLOC_GROW(remote->url, remote->url_nr + 1, remote->url_alloc);
101 remote->url[remote->url_nr++] = url;
104 static void add_url_alias(struct remote *remote, const char *url)
106 add_url(remote, alias_url(url));
109 static void add_pushurl(struct remote *remote, const char *pushurl)
111 ALLOC_GROW(remote->pushurl, remote->pushurl_nr + 1, remote->pushurl_alloc);
112 remote->pushurl[remote->pushurl_nr++] = pushurl;
115 static struct remote *make_remote(const char *name, int len)
117 struct remote *ret;
118 int i;
120 for (i = 0; i < remotes_nr; i++) {
121 if (len ? (!strncmp(name, remotes[i]->name, len) &&
122 !remotes[i]->name[len]) :
123 !strcmp(name, remotes[i]->name))
124 return remotes[i];
127 ret = xcalloc(1, sizeof(struct remote));
128 ALLOC_GROW(remotes, remotes_nr + 1, remotes_alloc);
129 remotes[remotes_nr++] = ret;
130 if (len)
131 ret->name = xstrndup(name, len);
132 else
133 ret->name = xstrdup(name);
134 return ret;
137 static void add_merge(struct branch *branch, const char *name)
139 ALLOC_GROW(branch->merge_name, branch->merge_nr + 1,
140 branch->merge_alloc);
141 branch->merge_name[branch->merge_nr++] = name;
144 static struct branch *make_branch(const char *name, int len)
146 struct branch *ret;
147 int i;
148 char *refname;
150 for (i = 0; i < branches_nr; i++) {
151 if (len ? (!strncmp(name, branches[i]->name, len) &&
152 !branches[i]->name[len]) :
153 !strcmp(name, branches[i]->name))
154 return branches[i];
157 ALLOC_GROW(branches, branches_nr + 1, branches_alloc);
158 ret = xcalloc(1, sizeof(struct branch));
159 branches[branches_nr++] = ret;
160 if (len)
161 ret->name = xstrndup(name, len);
162 else
163 ret->name = xstrdup(name);
164 refname = xmalloc(strlen(name) + strlen("refs/heads/") + 1);
165 strcpy(refname, "refs/heads/");
166 strcpy(refname + strlen("refs/heads/"), ret->name);
167 ret->refname = refname;
169 return ret;
172 static struct rewrite *make_rewrite(const char *base, int len)
174 struct rewrite *ret;
175 int i;
177 for (i = 0; i < rewrite_nr; i++) {
178 if (len
179 ? (len == rewrite[i]->baselen &&
180 !strncmp(base, rewrite[i]->base, len))
181 : !strcmp(base, rewrite[i]->base))
182 return rewrite[i];
185 ALLOC_GROW(rewrite, rewrite_nr + 1, rewrite_alloc);
186 ret = xcalloc(1, sizeof(struct rewrite));
187 rewrite[rewrite_nr++] = ret;
188 if (len) {
189 ret->base = xstrndup(base, len);
190 ret->baselen = len;
192 else {
193 ret->base = xstrdup(base);
194 ret->baselen = strlen(base);
196 return ret;
199 static void add_instead_of(struct rewrite *rewrite, const char *instead_of)
201 ALLOC_GROW(rewrite->instead_of, rewrite->instead_of_nr + 1, rewrite->instead_of_alloc);
202 rewrite->instead_of[rewrite->instead_of_nr].s = instead_of;
203 rewrite->instead_of[rewrite->instead_of_nr].len = strlen(instead_of);
204 rewrite->instead_of_nr++;
207 static void read_remotes_file(struct remote *remote)
209 FILE *f = fopen(git_path("remotes/%s", remote->name), "r");
211 if (!f)
212 return;
213 remote->origin = REMOTE_REMOTES;
214 while (fgets(buffer, BUF_SIZE, f)) {
215 int value_list;
216 char *s, *p;
218 if (!prefixcmp(buffer, "URL:")) {
219 value_list = 0;
220 s = buffer + 4;
221 } else if (!prefixcmp(buffer, "Push:")) {
222 value_list = 1;
223 s = buffer + 5;
224 } else if (!prefixcmp(buffer, "Pull:")) {
225 value_list = 2;
226 s = buffer + 5;
227 } else
228 continue;
230 while (isspace(*s))
231 s++;
232 if (!*s)
233 continue;
235 p = s + strlen(s);
236 while (isspace(p[-1]))
237 *--p = 0;
239 switch (value_list) {
240 case 0:
241 add_url_alias(remote, xstrdup(s));
242 break;
243 case 1:
244 add_push_refspec(remote, xstrdup(s));
245 break;
246 case 2:
247 add_fetch_refspec(remote, xstrdup(s));
248 break;
251 fclose(f);
254 static void read_branches_file(struct remote *remote)
256 const char *slash = strchr(remote->name, '/');
257 char *frag;
258 struct strbuf branch = STRBUF_INIT;
259 int n = slash ? slash - remote->name : 1000;
260 FILE *f = fopen(git_path("branches/%.*s", n, remote->name), "r");
261 char *s, *p;
262 int len;
264 if (!f)
265 return;
266 s = fgets(buffer, BUF_SIZE, f);
267 fclose(f);
268 if (!s)
269 return;
270 while (isspace(*s))
271 s++;
272 if (!*s)
273 return;
274 remote->origin = REMOTE_BRANCHES;
275 p = s + strlen(s);
276 while (isspace(p[-1]))
277 *--p = 0;
278 len = p - s;
279 if (slash)
280 len += strlen(slash);
281 p = xmalloc(len + 1);
282 strcpy(p, s);
283 if (slash)
284 strcat(p, slash);
287 * With "slash", e.g. "git fetch jgarzik/netdev-2.6" when
288 * reading from $GIT_DIR/branches/jgarzik fetches "HEAD" from
289 * the partial URL obtained from the branches file plus
290 * "/netdev-2.6" and does not store it in any tracking ref.
291 * #branch specifier in the file is ignored.
293 * Otherwise, the branches file would have URL and optionally
294 * #branch specified. The "master" (or specified) branch is
295 * fetched and stored in the local branch of the same name.
297 frag = strchr(p, '#');
298 if (frag) {
299 *(frag++) = '\0';
300 strbuf_addf(&branch, "refs/heads/%s", frag);
301 } else
302 strbuf_addstr(&branch, "refs/heads/master");
303 if (!slash) {
304 strbuf_addf(&branch, ":refs/heads/%s", remote->name);
305 } else {
306 strbuf_reset(&branch);
307 strbuf_addstr(&branch, "HEAD:");
309 add_url_alias(remote, p);
310 add_fetch_refspec(remote, strbuf_detach(&branch, NULL));
312 * Cogito compatible push: push current HEAD to remote #branch
313 * (master if missing)
315 strbuf_init(&branch, 0);
316 strbuf_addstr(&branch, "HEAD");
317 if (frag)
318 strbuf_addf(&branch, ":refs/heads/%s", frag);
319 else
320 strbuf_addstr(&branch, ":refs/heads/master");
321 add_push_refspec(remote, strbuf_detach(&branch, NULL));
322 remote->fetch_tags = 1; /* always auto-follow */
325 static int handle_config(const char *key, const char *value, void *cb)
327 const char *name;
328 const char *subkey;
329 struct remote *remote;
330 struct branch *branch;
331 if (!prefixcmp(key, "branch.")) {
332 name = key + 7;
333 subkey = strrchr(name, '.');
334 if (!subkey)
335 return 0;
336 branch = make_branch(name, subkey - name);
337 if (!strcmp(subkey, ".remote")) {
338 if (!value)
339 return config_error_nonbool(key);
340 branch->remote_name = xstrdup(value);
341 if (branch == current_branch) {
342 default_remote_name = branch->remote_name;
343 explicit_default_remote_name = 1;
345 } else if (!strcmp(subkey, ".merge")) {
346 if (!value)
347 return config_error_nonbool(key);
348 add_merge(branch, xstrdup(value));
350 return 0;
352 if (!prefixcmp(key, "url.")) {
353 struct rewrite *rewrite;
354 name = key + 4;
355 subkey = strrchr(name, '.');
356 if (!subkey)
357 return 0;
358 rewrite = make_rewrite(name, subkey - name);
359 if (!strcmp(subkey, ".insteadof")) {
360 if (!value)
361 return config_error_nonbool(key);
362 add_instead_of(rewrite, xstrdup(value));
365 if (prefixcmp(key, "remote."))
366 return 0;
367 name = key + 7;
368 if (*name == '/') {
369 warning("Config remote shorthand cannot begin with '/': %s",
370 name);
371 return 0;
373 subkey = strrchr(name, '.');
374 if (!subkey)
375 return 0;
376 remote = make_remote(name, subkey - name);
377 remote->origin = REMOTE_CONFIG;
378 if (!strcmp(subkey, ".mirror"))
379 remote->mirror = git_config_bool(key, value);
380 else if (!strcmp(subkey, ".skipdefaultupdate"))
381 remote->skip_default_update = git_config_bool(key, value);
383 else if (!strcmp(subkey, ".url")) {
384 const char *v;
385 if (git_config_string(&v, key, value))
386 return -1;
387 add_url(remote, v);
388 } else if (!strcmp(subkey, ".pushurl")) {
389 const char *v;
390 if (git_config_string(&v, key, value))
391 return -1;
392 add_pushurl(remote, v);
393 } else if (!strcmp(subkey, ".push")) {
394 const char *v;
395 if (git_config_string(&v, key, value))
396 return -1;
397 add_push_refspec(remote, v);
398 } else if (!strcmp(subkey, ".fetch")) {
399 const char *v;
400 if (git_config_string(&v, key, value))
401 return -1;
402 add_fetch_refspec(remote, v);
403 } else if (!strcmp(subkey, ".receivepack")) {
404 const char *v;
405 if (git_config_string(&v, key, value))
406 return -1;
407 if (!remote->receivepack)
408 remote->receivepack = v;
409 else
410 error("more than one receivepack given, using the first");
411 } else if (!strcmp(subkey, ".uploadpack")) {
412 const char *v;
413 if (git_config_string(&v, key, value))
414 return -1;
415 if (!remote->uploadpack)
416 remote->uploadpack = v;
417 else
418 error("more than one uploadpack given, using the first");
419 } else if (!strcmp(subkey, ".tagopt")) {
420 if (!strcmp(value, "--no-tags"))
421 remote->fetch_tags = -1;
422 } else if (!strcmp(subkey, ".proxy")) {
423 return git_config_string((const char **)&remote->http_proxy,
424 key, value);
426 return 0;
429 static void alias_all_urls(void)
431 int i, j;
432 for (i = 0; i < remotes_nr; i++) {
433 if (!remotes[i])
434 continue;
435 for (j = 0; j < remotes[i]->url_nr; j++) {
436 remotes[i]->url[j] = alias_url(remotes[i]->url[j]);
438 for (j = 0; j < remotes[i]->pushurl_nr; j++) {
439 remotes[i]->pushurl[j] = alias_url(remotes[i]->pushurl[j]);
444 static void read_config(void)
446 unsigned char sha1[20];
447 const char *head_ref;
448 int flag;
449 if (default_remote_name) // did this already
450 return;
451 default_remote_name = xstrdup("origin");
452 current_branch = NULL;
453 head_ref = resolve_ref("HEAD", sha1, 0, &flag);
454 if (head_ref && (flag & REF_ISSYMREF) &&
455 !prefixcmp(head_ref, "refs/heads/")) {
456 current_branch =
457 make_branch(head_ref + strlen("refs/heads/"), 0);
459 git_config(handle_config, NULL);
460 alias_all_urls();
464 * We need to make sure the tracking branches are well formed, but a
465 * wildcard refspec in "struct refspec" must have a trailing slash. We
466 * temporarily drop the trailing '/' while calling check_ref_format(),
467 * and put it back. The caller knows that a CHECK_REF_FORMAT_ONELEVEL
468 * error return is Ok for a wildcard refspec.
470 static int verify_refname(char *name, int is_glob)
472 int result;
474 result = check_ref_format(name);
475 if (is_glob && result == CHECK_REF_FORMAT_WILDCARD)
476 result = CHECK_REF_FORMAT_OK;
477 return result;
481 * This function frees a refspec array.
482 * Warning: code paths should be checked to ensure that the src
483 * and dst pointers are always freeable pointers as well
484 * as the refspec pointer itself.
486 static void free_refspecs(struct refspec *refspec, int nr_refspec)
488 int i;
490 if (!refspec)
491 return;
493 for (i = 0; i < nr_refspec; i++) {
494 free(refspec[i].src);
495 free(refspec[i].dst);
497 free(refspec);
500 static struct refspec *parse_refspec_internal(int nr_refspec, const char **refspec, int fetch, int verify)
502 int i;
503 int st;
504 struct refspec *rs = xcalloc(sizeof(*rs), nr_refspec);
506 for (i = 0; i < nr_refspec; i++) {
507 size_t llen;
508 int is_glob;
509 const char *lhs, *rhs;
511 is_glob = 0;
513 lhs = refspec[i];
514 if (*lhs == '+') {
515 rs[i].force = 1;
516 lhs++;
519 rhs = strrchr(lhs, ':');
522 * Before going on, special case ":" (or "+:") as a refspec
523 * for matching refs.
525 if (!fetch && rhs == lhs && rhs[1] == '\0') {
526 rs[i].matching = 1;
527 continue;
530 if (rhs) {
531 size_t rlen = strlen(++rhs);
532 is_glob = (1 <= rlen && strchr(rhs, '*'));
533 rs[i].dst = xstrndup(rhs, rlen);
536 llen = (rhs ? (rhs - lhs - 1) : strlen(lhs));
537 if (1 <= llen && memchr(lhs, '*', llen)) {
538 if ((rhs && !is_glob) || (!rhs && fetch))
539 goto invalid;
540 is_glob = 1;
541 } else if (rhs && is_glob) {
542 goto invalid;
545 rs[i].pattern = is_glob;
546 rs[i].src = xstrndup(lhs, llen);
548 if (fetch) {
550 * LHS
551 * - empty is allowed; it means HEAD.
552 * - otherwise it must be a valid looking ref.
554 if (!*rs[i].src)
555 ; /* empty is ok */
556 else {
557 st = verify_refname(rs[i].src, is_glob);
558 if (st && st != CHECK_REF_FORMAT_ONELEVEL)
559 goto invalid;
562 * RHS
563 * - missing is ok, and is same as empty.
564 * - empty is ok; it means not to store.
565 * - otherwise it must be a valid looking ref.
567 if (!rs[i].dst) {
568 ; /* ok */
569 } else if (!*rs[i].dst) {
570 ; /* ok */
571 } else {
572 st = verify_refname(rs[i].dst, is_glob);
573 if (st && st != CHECK_REF_FORMAT_ONELEVEL)
574 goto invalid;
576 } else {
578 * LHS
579 * - empty is allowed; it means delete.
580 * - when wildcarded, it must be a valid looking ref.
581 * - otherwise, it must be an extended SHA-1, but
582 * there is no existing way to validate this.
584 if (!*rs[i].src)
585 ; /* empty is ok */
586 else if (is_glob) {
587 st = verify_refname(rs[i].src, is_glob);
588 if (st && st != CHECK_REF_FORMAT_ONELEVEL)
589 goto invalid;
591 else
592 ; /* anything goes, for now */
594 * RHS
595 * - missing is allowed, but LHS then must be a
596 * valid looking ref.
597 * - empty is not allowed.
598 * - otherwise it must be a valid looking ref.
600 if (!rs[i].dst) {
601 st = verify_refname(rs[i].src, is_glob);
602 if (st && st != CHECK_REF_FORMAT_ONELEVEL)
603 goto invalid;
604 } else if (!*rs[i].dst) {
605 goto invalid;
606 } else {
607 st = verify_refname(rs[i].dst, is_glob);
608 if (st && st != CHECK_REF_FORMAT_ONELEVEL)
609 goto invalid;
613 return rs;
615 invalid:
616 if (verify) {
618 * nr_refspec must be greater than zero and i must be valid
619 * since it is only possible to reach this point from within
620 * the for loop above.
622 free_refspecs(rs, i+1);
623 return NULL;
625 die("Invalid refspec '%s'", refspec[i]);
628 int valid_fetch_refspec(const char *fetch_refspec_str)
630 const char *fetch_refspec[] = { fetch_refspec_str };
631 struct refspec *refspec;
633 refspec = parse_refspec_internal(1, fetch_refspec, 1, 1);
634 free_refspecs(refspec, 1);
635 return !!refspec;
638 struct refspec *parse_fetch_refspec(int nr_refspec, const char **refspec)
640 return parse_refspec_internal(nr_refspec, refspec, 1, 0);
643 static struct refspec *parse_push_refspec(int nr_refspec, const char **refspec)
645 return parse_refspec_internal(nr_refspec, refspec, 0, 0);
648 static int valid_remote_nick(const char *name)
650 if (!name[0] || is_dot_or_dotdot(name))
651 return 0;
652 return !strchr(name, '/'); /* no slash */
655 struct remote *remote_get(const char *name)
657 struct remote *ret;
658 int name_given = 0;
660 read_config();
661 if (name)
662 name_given = 1;
663 else {
664 name = default_remote_name;
665 name_given = explicit_default_remote_name;
668 ret = make_remote(name, 0);
669 if (valid_remote_nick(name)) {
670 if (!ret->url)
671 read_remotes_file(ret);
672 if (!ret->url)
673 read_branches_file(ret);
675 if (name_given && !ret->url)
676 add_url_alias(ret, name);
677 if (!ret->url)
678 return NULL;
679 ret->fetch = parse_fetch_refspec(ret->fetch_refspec_nr, ret->fetch_refspec);
680 ret->push = parse_push_refspec(ret->push_refspec_nr, ret->push_refspec);
681 return ret;
684 int remote_is_configured(const char *name)
686 int i;
687 read_config();
689 for (i = 0; i < remotes_nr; i++)
690 if (!strcmp(name, remotes[i]->name))
691 return 1;
692 return 0;
695 int for_each_remote(each_remote_fn fn, void *priv)
697 int i, result = 0;
698 read_config();
699 for (i = 0; i < remotes_nr && !result; i++) {
700 struct remote *r = remotes[i];
701 if (!r)
702 continue;
703 if (!r->fetch)
704 r->fetch = parse_fetch_refspec(r->fetch_refspec_nr,
705 r->fetch_refspec);
706 if (!r->push)
707 r->push = parse_push_refspec(r->push_refspec_nr,
708 r->push_refspec);
709 result = fn(r, priv);
711 return result;
714 void ref_remove_duplicates(struct ref *ref_map)
716 struct ref **posn;
717 struct ref *next;
718 for (; ref_map; ref_map = ref_map->next) {
719 if (!ref_map->peer_ref)
720 continue;
721 posn = &ref_map->next;
722 while (*posn) {
723 if ((*posn)->peer_ref &&
724 !strcmp((*posn)->peer_ref->name,
725 ref_map->peer_ref->name)) {
726 if (strcmp((*posn)->name, ref_map->name))
727 die("%s tracks both %s and %s",
728 ref_map->peer_ref->name,
729 (*posn)->name, ref_map->name);
730 next = (*posn)->next;
731 free((*posn)->peer_ref);
732 free(*posn);
733 *posn = next;
734 } else {
735 posn = &(*posn)->next;
741 int remote_has_url(struct remote *remote, const char *url)
743 int i;
744 for (i = 0; i < remote->url_nr; i++) {
745 if (!strcmp(remote->url[i], url))
746 return 1;
748 return 0;
751 static int match_name_with_pattern(const char *key, const char *name,
752 const char *value, char **result)
754 const char *kstar = strchr(key, '*');
755 size_t klen;
756 size_t ksuffixlen;
757 size_t namelen;
758 int ret;
759 if (!kstar)
760 die("Key '%s' of pattern had no '*'", key);
761 klen = kstar - key;
762 ksuffixlen = strlen(kstar + 1);
763 namelen = strlen(name);
764 ret = !strncmp(name, key, klen) && namelen >= klen + ksuffixlen &&
765 !memcmp(name + namelen - ksuffixlen, kstar + 1, ksuffixlen);
766 if (ret && value) {
767 const char *vstar = strchr(value, '*');
768 size_t vlen;
769 size_t vsuffixlen;
770 if (!vstar)
771 die("Value '%s' of pattern has no '*'", value);
772 vlen = vstar - value;
773 vsuffixlen = strlen(vstar + 1);
774 *result = xmalloc(vlen + vsuffixlen +
775 strlen(name) -
776 klen - ksuffixlen + 1);
777 strncpy(*result, value, vlen);
778 strncpy(*result + vlen,
779 name + klen, namelen - klen - ksuffixlen);
780 strcpy(*result + vlen + namelen - klen - ksuffixlen,
781 vstar + 1);
783 return ret;
786 int remote_find_tracking(struct remote *remote, struct refspec *refspec)
788 int find_src = refspec->src == NULL;
789 char *needle, **result;
790 int i;
792 if (find_src) {
793 if (!refspec->dst)
794 return error("find_tracking: need either src or dst");
795 needle = refspec->dst;
796 result = &refspec->src;
797 } else {
798 needle = refspec->src;
799 result = &refspec->dst;
802 for (i = 0; i < remote->fetch_refspec_nr; i++) {
803 struct refspec *fetch = &remote->fetch[i];
804 const char *key = find_src ? fetch->dst : fetch->src;
805 const char *value = find_src ? fetch->src : fetch->dst;
806 if (!fetch->dst)
807 continue;
808 if (fetch->pattern) {
809 if (match_name_with_pattern(key, needle, value, result)) {
810 refspec->force = fetch->force;
811 return 0;
813 } else if (!strcmp(needle, key)) {
814 *result = xstrdup(value);
815 refspec->force = fetch->force;
816 return 0;
819 return -1;
822 static struct ref *alloc_ref_with_prefix(const char *prefix, size_t prefixlen,
823 const char *name)
825 size_t len = strlen(name);
826 struct ref *ref = xcalloc(1, sizeof(struct ref) + prefixlen + len + 1);
827 memcpy(ref->name, prefix, prefixlen);
828 memcpy(ref->name + prefixlen, name, len);
829 return ref;
832 struct ref *alloc_ref(const char *name)
834 return alloc_ref_with_prefix("", 0, name);
837 static struct ref *copy_ref(const struct ref *ref)
839 struct ref *cpy;
840 size_t len;
841 if (!ref)
842 return NULL;
843 len = strlen(ref->name);
844 cpy = xmalloc(sizeof(struct ref) + len + 1);
845 memcpy(cpy, ref, sizeof(struct ref) + len + 1);
846 cpy->next = NULL;
847 cpy->symref = ref->symref ? xstrdup(ref->symref) : NULL;
848 cpy->remote_status = ref->remote_status ? xstrdup(ref->remote_status) : NULL;
849 cpy->peer_ref = copy_ref(ref->peer_ref);
850 return cpy;
853 struct ref *copy_ref_list(const struct ref *ref)
855 struct ref *ret = NULL;
856 struct ref **tail = &ret;
857 while (ref) {
858 *tail = copy_ref(ref);
859 ref = ref->next;
860 tail = &((*tail)->next);
862 return ret;
865 static void free_ref(struct ref *ref)
867 if (!ref)
868 return;
869 free_ref(ref->peer_ref);
870 free(ref->remote_status);
871 free(ref->symref);
872 free(ref);
875 void free_refs(struct ref *ref)
877 struct ref *next;
878 while (ref) {
879 next = ref->next;
880 free_ref(ref);
881 ref = next;
885 static int count_refspec_match(const char *pattern,
886 struct ref *refs,
887 struct ref **matched_ref)
889 int patlen = strlen(pattern);
890 struct ref *matched_weak = NULL;
891 struct ref *matched = NULL;
892 int weak_match = 0;
893 int match = 0;
895 for (weak_match = match = 0; refs; refs = refs->next) {
896 char *name = refs->name;
897 int namelen = strlen(name);
899 if (!refname_match(pattern, name, ref_rev_parse_rules))
900 continue;
902 /* A match is "weak" if it is with refs outside
903 * heads or tags, and did not specify the pattern
904 * in full (e.g. "refs/remotes/origin/master") or at
905 * least from the toplevel (e.g. "remotes/origin/master");
906 * otherwise "git push $URL master" would result in
907 * ambiguity between remotes/origin/master and heads/master
908 * at the remote site.
910 if (namelen != patlen &&
911 patlen != namelen - 5 &&
912 prefixcmp(name, "refs/heads/") &&
913 prefixcmp(name, "refs/tags/")) {
914 /* We want to catch the case where only weak
915 * matches are found and there are multiple
916 * matches, and where more than one strong
917 * matches are found, as ambiguous. One
918 * strong match with zero or more weak matches
919 * are acceptable as a unique match.
921 matched_weak = refs;
922 weak_match++;
924 else {
925 matched = refs;
926 match++;
929 if (!matched) {
930 *matched_ref = matched_weak;
931 return weak_match;
933 else {
934 *matched_ref = matched;
935 return match;
939 static void tail_link_ref(struct ref *ref, struct ref ***tail)
941 **tail = ref;
942 while (ref->next)
943 ref = ref->next;
944 *tail = &ref->next;
947 static struct ref *try_explicit_object_name(const char *name)
949 unsigned char sha1[20];
950 struct ref *ref;
952 if (!*name) {
953 ref = alloc_ref("(delete)");
954 hashclr(ref->new_sha1);
955 return ref;
957 if (get_sha1(name, sha1))
958 return NULL;
959 ref = alloc_ref(name);
960 hashcpy(ref->new_sha1, sha1);
961 return ref;
964 static struct ref *make_linked_ref(const char *name, struct ref ***tail)
966 struct ref *ret = alloc_ref(name);
967 tail_link_ref(ret, tail);
968 return ret;
971 static char *guess_ref(const char *name, struct ref *peer)
973 struct strbuf buf = STRBUF_INIT;
974 unsigned char sha1[20];
976 const char *r = resolve_ref(peer->name, sha1, 1, NULL);
977 if (!r)
978 return NULL;
980 if (!prefixcmp(r, "refs/heads/"))
981 strbuf_addstr(&buf, "refs/heads/");
982 else if (!prefixcmp(r, "refs/tags/"))
983 strbuf_addstr(&buf, "refs/tags/");
984 else
985 return NULL;
987 strbuf_addstr(&buf, name);
988 return strbuf_detach(&buf, NULL);
991 static int match_explicit(struct ref *src, struct ref *dst,
992 struct ref ***dst_tail,
993 struct refspec *rs)
995 struct ref *matched_src, *matched_dst;
996 int copy_src;
998 const char *dst_value = rs->dst;
999 char *dst_guess;
1001 if (rs->pattern || rs->matching)
1002 return 0;
1004 matched_src = matched_dst = NULL;
1005 switch (count_refspec_match(rs->src, src, &matched_src)) {
1006 case 1:
1007 copy_src = 1;
1008 break;
1009 case 0:
1010 /* The source could be in the get_sha1() format
1011 * not a reference name. :refs/other is a
1012 * way to delete 'other' ref at the remote end.
1014 matched_src = try_explicit_object_name(rs->src);
1015 if (!matched_src)
1016 return error("src refspec %s does not match any.", rs->src);
1017 copy_src = 0;
1018 break;
1019 default:
1020 return error("src refspec %s matches more than one.", rs->src);
1023 if (!dst_value) {
1024 unsigned char sha1[20];
1025 int flag;
1027 dst_value = resolve_ref(matched_src->name, sha1, 1, &flag);
1028 if (!dst_value ||
1029 ((flag & REF_ISSYMREF) &&
1030 prefixcmp(dst_value, "refs/heads/")))
1031 die("%s cannot be resolved to branch.",
1032 matched_src->name);
1035 switch (count_refspec_match(dst_value, dst, &matched_dst)) {
1036 case 1:
1037 break;
1038 case 0:
1039 if (!memcmp(dst_value, "refs/", 5))
1040 matched_dst = make_linked_ref(dst_value, dst_tail);
1041 else if((dst_guess = guess_ref(dst_value, matched_src)))
1042 matched_dst = make_linked_ref(dst_guess, dst_tail);
1043 else
1044 error("unable to push to unqualified destination: %s\n"
1045 "The destination refspec neither matches an "
1046 "existing ref on the remote nor\n"
1047 "begins with refs/, and we are unable to "
1048 "guess a prefix based on the source ref.",
1049 dst_value);
1050 break;
1051 default:
1052 matched_dst = NULL;
1053 error("dst refspec %s matches more than one.",
1054 dst_value);
1055 break;
1057 if (!matched_dst)
1058 return -1;
1059 if (matched_dst->peer_ref)
1060 return error("dst ref %s receives from more than one src.",
1061 matched_dst->name);
1062 else {
1063 matched_dst->peer_ref = copy_src ? copy_ref(matched_src) : matched_src;
1064 matched_dst->force = rs->force;
1066 return 0;
1069 static int match_explicit_refs(struct ref *src, struct ref *dst,
1070 struct ref ***dst_tail, struct refspec *rs,
1071 int rs_nr)
1073 int i, errs;
1074 for (i = errs = 0; i < rs_nr; i++)
1075 errs += match_explicit(src, dst, dst_tail, &rs[i]);
1076 return errs;
1079 static const struct refspec *check_pattern_match(const struct refspec *rs,
1080 int rs_nr,
1081 const struct ref *src)
1083 int i;
1084 int matching_refs = -1;
1085 for (i = 0; i < rs_nr; i++) {
1086 if (rs[i].matching &&
1087 (matching_refs == -1 || rs[i].force)) {
1088 matching_refs = i;
1089 continue;
1092 if (rs[i].pattern && match_name_with_pattern(rs[i].src, src->name,
1093 NULL, NULL))
1094 return rs + i;
1096 if (matching_refs != -1)
1097 return rs + matching_refs;
1098 else
1099 return NULL;
1102 static struct ref **tail_ref(struct ref **head)
1104 struct ref **tail = head;
1105 while (*tail)
1106 tail = &((*tail)->next);
1107 return tail;
1111 * Note. This is used only by "push"; refspec matching rules for
1112 * push and fetch are subtly different, so do not try to reuse it
1113 * without thinking.
1115 int match_refs(struct ref *src, struct ref **dst,
1116 int nr_refspec, const char **refspec, int flags)
1118 struct refspec *rs;
1119 int send_all = flags & MATCH_REFS_ALL;
1120 int send_mirror = flags & MATCH_REFS_MIRROR;
1121 int errs;
1122 static const char *default_refspec[] = { ":", NULL };
1123 struct ref **dst_tail = tail_ref(dst);
1125 if (!nr_refspec) {
1126 nr_refspec = 1;
1127 refspec = default_refspec;
1129 rs = parse_push_refspec(nr_refspec, (const char **) refspec);
1130 errs = match_explicit_refs(src, *dst, &dst_tail, rs, nr_refspec);
1132 /* pick the remainder */
1133 for ( ; src; src = src->next) {
1134 struct ref *dst_peer;
1135 const struct refspec *pat = NULL;
1136 char *dst_name;
1137 if (src->peer_ref)
1138 continue;
1140 pat = check_pattern_match(rs, nr_refspec, src);
1141 if (!pat)
1142 continue;
1144 if (pat->matching) {
1146 * "matching refs"; traditionally we pushed everything
1147 * including refs outside refs/heads/ hierarchy, but
1148 * that does not make much sense these days.
1150 if (!send_mirror && prefixcmp(src->name, "refs/heads/"))
1151 continue;
1152 dst_name = xstrdup(src->name);
1154 } else {
1155 const char *dst_side = pat->dst ? pat->dst : pat->src;
1156 if (!match_name_with_pattern(pat->src, src->name,
1157 dst_side, &dst_name))
1158 die("Didn't think it matches any more");
1160 dst_peer = find_ref_by_name(*dst, dst_name);
1161 if (dst_peer) {
1162 if (dst_peer->peer_ref)
1163 /* We're already sending something to this ref. */
1164 goto free_name;
1166 } else {
1167 if (pat->matching && !(send_all || send_mirror))
1169 * Remote doesn't have it, and we have no
1170 * explicit pattern, and we don't have
1171 * --all nor --mirror.
1173 goto free_name;
1175 /* Create a new one and link it */
1176 dst_peer = make_linked_ref(dst_name, &dst_tail);
1177 hashcpy(dst_peer->new_sha1, src->new_sha1);
1179 dst_peer->peer_ref = copy_ref(src);
1180 dst_peer->force = pat->force;
1181 free_name:
1182 free(dst_name);
1184 if (errs)
1185 return -1;
1186 return 0;
1189 struct branch *branch_get(const char *name)
1191 struct branch *ret;
1193 read_config();
1194 if (!name || !*name || !strcmp(name, "HEAD"))
1195 ret = current_branch;
1196 else
1197 ret = make_branch(name, 0);
1198 if (ret && ret->remote_name) {
1199 ret->remote = remote_get(ret->remote_name);
1200 if (ret->merge_nr) {
1201 int i;
1202 ret->merge = xcalloc(sizeof(*ret->merge),
1203 ret->merge_nr);
1204 for (i = 0; i < ret->merge_nr; i++) {
1205 ret->merge[i] = xcalloc(1, sizeof(**ret->merge));
1206 ret->merge[i]->src = xstrdup(ret->merge_name[i]);
1207 if (remote_find_tracking(ret->remote, ret->merge[i])
1208 && !strcmp(ret->remote_name, "."))
1209 ret->merge[i]->dst = xstrdup(ret->merge_name[i]);
1213 return ret;
1216 int branch_has_merge_config(struct branch *branch)
1218 return branch && !!branch->merge;
1221 int branch_merge_matches(struct branch *branch,
1222 int i,
1223 const char *refname)
1225 if (!branch || i < 0 || i >= branch->merge_nr)
1226 return 0;
1227 return refname_match(branch->merge[i]->src, refname, ref_fetch_rules);
1230 static struct ref *get_expanded_map(const struct ref *remote_refs,
1231 const struct refspec *refspec)
1233 const struct ref *ref;
1234 struct ref *ret = NULL;
1235 struct ref **tail = &ret;
1237 char *expn_name;
1239 for (ref = remote_refs; ref; ref = ref->next) {
1240 if (strchr(ref->name, '^'))
1241 continue; /* a dereference item */
1242 if (match_name_with_pattern(refspec->src, ref->name,
1243 refspec->dst, &expn_name)) {
1244 struct ref *cpy = copy_ref(ref);
1246 cpy->peer_ref = alloc_ref(expn_name);
1247 free(expn_name);
1248 if (refspec->force)
1249 cpy->peer_ref->force = 1;
1250 *tail = cpy;
1251 tail = &cpy->next;
1255 return ret;
1258 static const struct ref *find_ref_by_name_abbrev(const struct ref *refs, const char *name)
1260 const struct ref *ref;
1261 for (ref = refs; ref; ref = ref->next) {
1262 if (refname_match(name, ref->name, ref_fetch_rules))
1263 return ref;
1265 return NULL;
1268 struct ref *get_remote_ref(const struct ref *remote_refs, const char *name)
1270 const struct ref *ref = find_ref_by_name_abbrev(remote_refs, name);
1272 if (!ref)
1273 return NULL;
1275 return copy_ref(ref);
1278 static struct ref *get_local_ref(const char *name)
1280 if (!name || name[0] == '\0')
1281 return NULL;
1283 if (!prefixcmp(name, "refs/"))
1284 return alloc_ref(name);
1286 if (!prefixcmp(name, "heads/") ||
1287 !prefixcmp(name, "tags/") ||
1288 !prefixcmp(name, "remotes/"))
1289 return alloc_ref_with_prefix("refs/", 5, name);
1291 return alloc_ref_with_prefix("refs/heads/", 11, name);
1294 int get_fetch_map(const struct ref *remote_refs,
1295 const struct refspec *refspec,
1296 struct ref ***tail,
1297 int missing_ok)
1299 struct ref *ref_map, **rmp;
1301 if (refspec->pattern) {
1302 ref_map = get_expanded_map(remote_refs, refspec);
1303 } else {
1304 const char *name = refspec->src[0] ? refspec->src : "HEAD";
1306 ref_map = get_remote_ref(remote_refs, name);
1307 if (!missing_ok && !ref_map)
1308 die("Couldn't find remote ref %s", name);
1309 if (ref_map) {
1310 ref_map->peer_ref = get_local_ref(refspec->dst);
1311 if (ref_map->peer_ref && refspec->force)
1312 ref_map->peer_ref->force = 1;
1316 for (rmp = &ref_map; *rmp; ) {
1317 if ((*rmp)->peer_ref) {
1318 int st = check_ref_format((*rmp)->peer_ref->name + 5);
1319 if (st && st != CHECK_REF_FORMAT_ONELEVEL) {
1320 struct ref *ignore = *rmp;
1321 error("* Ignoring funny ref '%s' locally",
1322 (*rmp)->peer_ref->name);
1323 *rmp = (*rmp)->next;
1324 free(ignore->peer_ref);
1325 free(ignore);
1326 continue;
1329 rmp = &((*rmp)->next);
1332 if (ref_map)
1333 tail_link_ref(ref_map, tail);
1335 return 0;
1338 int resolve_remote_symref(struct ref *ref, struct ref *list)
1340 if (!ref->symref)
1341 return 0;
1342 for (; list; list = list->next)
1343 if (!strcmp(ref->symref, list->name)) {
1344 hashcpy(ref->old_sha1, list->old_sha1);
1345 return 0;
1347 return 1;
1350 static void unmark_and_free(struct commit_list *list, unsigned int mark)
1352 while (list) {
1353 struct commit_list *temp = list;
1354 temp->item->object.flags &= ~mark;
1355 list = temp->next;
1356 free(temp);
1360 int ref_newer(const unsigned char *new_sha1, const unsigned char *old_sha1)
1362 struct object *o;
1363 struct commit *old, *new;
1364 struct commit_list *list, *used;
1365 int found = 0;
1367 /* Both new and old must be commit-ish and new is descendant of
1368 * old. Otherwise we require --force.
1370 o = deref_tag(parse_object(old_sha1), NULL, 0);
1371 if (!o || o->type != OBJ_COMMIT)
1372 return 0;
1373 old = (struct commit *) o;
1375 o = deref_tag(parse_object(new_sha1), NULL, 0);
1376 if (!o || o->type != OBJ_COMMIT)
1377 return 0;
1378 new = (struct commit *) o;
1380 if (parse_commit(new) < 0)
1381 return 0;
1383 used = list = NULL;
1384 commit_list_insert(new, &list);
1385 while (list) {
1386 new = pop_most_recent_commit(&list, TMP_MARK);
1387 commit_list_insert(new, &used);
1388 if (new == old) {
1389 found = 1;
1390 break;
1393 unmark_and_free(list, TMP_MARK);
1394 unmark_and_free(used, TMP_MARK);
1395 return found;
1399 * Return true if there is anything to report, otherwise false.
1401 int stat_tracking_info(struct branch *branch, int *num_ours, int *num_theirs)
1403 unsigned char sha1[20];
1404 struct commit *ours, *theirs;
1405 char symmetric[84];
1406 struct rev_info revs;
1407 const char *rev_argv[10], *base;
1408 int rev_argc;
1411 * Nothing to report unless we are marked to build on top of
1412 * somebody else.
1414 if (!branch ||
1415 !branch->merge || !branch->merge[0] || !branch->merge[0]->dst)
1416 return 0;
1419 * If what we used to build on no longer exists, there is
1420 * nothing to report.
1422 base = branch->merge[0]->dst;
1423 if (!resolve_ref(base, sha1, 1, NULL))
1424 return 0;
1425 theirs = lookup_commit_reference(sha1);
1426 if (!theirs)
1427 return 0;
1429 if (!resolve_ref(branch->refname, sha1, 1, NULL))
1430 return 0;
1431 ours = lookup_commit_reference(sha1);
1432 if (!ours)
1433 return 0;
1435 /* are we the same? */
1436 if (theirs == ours)
1437 return 0;
1439 /* Run "rev-list --left-right ours...theirs" internally... */
1440 rev_argc = 0;
1441 rev_argv[rev_argc++] = NULL;
1442 rev_argv[rev_argc++] = "--left-right";
1443 rev_argv[rev_argc++] = symmetric;
1444 rev_argv[rev_argc++] = "--";
1445 rev_argv[rev_argc] = NULL;
1447 strcpy(symmetric, sha1_to_hex(ours->object.sha1));
1448 strcpy(symmetric + 40, "...");
1449 strcpy(symmetric + 43, sha1_to_hex(theirs->object.sha1));
1451 init_revisions(&revs, NULL);
1452 setup_revisions(rev_argc, rev_argv, &revs, NULL);
1453 prepare_revision_walk(&revs);
1455 /* ... and count the commits on each side. */
1456 *num_ours = 0;
1457 *num_theirs = 0;
1458 while (1) {
1459 struct commit *c = get_revision(&revs);
1460 if (!c)
1461 break;
1462 if (c->object.flags & SYMMETRIC_LEFT)
1463 (*num_ours)++;
1464 else
1465 (*num_theirs)++;
1468 /* clear object flags smudged by the above traversal */
1469 clear_commit_marks(ours, ALL_REV_FLAGS);
1470 clear_commit_marks(theirs, ALL_REV_FLAGS);
1471 return 1;
1475 * Return true when there is anything to report, otherwise false.
1477 int format_tracking_info(struct branch *branch, struct strbuf *sb)
1479 int num_ours, num_theirs;
1480 const char *base;
1482 if (!stat_tracking_info(branch, &num_ours, &num_theirs))
1483 return 0;
1485 base = branch->merge[0]->dst;
1486 base = shorten_unambiguous_ref(base, 0);
1487 if (!num_theirs)
1488 strbuf_addf(sb, "Your branch is ahead of '%s' "
1489 "by %d commit%s.\n",
1490 base, num_ours, (num_ours == 1) ? "" : "s");
1491 else if (!num_ours)
1492 strbuf_addf(sb, "Your branch is behind '%s' "
1493 "by %d commit%s, "
1494 "and can be fast-forwarded.\n",
1495 base, num_theirs, (num_theirs == 1) ? "" : "s");
1496 else
1497 strbuf_addf(sb, "Your branch and '%s' have diverged,\n"
1498 "and have %d and %d different commit(s) each, "
1499 "respectively.\n",
1500 base, num_ours, num_theirs);
1501 return 1;
1504 static int one_local_ref(const char *refname, const unsigned char *sha1, int flag, void *cb_data)
1506 struct ref ***local_tail = cb_data;
1507 struct ref *ref;
1508 int len;
1510 /* we already know it starts with refs/ to get here */
1511 if (check_ref_format(refname + 5))
1512 return 0;
1514 len = strlen(refname) + 1;
1515 ref = xcalloc(1, sizeof(*ref) + len);
1516 hashcpy(ref->new_sha1, sha1);
1517 memcpy(ref->name, refname, len);
1518 **local_tail = ref;
1519 *local_tail = &ref->next;
1520 return 0;
1523 struct ref *get_local_heads(void)
1525 struct ref *local_refs = NULL, **local_tail = &local_refs;
1526 for_each_ref(one_local_ref, &local_tail);
1527 return local_refs;
1530 struct ref *guess_remote_head(const struct ref *head,
1531 const struct ref *refs,
1532 int all)
1534 const struct ref *r;
1535 struct ref *list = NULL;
1536 struct ref **tail = &list;
1538 if (!head)
1539 return NULL;
1542 * Some transports support directly peeking at
1543 * where HEAD points; if that is the case, then
1544 * we don't have to guess.
1546 if (head->symref)
1547 return copy_ref(find_ref_by_name(refs, head->symref));
1549 /* If refs/heads/master could be right, it is. */
1550 if (!all) {
1551 r = find_ref_by_name(refs, "refs/heads/master");
1552 if (r && !hashcmp(r->old_sha1, head->old_sha1))
1553 return copy_ref(r);
1556 /* Look for another ref that points there */
1557 for (r = refs; r; r = r->next) {
1558 if (r != head && !hashcmp(r->old_sha1, head->old_sha1)) {
1559 *tail = copy_ref(r);
1560 tail = &((*tail)->next);
1561 if (!all)
1562 break;
1566 return list;