Support '*' in the middle of a refspec
[git] / remote.c
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
9 static struct refspec s_tag_refspec = {
10         0,
11         1,
12         0,
13         "refs/tags/*",
14         "refs/tags/*"
15 };
16
17 const struct refspec *tag_refspec = &s_tag_refspec;
18
19 struct counted_string {
20         size_t len;
21         const char *s;
22 };
23 struct rewrite {
24         const char *base;
25         size_t baselen;
26         struct counted_string *instead_of;
27         int instead_of_nr;
28         int instead_of_alloc;
29 };
30
31 static struct remote **remotes;
32 static int remotes_alloc;
33 static int remotes_nr;
34
35 static struct branch **branches;
36 static int branches_alloc;
37 static int branches_nr;
38
39 static struct branch *current_branch;
40 static const char *default_remote_name;
41
42 static struct rewrite **rewrite;
43 static int rewrite_alloc;
44 static int rewrite_nr;
45
46 #define BUF_SIZE (2048)
47 static char buffer[BUF_SIZE];
48
49 static const char *alias_url(const char *url)
50 {
51         int i, j;
52         char *ret;
53         struct counted_string *longest;
54         int longest_i;
55
56         longest = NULL;
57         longest_i = -1;
58         for (i = 0; i < rewrite_nr; i++) {
59                 if (!rewrite[i])
60                         continue;
61                 for (j = 0; j < rewrite[i]->instead_of_nr; j++) {
62                         if (!prefixcmp(url, rewrite[i]->instead_of[j].s) &&
63                             (!longest ||
64                              longest->len < rewrite[i]->instead_of[j].len)) {
65                                 longest = &(rewrite[i]->instead_of[j]);
66                                 longest_i = i;
67                         }
68                 }
69         }
70         if (!longest)
71                 return url;
72
73         ret = xmalloc(rewrite[longest_i]->baselen +
74                      (strlen(url) - longest->len) + 1);
75         strcpy(ret, rewrite[longest_i]->base);
76         strcpy(ret + rewrite[longest_i]->baselen, url + longest->len);
77         return ret;
78 }
79
80 static void add_push_refspec(struct remote *remote, const char *ref)
81 {
82         ALLOC_GROW(remote->push_refspec,
83                    remote->push_refspec_nr + 1,
84                    remote->push_refspec_alloc);
85         remote->push_refspec[remote->push_refspec_nr++] = ref;
86 }
87
88 static void add_fetch_refspec(struct remote *remote, const char *ref)
89 {
90         ALLOC_GROW(remote->fetch_refspec,
91                    remote->fetch_refspec_nr + 1,
92                    remote->fetch_refspec_alloc);
93         remote->fetch_refspec[remote->fetch_refspec_nr++] = ref;
94 }
95
96 static void add_url(struct remote *remote, const char *url)
97 {
98         ALLOC_GROW(remote->url, remote->url_nr + 1, remote->url_alloc);
99         remote->url[remote->url_nr++] = url;
100 }
101
102 static void add_url_alias(struct remote *remote, const char *url)
103 {
104         add_url(remote, alias_url(url));
105 }
106
107 static struct remote *make_remote(const char *name, int len)
108 {
109         struct remote *ret;
110         int i;
111
112         for (i = 0; i < remotes_nr; i++) {
113                 if (len ? (!strncmp(name, remotes[i]->name, len) &&
114                            !remotes[i]->name[len]) :
115                     !strcmp(name, remotes[i]->name))
116                         return remotes[i];
117         }
118
119         ret = xcalloc(1, sizeof(struct remote));
120         ALLOC_GROW(remotes, remotes_nr + 1, remotes_alloc);
121         remotes[remotes_nr++] = ret;
122         if (len)
123                 ret->name = xstrndup(name, len);
124         else
125                 ret->name = xstrdup(name);
126         return ret;
127 }
128
129 static void add_merge(struct branch *branch, const char *name)
130 {
131         ALLOC_GROW(branch->merge_name, branch->merge_nr + 1,
132                    branch->merge_alloc);
133         branch->merge_name[branch->merge_nr++] = name;
134 }
135
136 static struct branch *make_branch(const char *name, int len)
137 {
138         struct branch *ret;
139         int i;
140         char *refname;
141
142         for (i = 0; i < branches_nr; i++) {
143                 if (len ? (!strncmp(name, branches[i]->name, len) &&
144                            !branches[i]->name[len]) :
145                     !strcmp(name, branches[i]->name))
146                         return branches[i];
147         }
148
149         ALLOC_GROW(branches, branches_nr + 1, branches_alloc);
150         ret = xcalloc(1, sizeof(struct branch));
151         branches[branches_nr++] = ret;
152         if (len)
153                 ret->name = xstrndup(name, len);
154         else
155                 ret->name = xstrdup(name);
156         refname = xmalloc(strlen(name) + strlen("refs/heads/") + 1);
157         strcpy(refname, "refs/heads/");
158         strcpy(refname + strlen("refs/heads/"), ret->name);
159         ret->refname = refname;
160
161         return ret;
162 }
163
164 static struct rewrite *make_rewrite(const char *base, int len)
165 {
166         struct rewrite *ret;
167         int i;
168
169         for (i = 0; i < rewrite_nr; i++) {
170                 if (len
171                     ? (len == rewrite[i]->baselen &&
172                        !strncmp(base, rewrite[i]->base, len))
173                     : !strcmp(base, rewrite[i]->base))
174                         return rewrite[i];
175         }
176
177         ALLOC_GROW(rewrite, rewrite_nr + 1, rewrite_alloc);
178         ret = xcalloc(1, sizeof(struct rewrite));
179         rewrite[rewrite_nr++] = ret;
180         if (len) {
181                 ret->base = xstrndup(base, len);
182                 ret->baselen = len;
183         }
184         else {
185                 ret->base = xstrdup(base);
186                 ret->baselen = strlen(base);
187         }
188         return ret;
189 }
190
191 static void add_instead_of(struct rewrite *rewrite, const char *instead_of)
192 {
193         ALLOC_GROW(rewrite->instead_of, rewrite->instead_of_nr + 1, rewrite->instead_of_alloc);
194         rewrite->instead_of[rewrite->instead_of_nr].s = instead_of;
195         rewrite->instead_of[rewrite->instead_of_nr].len = strlen(instead_of);
196         rewrite->instead_of_nr++;
197 }
198
199 static void read_remotes_file(struct remote *remote)
200 {
201         FILE *f = fopen(git_path("remotes/%s", remote->name), "r");
202
203         if (!f)
204                 return;
205         remote->origin = REMOTE_REMOTES;
206         while (fgets(buffer, BUF_SIZE, f)) {
207                 int value_list;
208                 char *s, *p;
209
210                 if (!prefixcmp(buffer, "URL:")) {
211                         value_list = 0;
212                         s = buffer + 4;
213                 } else if (!prefixcmp(buffer, "Push:")) {
214                         value_list = 1;
215                         s = buffer + 5;
216                 } else if (!prefixcmp(buffer, "Pull:")) {
217                         value_list = 2;
218                         s = buffer + 5;
219                 } else
220                         continue;
221
222                 while (isspace(*s))
223                         s++;
224                 if (!*s)
225                         continue;
226
227                 p = s + strlen(s);
228                 while (isspace(p[-1]))
229                         *--p = 0;
230
231                 switch (value_list) {
232                 case 0:
233                         add_url_alias(remote, xstrdup(s));
234                         break;
235                 case 1:
236                         add_push_refspec(remote, xstrdup(s));
237                         break;
238                 case 2:
239                         add_fetch_refspec(remote, xstrdup(s));
240                         break;
241                 }
242         }
243         fclose(f);
244 }
245
246 static void read_branches_file(struct remote *remote)
247 {
248         const char *slash = strchr(remote->name, '/');
249         char *frag;
250         struct strbuf branch = STRBUF_INIT;
251         int n = slash ? slash - remote->name : 1000;
252         FILE *f = fopen(git_path("branches/%.*s", n, remote->name), "r");
253         char *s, *p;
254         int len;
255
256         if (!f)
257                 return;
258         s = fgets(buffer, BUF_SIZE, f);
259         fclose(f);
260         if (!s)
261                 return;
262         while (isspace(*s))
263                 s++;
264         if (!*s)
265                 return;
266         remote->origin = REMOTE_BRANCHES;
267         p = s + strlen(s);
268         while (isspace(p[-1]))
269                 *--p = 0;
270         len = p - s;
271         if (slash)
272                 len += strlen(slash);
273         p = xmalloc(len + 1);
274         strcpy(p, s);
275         if (slash)
276                 strcat(p, slash);
277
278         /*
279          * With "slash", e.g. "git fetch jgarzik/netdev-2.6" when
280          * reading from $GIT_DIR/branches/jgarzik fetches "HEAD" from
281          * the partial URL obtained from the branches file plus
282          * "/netdev-2.6" and does not store it in any tracking ref.
283          * #branch specifier in the file is ignored.
284          *
285          * Otherwise, the branches file would have URL and optionally
286          * #branch specified.  The "master" (or specified) branch is
287          * fetched and stored in the local branch of the same name.
288          */
289         frag = strchr(p, '#');
290         if (frag) {
291                 *(frag++) = '\0';
292                 strbuf_addf(&branch, "refs/heads/%s", frag);
293         } else
294                 strbuf_addstr(&branch, "refs/heads/master");
295         if (!slash) {
296                 strbuf_addf(&branch, ":refs/heads/%s", remote->name);
297         } else {
298                 strbuf_reset(&branch);
299                 strbuf_addstr(&branch, "HEAD:");
300         }
301         add_url_alias(remote, p);
302         add_fetch_refspec(remote, strbuf_detach(&branch, 0));
303         /*
304          * Cogito compatible push: push current HEAD to remote #branch
305          * (master if missing)
306          */
307         strbuf_init(&branch, 0);
308         strbuf_addstr(&branch, "HEAD");
309         if (frag)
310                 strbuf_addf(&branch, ":refs/heads/%s", frag);
311         else
312                 strbuf_addstr(&branch, ":refs/heads/master");
313         add_push_refspec(remote, strbuf_detach(&branch, 0));
314         remote->fetch_tags = 1; /* always auto-follow */
315 }
316
317 static int handle_config(const char *key, const char *value, void *cb)
318 {
319         const char *name;
320         const char *subkey;
321         struct remote *remote;
322         struct branch *branch;
323         if (!prefixcmp(key, "branch.")) {
324                 name = key + 7;
325                 subkey = strrchr(name, '.');
326                 if (!subkey)
327                         return 0;
328                 branch = make_branch(name, subkey - name);
329                 if (!strcmp(subkey, ".remote")) {
330                         if (!value)
331                                 return config_error_nonbool(key);
332                         branch->remote_name = xstrdup(value);
333                         if (branch == current_branch)
334                                 default_remote_name = branch->remote_name;
335                 } else if (!strcmp(subkey, ".merge")) {
336                         if (!value)
337                                 return config_error_nonbool(key);
338                         add_merge(branch, xstrdup(value));
339                 }
340                 return 0;
341         }
342         if (!prefixcmp(key, "url.")) {
343                 struct rewrite *rewrite;
344                 name = key + 4;
345                 subkey = strrchr(name, '.');
346                 if (!subkey)
347                         return 0;
348                 rewrite = make_rewrite(name, subkey - name);
349                 if (!strcmp(subkey, ".insteadof")) {
350                         if (!value)
351                                 return config_error_nonbool(key);
352                         add_instead_of(rewrite, xstrdup(value));
353                 }
354         }
355         if (prefixcmp(key,  "remote."))
356                 return 0;
357         name = key + 7;
358         if (*name == '/') {
359                 warning("Config remote shorthand cannot begin with '/': %s",
360                         name);
361                 return 0;
362         }
363         subkey = strrchr(name, '.');
364         if (!subkey)
365                 return error("Config with no key for remote %s", name);
366         remote = make_remote(name, subkey - name);
367         remote->origin = REMOTE_CONFIG;
368         if (!strcmp(subkey, ".mirror"))
369                 remote->mirror = git_config_bool(key, value);
370         else if (!strcmp(subkey, ".skipdefaultupdate"))
371                 remote->skip_default_update = git_config_bool(key, value);
372
373         else if (!strcmp(subkey, ".url")) {
374                 const char *v;
375                 if (git_config_string(&v, key, value))
376                         return -1;
377                 add_url(remote, v);
378         } else if (!strcmp(subkey, ".push")) {
379                 const char *v;
380                 if (git_config_string(&v, key, value))
381                         return -1;
382                 add_push_refspec(remote, v);
383         } else if (!strcmp(subkey, ".fetch")) {
384                 const char *v;
385                 if (git_config_string(&v, key, value))
386                         return -1;
387                 add_fetch_refspec(remote, v);
388         } else if (!strcmp(subkey, ".receivepack")) {
389                 const char *v;
390                 if (git_config_string(&v, key, value))
391                         return -1;
392                 if (!remote->receivepack)
393                         remote->receivepack = v;
394                 else
395                         error("more than one receivepack given, using the first");
396         } else if (!strcmp(subkey, ".uploadpack")) {
397                 const char *v;
398                 if (git_config_string(&v, key, value))
399                         return -1;
400                 if (!remote->uploadpack)
401                         remote->uploadpack = v;
402                 else
403                         error("more than one uploadpack given, using the first");
404         } else if (!strcmp(subkey, ".tagopt")) {
405                 if (!strcmp(value, "--no-tags"))
406                         remote->fetch_tags = -1;
407         } else if (!strcmp(subkey, ".proxy")) {
408                 return git_config_string((const char **)&remote->http_proxy,
409                                          key, value);
410         }
411         return 0;
412 }
413
414 static void alias_all_urls(void)
415 {
416         int i, j;
417         for (i = 0; i < remotes_nr; i++) {
418                 if (!remotes[i])
419                         continue;
420                 for (j = 0; j < remotes[i]->url_nr; j++) {
421                         remotes[i]->url[j] = alias_url(remotes[i]->url[j]);
422                 }
423         }
424 }
425
426 static void read_config(void)
427 {
428         unsigned char sha1[20];
429         const char *head_ref;
430         int flag;
431         if (default_remote_name) // did this already
432                 return;
433         default_remote_name = xstrdup("origin");
434         current_branch = NULL;
435         head_ref = resolve_ref("HEAD", sha1, 0, &flag);
436         if (head_ref && (flag & REF_ISSYMREF) &&
437             !prefixcmp(head_ref, "refs/heads/")) {
438                 current_branch =
439                         make_branch(head_ref + strlen("refs/heads/"), 0);
440         }
441         git_config(handle_config, NULL);
442         alias_all_urls();
443 }
444
445 /*
446  * We need to make sure the tracking branches are well formed, but a
447  * wildcard refspec in "struct refspec" must have a trailing slash. We
448  * temporarily drop the trailing '/' while calling check_ref_format(),
449  * and put it back.  The caller knows that a CHECK_REF_FORMAT_ONELEVEL
450  * error return is Ok for a wildcard refspec.
451  */
452 static int verify_refname(char *name, int is_glob)
453 {
454         int result;
455
456         result = check_ref_format(name);
457         if (is_glob && result == CHECK_REF_FORMAT_WILDCARD)
458                 result = CHECK_REF_FORMAT_OK;
459         return result;
460 }
461
462 /*
463  * This function frees a refspec array.
464  * Warning: code paths should be checked to ensure that the src
465  *          and dst pointers are always freeable pointers as well
466  *          as the refspec pointer itself.
467  */
468 static void free_refspecs(struct refspec *refspec, int nr_refspec)
469 {
470         int i;
471
472         if (!refspec)
473                 return;
474
475         for (i = 0; i < nr_refspec; i++) {
476                 free(refspec[i].src);
477                 free(refspec[i].dst);
478         }
479         free(refspec);
480 }
481
482 static struct refspec *parse_refspec_internal(int nr_refspec, const char **refspec, int fetch, int verify)
483 {
484         int i;
485         int st;
486         struct refspec *rs = xcalloc(sizeof(*rs), nr_refspec);
487
488         for (i = 0; i < nr_refspec; i++) {
489                 size_t llen;
490                 int is_glob;
491                 const char *lhs, *rhs;
492
493                 llen = is_glob = 0;
494
495                 lhs = refspec[i];
496                 if (*lhs == '+') {
497                         rs[i].force = 1;
498                         lhs++;
499                 }
500
501                 rhs = strrchr(lhs, ':');
502
503                 /*
504                  * Before going on, special case ":" (or "+:") as a refspec
505                  * for matching refs.
506                  */
507                 if (!fetch && rhs == lhs && rhs[1] == '\0') {
508                         rs[i].matching = 1;
509                         continue;
510                 }
511
512                 if (rhs) {
513                         size_t rlen = strlen(++rhs);
514                         is_glob = (1 <= rlen && strchr(rhs, '*'));
515                         rs[i].dst = xstrndup(rhs, rlen);
516                 }
517
518                 llen = (rhs ? (rhs - lhs - 1) : strlen(lhs));
519                 if (1 <= llen && memchr(lhs, '*', llen)) {
520                         if ((rhs && !is_glob) || (!rhs && fetch))
521                                 goto invalid;
522                         is_glob = 1;
523                 } else if (rhs && is_glob) {
524                         goto invalid;
525                 }
526
527                 rs[i].pattern = is_glob;
528                 rs[i].src = xstrndup(lhs, llen);
529
530                 if (fetch) {
531                         /*
532                          * LHS
533                          * - empty is allowed; it means HEAD.
534                          * - otherwise it must be a valid looking ref.
535                          */
536                         if (!*rs[i].src)
537                                 ; /* empty is ok */
538                         else {
539                                 st = verify_refname(rs[i].src, is_glob);
540                                 if (st && st != CHECK_REF_FORMAT_ONELEVEL)
541                                         goto invalid;
542                         }
543                         /*
544                          * RHS
545                          * - missing is ok, and is same as empty.
546                          * - empty is ok; it means not to store.
547                          * - otherwise it must be a valid looking ref.
548                          */
549                         if (!rs[i].dst) {
550                                 ; /* ok */
551                         } else if (!*rs[i].dst) {
552                                 ; /* ok */
553                         } else {
554                                 st = verify_refname(rs[i].dst, is_glob);
555                                 if (st && st != CHECK_REF_FORMAT_ONELEVEL)
556                                         goto invalid;
557                         }
558                 } else {
559                         /*
560                          * LHS
561                          * - empty is allowed; it means delete.
562                          * - when wildcarded, it must be a valid looking ref.
563                          * - otherwise, it must be an extended SHA-1, but
564                          *   there is no existing way to validate this.
565                          */
566                         if (!*rs[i].src)
567                                 ; /* empty is ok */
568                         else if (is_glob) {
569                                 st = verify_refname(rs[i].src, is_glob);
570                                 if (st && st != CHECK_REF_FORMAT_ONELEVEL)
571                                         goto invalid;
572                         }
573                         else
574                                 ; /* anything goes, for now */
575                         /*
576                          * RHS
577                          * - missing is allowed, but LHS then must be a
578                          *   valid looking ref.
579                          * - empty is not allowed.
580                          * - otherwise it must be a valid looking ref.
581                          */
582                         if (!rs[i].dst) {
583                                 st = verify_refname(rs[i].src, is_glob);
584                                 if (st && st != CHECK_REF_FORMAT_ONELEVEL)
585                                         goto invalid;
586                         } else if (!*rs[i].dst) {
587                                 goto invalid;
588                         } else {
589                                 st = verify_refname(rs[i].dst, is_glob);
590                                 if (st && st != CHECK_REF_FORMAT_ONELEVEL)
591                                         goto invalid;
592                         }
593                 }
594         }
595         return rs;
596
597  invalid:
598         if (verify) {
599                 /*
600                  * nr_refspec must be greater than zero and i must be valid
601                  * since it is only possible to reach this point from within
602                  * the for loop above.
603                  */
604                 free_refspecs(rs, i+1);
605                 return NULL;
606         }
607         die("Invalid refspec '%s'", refspec[i]);
608 }
609
610 int valid_fetch_refspec(const char *fetch_refspec_str)
611 {
612         const char *fetch_refspec[] = { fetch_refspec_str };
613         struct refspec *refspec;
614
615         refspec = parse_refspec_internal(1, fetch_refspec, 1, 1);
616         free_refspecs(refspec, 1);
617         return !!refspec;
618 }
619
620 struct refspec *parse_fetch_refspec(int nr_refspec, const char **refspec)
621 {
622         return parse_refspec_internal(nr_refspec, refspec, 1, 0);
623 }
624
625 static struct refspec *parse_push_refspec(int nr_refspec, const char **refspec)
626 {
627         return parse_refspec_internal(nr_refspec, refspec, 0, 0);
628 }
629
630 static int valid_remote_nick(const char *name)
631 {
632         if (!name[0] || is_dot_or_dotdot(name))
633                 return 0;
634         return !strchr(name, '/'); /* no slash */
635 }
636
637 struct remote *remote_get(const char *name)
638 {
639         struct remote *ret;
640
641         read_config();
642         if (!name)
643                 name = default_remote_name;
644         ret = make_remote(name, 0);
645         if (valid_remote_nick(name)) {
646                 if (!ret->url)
647                         read_remotes_file(ret);
648                 if (!ret->url)
649                         read_branches_file(ret);
650         }
651         if (!ret->url)
652                 add_url_alias(ret, name);
653         if (!ret->url)
654                 return NULL;
655         ret->fetch = parse_fetch_refspec(ret->fetch_refspec_nr, ret->fetch_refspec);
656         ret->push = parse_push_refspec(ret->push_refspec_nr, ret->push_refspec);
657         return ret;
658 }
659
660 int for_each_remote(each_remote_fn fn, void *priv)
661 {
662         int i, result = 0;
663         read_config();
664         for (i = 0; i < remotes_nr && !result; i++) {
665                 struct remote *r = remotes[i];
666                 if (!r)
667                         continue;
668                 if (!r->fetch)
669                         r->fetch = parse_fetch_refspec(r->fetch_refspec_nr,
670                                                        r->fetch_refspec);
671                 if (!r->push)
672                         r->push = parse_push_refspec(r->push_refspec_nr,
673                                                      r->push_refspec);
674                 result = fn(r, priv);
675         }
676         return result;
677 }
678
679 void ref_remove_duplicates(struct ref *ref_map)
680 {
681         struct ref **posn;
682         struct ref *next;
683         for (; ref_map; ref_map = ref_map->next) {
684                 if (!ref_map->peer_ref)
685                         continue;
686                 posn = &ref_map->next;
687                 while (*posn) {
688                         if ((*posn)->peer_ref &&
689                             !strcmp((*posn)->peer_ref->name,
690                                     ref_map->peer_ref->name)) {
691                                 if (strcmp((*posn)->name, ref_map->name))
692                                         die("%s tracks both %s and %s",
693                                             ref_map->peer_ref->name,
694                                             (*posn)->name, ref_map->name);
695                                 next = (*posn)->next;
696                                 free((*posn)->peer_ref);
697                                 free(*posn);
698                                 *posn = next;
699                         } else {
700                                 posn = &(*posn)->next;
701                         }
702                 }
703         }
704 }
705
706 int remote_has_url(struct remote *remote, const char *url)
707 {
708         int i;
709         for (i = 0; i < remote->url_nr; i++) {
710                 if (!strcmp(remote->url[i], url))
711                         return 1;
712         }
713         return 0;
714 }
715
716 static int match_name_with_pattern(const char *key, const char *name,
717                                    const char *value, char **result)
718 {
719         const char *kstar = strchr(key, '*');
720         size_t klen;
721         size_t ksuffixlen;
722         size_t namelen;
723         int ret;
724         if (!kstar)
725                 die("Key '%s' of pattern had no '*'", key);
726         klen = kstar - key;
727         ksuffixlen = strlen(kstar + 1);
728         namelen = strlen(name);
729         ret = !strncmp(name, key, klen) && namelen >= klen + ksuffixlen &&
730                 !memcmp(name + namelen - ksuffixlen, kstar + 1, ksuffixlen);
731         if (ret && value) {
732                 const char *vstar = strchr(value, '*');
733                 size_t vlen;
734                 size_t vsuffixlen;
735                 if (!vstar)
736                         die("Value '%s' of pattern has no '*'", value);
737                 vlen = vstar - value;
738                 vsuffixlen = strlen(vstar + 1);
739                 *result = xmalloc(vlen + vsuffixlen +
740                                   strlen(name) -
741                                   klen - ksuffixlen + 1);
742                 strncpy(*result, value, vlen);
743                 strncpy(*result + vlen,
744                         name + klen, namelen - klen - ksuffixlen);
745                 strcpy(*result + vlen + namelen - klen - ksuffixlen,
746                        vstar + 1);
747         }
748         return ret;
749 }
750
751 int remote_find_tracking(struct remote *remote, struct refspec *refspec)
752 {
753         int find_src = refspec->src == NULL;
754         char *needle, **result;
755         int i;
756
757         if (find_src) {
758                 if (!refspec->dst)
759                         return error("find_tracking: need either src or dst");
760                 needle = refspec->dst;
761                 result = &refspec->src;
762         } else {
763                 needle = refspec->src;
764                 result = &refspec->dst;
765         }
766
767         for (i = 0; i < remote->fetch_refspec_nr; i++) {
768                 struct refspec *fetch = &remote->fetch[i];
769                 const char *key = find_src ? fetch->dst : fetch->src;
770                 const char *value = find_src ? fetch->src : fetch->dst;
771                 if (!fetch->dst)
772                         continue;
773                 if (fetch->pattern) {
774                         if (match_name_with_pattern(key, needle, value, result)) {
775                                 refspec->force = fetch->force;
776                                 return 0;
777                         }
778                 } else if (!strcmp(needle, key)) {
779                         *result = xstrdup(value);
780                         refspec->force = fetch->force;
781                         return 0;
782                 }
783         }
784         return -1;
785 }
786
787 static struct ref *alloc_ref_with_prefix(const char *prefix, size_t prefixlen,
788                 const char *name)
789 {
790         size_t len = strlen(name);
791         struct ref *ref = xcalloc(1, sizeof(struct ref) + prefixlen + len + 1);
792         memcpy(ref->name, prefix, prefixlen);
793         memcpy(ref->name + prefixlen, name, len);
794         return ref;
795 }
796
797 struct ref *alloc_ref(const char *name)
798 {
799         return alloc_ref_with_prefix("", 0, name);
800 }
801
802 static struct ref *copy_ref(const struct ref *ref)
803 {
804         struct ref *ret = xmalloc(sizeof(struct ref) + strlen(ref->name) + 1);
805         memcpy(ret, ref, sizeof(struct ref) + strlen(ref->name) + 1);
806         ret->next = NULL;
807         return ret;
808 }
809
810 struct ref *copy_ref_list(const struct ref *ref)
811 {
812         struct ref *ret = NULL;
813         struct ref **tail = &ret;
814         while (ref) {
815                 *tail = copy_ref(ref);
816                 ref = ref->next;
817                 tail = &((*tail)->next);
818         }
819         return ret;
820 }
821
822 static void free_ref(struct ref *ref)
823 {
824         if (!ref)
825                 return;
826         free(ref->remote_status);
827         free(ref->symref);
828         free(ref);
829 }
830
831 void free_refs(struct ref *ref)
832 {
833         struct ref *next;
834         while (ref) {
835                 next = ref->next;
836                 free(ref->peer_ref);
837                 free_ref(ref);
838                 ref = next;
839         }
840 }
841
842 static int count_refspec_match(const char *pattern,
843                                struct ref *refs,
844                                struct ref **matched_ref)
845 {
846         int patlen = strlen(pattern);
847         struct ref *matched_weak = NULL;
848         struct ref *matched = NULL;
849         int weak_match = 0;
850         int match = 0;
851
852         for (weak_match = match = 0; refs; refs = refs->next) {
853                 char *name = refs->name;
854                 int namelen = strlen(name);
855
856                 if (!refname_match(pattern, name, ref_rev_parse_rules))
857                         continue;
858
859                 /* A match is "weak" if it is with refs outside
860                  * heads or tags, and did not specify the pattern
861                  * in full (e.g. "refs/remotes/origin/master") or at
862                  * least from the toplevel (e.g. "remotes/origin/master");
863                  * otherwise "git push $URL master" would result in
864                  * ambiguity between remotes/origin/master and heads/master
865                  * at the remote site.
866                  */
867                 if (namelen != patlen &&
868                     patlen != namelen - 5 &&
869                     prefixcmp(name, "refs/heads/") &&
870                     prefixcmp(name, "refs/tags/")) {
871                         /* We want to catch the case where only weak
872                          * matches are found and there are multiple
873                          * matches, and where more than one strong
874                          * matches are found, as ambiguous.  One
875                          * strong match with zero or more weak matches
876                          * are acceptable as a unique match.
877                          */
878                         matched_weak = refs;
879                         weak_match++;
880                 }
881                 else {
882                         matched = refs;
883                         match++;
884                 }
885         }
886         if (!matched) {
887                 *matched_ref = matched_weak;
888                 return weak_match;
889         }
890         else {
891                 *matched_ref = matched;
892                 return match;
893         }
894 }
895
896 static void tail_link_ref(struct ref *ref, struct ref ***tail)
897 {
898         **tail = ref;
899         while (ref->next)
900                 ref = ref->next;
901         *tail = &ref->next;
902 }
903
904 static struct ref *try_explicit_object_name(const char *name)
905 {
906         unsigned char sha1[20];
907         struct ref *ref;
908
909         if (!*name) {
910                 ref = alloc_ref("(delete)");
911                 hashclr(ref->new_sha1);
912                 return ref;
913         }
914         if (get_sha1(name, sha1))
915                 return NULL;
916         ref = alloc_ref(name);
917         hashcpy(ref->new_sha1, sha1);
918         return ref;
919 }
920
921 static struct ref *make_linked_ref(const char *name, struct ref ***tail)
922 {
923         struct ref *ret = alloc_ref(name);
924         tail_link_ref(ret, tail);
925         return ret;
926 }
927
928 static char *guess_ref(const char *name, struct ref *peer)
929 {
930         struct strbuf buf = STRBUF_INIT;
931         unsigned char sha1[20];
932
933         const char *r = resolve_ref(peer->name, sha1, 1, NULL);
934         if (!r)
935                 return NULL;
936
937         if (!prefixcmp(r, "refs/heads/"))
938                 strbuf_addstr(&buf, "refs/heads/");
939         else if (!prefixcmp(r, "refs/tags/"))
940                 strbuf_addstr(&buf, "refs/tags/");
941         else
942                 return NULL;
943
944         strbuf_addstr(&buf, name);
945         return strbuf_detach(&buf, NULL);
946 }
947
948 static int match_explicit(struct ref *src, struct ref *dst,
949                           struct ref ***dst_tail,
950                           struct refspec *rs)
951 {
952         struct ref *matched_src, *matched_dst;
953
954         const char *dst_value = rs->dst;
955         char *dst_guess;
956
957         if (rs->pattern || rs->matching)
958                 return 0;
959
960         matched_src = matched_dst = NULL;
961         switch (count_refspec_match(rs->src, src, &matched_src)) {
962         case 1:
963                 break;
964         case 0:
965                 /* The source could be in the get_sha1() format
966                  * not a reference name.  :refs/other is a
967                  * way to delete 'other' ref at the remote end.
968                  */
969                 matched_src = try_explicit_object_name(rs->src);
970                 if (!matched_src)
971                         return error("src refspec %s does not match any.", rs->src);
972                 break;
973         default:
974                 return error("src refspec %s matches more than one.", rs->src);
975         }
976
977         if (!dst_value) {
978                 unsigned char sha1[20];
979                 int flag;
980
981                 dst_value = resolve_ref(matched_src->name, sha1, 1, &flag);
982                 if (!dst_value ||
983                     ((flag & REF_ISSYMREF) &&
984                      prefixcmp(dst_value, "refs/heads/")))
985                         die("%s cannot be resolved to branch.",
986                             matched_src->name);
987         }
988
989         switch (count_refspec_match(dst_value, dst, &matched_dst)) {
990         case 1:
991                 break;
992         case 0:
993                 if (!memcmp(dst_value, "refs/", 5))
994                         matched_dst = make_linked_ref(dst_value, dst_tail);
995                 else if((dst_guess = guess_ref(dst_value, matched_src)))
996                         matched_dst = make_linked_ref(dst_guess, dst_tail);
997                 else
998                         error("unable to push to unqualified destination: %s\n"
999                               "The destination refspec neither matches an "
1000                               "existing ref on the remote nor\n"
1001                               "begins with refs/, and we are unable to "
1002                               "guess a prefix based on the source ref.",
1003                               dst_value);
1004                 break;
1005         default:
1006                 matched_dst = NULL;
1007                 error("dst refspec %s matches more than one.",
1008                       dst_value);
1009                 break;
1010         }
1011         if (!matched_dst)
1012                 return -1;
1013         if (matched_dst->peer_ref)
1014                 return error("dst ref %s receives from more than one src.",
1015                       matched_dst->name);
1016         else {
1017                 matched_dst->peer_ref = matched_src;
1018                 matched_dst->force = rs->force;
1019         }
1020         return 0;
1021 }
1022
1023 static int match_explicit_refs(struct ref *src, struct ref *dst,
1024                                struct ref ***dst_tail, struct refspec *rs,
1025                                int rs_nr)
1026 {
1027         int i, errs;
1028         for (i = errs = 0; i < rs_nr; i++)
1029                 errs += match_explicit(src, dst, dst_tail, &rs[i]);
1030         return errs;
1031 }
1032
1033 static const struct refspec *check_pattern_match(const struct refspec *rs,
1034                                                  int rs_nr,
1035                                                  const struct ref *src)
1036 {
1037         int i;
1038         int matching_refs = -1;
1039         for (i = 0; i < rs_nr; i++) {
1040                 if (rs[i].matching &&
1041                     (matching_refs == -1 || rs[i].force)) {
1042                         matching_refs = i;
1043                         continue;
1044                 }
1045
1046                 if (rs[i].pattern && match_name_with_pattern(rs[i].src, src->name,
1047                                                              NULL, NULL))
1048                         return rs + i;
1049         }
1050         if (matching_refs != -1)
1051                 return rs + matching_refs;
1052         else
1053                 return NULL;
1054 }
1055
1056 /*
1057  * Note. This is used only by "push"; refspec matching rules for
1058  * push and fetch are subtly different, so do not try to reuse it
1059  * without thinking.
1060  */
1061 int match_refs(struct ref *src, struct ref *dst, struct ref ***dst_tail,
1062                int nr_refspec, const char **refspec, int flags)
1063 {
1064         struct refspec *rs;
1065         int send_all = flags & MATCH_REFS_ALL;
1066         int send_mirror = flags & MATCH_REFS_MIRROR;
1067         static const char *default_refspec[] = { ":", 0 };
1068
1069         if (!nr_refspec) {
1070                 nr_refspec = 1;
1071                 refspec = default_refspec;
1072         }
1073         rs = parse_push_refspec(nr_refspec, (const char **) refspec);
1074         if (match_explicit_refs(src, dst, dst_tail, rs, nr_refspec))
1075                 return -1;
1076
1077         /* pick the remainder */
1078         for ( ; src; src = src->next) {
1079                 struct ref *dst_peer;
1080                 const struct refspec *pat = NULL;
1081                 char *dst_name;
1082                 if (src->peer_ref)
1083                         continue;
1084
1085                 pat = check_pattern_match(rs, nr_refspec, src);
1086                 if (!pat)
1087                         continue;
1088
1089                 if (pat->matching) {
1090                         /*
1091                          * "matching refs"; traditionally we pushed everything
1092                          * including refs outside refs/heads/ hierarchy, but
1093                          * that does not make much sense these days.
1094                          */
1095                         if (!send_mirror && prefixcmp(src->name, "refs/heads/"))
1096                                 continue;
1097                         dst_name = xstrdup(src->name);
1098
1099                 } else {
1100                         const char *dst_side = pat->dst ? pat->dst : pat->src;
1101                         if (!match_name_with_pattern(pat->src, src->name,
1102                                                      dst_side, &dst_name))
1103                                 die("Didn't think it matches any more");
1104                 }
1105                 dst_peer = find_ref_by_name(dst, dst_name);
1106                 if (dst_peer) {
1107                         if (dst_peer->peer_ref)
1108                                 /* We're already sending something to this ref. */
1109                                 goto free_name;
1110
1111                 } else {
1112                         if (pat->matching && !(send_all || send_mirror))
1113                                 /*
1114                                  * Remote doesn't have it, and we have no
1115                                  * explicit pattern, and we don't have
1116                                  * --all nor --mirror.
1117                                  */
1118                                 goto free_name;
1119
1120                         /* Create a new one and link it */
1121                         dst_peer = make_linked_ref(dst_name, dst_tail);
1122                         hashcpy(dst_peer->new_sha1, src->new_sha1);
1123                 }
1124                 dst_peer->peer_ref = src;
1125                 dst_peer->force = pat->force;
1126         free_name:
1127                 free(dst_name);
1128         }
1129         return 0;
1130 }
1131
1132 struct branch *branch_get(const char *name)
1133 {
1134         struct branch *ret;
1135
1136         read_config();
1137         if (!name || !*name || !strcmp(name, "HEAD"))
1138                 ret = current_branch;
1139         else
1140                 ret = make_branch(name, 0);
1141         if (ret && ret->remote_name) {
1142                 ret->remote = remote_get(ret->remote_name);
1143                 if (ret->merge_nr) {
1144                         int i;
1145                         ret->merge = xcalloc(sizeof(*ret->merge),
1146                                              ret->merge_nr);
1147                         for (i = 0; i < ret->merge_nr; i++) {
1148                                 ret->merge[i] = xcalloc(1, sizeof(**ret->merge));
1149                                 ret->merge[i]->src = xstrdup(ret->merge_name[i]);
1150                                 remote_find_tracking(ret->remote,
1151                                                      ret->merge[i]);
1152                         }
1153                 }
1154         }
1155         return ret;
1156 }
1157
1158 int branch_has_merge_config(struct branch *branch)
1159 {
1160         return branch && !!branch->merge;
1161 }
1162
1163 int branch_merge_matches(struct branch *branch,
1164                                  int i,
1165                                  const char *refname)
1166 {
1167         if (!branch || i < 0 || i >= branch->merge_nr)
1168                 return 0;
1169         return refname_match(branch->merge[i]->src, refname, ref_fetch_rules);
1170 }
1171
1172 static struct ref *get_expanded_map(const struct ref *remote_refs,
1173                                     const struct refspec *refspec)
1174 {
1175         const struct ref *ref;
1176         struct ref *ret = NULL;
1177         struct ref **tail = &ret;
1178
1179         char *expn_name;
1180
1181         for (ref = remote_refs; ref; ref = ref->next) {
1182                 if (strchr(ref->name, '^'))
1183                         continue; /* a dereference item */
1184                 if (match_name_with_pattern(refspec->src, ref->name,
1185                                             refspec->dst, &expn_name)) {
1186                         struct ref *cpy = copy_ref(ref);
1187
1188                         cpy->peer_ref = alloc_ref(expn_name);
1189                         free(expn_name);
1190                         if (refspec->force)
1191                                 cpy->peer_ref->force = 1;
1192                         *tail = cpy;
1193                         tail = &cpy->next;
1194                 }
1195         }
1196
1197         return ret;
1198 }
1199
1200 static const struct ref *find_ref_by_name_abbrev(const struct ref *refs, const char *name)
1201 {
1202         const struct ref *ref;
1203         for (ref = refs; ref; ref = ref->next) {
1204                 if (refname_match(name, ref->name, ref_fetch_rules))
1205                         return ref;
1206         }
1207         return NULL;
1208 }
1209
1210 struct ref *get_remote_ref(const struct ref *remote_refs, const char *name)
1211 {
1212         const struct ref *ref = find_ref_by_name_abbrev(remote_refs, name);
1213
1214         if (!ref)
1215                 return NULL;
1216
1217         return copy_ref(ref);
1218 }
1219
1220 static struct ref *get_local_ref(const char *name)
1221 {
1222         if (!name)
1223                 return NULL;
1224
1225         if (!prefixcmp(name, "refs/"))
1226                 return alloc_ref(name);
1227
1228         if (!prefixcmp(name, "heads/") ||
1229             !prefixcmp(name, "tags/") ||
1230             !prefixcmp(name, "remotes/"))
1231                 return alloc_ref_with_prefix("refs/", 5, name);
1232
1233         return alloc_ref_with_prefix("refs/heads/", 11, name);
1234 }
1235
1236 int get_fetch_map(const struct ref *remote_refs,
1237                   const struct refspec *refspec,
1238                   struct ref ***tail,
1239                   int missing_ok)
1240 {
1241         struct ref *ref_map, **rmp;
1242
1243         if (refspec->pattern) {
1244                 ref_map = get_expanded_map(remote_refs, refspec);
1245         } else {
1246                 const char *name = refspec->src[0] ? refspec->src : "HEAD";
1247
1248                 ref_map = get_remote_ref(remote_refs, name);
1249                 if (!missing_ok && !ref_map)
1250                         die("Couldn't find remote ref %s", name);
1251                 if (ref_map) {
1252                         ref_map->peer_ref = get_local_ref(refspec->dst);
1253                         if (ref_map->peer_ref && refspec->force)
1254                                 ref_map->peer_ref->force = 1;
1255                 }
1256         }
1257
1258         for (rmp = &ref_map; *rmp; ) {
1259                 if ((*rmp)->peer_ref) {
1260                         int st = check_ref_format((*rmp)->peer_ref->name + 5);
1261                         if (st && st != CHECK_REF_FORMAT_ONELEVEL) {
1262                                 struct ref *ignore = *rmp;
1263                                 error("* Ignoring funny ref '%s' locally",
1264                                       (*rmp)->peer_ref->name);
1265                                 *rmp = (*rmp)->next;
1266                                 free(ignore->peer_ref);
1267                                 free(ignore);
1268                                 continue;
1269                         }
1270                 }
1271                 rmp = &((*rmp)->next);
1272         }
1273
1274         if (ref_map)
1275                 tail_link_ref(ref_map, tail);
1276
1277         return 0;
1278 }
1279
1280 int resolve_remote_symref(struct ref *ref, struct ref *list)
1281 {
1282         if (!ref->symref)
1283                 return 0;
1284         for (; list; list = list->next)
1285                 if (!strcmp(ref->symref, list->name)) {
1286                         hashcpy(ref->old_sha1, list->old_sha1);
1287                         return 0;
1288                 }
1289         return 1;
1290 }
1291
1292 /*
1293  * Return true if there is anything to report, otherwise false.
1294  */
1295 int stat_tracking_info(struct branch *branch, int *num_ours, int *num_theirs)
1296 {
1297         unsigned char sha1[20];
1298         struct commit *ours, *theirs;
1299         char symmetric[84];
1300         struct rev_info revs;
1301         const char *rev_argv[10], *base;
1302         int rev_argc;
1303
1304         /*
1305          * Nothing to report unless we are marked to build on top of
1306          * somebody else.
1307          */
1308         if (!branch ||
1309             !branch->merge || !branch->merge[0] || !branch->merge[0]->dst)
1310                 return 0;
1311
1312         /*
1313          * If what we used to build on no longer exists, there is
1314          * nothing to report.
1315          */
1316         base = branch->merge[0]->dst;
1317         if (!resolve_ref(base, sha1, 1, NULL))
1318                 return 0;
1319         theirs = lookup_commit(sha1);
1320         if (!theirs)
1321                 return 0;
1322
1323         if (!resolve_ref(branch->refname, sha1, 1, NULL))
1324                 return 0;
1325         ours = lookup_commit(sha1);
1326         if (!ours)
1327                 return 0;
1328
1329         /* are we the same? */
1330         if (theirs == ours)
1331                 return 0;
1332
1333         /* Run "rev-list --left-right ours...theirs" internally... */
1334         rev_argc = 0;
1335         rev_argv[rev_argc++] = NULL;
1336         rev_argv[rev_argc++] = "--left-right";
1337         rev_argv[rev_argc++] = symmetric;
1338         rev_argv[rev_argc++] = "--";
1339         rev_argv[rev_argc] = NULL;
1340
1341         strcpy(symmetric, sha1_to_hex(ours->object.sha1));
1342         strcpy(symmetric + 40, "...");
1343         strcpy(symmetric + 43, sha1_to_hex(theirs->object.sha1));
1344
1345         init_revisions(&revs, NULL);
1346         setup_revisions(rev_argc, rev_argv, &revs, NULL);
1347         prepare_revision_walk(&revs);
1348
1349         /* ... and count the commits on each side. */
1350         *num_ours = 0;
1351         *num_theirs = 0;
1352         while (1) {
1353                 struct commit *c = get_revision(&revs);
1354                 if (!c)
1355                         break;
1356                 if (c->object.flags & SYMMETRIC_LEFT)
1357                         (*num_ours)++;
1358                 else
1359                         (*num_theirs)++;
1360         }
1361
1362         /* clear object flags smudged by the above traversal */
1363         clear_commit_marks(ours, ALL_REV_FLAGS);
1364         clear_commit_marks(theirs, ALL_REV_FLAGS);
1365         return 1;
1366 }
1367
1368 /*
1369  * Return true when there is anything to report, otherwise false.
1370  */
1371 int format_tracking_info(struct branch *branch, struct strbuf *sb)
1372 {
1373         int num_ours, num_theirs;
1374         const char *base;
1375
1376         if (!stat_tracking_info(branch, &num_ours, &num_theirs))
1377                 return 0;
1378
1379         base = branch->merge[0]->dst;
1380         if (!prefixcmp(base, "refs/remotes/")) {
1381                 base += strlen("refs/remotes/");
1382         }
1383         if (!num_theirs)
1384                 strbuf_addf(sb, "Your branch is ahead of '%s' "
1385                             "by %d commit%s.\n",
1386                             base, num_ours, (num_ours == 1) ? "" : "s");
1387         else if (!num_ours)
1388                 strbuf_addf(sb, "Your branch is behind '%s' "
1389                             "by %d commit%s, "
1390                             "and can be fast-forwarded.\n",
1391                             base, num_theirs, (num_theirs == 1) ? "" : "s");
1392         else
1393                 strbuf_addf(sb, "Your branch and '%s' have diverged,\n"
1394                             "and have %d and %d different commit(s) each, "
1395                             "respectively.\n",
1396                             base, num_ours, num_theirs);
1397         return 1;
1398 }