Merge branch 'jc/maint-fetch-regression-1.5.4' into maint
[git] / remote.c
1 #include "cache.h"
2 #include "remote.h"
3 #include "refs.h"
4
5 static struct remote **remotes;
6 static int allocated_remotes;
7
8 static struct branch **branches;
9 static int allocated_branches;
10
11 static struct branch *current_branch;
12 static const char *default_remote_name;
13
14 #define BUF_SIZE (2048)
15 static char buffer[BUF_SIZE];
16
17 static void add_push_refspec(struct remote *remote, const char *ref)
18 {
19         int nr = remote->push_refspec_nr + 1;
20         remote->push_refspec =
21                 xrealloc(remote->push_refspec, nr * sizeof(char *));
22         remote->push_refspec[nr-1] = ref;
23         remote->push_refspec_nr = nr;
24 }
25
26 static void add_fetch_refspec(struct remote *remote, const char *ref)
27 {
28         int nr = remote->fetch_refspec_nr + 1;
29         remote->fetch_refspec =
30                 xrealloc(remote->fetch_refspec, nr * sizeof(char *));
31         remote->fetch_refspec[nr-1] = ref;
32         remote->fetch_refspec_nr = nr;
33 }
34
35 static void add_url(struct remote *remote, const char *url)
36 {
37         int nr = remote->url_nr + 1;
38         remote->url =
39                 xrealloc(remote->url, nr * sizeof(char *));
40         remote->url[nr-1] = url;
41         remote->url_nr = nr;
42 }
43
44 static struct remote *make_remote(const char *name, int len)
45 {
46         int i, empty = -1;
47
48         for (i = 0; i < allocated_remotes; i++) {
49                 if (!remotes[i]) {
50                         if (empty < 0)
51                                 empty = i;
52                 } else {
53                         if (len ? (!strncmp(name, remotes[i]->name, len) &&
54                                    !remotes[i]->name[len]) :
55                             !strcmp(name, remotes[i]->name))
56                                 return remotes[i];
57                 }
58         }
59
60         if (empty < 0) {
61                 empty = allocated_remotes;
62                 allocated_remotes += allocated_remotes ? allocated_remotes : 1;
63                 remotes = xrealloc(remotes,
64                                    sizeof(*remotes) * allocated_remotes);
65                 memset(remotes + empty, 0,
66                        (allocated_remotes - empty) * sizeof(*remotes));
67         }
68         remotes[empty] = xcalloc(1, sizeof(struct remote));
69         if (len)
70                 remotes[empty]->name = xstrndup(name, len);
71         else
72                 remotes[empty]->name = xstrdup(name);
73         return remotes[empty];
74 }
75
76 static void add_merge(struct branch *branch, const char *name)
77 {
78         int nr = branch->merge_nr + 1;
79         branch->merge_name =
80                 xrealloc(branch->merge_name, nr * sizeof(char *));
81         branch->merge_name[nr-1] = name;
82         branch->merge_nr = nr;
83 }
84
85 static struct branch *make_branch(const char *name, int len)
86 {
87         int i, empty = -1;
88         char *refname;
89
90         for (i = 0; i < allocated_branches; i++) {
91                 if (!branches[i]) {
92                         if (empty < 0)
93                                 empty = i;
94                 } else {
95                         if (len ? (!strncmp(name, branches[i]->name, len) &&
96                                    !branches[i]->name[len]) :
97                             !strcmp(name, branches[i]->name))
98                                 return branches[i];
99                 }
100         }
101
102         if (empty < 0) {
103                 empty = allocated_branches;
104                 allocated_branches += allocated_branches ? allocated_branches : 1;
105                 branches = xrealloc(branches,
106                                    sizeof(*branches) * allocated_branches);
107                 memset(branches + empty, 0,
108                        (allocated_branches - empty) * sizeof(*branches));
109         }
110         branches[empty] = xcalloc(1, sizeof(struct branch));
111         if (len)
112                 branches[empty]->name = xstrndup(name, len);
113         else
114                 branches[empty]->name = xstrdup(name);
115         refname = malloc(strlen(name) + strlen("refs/heads/") + 1);
116         strcpy(refname, "refs/heads/");
117         strcpy(refname + strlen("refs/heads/"),
118                branches[empty]->name);
119         branches[empty]->refname = refname;
120
121         return branches[empty];
122 }
123
124 static void read_remotes_file(struct remote *remote)
125 {
126         FILE *f = fopen(git_path("remotes/%s", remote->name), "r");
127
128         if (!f)
129                 return;
130         while (fgets(buffer, BUF_SIZE, f)) {
131                 int value_list;
132                 char *s, *p;
133
134                 if (!prefixcmp(buffer, "URL:")) {
135                         value_list = 0;
136                         s = buffer + 4;
137                 } else if (!prefixcmp(buffer, "Push:")) {
138                         value_list = 1;
139                         s = buffer + 5;
140                 } else if (!prefixcmp(buffer, "Pull:")) {
141                         value_list = 2;
142                         s = buffer + 5;
143                 } else
144                         continue;
145
146                 while (isspace(*s))
147                         s++;
148                 if (!*s)
149                         continue;
150
151                 p = s + strlen(s);
152                 while (isspace(p[-1]))
153                         *--p = 0;
154
155                 switch (value_list) {
156                 case 0:
157                         add_url(remote, xstrdup(s));
158                         break;
159                 case 1:
160                         add_push_refspec(remote, xstrdup(s));
161                         break;
162                 case 2:
163                         add_fetch_refspec(remote, xstrdup(s));
164                         break;
165                 }
166         }
167         fclose(f);
168 }
169
170 static void read_branches_file(struct remote *remote)
171 {
172         const char *slash = strchr(remote->name, '/');
173         char *frag;
174         struct strbuf branch;
175         int n = slash ? slash - remote->name : 1000;
176         FILE *f = fopen(git_path("branches/%.*s", n, remote->name), "r");
177         char *s, *p;
178         int len;
179
180         if (!f)
181                 return;
182         s = fgets(buffer, BUF_SIZE, f);
183         fclose(f);
184         if (!s)
185                 return;
186         while (isspace(*s))
187                 s++;
188         if (!*s)
189                 return;
190         p = s + strlen(s);
191         while (isspace(p[-1]))
192                 *--p = 0;
193         len = p - s;
194         if (slash)
195                 len += strlen(slash);
196         p = xmalloc(len + 1);
197         strcpy(p, s);
198         if (slash)
199                 strcat(p, slash);
200
201         /*
202          * With "slash", e.g. "git fetch jgarzik/netdev-2.6" when
203          * reading from $GIT_DIR/branches/jgarzik fetches "HEAD" from
204          * the partial URL obtained from the branches file plus
205          * "/netdev-2.6" and does not store it in any tracking ref.
206          * #branch specifier in the file is ignored.
207          *
208          * Otherwise, the branches file would have URL and optionally
209          * #branch specified.  The "master" (or specified) branch is
210          * fetched and stored in the local branch of the same name.
211          */
212         strbuf_init(&branch, 0);
213         frag = strchr(p, '#');
214         if (frag) {
215                 *(frag++) = '\0';
216                 strbuf_addf(&branch, "refs/heads/%s", frag);
217         } else
218                 strbuf_addstr(&branch, "refs/heads/master");
219         if (!slash) {
220                 strbuf_addf(&branch, ":refs/heads/%s", remote->name);
221         } else {
222                 strbuf_reset(&branch);
223                 strbuf_addstr(&branch, "HEAD:");
224         }
225         add_url(remote, p);
226         add_fetch_refspec(remote, strbuf_detach(&branch, 0));
227         remote->fetch_tags = 1; /* always auto-follow */
228 }
229
230 static int handle_config(const char *key, const char *value)
231 {
232         const char *name;
233         const char *subkey;
234         struct remote *remote;
235         struct branch *branch;
236         if (!prefixcmp(key, "branch.")) {
237                 name = key + 7;
238                 subkey = strrchr(name, '.');
239                 if (!subkey)
240                         return 0;
241                 branch = make_branch(name, subkey - name);
242                 if (!strcmp(subkey, ".remote")) {
243                         if (!value)
244                                 return config_error_nonbool(key);
245                         branch->remote_name = xstrdup(value);
246                         if (branch == current_branch)
247                                 default_remote_name = branch->remote_name;
248                 } else if (!strcmp(subkey, ".merge")) {
249                         if (!value)
250                                 return config_error_nonbool(key);
251                         add_merge(branch, xstrdup(value));
252                 }
253                 return 0;
254         }
255         if (prefixcmp(key,  "remote."))
256                 return 0;
257         name = key + 7;
258         subkey = strrchr(name, '.');
259         if (!subkey)
260                 return error("Config with no key for remote %s", name);
261         if (*subkey == '/') {
262                 warning("Config remote shorthand cannot begin with '/': %s", name);
263                 return 0;
264         }
265         remote = make_remote(name, subkey - name);
266         if (!value) {
267                 /* if we ever have a boolean variable, e.g. "remote.*.disabled"
268                  * [remote "frotz"]
269                  *      disabled
270                  * is a valid way to set it to true; we get NULL in value so
271                  * we need to handle it here.
272                  *
273                  * if (!strcmp(subkey, ".disabled")) {
274                  *      val = git_config_bool(key, value);
275                  *      return 0;
276                  * } else
277                  *
278                  */
279                 return 0; /* ignore unknown booleans */
280         }
281         if (!strcmp(subkey, ".url")) {
282                 add_url(remote, xstrdup(value));
283         } else if (!strcmp(subkey, ".push")) {
284                 add_push_refspec(remote, xstrdup(value));
285         } else if (!strcmp(subkey, ".fetch")) {
286                 add_fetch_refspec(remote, xstrdup(value));
287         } else if (!strcmp(subkey, ".receivepack")) {
288                 if (!remote->receivepack)
289                         remote->receivepack = xstrdup(value);
290                 else
291                         error("more than one receivepack given, using the first");
292         } else if (!strcmp(subkey, ".uploadpack")) {
293                 if (!remote->uploadpack)
294                         remote->uploadpack = xstrdup(value);
295                 else
296                         error("more than one uploadpack given, using the first");
297         } else if (!strcmp(subkey, ".tagopt")) {
298                 if (!strcmp(value, "--no-tags"))
299                         remote->fetch_tags = -1;
300         } else if (!strcmp(subkey, ".proxy")) {
301                 remote->http_proxy = xstrdup(value);
302         }
303         return 0;
304 }
305
306 static void read_config(void)
307 {
308         unsigned char sha1[20];
309         const char *head_ref;
310         int flag;
311         if (default_remote_name) // did this already
312                 return;
313         default_remote_name = xstrdup("origin");
314         current_branch = NULL;
315         head_ref = resolve_ref("HEAD", sha1, 0, &flag);
316         if (head_ref && (flag & REF_ISSYMREF) &&
317             !prefixcmp(head_ref, "refs/heads/")) {
318                 current_branch =
319                         make_branch(head_ref + strlen("refs/heads/"), 0);
320         }
321         git_config(handle_config);
322 }
323
324 static struct refspec *parse_refspec_internal(int nr_refspec, const char **refspec, int fetch)
325 {
326         int i;
327         int st;
328         struct refspec *rs = xcalloc(sizeof(*rs), nr_refspec);
329
330         for (i = 0; i < nr_refspec; i++) {
331                 size_t llen, rlen;
332                 int is_glob;
333                 const char *lhs, *rhs;
334
335                 llen = rlen = is_glob = 0;
336
337                 lhs = refspec[i];
338                 if (*lhs == '+') {
339                         rs[i].force = 1;
340                         lhs++;
341                 }
342
343                 rhs = strrchr(lhs, ':');
344                 if (rhs) {
345                         rhs++;
346                         rlen = strlen(rhs);
347                         is_glob = (2 <= rlen && !strcmp(rhs + rlen - 2, "/*"));
348                         if (is_glob)
349                                 rlen -= 2;
350                         rs[i].dst = xstrndup(rhs, rlen);
351                 }
352
353                 llen = (rhs ? (rhs - lhs - 1) : strlen(lhs));
354                 if (2 <= llen && !memcmp(lhs + llen - 2, "/*", 2)) {
355                         if ((rhs && !is_glob) || (!rhs && fetch))
356                                 goto invalid;
357                         is_glob = 1;
358                         llen -= 2;
359                 } else if (rhs && is_glob) {
360                         goto invalid;
361                 }
362
363                 rs[i].pattern = is_glob;
364                 rs[i].src = xstrndup(lhs, llen);
365
366                 if (fetch) {
367                         /*
368                          * LHS
369                          * - empty is allowed; it means HEAD.
370                          * - otherwise it must be a valid looking ref.
371                          */
372                         if (!*rs[i].src)
373                                 ; /* empty is ok */
374                         else {
375                                 st = check_ref_format(rs[i].src);
376                                 if (st && st != CHECK_REF_FORMAT_ONELEVEL)
377                                         goto invalid;
378                         }
379                         /*
380                          * RHS
381                          * - missing is ok, and is same as empty.
382                          * - empty is ok; it means not to store.
383                          * - otherwise it must be a valid looking ref.
384                          */
385                         if (!rs[i].dst) {
386                                 ; /* ok */
387                         } else if (!*rs[i].dst) {
388                                 ; /* ok */
389                         } else {
390                                 st = check_ref_format(rs[i].dst);
391                                 if (st && st != CHECK_REF_FORMAT_ONELEVEL)
392                                         goto invalid;
393                         }
394                 } else {
395                         /*
396                          * LHS
397                          * - empty is allowed; it means delete.
398                          * - when wildcarded, it must be a valid looking ref.
399                          * - otherwise, it must be an extended SHA-1, but
400                          *   there is no existing way to validate this.
401                          */
402                         if (!*rs[i].src)
403                                 ; /* empty is ok */
404                         else if (is_glob) {
405                                 st = check_ref_format(rs[i].src);
406                                 if (st && st != CHECK_REF_FORMAT_ONELEVEL)
407                                         goto invalid;
408                         }
409                         else
410                                 ; /* anything goes, for now */
411                         /*
412                          * RHS
413                          * - missing is allowed, but LHS then must be a
414                          *   valid looking ref.
415                          * - empty is not allowed.
416                          * - otherwise it must be a valid looking ref.
417                          */
418                         if (!rs[i].dst) {
419                                 st = check_ref_format(rs[i].src);
420                                 if (st && st != CHECK_REF_FORMAT_ONELEVEL)
421                                         goto invalid;
422                         } else if (!*rs[i].dst) {
423                                 goto invalid;
424                         } else {
425                                 st = check_ref_format(rs[i].dst);
426                                 if (st && st != CHECK_REF_FORMAT_ONELEVEL)
427                                         goto invalid;
428                         }
429                 }
430         }
431         return rs;
432
433  invalid:
434         die("Invalid refspec '%s'", refspec[i]);
435 }
436
437 struct refspec *parse_fetch_refspec(int nr_refspec, const char **refspec)
438 {
439         return parse_refspec_internal(nr_refspec, refspec, 1);
440 }
441
442 struct refspec *parse_push_refspec(int nr_refspec, const char **refspec)
443 {
444         return parse_refspec_internal(nr_refspec, refspec, 0);
445 }
446
447 static int valid_remote_nick(const char *name)
448 {
449         if (!name[0] || /* not empty */
450             (name[0] == '.' && /* not "." */
451              (!name[1] || /* not ".." */
452               (name[1] == '.' && !name[2]))))
453                 return 0;
454         return !strchr(name, '/'); /* no slash */
455 }
456
457 struct remote *remote_get(const char *name)
458 {
459         struct remote *ret;
460
461         read_config();
462         if (!name)
463                 name = default_remote_name;
464         ret = make_remote(name, 0);
465         if (valid_remote_nick(name)) {
466                 if (!ret->url)
467                         read_remotes_file(ret);
468                 if (!ret->url)
469                         read_branches_file(ret);
470         }
471         if (!ret->url)
472                 add_url(ret, name);
473         if (!ret->url)
474                 return NULL;
475         ret->fetch = parse_fetch_refspec(ret->fetch_refspec_nr, ret->fetch_refspec);
476         ret->push = parse_push_refspec(ret->push_refspec_nr, ret->push_refspec);
477         return ret;
478 }
479
480 int for_each_remote(each_remote_fn fn, void *priv)
481 {
482         int i, result = 0;
483         read_config();
484         for (i = 0; i < allocated_remotes && !result; i++) {
485                 struct remote *r = remotes[i];
486                 if (!r)
487                         continue;
488                 if (!r->fetch)
489                         r->fetch = parse_fetch_refspec(r->fetch_refspec_nr,
490                                                        r->fetch_refspec);
491                 if (!r->push)
492                         r->push = parse_push_refspec(r->push_refspec_nr,
493                                                      r->push_refspec);
494                 result = fn(r, priv);
495         }
496         return result;
497 }
498
499 void ref_remove_duplicates(struct ref *ref_map)
500 {
501         struct ref **posn;
502         struct ref *next;
503         for (; ref_map; ref_map = ref_map->next) {
504                 if (!ref_map->peer_ref)
505                         continue;
506                 posn = &ref_map->next;
507                 while (*posn) {
508                         if ((*posn)->peer_ref &&
509                             !strcmp((*posn)->peer_ref->name,
510                                     ref_map->peer_ref->name)) {
511                                 if (strcmp((*posn)->name, ref_map->name))
512                                         die("%s tracks both %s and %s",
513                                             ref_map->peer_ref->name,
514                                             (*posn)->name, ref_map->name);
515                                 next = (*posn)->next;
516                                 free((*posn)->peer_ref);
517                                 free(*posn);
518                                 *posn = next;
519                         } else {
520                                 posn = &(*posn)->next;
521                         }
522                 }
523         }
524 }
525
526 int remote_has_url(struct remote *remote, const char *url)
527 {
528         int i;
529         for (i = 0; i < remote->url_nr; i++) {
530                 if (!strcmp(remote->url[i], url))
531                         return 1;
532         }
533         return 0;
534 }
535
536 int remote_find_tracking(struct remote *remote, struct refspec *refspec)
537 {
538         int find_src = refspec->src == NULL;
539         char *needle, **result;
540         int i;
541
542         if (find_src) {
543                 if (!refspec->dst)
544                         return error("find_tracking: need either src or dst");
545                 needle = refspec->dst;
546                 result = &refspec->src;
547         } else {
548                 needle = refspec->src;
549                 result = &refspec->dst;
550         }
551
552         for (i = 0; i < remote->fetch_refspec_nr; i++) {
553                 struct refspec *fetch = &remote->fetch[i];
554                 const char *key = find_src ? fetch->dst : fetch->src;
555                 const char *value = find_src ? fetch->src : fetch->dst;
556                 if (!fetch->dst)
557                         continue;
558                 if (fetch->pattern) {
559                         if (!prefixcmp(needle, key) &&
560                             needle[strlen(key)] == '/') {
561                                 *result = xmalloc(strlen(value) +
562                                                   strlen(needle) -
563                                                   strlen(key) + 1);
564                                 strcpy(*result, value);
565                                 strcpy(*result + strlen(value),
566                                        needle + strlen(key));
567                                 refspec->force = fetch->force;
568                                 return 0;
569                         }
570                 } else if (!strcmp(needle, key)) {
571                         *result = xstrdup(value);
572                         refspec->force = fetch->force;
573                         return 0;
574                 }
575         }
576         return -1;
577 }
578
579 struct ref *alloc_ref(unsigned namelen)
580 {
581         struct ref *ret = xmalloc(sizeof(struct ref) + namelen);
582         memset(ret, 0, sizeof(struct ref) + namelen);
583         return ret;
584 }
585
586 static struct ref *copy_ref(const struct ref *ref)
587 {
588         struct ref *ret = xmalloc(sizeof(struct ref) + strlen(ref->name) + 1);
589         memcpy(ret, ref, sizeof(struct ref) + strlen(ref->name) + 1);
590         ret->next = NULL;
591         return ret;
592 }
593
594 struct ref *copy_ref_list(const struct ref *ref)
595 {
596         struct ref *ret = NULL;
597         struct ref **tail = &ret;
598         while (ref) {
599                 *tail = copy_ref(ref);
600                 ref = ref->next;
601                 tail = &((*tail)->next);
602         }
603         return ret;
604 }
605
606 void free_refs(struct ref *ref)
607 {
608         struct ref *next;
609         while (ref) {
610                 next = ref->next;
611                 if (ref->peer_ref)
612                         free(ref->peer_ref);
613                 free(ref);
614                 ref = next;
615         }
616 }
617
618 static int count_refspec_match(const char *pattern,
619                                struct ref *refs,
620                                struct ref **matched_ref)
621 {
622         int patlen = strlen(pattern);
623         struct ref *matched_weak = NULL;
624         struct ref *matched = NULL;
625         int weak_match = 0;
626         int match = 0;
627
628         for (weak_match = match = 0; refs; refs = refs->next) {
629                 char *name = refs->name;
630                 int namelen = strlen(name);
631
632                 if (!refname_match(pattern, name, ref_rev_parse_rules))
633                         continue;
634
635                 /* A match is "weak" if it is with refs outside
636                  * heads or tags, and did not specify the pattern
637                  * in full (e.g. "refs/remotes/origin/master") or at
638                  * least from the toplevel (e.g. "remotes/origin/master");
639                  * otherwise "git push $URL master" would result in
640                  * ambiguity between remotes/origin/master and heads/master
641                  * at the remote site.
642                  */
643                 if (namelen != patlen &&
644                     patlen != namelen - 5 &&
645                     prefixcmp(name, "refs/heads/") &&
646                     prefixcmp(name, "refs/tags/")) {
647                         /* We want to catch the case where only weak
648                          * matches are found and there are multiple
649                          * matches, and where more than one strong
650                          * matches are found, as ambiguous.  One
651                          * strong match with zero or more weak matches
652                          * are acceptable as a unique match.
653                          */
654                         matched_weak = refs;
655                         weak_match++;
656                 }
657                 else {
658                         matched = refs;
659                         match++;
660                 }
661         }
662         if (!matched) {
663                 *matched_ref = matched_weak;
664                 return weak_match;
665         }
666         else {
667                 *matched_ref = matched;
668                 return match;
669         }
670 }
671
672 static void tail_link_ref(struct ref *ref, struct ref ***tail)
673 {
674         **tail = ref;
675         while (ref->next)
676                 ref = ref->next;
677         *tail = &ref->next;
678 }
679
680 static struct ref *try_explicit_object_name(const char *name)
681 {
682         unsigned char sha1[20];
683         struct ref *ref;
684         int len;
685
686         if (!*name) {
687                 ref = alloc_ref(20);
688                 strcpy(ref->name, "(delete)");
689                 hashclr(ref->new_sha1);
690                 return ref;
691         }
692         if (get_sha1(name, sha1))
693                 return NULL;
694         len = strlen(name) + 1;
695         ref = alloc_ref(len);
696         memcpy(ref->name, name, len);
697         hashcpy(ref->new_sha1, sha1);
698         return ref;
699 }
700
701 static struct ref *make_linked_ref(const char *name, struct ref ***tail)
702 {
703         struct ref *ret;
704         size_t len;
705
706         len = strlen(name) + 1;
707         ret = alloc_ref(len);
708         memcpy(ret->name, name, len);
709         tail_link_ref(ret, tail);
710         return ret;
711 }
712
713 static int match_explicit(struct ref *src, struct ref *dst,
714                           struct ref ***dst_tail,
715                           struct refspec *rs,
716                           int errs)
717 {
718         struct ref *matched_src, *matched_dst;
719
720         const char *dst_value = rs->dst;
721
722         if (rs->pattern)
723                 return errs;
724
725         matched_src = matched_dst = NULL;
726         switch (count_refspec_match(rs->src, src, &matched_src)) {
727         case 1:
728                 break;
729         case 0:
730                 /* The source could be in the get_sha1() format
731                  * not a reference name.  :refs/other is a
732                  * way to delete 'other' ref at the remote end.
733                  */
734                 matched_src = try_explicit_object_name(rs->src);
735                 if (!matched_src)
736                         error("src refspec %s does not match any.", rs->src);
737                 break;
738         default:
739                 matched_src = NULL;
740                 error("src refspec %s matches more than one.", rs->src);
741                 break;
742         }
743
744         if (!matched_src)
745                 errs = 1;
746
747         if (!dst_value) {
748                 if (!matched_src)
749                         return errs;
750                 dst_value = matched_src->name;
751         }
752
753         switch (count_refspec_match(dst_value, dst, &matched_dst)) {
754         case 1:
755                 break;
756         case 0:
757                 if (!memcmp(dst_value, "refs/", 5))
758                         matched_dst = make_linked_ref(dst_value, dst_tail);
759                 else
760                         error("dst refspec %s does not match any "
761                               "existing ref on the remote and does "
762                               "not start with refs/.", dst_value);
763                 break;
764         default:
765                 matched_dst = NULL;
766                 error("dst refspec %s matches more than one.",
767                       dst_value);
768                 break;
769         }
770         if (errs || !matched_dst)
771                 return 1;
772         if (matched_dst->peer_ref) {
773                 errs = 1;
774                 error("dst ref %s receives from more than one src.",
775                       matched_dst->name);
776         }
777         else {
778                 matched_dst->peer_ref = matched_src;
779                 matched_dst->force = rs->force;
780         }
781         return errs;
782 }
783
784 static int match_explicit_refs(struct ref *src, struct ref *dst,
785                                struct ref ***dst_tail, struct refspec *rs,
786                                int rs_nr)
787 {
788         int i, errs;
789         for (i = errs = 0; i < rs_nr; i++)
790                 errs |= match_explicit(src, dst, dst_tail, &rs[i], errs);
791         return -errs;
792 }
793
794 static const struct refspec *check_pattern_match(const struct refspec *rs,
795                                                  int rs_nr,
796                                                  const struct ref *src)
797 {
798         int i;
799         for (i = 0; i < rs_nr; i++) {
800                 if (rs[i].pattern &&
801                     !prefixcmp(src->name, rs[i].src) &&
802                     src->name[strlen(rs[i].src)] == '/')
803                         return rs + i;
804         }
805         return NULL;
806 }
807
808 /*
809  * Note. This is used only by "push"; refspec matching rules for
810  * push and fetch are subtly different, so do not try to reuse it
811  * without thinking.
812  */
813 int match_refs(struct ref *src, struct ref *dst, struct ref ***dst_tail,
814                int nr_refspec, const char **refspec, int flags)
815 {
816         struct refspec *rs =
817                 parse_push_refspec(nr_refspec, (const char **) refspec);
818         int send_all = flags & MATCH_REFS_ALL;
819         int send_mirror = flags & MATCH_REFS_MIRROR;
820
821         if (match_explicit_refs(src, dst, dst_tail, rs, nr_refspec))
822                 return -1;
823
824         /* pick the remainder */
825         for ( ; src; src = src->next) {
826                 struct ref *dst_peer;
827                 const struct refspec *pat = NULL;
828                 char *dst_name;
829                 if (src->peer_ref)
830                         continue;
831                 if (nr_refspec) {
832                         pat = check_pattern_match(rs, nr_refspec, src);
833                         if (!pat)
834                                 continue;
835                 }
836                 else if (!send_mirror && prefixcmp(src->name, "refs/heads/"))
837                         /*
838                          * "matching refs"; traditionally we pushed everything
839                          * including refs outside refs/heads/ hierarchy, but
840                          * that does not make much sense these days.
841                          */
842                         continue;
843
844                 if (pat) {
845                         const char *dst_side = pat->dst ? pat->dst : pat->src;
846                         dst_name = xmalloc(strlen(dst_side) +
847                                            strlen(src->name) -
848                                            strlen(pat->src) + 2);
849                         strcpy(dst_name, dst_side);
850                         strcat(dst_name, src->name + strlen(pat->src));
851                 } else
852                         dst_name = xstrdup(src->name);
853                 dst_peer = find_ref_by_name(dst, dst_name);
854                 if (dst_peer && dst_peer->peer_ref)
855                         /* We're already sending something to this ref. */
856                         goto free_name;
857
858                 if (!dst_peer && !nr_refspec && !(send_all || send_mirror))
859                         /*
860                          * Remote doesn't have it, and we have no
861                          * explicit pattern, and we don't have
862                          * --all nor --mirror.
863                          */
864                         goto free_name;
865                 if (!dst_peer) {
866                         /* Create a new one and link it */
867                         dst_peer = make_linked_ref(dst_name, dst_tail);
868                         hashcpy(dst_peer->new_sha1, src->new_sha1);
869                 }
870                 dst_peer->peer_ref = src;
871                 if (pat)
872                         dst_peer->force = pat->force;
873         free_name:
874                 free(dst_name);
875         }
876         return 0;
877 }
878
879 struct branch *branch_get(const char *name)
880 {
881         struct branch *ret;
882
883         read_config();
884         if (!name || !*name || !strcmp(name, "HEAD"))
885                 ret = current_branch;
886         else
887                 ret = make_branch(name, 0);
888         if (ret && ret->remote_name) {
889                 ret->remote = remote_get(ret->remote_name);
890                 if (ret->merge_nr) {
891                         int i;
892                         ret->merge = xcalloc(sizeof(*ret->merge),
893                                              ret->merge_nr);
894                         for (i = 0; i < ret->merge_nr; i++) {
895                                 ret->merge[i] = xcalloc(1, sizeof(**ret->merge));
896                                 ret->merge[i]->src = xstrdup(ret->merge_name[i]);
897                                 remote_find_tracking(ret->remote,
898                                                      ret->merge[i]);
899                         }
900                 }
901         }
902         return ret;
903 }
904
905 int branch_has_merge_config(struct branch *branch)
906 {
907         return branch && !!branch->merge;
908 }
909
910 int branch_merge_matches(struct branch *branch,
911                                  int i,
912                                  const char *refname)
913 {
914         if (!branch || i < 0 || i >= branch->merge_nr)
915                 return 0;
916         return refname_match(branch->merge[i]->src, refname, ref_fetch_rules);
917 }
918
919 static struct ref *get_expanded_map(const struct ref *remote_refs,
920                                     const struct refspec *refspec)
921 {
922         const struct ref *ref;
923         struct ref *ret = NULL;
924         struct ref **tail = &ret;
925
926         int remote_prefix_len = strlen(refspec->src);
927         int local_prefix_len = strlen(refspec->dst);
928
929         for (ref = remote_refs; ref; ref = ref->next) {
930                 if (strchr(ref->name, '^'))
931                         continue; /* a dereference item */
932                 if (!prefixcmp(ref->name, refspec->src)) {
933                         const char *match;
934                         struct ref *cpy = copy_ref(ref);
935                         match = ref->name + remote_prefix_len;
936
937                         cpy->peer_ref = alloc_ref(local_prefix_len +
938                                                   strlen(match) + 1);
939                         sprintf(cpy->peer_ref->name, "%s%s",
940                                 refspec->dst, match);
941                         if (refspec->force)
942                                 cpy->peer_ref->force = 1;
943                         *tail = cpy;
944                         tail = &cpy->next;
945                 }
946         }
947
948         return ret;
949 }
950
951 static const struct ref *find_ref_by_name_abbrev(const struct ref *refs, const char *name)
952 {
953         const struct ref *ref;
954         for (ref = refs; ref; ref = ref->next) {
955                 if (refname_match(name, ref->name, ref_fetch_rules))
956                         return ref;
957         }
958         return NULL;
959 }
960
961 struct ref *get_remote_ref(const struct ref *remote_refs, const char *name)
962 {
963         const struct ref *ref = find_ref_by_name_abbrev(remote_refs, name);
964
965         if (!ref)
966                 return NULL;
967
968         return copy_ref(ref);
969 }
970
971 static struct ref *get_local_ref(const char *name)
972 {
973         struct ref *ret;
974         if (!name)
975                 return NULL;
976
977         if (!prefixcmp(name, "refs/")) {
978                 ret = alloc_ref(strlen(name) + 1);
979                 strcpy(ret->name, name);
980                 return ret;
981         }
982
983         if (!prefixcmp(name, "heads/") ||
984             !prefixcmp(name, "tags/") ||
985             !prefixcmp(name, "remotes/")) {
986                 ret = alloc_ref(strlen(name) + 6);
987                 sprintf(ret->name, "refs/%s", name);
988                 return ret;
989         }
990
991         ret = alloc_ref(strlen(name) + 12);
992         sprintf(ret->name, "refs/heads/%s", name);
993         return ret;
994 }
995
996 int get_fetch_map(const struct ref *remote_refs,
997                   const struct refspec *refspec,
998                   struct ref ***tail,
999                   int missing_ok)
1000 {
1001         struct ref *ref_map, **rmp;
1002
1003         if (refspec->pattern) {
1004                 ref_map = get_expanded_map(remote_refs, refspec);
1005         } else {
1006                 const char *name = refspec->src[0] ? refspec->src : "HEAD";
1007
1008                 ref_map = get_remote_ref(remote_refs, name);
1009                 if (!missing_ok && !ref_map)
1010                         die("Couldn't find remote ref %s", name);
1011                 if (ref_map) {
1012                         ref_map->peer_ref = get_local_ref(refspec->dst);
1013                         if (ref_map->peer_ref && refspec->force)
1014                                 ref_map->peer_ref->force = 1;
1015                 }
1016         }
1017
1018         for (rmp = &ref_map; *rmp; ) {
1019                 if ((*rmp)->peer_ref) {
1020                         int st = check_ref_format((*rmp)->peer_ref->name + 5);
1021                         if (st && st != CHECK_REF_FORMAT_ONELEVEL) {
1022                                 struct ref *ignore = *rmp;
1023                                 error("* Ignoring funny ref '%s' locally",
1024                                       (*rmp)->peer_ref->name);
1025                                 *rmp = (*rmp)->next;
1026                                 free(ignore->peer_ref);
1027                                 free(ignore);
1028                                 continue;
1029                         }
1030                 }
1031                 rmp = &((*rmp)->next);
1032         }
1033
1034         if (ref_map)
1035                 tail_link_ref(ref_map, tail);
1036
1037         return 0;
1038 }