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