git repack: keep commits hidden by a graft
[git/dscho.git] / remote.c
blob5e21da39853cbe9d2a318ace9774701a5ce7e34d
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 ret->track = git_branch_track;
135 return ret;
138 static void add_merge(struct branch *branch, const char *name)
140 ALLOC_GROW(branch->merge_name, branch->merge_nr + 1,
141 branch->merge_alloc);
142 branch->merge_name[branch->merge_nr++] = name;
145 static struct branch *make_branch(const char *name, int len)
147 struct branch *ret;
148 int i;
149 char *refname;
151 for (i = 0; i < branches_nr; i++) {
152 if (len ? (!strncmp(name, branches[i]->name, len) &&
153 !branches[i]->name[len]) :
154 !strcmp(name, branches[i]->name))
155 return branches[i];
158 ALLOC_GROW(branches, branches_nr + 1, branches_alloc);
159 ret = xcalloc(1, sizeof(struct branch));
160 branches[branches_nr++] = ret;
161 if (len)
162 ret->name = xstrndup(name, len);
163 else
164 ret->name = xstrdup(name);
165 refname = xmalloc(strlen(name) + strlen("refs/heads/") + 1);
166 strcpy(refname, "refs/heads/");
167 strcpy(refname + strlen("refs/heads/"), ret->name);
168 ret->refname = refname;
170 return ret;
173 static struct rewrite *make_rewrite(const char *base, int len)
175 struct rewrite *ret;
176 int i;
178 for (i = 0; i < rewrite_nr; i++) {
179 if (len
180 ? (len == rewrite[i]->baselen &&
181 !strncmp(base, rewrite[i]->base, len))
182 : !strcmp(base, rewrite[i]->base))
183 return rewrite[i];
186 ALLOC_GROW(rewrite, rewrite_nr + 1, rewrite_alloc);
187 ret = xcalloc(1, sizeof(struct rewrite));
188 rewrite[rewrite_nr++] = ret;
189 if (len) {
190 ret->base = xstrndup(base, len);
191 ret->baselen = len;
193 else {
194 ret->base = xstrdup(base);
195 ret->baselen = strlen(base);
197 return ret;
200 static void add_instead_of(struct rewrite *rewrite, const char *instead_of)
202 ALLOC_GROW(rewrite->instead_of, rewrite->instead_of_nr + 1, rewrite->instead_of_alloc);
203 rewrite->instead_of[rewrite->instead_of_nr].s = instead_of;
204 rewrite->instead_of[rewrite->instead_of_nr].len = strlen(instead_of);
205 rewrite->instead_of_nr++;
208 static void read_remotes_file(struct remote *remote)
210 FILE *f = fopen(git_path("remotes/%s", remote->name), "r");
212 if (!f)
213 return;
214 remote->origin = REMOTE_REMOTES;
215 while (fgets(buffer, BUF_SIZE, f)) {
216 int value_list;
217 char *s, *p;
219 if (!prefixcmp(buffer, "URL:")) {
220 value_list = 0;
221 s = buffer + 4;
222 } else if (!prefixcmp(buffer, "Push:")) {
223 value_list = 1;
224 s = buffer + 5;
225 } else if (!prefixcmp(buffer, "Pull:")) {
226 value_list = 2;
227 s = buffer + 5;
228 } else
229 continue;
231 while (isspace(*s))
232 s++;
233 if (!*s)
234 continue;
236 p = s + strlen(s);
237 while (isspace(p[-1]))
238 *--p = 0;
240 switch (value_list) {
241 case 0:
242 add_url_alias(remote, xstrdup(s));
243 break;
244 case 1:
245 add_push_refspec(remote, xstrdup(s));
246 break;
247 case 2:
248 add_fetch_refspec(remote, xstrdup(s));
249 break;
252 fclose(f);
255 static void read_branches_file(struct remote *remote)
257 const char *slash = strchr(remote->name, '/');
258 char *frag;
259 struct strbuf branch = STRBUF_INIT;
260 int n = slash ? slash - remote->name : 1000;
261 FILE *f = fopen(git_path("branches/%.*s", n, remote->name), "r");
262 char *s, *p;
263 int len;
265 if (!f)
266 return;
267 s = fgets(buffer, BUF_SIZE, f);
268 fclose(f);
269 if (!s)
270 return;
271 while (isspace(*s))
272 s++;
273 if (!*s)
274 return;
275 remote->origin = REMOTE_BRANCHES;
276 p = s + strlen(s);
277 while (isspace(p[-1]))
278 *--p = 0;
279 len = p - s;
280 if (slash)
281 len += strlen(slash);
282 p = xmalloc(len + 1);
283 strcpy(p, s);
284 if (slash)
285 strcat(p, slash);
288 * With "slash", e.g. "git fetch jgarzik/netdev-2.6" when
289 * reading from $GIT_DIR/branches/jgarzik fetches "HEAD" from
290 * the partial URL obtained from the branches file plus
291 * "/netdev-2.6" and does not store it in any tracking ref.
292 * #branch specifier in the file is ignored.
294 * Otherwise, the branches file would have URL and optionally
295 * #branch specified. The "master" (or specified) branch is
296 * fetched and stored in the local branch of the same name.
298 frag = strchr(p, '#');
299 if (frag) {
300 *(frag++) = '\0';
301 strbuf_addf(&branch, "refs/heads/%s", frag);
302 } else
303 strbuf_addstr(&branch, "refs/heads/master");
304 if (!slash) {
305 strbuf_addf(&branch, ":refs/heads/%s", remote->name);
306 } else {
307 strbuf_reset(&branch);
308 strbuf_addstr(&branch, "HEAD:");
310 add_url_alias(remote, p);
311 add_fetch_refspec(remote, strbuf_detach(&branch, NULL));
313 * Cogito compatible push: push current HEAD to remote #branch
314 * (master if missing)
316 strbuf_init(&branch, 0);
317 strbuf_addstr(&branch, "HEAD");
318 if (frag)
319 strbuf_addf(&branch, ":refs/heads/%s", frag);
320 else
321 strbuf_addstr(&branch, ":refs/heads/master");
322 add_push_refspec(remote, strbuf_detach(&branch, NULL));
323 remote->fetch_tags = 1; /* always auto-follow */
326 static int handle_config(const char *key, const char *value, void *cb)
328 const char *name;
329 const char *subkey;
330 struct remote *remote;
331 struct branch *branch;
332 if (!prefixcmp(key, "branch.")) {
333 name = key + 7;
334 subkey = strrchr(name, '.');
335 if (!subkey)
336 return 0;
337 branch = make_branch(name, subkey - name);
338 if (!strcmp(subkey, ".remote")) {
339 if (!value)
340 return config_error_nonbool(key);
341 branch->remote_name = xstrdup(value);
342 if (branch == current_branch) {
343 default_remote_name = branch->remote_name;
344 explicit_default_remote_name = 1;
346 } else if (!strcmp(subkey, ".merge")) {
347 if (!value)
348 return config_error_nonbool(key);
349 add_merge(branch, xstrdup(value));
351 return 0;
353 if (!prefixcmp(key, "url.")) {
354 struct rewrite *rewrite;
355 name = key + 4;
356 subkey = strrchr(name, '.');
357 if (!subkey)
358 return 0;
359 rewrite = make_rewrite(name, subkey - name);
360 if (!strcmp(subkey, ".insteadof")) {
361 if (!value)
362 return config_error_nonbool(key);
363 add_instead_of(rewrite, xstrdup(value));
366 if (prefixcmp(key, "remote."))
367 return 0;
368 name = key + 7;
369 if (*name == '/') {
370 warning("Config remote shorthand cannot begin with '/': %s",
371 name);
372 return 0;
374 subkey = strrchr(name, '.');
375 if (!subkey)
376 return 0;
377 remote = make_remote(name, subkey - name);
378 remote->origin = REMOTE_CONFIG;
379 if (git_tracking_config(key, value, &remote->track))
380 return -1;
381 if (!strcmp(subkey, ".mirror"))
382 remote->mirror = git_config_bool(key, value);
383 else if (!strcmp(subkey, ".skipdefaultupdate"))
384 remote->skip_default_update = git_config_bool(key, value);
386 else if (!strcmp(subkey, ".url")) {
387 const char *v;
388 if (git_config_string(&v, key, value))
389 return -1;
390 add_url(remote, v);
391 } else if (!strcmp(subkey, ".pushurl")) {
392 const char *v;
393 if (git_config_string(&v, key, value))
394 return -1;
395 add_pushurl(remote, v);
396 } else if (!strcmp(subkey, ".push")) {
397 const char *v;
398 if (git_config_string(&v, key, value))
399 return -1;
400 add_push_refspec(remote, v);
401 } else if (!strcmp(subkey, ".fetch")) {
402 const char *v;
403 if (git_config_string(&v, key, value))
404 return -1;
405 add_fetch_refspec(remote, v);
406 } else if (!strcmp(subkey, ".receivepack")) {
407 const char *v;
408 if (git_config_string(&v, key, value))
409 return -1;
410 if (!remote->receivepack)
411 remote->receivepack = v;
412 else
413 error("more than one receivepack given, using the first");
414 } else if (!strcmp(subkey, ".uploadpack")) {
415 const char *v;
416 if (git_config_string(&v, key, value))
417 return -1;
418 if (!remote->uploadpack)
419 remote->uploadpack = v;
420 else
421 error("more than one uploadpack given, using the first");
422 } else if (!strcmp(subkey, ".tagopt")) {
423 if (!strcmp(value, "--no-tags"))
424 remote->fetch_tags = -1;
425 } else if (!strcmp(subkey, ".proxy")) {
426 return git_config_string((const char **)&remote->http_proxy,
427 key, value);
429 return 0;
432 static void alias_all_urls(void)
434 int i, j;
435 for (i = 0; i < remotes_nr; i++) {
436 if (!remotes[i])
437 continue;
438 for (j = 0; j < remotes[i]->url_nr; j++) {
439 remotes[i]->url[j] = alias_url(remotes[i]->url[j]);
441 for (j = 0; j < remotes[i]->pushurl_nr; j++) {
442 remotes[i]->pushurl[j] = alias_url(remotes[i]->pushurl[j]);
447 static void read_config(void)
449 unsigned char sha1[20];
450 const char *head_ref;
451 int flag;
452 if (default_remote_name) // did this already
453 return;
454 default_remote_name = xstrdup("origin");
455 current_branch = NULL;
456 head_ref = resolve_ref("HEAD", sha1, 0, &flag);
457 if (head_ref && (flag & REF_ISSYMREF) &&
458 !prefixcmp(head_ref, "refs/heads/")) {
459 current_branch =
460 make_branch(head_ref + strlen("refs/heads/"), 0);
462 git_config(handle_config, NULL);
463 alias_all_urls();
467 * We need to make sure the tracking branches are well formed, but a
468 * wildcard refspec in "struct refspec" must have a trailing slash. We
469 * temporarily drop the trailing '/' while calling check_ref_format(),
470 * and put it back. The caller knows that a CHECK_REF_FORMAT_ONELEVEL
471 * error return is Ok for a wildcard refspec.
473 static int verify_refname(char *name, int is_glob)
475 int result;
477 result = check_ref_format(name);
478 if (is_glob && result == CHECK_REF_FORMAT_WILDCARD)
479 result = CHECK_REF_FORMAT_OK;
480 return result;
484 * This function frees a refspec array.
485 * Warning: code paths should be checked to ensure that the src
486 * and dst pointers are always freeable pointers as well
487 * as the refspec pointer itself.
489 static void free_refspecs(struct refspec *refspec, int nr_refspec)
491 int i;
493 if (!refspec)
494 return;
496 for (i = 0; i < nr_refspec; i++) {
497 free(refspec[i].src);
498 free(refspec[i].dst);
500 free(refspec);
503 static struct refspec *parse_refspec_internal(int nr_refspec, const char **refspec, int fetch, int verify)
505 int i;
506 int st;
507 struct refspec *rs = xcalloc(sizeof(*rs), nr_refspec);
509 for (i = 0; i < nr_refspec; i++) {
510 size_t llen;
511 int is_glob;
512 const char *lhs, *rhs;
514 is_glob = 0;
516 lhs = refspec[i];
517 if (*lhs == '+') {
518 rs[i].force = 1;
519 lhs++;
522 rhs = strrchr(lhs, ':');
525 * Before going on, special case ":" (or "+:") as a refspec
526 * for matching refs.
528 if (!fetch && rhs == lhs && rhs[1] == '\0') {
529 rs[i].matching = 1;
530 continue;
533 if (rhs) {
534 size_t rlen = strlen(++rhs);
535 is_glob = (1 <= rlen && strchr(rhs, '*'));
536 rs[i].dst = xstrndup(rhs, rlen);
539 llen = (rhs ? (rhs - lhs - 1) : strlen(lhs));
540 if (1 <= llen && memchr(lhs, '*', llen)) {
541 if ((rhs && !is_glob) || (!rhs && fetch))
542 goto invalid;
543 is_glob = 1;
544 } else if (rhs && is_glob) {
545 goto invalid;
548 rs[i].pattern = is_glob;
549 rs[i].src = xstrndup(lhs, llen);
551 if (fetch) {
553 * LHS
554 * - empty is allowed; it means HEAD.
555 * - otherwise it must be a valid looking ref.
557 if (!*rs[i].src)
558 ; /* empty is ok */
559 else {
560 st = verify_refname(rs[i].src, is_glob);
561 if (st && st != CHECK_REF_FORMAT_ONELEVEL)
562 goto invalid;
565 * RHS
566 * - missing is ok, and is same as empty.
567 * - empty is ok; it means not to store.
568 * - otherwise it must be a valid looking ref.
570 if (!rs[i].dst) {
571 ; /* ok */
572 } else if (!*rs[i].dst) {
573 ; /* ok */
574 } else {
575 st = verify_refname(rs[i].dst, is_glob);
576 if (st && st != CHECK_REF_FORMAT_ONELEVEL)
577 goto invalid;
579 } else {
581 * LHS
582 * - empty is allowed; it means delete.
583 * - when wildcarded, it must be a valid looking ref.
584 * - otherwise, it must be an extended SHA-1, but
585 * there is no existing way to validate this.
587 if (!*rs[i].src)
588 ; /* empty is ok */
589 else if (is_glob) {
590 st = verify_refname(rs[i].src, is_glob);
591 if (st && st != CHECK_REF_FORMAT_ONELEVEL)
592 goto invalid;
594 else
595 ; /* anything goes, for now */
597 * RHS
598 * - missing is allowed, but LHS then must be a
599 * valid looking ref.
600 * - empty is not allowed.
601 * - otherwise it must be a valid looking ref.
603 if (!rs[i].dst) {
604 st = verify_refname(rs[i].src, is_glob);
605 if (st && st != CHECK_REF_FORMAT_ONELEVEL)
606 goto invalid;
607 } else if (!*rs[i].dst) {
608 goto invalid;
609 } else {
610 st = verify_refname(rs[i].dst, is_glob);
611 if (st && st != CHECK_REF_FORMAT_ONELEVEL)
612 goto invalid;
616 return rs;
618 invalid:
619 if (verify) {
621 * nr_refspec must be greater than zero and i must be valid
622 * since it is only possible to reach this point from within
623 * the for loop above.
625 free_refspecs(rs, i+1);
626 return NULL;
628 die("Invalid refspec '%s'", refspec[i]);
631 int valid_fetch_refspec(const char *fetch_refspec_str)
633 const char *fetch_refspec[] = { fetch_refspec_str };
634 struct refspec *refspec;
636 refspec = parse_refspec_internal(1, fetch_refspec, 1, 1);
637 free_refspecs(refspec, 1);
638 return !!refspec;
641 struct refspec *parse_fetch_refspec(int nr_refspec, const char **refspec)
643 return parse_refspec_internal(nr_refspec, refspec, 1, 0);
646 static struct refspec *parse_push_refspec(int nr_refspec, const char **refspec)
648 return parse_refspec_internal(nr_refspec, refspec, 0, 0);
651 static int valid_remote_nick(const char *name)
653 if (!name[0] || is_dot_or_dotdot(name))
654 return 0;
655 return !strchr(name, '/'); /* no slash */
658 struct remote *remote_get(const char *name)
660 struct remote *ret;
661 int name_given = 0;
663 read_config();
664 if (name)
665 name_given = 1;
666 else {
667 name = default_remote_name;
668 name_given = explicit_default_remote_name;
671 ret = make_remote(name, 0);
672 if (valid_remote_nick(name)) {
673 if (!ret->url)
674 read_remotes_file(ret);
675 if (!ret->url)
676 read_branches_file(ret);
678 if (name_given && !ret->url)
679 add_url_alias(ret, name);
680 if (!ret->url)
681 return NULL;
682 ret->fetch = parse_fetch_refspec(ret->fetch_refspec_nr, ret->fetch_refspec);
683 ret->push = parse_push_refspec(ret->push_refspec_nr, ret->push_refspec);
684 return ret;
687 int remote_is_configured(const char *name)
689 int i;
690 read_config();
692 for (i = 0; i < remotes_nr; i++)
693 if (!strcmp(name, remotes[i]->name))
694 return 1;
695 return 0;
698 int for_each_remote(each_remote_fn fn, void *priv)
700 int i, result = 0;
701 read_config();
702 for (i = 0; i < remotes_nr && !result; i++) {
703 struct remote *r = remotes[i];
704 if (!r)
705 continue;
706 if (!r->fetch)
707 r->fetch = parse_fetch_refspec(r->fetch_refspec_nr,
708 r->fetch_refspec);
709 if (!r->push)
710 r->push = parse_push_refspec(r->push_refspec_nr,
711 r->push_refspec);
712 result = fn(r, priv);
714 return result;
717 void ref_remove_duplicates(struct ref *ref_map)
719 struct ref **posn;
720 struct ref *next;
721 for (; ref_map; ref_map = ref_map->next) {
722 if (!ref_map->peer_ref)
723 continue;
724 posn = &ref_map->next;
725 while (*posn) {
726 if ((*posn)->peer_ref &&
727 !strcmp((*posn)->peer_ref->name,
728 ref_map->peer_ref->name)) {
729 if (strcmp((*posn)->name, ref_map->name))
730 die("%s tracks both %s and %s",
731 ref_map->peer_ref->name,
732 (*posn)->name, ref_map->name);
733 next = (*posn)->next;
734 free((*posn)->peer_ref);
735 free(*posn);
736 *posn = next;
737 } else {
738 posn = &(*posn)->next;
744 int remote_has_url(struct remote *remote, const char *url)
746 int i;
747 for (i = 0; i < remote->url_nr; i++) {
748 if (!strcmp(remote->url[i], url))
749 return 1;
751 return 0;
754 static int match_name_with_pattern(const char *key, const char *name,
755 const char *value, char **result)
757 const char *kstar = strchr(key, '*');
758 size_t klen;
759 size_t ksuffixlen;
760 size_t namelen;
761 int ret;
762 if (!kstar)
763 die("Key '%s' of pattern had no '*'", key);
764 klen = kstar - key;
765 ksuffixlen = strlen(kstar + 1);
766 namelen = strlen(name);
767 ret = !strncmp(name, key, klen) && namelen >= klen + ksuffixlen &&
768 !memcmp(name + namelen - ksuffixlen, kstar + 1, ksuffixlen);
769 if (ret && value) {
770 const char *vstar = strchr(value, '*');
771 size_t vlen;
772 size_t vsuffixlen;
773 if (!vstar)
774 die("Value '%s' of pattern has no '*'", value);
775 vlen = vstar - value;
776 vsuffixlen = strlen(vstar + 1);
777 *result = xmalloc(vlen + vsuffixlen +
778 strlen(name) -
779 klen - ksuffixlen + 1);
780 strncpy(*result, value, vlen);
781 strncpy(*result + vlen,
782 name + klen, namelen - klen - ksuffixlen);
783 strcpy(*result + vlen + namelen - klen - ksuffixlen,
784 vstar + 1);
786 return ret;
789 int remote_find_tracking(struct remote *remote, struct refspec *refspec)
791 int find_src = refspec->src == NULL;
792 char *needle, **result;
793 int i;
795 if (find_src) {
796 if (!refspec->dst)
797 return error("find_tracking: need either src or dst");
798 needle = refspec->dst;
799 result = &refspec->src;
800 } else {
801 needle = refspec->src;
802 result = &refspec->dst;
805 for (i = 0; i < remote->fetch_refspec_nr; i++) {
806 struct refspec *fetch = &remote->fetch[i];
807 const char *key = find_src ? fetch->dst : fetch->src;
808 const char *value = find_src ? fetch->src : fetch->dst;
809 if (!fetch->dst)
810 continue;
811 if (fetch->pattern) {
812 if (match_name_with_pattern(key, needle, value, result)) {
813 refspec->force = fetch->force;
814 return 0;
816 } else if (!strcmp(needle, key)) {
817 *result = xstrdup(value);
818 refspec->force = fetch->force;
819 return 0;
822 return -1;
825 static struct ref *alloc_ref_with_prefix(const char *prefix, size_t prefixlen,
826 const char *name)
828 size_t len = strlen(name);
829 struct ref *ref = xcalloc(1, sizeof(struct ref) + prefixlen + len + 1);
830 memcpy(ref->name, prefix, prefixlen);
831 memcpy(ref->name + prefixlen, name, len);
832 return ref;
835 struct ref *alloc_ref(const char *name)
837 return alloc_ref_with_prefix("", 0, name);
840 static struct ref *copy_ref(const struct ref *ref)
842 struct ref *cpy;
843 size_t len;
844 if (!ref)
845 return NULL;
846 len = strlen(ref->name);
847 cpy = xmalloc(sizeof(struct ref) + len + 1);
848 memcpy(cpy, ref, sizeof(struct ref) + len + 1);
849 cpy->next = NULL;
850 cpy->symref = ref->symref ? xstrdup(ref->symref) : NULL;
851 cpy->remote_status = ref->remote_status ? xstrdup(ref->remote_status) : NULL;
852 cpy->peer_ref = copy_ref(ref->peer_ref);
853 return cpy;
856 struct ref *copy_ref_list(const struct ref *ref)
858 struct ref *ret = NULL;
859 struct ref **tail = &ret;
860 while (ref) {
861 *tail = copy_ref(ref);
862 ref = ref->next;
863 tail = &((*tail)->next);
865 return ret;
868 static void free_ref(struct ref *ref)
870 if (!ref)
871 return;
872 free_ref(ref->peer_ref);
873 free(ref->remote_status);
874 free(ref->symref);
875 free(ref);
878 void free_refs(struct ref *ref)
880 struct ref *next;
881 while (ref) {
882 next = ref->next;
883 free_ref(ref);
884 ref = next;
888 static int count_refspec_match(const char *pattern,
889 struct ref *refs,
890 struct ref **matched_ref)
892 int patlen = strlen(pattern);
893 struct ref *matched_weak = NULL;
894 struct ref *matched = NULL;
895 int weak_match = 0;
896 int match = 0;
898 for (weak_match = match = 0; refs; refs = refs->next) {
899 char *name = refs->name;
900 int namelen = strlen(name);
902 if (!refname_match(pattern, name, ref_rev_parse_rules))
903 continue;
905 /* A match is "weak" if it is with refs outside
906 * heads or tags, and did not specify the pattern
907 * in full (e.g. "refs/remotes/origin/master") or at
908 * least from the toplevel (e.g. "remotes/origin/master");
909 * otherwise "git push $URL master" would result in
910 * ambiguity between remotes/origin/master and heads/master
911 * at the remote site.
913 if (namelen != patlen &&
914 patlen != namelen - 5 &&
915 prefixcmp(name, "refs/heads/") &&
916 prefixcmp(name, "refs/tags/")) {
917 /* We want to catch the case where only weak
918 * matches are found and there are multiple
919 * matches, and where more than one strong
920 * matches are found, as ambiguous. One
921 * strong match with zero or more weak matches
922 * are acceptable as a unique match.
924 matched_weak = refs;
925 weak_match++;
927 else {
928 matched = refs;
929 match++;
932 if (!matched) {
933 *matched_ref = matched_weak;
934 return weak_match;
936 else {
937 *matched_ref = matched;
938 return match;
942 static void tail_link_ref(struct ref *ref, struct ref ***tail)
944 **tail = ref;
945 while (ref->next)
946 ref = ref->next;
947 *tail = &ref->next;
950 static struct ref *try_explicit_object_name(const char *name)
952 unsigned char sha1[20];
953 struct ref *ref;
955 if (!*name) {
956 ref = alloc_ref("(delete)");
957 hashclr(ref->new_sha1);
958 return ref;
960 if (get_sha1(name, sha1))
961 return NULL;
962 ref = alloc_ref(name);
963 hashcpy(ref->new_sha1, sha1);
964 return ref;
967 static struct ref *make_linked_ref(const char *name, struct ref ***tail)
969 struct ref *ret = alloc_ref(name);
970 tail_link_ref(ret, tail);
971 return ret;
974 static char *guess_ref(const char *name, struct ref *peer)
976 struct strbuf buf = STRBUF_INIT;
977 unsigned char sha1[20];
979 const char *r = resolve_ref(peer->name, sha1, 1, NULL);
980 if (!r)
981 return NULL;
983 if (!prefixcmp(r, "refs/heads/"))
984 strbuf_addstr(&buf, "refs/heads/");
985 else if (!prefixcmp(r, "refs/tags/"))
986 strbuf_addstr(&buf, "refs/tags/");
987 else
988 return NULL;
990 strbuf_addstr(&buf, name);
991 return strbuf_detach(&buf, NULL);
994 static int match_explicit(struct ref *src, struct ref *dst,
995 struct ref ***dst_tail,
996 struct refspec *rs)
998 struct ref *matched_src, *matched_dst;
999 int copy_src;
1001 const char *dst_value = rs->dst;
1002 char *dst_guess;
1004 if (rs->pattern || rs->matching)
1005 return 0;
1007 matched_src = matched_dst = NULL;
1008 switch (count_refspec_match(rs->src, src, &matched_src)) {
1009 case 1:
1010 copy_src = 1;
1011 break;
1012 case 0:
1013 /* The source could be in the get_sha1() format
1014 * not a reference name. :refs/other is a
1015 * way to delete 'other' ref at the remote end.
1017 matched_src = try_explicit_object_name(rs->src);
1018 if (!matched_src)
1019 return error("src refspec %s does not match any.", rs->src);
1020 copy_src = 0;
1021 break;
1022 default:
1023 return error("src refspec %s matches more than one.", rs->src);
1026 if (!dst_value) {
1027 unsigned char sha1[20];
1028 int flag;
1030 dst_value = resolve_ref(matched_src->name, sha1, 1, &flag);
1031 if (!dst_value ||
1032 ((flag & REF_ISSYMREF) &&
1033 prefixcmp(dst_value, "refs/heads/")))
1034 die("%s cannot be resolved to branch.",
1035 matched_src->name);
1038 switch (count_refspec_match(dst_value, dst, &matched_dst)) {
1039 case 1:
1040 break;
1041 case 0:
1042 if (!memcmp(dst_value, "refs/", 5))
1043 matched_dst = make_linked_ref(dst_value, dst_tail);
1044 else if((dst_guess = guess_ref(dst_value, matched_src)))
1045 matched_dst = make_linked_ref(dst_guess, dst_tail);
1046 else
1047 error("unable to push to unqualified destination: %s\n"
1048 "The destination refspec neither matches an "
1049 "existing ref on the remote nor\n"
1050 "begins with refs/, and we are unable to "
1051 "guess a prefix based on the source ref.",
1052 dst_value);
1053 break;
1054 default:
1055 matched_dst = NULL;
1056 error("dst refspec %s matches more than one.",
1057 dst_value);
1058 break;
1060 if (!matched_dst)
1061 return -1;
1062 if (matched_dst->peer_ref)
1063 return error("dst ref %s receives from more than one src.",
1064 matched_dst->name);
1065 else {
1066 matched_dst->peer_ref = copy_src ? copy_ref(matched_src) : matched_src;
1067 matched_dst->force = rs->force;
1069 return 0;
1072 static int match_explicit_refs(struct ref *src, struct ref *dst,
1073 struct ref ***dst_tail, struct refspec *rs,
1074 int rs_nr)
1076 int i, errs;
1077 for (i = errs = 0; i < rs_nr; i++)
1078 errs += match_explicit(src, dst, dst_tail, &rs[i]);
1079 return errs;
1082 static const struct refspec *check_pattern_match(const struct refspec *rs,
1083 int rs_nr,
1084 const struct ref *src)
1086 int i;
1087 int matching_refs = -1;
1088 for (i = 0; i < rs_nr; i++) {
1089 if (rs[i].matching &&
1090 (matching_refs == -1 || rs[i].force)) {
1091 matching_refs = i;
1092 continue;
1095 if (rs[i].pattern && match_name_with_pattern(rs[i].src, src->name,
1096 NULL, NULL))
1097 return rs + i;
1099 if (matching_refs != -1)
1100 return rs + matching_refs;
1101 else
1102 return NULL;
1105 static struct ref **tail_ref(struct ref **head)
1107 struct ref **tail = head;
1108 while (*tail)
1109 tail = &((*tail)->next);
1110 return tail;
1114 * Note. This is used only by "push"; refspec matching rules for
1115 * push and fetch are subtly different, so do not try to reuse it
1116 * without thinking.
1118 int match_refs(struct ref *src, struct ref **dst,
1119 int nr_refspec, const char **refspec, int flags)
1121 struct refspec *rs;
1122 int send_all = flags & MATCH_REFS_ALL;
1123 int send_mirror = flags & MATCH_REFS_MIRROR;
1124 int errs;
1125 static const char *default_refspec[] = { ":", NULL };
1126 struct ref **dst_tail = tail_ref(dst);
1128 if (!nr_refspec) {
1129 nr_refspec = 1;
1130 refspec = default_refspec;
1132 rs = parse_push_refspec(nr_refspec, (const char **) refspec);
1133 errs = match_explicit_refs(src, *dst, &dst_tail, rs, nr_refspec);
1135 /* pick the remainder */
1136 for ( ; src; src = src->next) {
1137 struct ref *dst_peer;
1138 const struct refspec *pat = NULL;
1139 char *dst_name;
1140 if (src->peer_ref)
1141 continue;
1143 pat = check_pattern_match(rs, nr_refspec, src);
1144 if (!pat)
1145 continue;
1147 if (pat->matching) {
1149 * "matching refs"; traditionally we pushed everything
1150 * including refs outside refs/heads/ hierarchy, but
1151 * that does not make much sense these days.
1153 if (!send_mirror && prefixcmp(src->name, "refs/heads/"))
1154 continue;
1155 dst_name = xstrdup(src->name);
1157 } else {
1158 const char *dst_side = pat->dst ? pat->dst : pat->src;
1159 if (!match_name_with_pattern(pat->src, src->name,
1160 dst_side, &dst_name))
1161 die("Didn't think it matches any more");
1163 dst_peer = find_ref_by_name(*dst, dst_name);
1164 if (dst_peer) {
1165 if (dst_peer->peer_ref)
1166 /* We're already sending something to this ref. */
1167 goto free_name;
1169 } else {
1170 if (pat->matching && !(send_all || send_mirror))
1172 * Remote doesn't have it, and we have no
1173 * explicit pattern, and we don't have
1174 * --all nor --mirror.
1176 goto free_name;
1178 /* Create a new one and link it */
1179 dst_peer = make_linked_ref(dst_name, &dst_tail);
1180 hashcpy(dst_peer->new_sha1, src->new_sha1);
1182 dst_peer->peer_ref = copy_ref(src);
1183 dst_peer->force = pat->force;
1184 free_name:
1185 free(dst_name);
1187 if (errs)
1188 return -1;
1189 return 0;
1192 struct branch *branch_get(const char *name)
1194 struct branch *ret;
1196 read_config();
1197 if (!name || !*name || !strcmp(name, "HEAD"))
1198 ret = current_branch;
1199 else
1200 ret = make_branch(name, 0);
1201 if (ret && ret->remote_name) {
1202 ret->remote = remote_get(ret->remote_name);
1203 if (ret->merge_nr) {
1204 int i;
1205 ret->merge = xcalloc(sizeof(*ret->merge),
1206 ret->merge_nr);
1207 for (i = 0; i < ret->merge_nr; i++) {
1208 ret->merge[i] = xcalloc(1, sizeof(**ret->merge));
1209 ret->merge[i]->src = xstrdup(ret->merge_name[i]);
1210 if (remote_find_tracking(ret->remote, ret->merge[i])
1211 && !strcmp(ret->remote_name, "."))
1212 ret->merge[i]->dst = xstrdup(ret->merge_name[i]);
1216 return ret;
1219 int branch_has_merge_config(struct branch *branch)
1221 return branch && !!branch->merge;
1224 int branch_merge_matches(struct branch *branch,
1225 int i,
1226 const char *refname)
1228 if (!branch || i < 0 || i >= branch->merge_nr)
1229 return 0;
1230 return refname_match(branch->merge[i]->src, refname, ref_fetch_rules);
1233 static struct ref *get_expanded_map(const struct ref *remote_refs,
1234 const struct refspec *refspec)
1236 const struct ref *ref;
1237 struct ref *ret = NULL;
1238 struct ref **tail = &ret;
1240 char *expn_name;
1242 for (ref = remote_refs; ref; ref = ref->next) {
1243 if (strchr(ref->name, '^'))
1244 continue; /* a dereference item */
1245 if (match_name_with_pattern(refspec->src, ref->name,
1246 refspec->dst, &expn_name)) {
1247 struct ref *cpy = copy_ref(ref);
1249 cpy->peer_ref = alloc_ref(expn_name);
1250 free(expn_name);
1251 if (refspec->force)
1252 cpy->peer_ref->force = 1;
1253 *tail = cpy;
1254 tail = &cpy->next;
1258 return ret;
1261 static const struct ref *find_ref_by_name_abbrev(const struct ref *refs, const char *name)
1263 const struct ref *ref;
1264 for (ref = refs; ref; ref = ref->next) {
1265 if (refname_match(name, ref->name, ref_fetch_rules))
1266 return ref;
1268 return NULL;
1271 struct ref *get_remote_ref(const struct ref *remote_refs, const char *name)
1273 const struct ref *ref = find_ref_by_name_abbrev(remote_refs, name);
1275 if (!ref)
1276 return NULL;
1278 return copy_ref(ref);
1281 static struct ref *get_local_ref(const char *name)
1283 if (!name || name[0] == '\0')
1284 return NULL;
1286 if (!prefixcmp(name, "refs/"))
1287 return alloc_ref(name);
1289 if (!prefixcmp(name, "heads/") ||
1290 !prefixcmp(name, "tags/") ||
1291 !prefixcmp(name, "remotes/"))
1292 return alloc_ref_with_prefix("refs/", 5, name);
1294 return alloc_ref_with_prefix("refs/heads/", 11, name);
1297 int get_fetch_map(const struct ref *remote_refs,
1298 const struct refspec *refspec,
1299 struct ref ***tail,
1300 int missing_ok)
1302 struct ref *ref_map, **rmp;
1304 if (refspec->pattern) {
1305 ref_map = get_expanded_map(remote_refs, refspec);
1306 } else {
1307 const char *name = refspec->src[0] ? refspec->src : "HEAD";
1309 ref_map = get_remote_ref(remote_refs, name);
1310 if (!missing_ok && !ref_map)
1311 die("Couldn't find remote ref %s", name);
1312 if (ref_map) {
1313 ref_map->peer_ref = get_local_ref(refspec->dst);
1314 if (ref_map->peer_ref && refspec->force)
1315 ref_map->peer_ref->force = 1;
1319 for (rmp = &ref_map; *rmp; ) {
1320 if ((*rmp)->peer_ref) {
1321 int st = check_ref_format((*rmp)->peer_ref->name + 5);
1322 if (st && st != CHECK_REF_FORMAT_ONELEVEL) {
1323 struct ref *ignore = *rmp;
1324 error("* Ignoring funny ref '%s' locally",
1325 (*rmp)->peer_ref->name);
1326 *rmp = (*rmp)->next;
1327 free(ignore->peer_ref);
1328 free(ignore);
1329 continue;
1332 rmp = &((*rmp)->next);
1335 if (ref_map)
1336 tail_link_ref(ref_map, tail);
1338 return 0;
1341 int resolve_remote_symref(struct ref *ref, struct ref *list)
1343 if (!ref->symref)
1344 return 0;
1345 for (; list; list = list->next)
1346 if (!strcmp(ref->symref, list->name)) {
1347 hashcpy(ref->old_sha1, list->old_sha1);
1348 return 0;
1350 return 1;
1353 static void unmark_and_free(struct commit_list *list, unsigned int mark)
1355 while (list) {
1356 struct commit_list *temp = list;
1357 temp->item->object.flags &= ~mark;
1358 list = temp->next;
1359 free(temp);
1363 int ref_newer(const unsigned char *new_sha1, const unsigned char *old_sha1)
1365 struct object *o;
1366 struct commit *old, *new;
1367 struct commit_list *list, *used;
1368 int found = 0;
1370 /* Both new and old must be commit-ish and new is descendant of
1371 * old. Otherwise we require --force.
1373 o = deref_tag(parse_object(old_sha1), NULL, 0);
1374 if (!o || o->type != OBJ_COMMIT)
1375 return 0;
1376 old = (struct commit *) o;
1378 o = deref_tag(parse_object(new_sha1), NULL, 0);
1379 if (!o || o->type != OBJ_COMMIT)
1380 return 0;
1381 new = (struct commit *) o;
1383 if (parse_commit(new) < 0)
1384 return 0;
1386 used = list = NULL;
1387 commit_list_insert(new, &list);
1388 while (list) {
1389 new = pop_most_recent_commit(&list, TMP_MARK);
1390 commit_list_insert(new, &used);
1391 if (new == old) {
1392 found = 1;
1393 break;
1396 unmark_and_free(list, TMP_MARK);
1397 unmark_and_free(used, TMP_MARK);
1398 return found;
1402 * Return true if there is anything to report, otherwise false.
1404 int stat_tracking_info(struct branch *branch, int *num_ours, int *num_theirs)
1406 unsigned char sha1[20];
1407 struct commit *ours, *theirs;
1408 char symmetric[84];
1409 struct rev_info revs;
1410 const char *rev_argv[10], *base;
1411 int rev_argc;
1414 * Nothing to report unless we are marked to build on top of
1415 * somebody else.
1417 if (!branch ||
1418 !branch->merge || !branch->merge[0] || !branch->merge[0]->dst)
1419 return 0;
1422 * If what we used to build on no longer exists, there is
1423 * nothing to report.
1425 base = branch->merge[0]->dst;
1426 if (!resolve_ref(base, sha1, 1, NULL))
1427 return 0;
1428 theirs = lookup_commit_reference(sha1);
1429 if (!theirs)
1430 return 0;
1432 if (!resolve_ref(branch->refname, sha1, 1, NULL))
1433 return 0;
1434 ours = lookup_commit_reference(sha1);
1435 if (!ours)
1436 return 0;
1438 /* are we the same? */
1439 if (theirs == ours)
1440 return 0;
1442 /* Run "rev-list --left-right ours...theirs" internally... */
1443 rev_argc = 0;
1444 rev_argv[rev_argc++] = NULL;
1445 rev_argv[rev_argc++] = "--left-right";
1446 rev_argv[rev_argc++] = symmetric;
1447 rev_argv[rev_argc++] = "--";
1448 rev_argv[rev_argc] = NULL;
1450 strcpy(symmetric, sha1_to_hex(ours->object.sha1));
1451 strcpy(symmetric + 40, "...");
1452 strcpy(symmetric + 43, sha1_to_hex(theirs->object.sha1));
1454 init_revisions(&revs, NULL);
1455 setup_revisions(rev_argc, rev_argv, &revs, NULL);
1456 prepare_revision_walk(&revs);
1458 /* ... and count the commits on each side. */
1459 *num_ours = 0;
1460 *num_theirs = 0;
1461 while (1) {
1462 struct commit *c = get_revision(&revs);
1463 if (!c)
1464 break;
1465 if (c->object.flags & SYMMETRIC_LEFT)
1466 (*num_ours)++;
1467 else
1468 (*num_theirs)++;
1471 /* clear object flags smudged by the above traversal */
1472 clear_commit_marks(ours, ALL_REV_FLAGS);
1473 clear_commit_marks(theirs, ALL_REV_FLAGS);
1474 return 1;
1478 * Return true when there is anything to report, otherwise false.
1480 int format_tracking_info(struct branch *branch, struct strbuf *sb)
1482 int num_ours, num_theirs;
1483 const char *base;
1485 if (!stat_tracking_info(branch, &num_ours, &num_theirs))
1486 return 0;
1488 base = branch->merge[0]->dst;
1489 base = shorten_unambiguous_ref(base, 0);
1490 if (!num_theirs)
1491 strbuf_addf(sb, "Your branch is ahead of '%s' "
1492 "by %d commit%s.\n",
1493 base, num_ours, (num_ours == 1) ? "" : "s");
1494 else if (!num_ours)
1495 strbuf_addf(sb, "Your branch is behind '%s' "
1496 "by %d commit%s, "
1497 "and can be fast-forwarded.\n",
1498 base, num_theirs, (num_theirs == 1) ? "" : "s");
1499 else
1500 strbuf_addf(sb, "Your branch and '%s' have diverged,\n"
1501 "and have %d and %d different commit(s) each, "
1502 "respectively.\n",
1503 base, num_ours, num_theirs);
1504 return 1;
1507 static int one_local_ref(const char *refname, const unsigned char *sha1, int flag, void *cb_data)
1509 struct ref ***local_tail = cb_data;
1510 struct ref *ref;
1511 int len;
1513 /* we already know it starts with refs/ to get here */
1514 if (check_ref_format(refname + 5))
1515 return 0;
1517 len = strlen(refname) + 1;
1518 ref = xcalloc(1, sizeof(*ref) + len);
1519 hashcpy(ref->new_sha1, sha1);
1520 memcpy(ref->name, refname, len);
1521 **local_tail = ref;
1522 *local_tail = &ref->next;
1523 return 0;
1526 struct ref *get_local_heads(void)
1528 struct ref *local_refs = NULL, **local_tail = &local_refs;
1529 for_each_ref(one_local_ref, &local_tail);
1530 return local_refs;
1533 struct ref *guess_remote_head(const struct ref *head,
1534 const struct ref *refs,
1535 int all)
1537 const struct ref *r;
1538 struct ref *list = NULL;
1539 struct ref **tail = &list;
1541 if (!head)
1542 return NULL;
1545 * Some transports support directly peeking at
1546 * where HEAD points; if that is the case, then
1547 * we don't have to guess.
1549 if (head->symref)
1550 return copy_ref(find_ref_by_name(refs, head->symref));
1552 /* If refs/heads/master could be right, it is. */
1553 if (!all) {
1554 r = find_ref_by_name(refs, "refs/heads/master");
1555 if (r && !hashcmp(r->old_sha1, head->old_sha1))
1556 return copy_ref(r);
1559 /* Look for another ref that points there */
1560 for (r = refs; r; r = r->next) {
1561 if (r != head && !hashcmp(r->old_sha1, head->old_sha1)) {
1562 *tail = copy_ref(r);
1563 tail = &((*tail)->next);
1564 if (!all)
1565 break;
1569 return list;