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