Code

add special "matching refs" refspec
[git.git] / remote.c
1 #include "cache.h"
2 #include "remote.h"
3 #include "refs.h"
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 };
17 static struct remote **remotes;
18 static int remotes_alloc;
19 static int remotes_nr;
21 static struct branch **branches;
22 static int branches_alloc;
23 static int branches_nr;
25 static struct branch *current_branch;
26 static const char *default_remote_name;
28 static struct rewrite **rewrite;
29 static int rewrite_alloc;
30 static int rewrite_nr;
32 #define BUF_SIZE (2048)
33 static char buffer[BUF_SIZE];
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;
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;
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 }
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 }
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 }
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 }
88 static void add_url_alias(struct remote *remote, const char *url)
89 {
90         add_url(remote, alias_url(url));
91 }
93 static struct remote *make_remote(const char *name, int len)
94 {
95         struct remote *ret;
96         int i;
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         }
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;
115 static void add_merge(struct branch *branch, const char *name)
117         ALLOC_GROW(branch->merge_name, branch->merge_nr + 1,
118                    branch->merge_alloc);
119         branch->merge_name[branch->merge_nr++] = name;
122 static struct branch *make_branch(const char *name, int len)
124         struct branch *ret;
125         int i;
126         char *refname;
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         }
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;
147         return ret;
150 static struct rewrite *make_rewrite(const char *base, int len)
152         struct rewrite *ret;
153         int i;
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         }
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;
177 static void add_instead_of(struct rewrite *rewrite, const char *instead_of)
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++;
185 static void read_remotes_file(struct remote *remote)
187         FILE *f = fopen(git_path("remotes/%s", remote->name), "r");
189         if (!f)
190                 return;
191         while (fgets(buffer, BUF_SIZE, f)) {
192                 int value_list;
193                 char *s, *p;
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;
207                 while (isspace(*s))
208                         s++;
209                 if (!*s)
210                         continue;
212                 p = s + strlen(s);
213                 while (isspace(p[-1]))
214                         *--p = 0;
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);
231 static void read_branches_file(struct remote *remote)
233         const char *slash = strchr(remote->name, '/');
234         char *frag;
235         struct strbuf 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;
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);
262         /*
263          * With "slash", e.g. "git fetch jgarzik/netdev-2.6" when
264          * reading from $GIT_DIR/branches/jgarzik fetches "HEAD" from
265          * the partial URL obtained from the branches file plus
266          * "/netdev-2.6" and does not store it in any tracking ref.
267          * #branch specifier in the file is ignored.
268          *
269          * Otherwise, the branches file would have URL and optionally
270          * #branch specified.  The "master" (or specified) branch is
271          * fetched and stored in the local branch of the same name.
272          */
273         strbuf_init(&branch, 0);
274         frag = strchr(p, '#');
275         if (frag) {
276                 *(frag++) = '\0';
277                 strbuf_addf(&branch, "refs/heads/%s", frag);
278         } else
279                 strbuf_addstr(&branch, "refs/heads/master");
280         if (!slash) {
281                 strbuf_addf(&branch, ":refs/heads/%s", remote->name);
282         } else {
283                 strbuf_reset(&branch);
284                 strbuf_addstr(&branch, "HEAD:");
285         }
286         add_url_alias(remote, p);
287         add_fetch_refspec(remote, strbuf_detach(&branch, 0));
288         remote->fetch_tags = 1; /* always auto-follow */
291 static int handle_config(const char *key, const char *value)
293         const char *name;
294         const char *subkey;
295         struct remote *remote;
296         struct branch *branch;
297         if (!prefixcmp(key, "branch.")) {
298                 name = key + 7;
299                 subkey = strrchr(name, '.');
300                 if (!subkey)
301                         return 0;
302                 branch = make_branch(name, subkey - name);
303                 if (!strcmp(subkey, ".remote")) {
304                         if (!value)
305                                 return config_error_nonbool(key);
306                         branch->remote_name = xstrdup(value);
307                         if (branch == current_branch)
308                                 default_remote_name = branch->remote_name;
309                 } else if (!strcmp(subkey, ".merge")) {
310                         if (!value)
311                                 return config_error_nonbool(key);
312                         add_merge(branch, xstrdup(value));
313                 }
314                 return 0;
315         }
316         if (!prefixcmp(key, "url.")) {
317                 struct rewrite *rewrite;
318                 name = key + 4;
319                 subkey = strrchr(name, '.');
320                 if (!subkey)
321                         return 0;
322                 rewrite = make_rewrite(name, subkey - name);
323                 if (!strcmp(subkey, ".insteadof")) {
324                         if (!value)
325                                 return config_error_nonbool(key);
326                         add_instead_of(rewrite, xstrdup(value));
327                 }
328         }
329         if (prefixcmp(key,  "remote."))
330                 return 0;
331         name = key + 7;
332         subkey = strrchr(name, '.');
333         if (!subkey)
334                 return error("Config with no key for remote %s", name);
335         if (*subkey == '/') {
336                 warning("Config remote shorthand cannot begin with '/': %s", name);
337                 return 0;
338         }
339         remote = make_remote(name, subkey - name);
340         if (!value) {
341                 /* if we ever have a boolean variable, e.g. "remote.*.disabled"
342                  * [remote "frotz"]
343                  *      disabled
344                  * is a valid way to set it to true; we get NULL in value so
345                  * we need to handle it here.
346                  *
347                  * if (!strcmp(subkey, ".disabled")) {
348                  *      val = git_config_bool(key, value);
349                  *      return 0;
350                  * } else
351                  *
352                  */
353                 return 0; /* ignore unknown booleans */
354         }
355         if (!strcmp(subkey, ".url")) {
356                 add_url(remote, xstrdup(value));
357         } else if (!strcmp(subkey, ".push")) {
358                 add_push_refspec(remote, xstrdup(value));
359         } else if (!strcmp(subkey, ".fetch")) {
360                 add_fetch_refspec(remote, xstrdup(value));
361         } else if (!strcmp(subkey, ".receivepack")) {
362                 if (!remote->receivepack)
363                         remote->receivepack = xstrdup(value);
364                 else
365                         error("more than one receivepack given, using the first");
366         } else if (!strcmp(subkey, ".uploadpack")) {
367                 if (!remote->uploadpack)
368                         remote->uploadpack = xstrdup(value);
369                 else
370                         error("more than one uploadpack given, using the first");
371         } else if (!strcmp(subkey, ".tagopt")) {
372                 if (!strcmp(value, "--no-tags"))
373                         remote->fetch_tags = -1;
374         } else if (!strcmp(subkey, ".proxy")) {
375                 remote->http_proxy = xstrdup(value);
376         } else if (!strcmp(subkey, ".skipdefaultupdate"))
377                 remote->skip_default_update = 1;
378         return 0;
381 static void alias_all_urls(void)
383         int i, j;
384         for (i = 0; i < remotes_nr; i++) {
385                 if (!remotes[i])
386                         continue;
387                 for (j = 0; j < remotes[i]->url_nr; j++) {
388                         remotes[i]->url[j] = alias_url(remotes[i]->url[j]);
389                 }
390         }
393 static void read_config(void)
395         unsigned char sha1[20];
396         const char *head_ref;
397         int flag;
398         if (default_remote_name) // did this already
399                 return;
400         default_remote_name = xstrdup("origin");
401         current_branch = NULL;
402         head_ref = resolve_ref("HEAD", sha1, 0, &flag);
403         if (head_ref && (flag & REF_ISSYMREF) &&
404             !prefixcmp(head_ref, "refs/heads/")) {
405                 current_branch =
406                         make_branch(head_ref + strlen("refs/heads/"), 0);
407         }
408         git_config(handle_config);
409         alias_all_urls();
412 static struct refspec *parse_refspec_internal(int nr_refspec, const char **refspec, int fetch, int verify)
414         int i;
415         int st;
416         struct refspec *rs = xcalloc(sizeof(*rs), nr_refspec);
418         for (i = 0; i < nr_refspec; i++) {
419                 size_t llen, rlen;
420                 int is_glob;
421                 const char *lhs, *rhs;
423                 llen = rlen = is_glob = 0;
425                 lhs = refspec[i];
426                 if (*lhs == '+') {
427                         rs[i].force = 1;
428                         lhs++;
429                 }
431                 rhs = strrchr(lhs, ':');
433                 /*
434                  * Before going on, special case ":" (or "+:") as a refspec
435                  * for matching refs.
436                  */
437                 if (!fetch && rhs == lhs && rhs[1] == '\0') {
438                         rs[i].matching = 1;
439                         continue;
440                 }
442                 if (rhs) {
443                         rhs++;
444                         rlen = strlen(rhs);
445                         is_glob = (2 <= rlen && !strcmp(rhs + rlen - 2, "/*"));
446                         if (is_glob)
447                                 rlen -= 2;
448                         rs[i].dst = xstrndup(rhs, rlen);
449                 }
451                 llen = (rhs ? (rhs - lhs - 1) : strlen(lhs));
452                 if (2 <= llen && !memcmp(lhs + llen - 2, "/*", 2)) {
453                         if ((rhs && !is_glob) || (!rhs && fetch))
454                                 goto invalid;
455                         is_glob = 1;
456                         llen -= 2;
457                 } else if (rhs && is_glob) {
458                         goto invalid;
459                 }
461                 rs[i].pattern = is_glob;
462                 rs[i].src = xstrndup(lhs, llen);
464                 if (fetch) {
465                         /*
466                          * LHS
467                          * - empty is allowed; it means HEAD.
468                          * - otherwise it must be a valid looking ref.
469                          */
470                         if (!*rs[i].src)
471                                 ; /* empty is ok */
472                         else {
473                                 st = check_ref_format(rs[i].src);
474                                 if (st && st != CHECK_REF_FORMAT_ONELEVEL)
475                                         goto invalid;
476                         }
477                         /*
478                          * RHS
479                          * - missing is ok, and is same as empty.
480                          * - empty is ok; it means not to store.
481                          * - otherwise it must be a valid looking ref.
482                          */
483                         if (!rs[i].dst) {
484                                 ; /* ok */
485                         } else if (!*rs[i].dst) {
486                                 ; /* ok */
487                         } else {
488                                 st = check_ref_format(rs[i].dst);
489                                 if (st && st != CHECK_REF_FORMAT_ONELEVEL)
490                                         goto invalid;
491                         }
492                 } else {
493                         /*
494                          * LHS
495                          * - empty is allowed; it means delete.
496                          * - when wildcarded, it must be a valid looking ref.
497                          * - otherwise, it must be an extended SHA-1, but
498                          *   there is no existing way to validate this.
499                          */
500                         if (!*rs[i].src)
501                                 ; /* empty is ok */
502                         else if (is_glob) {
503                                 st = check_ref_format(rs[i].src);
504                                 if (st && st != CHECK_REF_FORMAT_ONELEVEL)
505                                         goto invalid;
506                         }
507                         else
508                                 ; /* anything goes, for now */
509                         /*
510                          * RHS
511                          * - missing is allowed, but LHS then must be a
512                          *   valid looking ref.
513                          * - empty is not allowed.
514                          * - otherwise it must be a valid looking ref.
515                          */
516                         if (!rs[i].dst) {
517                                 st = check_ref_format(rs[i].src);
518                                 if (st && st != CHECK_REF_FORMAT_ONELEVEL)
519                                         goto invalid;
520                         } else if (!*rs[i].dst) {
521                                 goto invalid;
522                         } else {
523                                 st = check_ref_format(rs[i].dst);
524                                 if (st && st != CHECK_REF_FORMAT_ONELEVEL)
525                                         goto invalid;
526                         }
527                 }
528         }
529         return rs;
531  invalid:
532         if (verify) {
533                 free(rs);
534                 return NULL;
535         }
536         die("Invalid refspec '%s'", refspec[i]);
539 int valid_fetch_refspec(const char *fetch_refspec_str)
541         const char *fetch_refspec[] = { fetch_refspec_str };
542         struct refspec *refspec;
544         refspec = parse_refspec_internal(1, fetch_refspec, 1, 1);
545         if (refspec)
546                 free(refspec);
547         return !!refspec;
550 struct refspec *parse_fetch_refspec(int nr_refspec, const char **refspec)
552         return parse_refspec_internal(nr_refspec, refspec, 1, 0);
555 struct refspec *parse_push_refspec(int nr_refspec, const char **refspec)
557         return parse_refspec_internal(nr_refspec, refspec, 0, 0);
560 static int valid_remote_nick(const char *name)
562         if (!name[0] || /* not empty */
563             (name[0] == '.' && /* not "." */
564              (!name[1] || /* not ".." */
565               (name[1] == '.' && !name[2]))))
566                 return 0;
567         return !strchr(name, '/'); /* no slash */
570 struct remote *remote_get(const char *name)
572         struct remote *ret;
574         read_config();
575         if (!name)
576                 name = default_remote_name;
577         ret = make_remote(name, 0);
578         if (valid_remote_nick(name)) {
579                 if (!ret->url)
580                         read_remotes_file(ret);
581                 if (!ret->url)
582                         read_branches_file(ret);
583         }
584         if (!ret->url)
585                 add_url_alias(ret, name);
586         if (!ret->url)
587                 return NULL;
588         ret->fetch = parse_fetch_refspec(ret->fetch_refspec_nr, ret->fetch_refspec);
589         ret->push = parse_push_refspec(ret->push_refspec_nr, ret->push_refspec);
590         return ret;
593 int for_each_remote(each_remote_fn fn, void *priv)
595         int i, result = 0;
596         read_config();
597         for (i = 0; i < remotes_nr && !result; i++) {
598                 struct remote *r = remotes[i];
599                 if (!r)
600                         continue;
601                 if (!r->fetch)
602                         r->fetch = parse_fetch_refspec(r->fetch_refspec_nr,
603                                                        r->fetch_refspec);
604                 if (!r->push)
605                         r->push = parse_push_refspec(r->push_refspec_nr,
606                                                      r->push_refspec);
607                 result = fn(r, priv);
608         }
609         return result;
612 void ref_remove_duplicates(struct ref *ref_map)
614         struct ref **posn;
615         struct ref *next;
616         for (; ref_map; ref_map = ref_map->next) {
617                 if (!ref_map->peer_ref)
618                         continue;
619                 posn = &ref_map->next;
620                 while (*posn) {
621                         if ((*posn)->peer_ref &&
622                             !strcmp((*posn)->peer_ref->name,
623                                     ref_map->peer_ref->name)) {
624                                 if (strcmp((*posn)->name, ref_map->name))
625                                         die("%s tracks both %s and %s",
626                                             ref_map->peer_ref->name,
627                                             (*posn)->name, ref_map->name);
628                                 next = (*posn)->next;
629                                 free((*posn)->peer_ref);
630                                 free(*posn);
631                                 *posn = next;
632                         } else {
633                                 posn = &(*posn)->next;
634                         }
635                 }
636         }
639 int remote_has_url(struct remote *remote, const char *url)
641         int i;
642         for (i = 0; i < remote->url_nr; i++) {
643                 if (!strcmp(remote->url[i], url))
644                         return 1;
645         }
646         return 0;
649 int remote_find_tracking(struct remote *remote, struct refspec *refspec)
651         int find_src = refspec->src == NULL;
652         char *needle, **result;
653         int i;
655         if (find_src) {
656                 if (!refspec->dst)
657                         return error("find_tracking: need either src or dst");
658                 needle = refspec->dst;
659                 result = &refspec->src;
660         } else {
661                 needle = refspec->src;
662                 result = &refspec->dst;
663         }
665         for (i = 0; i < remote->fetch_refspec_nr; i++) {
666                 struct refspec *fetch = &remote->fetch[i];
667                 const char *key = find_src ? fetch->dst : fetch->src;
668                 const char *value = find_src ? fetch->src : fetch->dst;
669                 if (!fetch->dst)
670                         continue;
671                 if (fetch->pattern) {
672                         if (!prefixcmp(needle, key) &&
673                             needle[strlen(key)] == '/') {
674                                 *result = xmalloc(strlen(value) +
675                                                   strlen(needle) -
676                                                   strlen(key) + 1);
677                                 strcpy(*result, value);
678                                 strcpy(*result + strlen(value),
679                                        needle + strlen(key));
680                                 refspec->force = fetch->force;
681                                 return 0;
682                         }
683                 } else if (!strcmp(needle, key)) {
684                         *result = xstrdup(value);
685                         refspec->force = fetch->force;
686                         return 0;
687                 }
688         }
689         return -1;
692 struct ref *alloc_ref(unsigned namelen)
694         struct ref *ret = xmalloc(sizeof(struct ref) + namelen);
695         memset(ret, 0, sizeof(struct ref) + namelen);
696         return ret;
699 static struct ref *copy_ref(const struct ref *ref)
701         struct ref *ret = xmalloc(sizeof(struct ref) + strlen(ref->name) + 1);
702         memcpy(ret, ref, sizeof(struct ref) + strlen(ref->name) + 1);
703         ret->next = NULL;
704         return ret;
707 struct ref *copy_ref_list(const struct ref *ref)
709         struct ref *ret = NULL;
710         struct ref **tail = &ret;
711         while (ref) {
712                 *tail = copy_ref(ref);
713                 ref = ref->next;
714                 tail = &((*tail)->next);
715         }
716         return ret;
719 void free_refs(struct ref *ref)
721         struct ref *next;
722         while (ref) {
723                 next = ref->next;
724                 free(ref->peer_ref);
725                 free(ref);
726                 ref = next;
727         }
730 static int count_refspec_match(const char *pattern,
731                                struct ref *refs,
732                                struct ref **matched_ref)
734         int patlen = strlen(pattern);
735         struct ref *matched_weak = NULL;
736         struct ref *matched = NULL;
737         int weak_match = 0;
738         int match = 0;
740         for (weak_match = match = 0; refs; refs = refs->next) {
741                 char *name = refs->name;
742                 int namelen = strlen(name);
744                 if (!refname_match(pattern, name, ref_rev_parse_rules))
745                         continue;
747                 /* A match is "weak" if it is with refs outside
748                  * heads or tags, and did not specify the pattern
749                  * in full (e.g. "refs/remotes/origin/master") or at
750                  * least from the toplevel (e.g. "remotes/origin/master");
751                  * otherwise "git push $URL master" would result in
752                  * ambiguity between remotes/origin/master and heads/master
753                  * at the remote site.
754                  */
755                 if (namelen != patlen &&
756                     patlen != namelen - 5 &&
757                     prefixcmp(name, "refs/heads/") &&
758                     prefixcmp(name, "refs/tags/")) {
759                         /* We want to catch the case where only weak
760                          * matches are found and there are multiple
761                          * matches, and where more than one strong
762                          * matches are found, as ambiguous.  One
763                          * strong match with zero or more weak matches
764                          * are acceptable as a unique match.
765                          */
766                         matched_weak = refs;
767                         weak_match++;
768                 }
769                 else {
770                         matched = refs;
771                         match++;
772                 }
773         }
774         if (!matched) {
775                 *matched_ref = matched_weak;
776                 return weak_match;
777         }
778         else {
779                 *matched_ref = matched;
780                 return match;
781         }
784 static void tail_link_ref(struct ref *ref, struct ref ***tail)
786         **tail = ref;
787         while (ref->next)
788                 ref = ref->next;
789         *tail = &ref->next;
792 static struct ref *try_explicit_object_name(const char *name)
794         unsigned char sha1[20];
795         struct ref *ref;
796         int len;
798         if (!*name) {
799                 ref = alloc_ref(20);
800                 strcpy(ref->name, "(delete)");
801                 hashclr(ref->new_sha1);
802                 return ref;
803         }
804         if (get_sha1(name, sha1))
805                 return NULL;
806         len = strlen(name) + 1;
807         ref = alloc_ref(len);
808         memcpy(ref->name, name, len);
809         hashcpy(ref->new_sha1, sha1);
810         return ref;
813 static struct ref *make_linked_ref(const char *name, struct ref ***tail)
815         struct ref *ret;
816         size_t len;
818         len = strlen(name) + 1;
819         ret = alloc_ref(len);
820         memcpy(ret->name, name, len);
821         tail_link_ref(ret, tail);
822         return ret;
825 static char *guess_ref(const char *name, struct ref *peer)
827         struct strbuf buf = STRBUF_INIT;
828         unsigned char sha1[20];
830         const char *r = resolve_ref(peer->name, sha1, 1, NULL);
831         if (!r)
832                 return NULL;
834         if (!prefixcmp(r, "refs/heads/"))
835                 strbuf_addstr(&buf, "refs/heads/");
836         else if (!prefixcmp(r, "refs/tags/"))
837                 strbuf_addstr(&buf, "refs/tags/");
838         else
839                 return NULL;
841         strbuf_addstr(&buf, name);
842         return strbuf_detach(&buf, NULL);
845 static int match_explicit(struct ref *src, struct ref *dst,
846                           struct ref ***dst_tail,
847                           struct refspec *rs,
848                           int errs)
850         struct ref *matched_src, *matched_dst;
852         const char *dst_value = rs->dst;
853         char *dst_guess;
855         if (rs->pattern || rs->matching)
856                 return errs;
858         matched_src = matched_dst = NULL;
859         switch (count_refspec_match(rs->src, src, &matched_src)) {
860         case 1:
861                 break;
862         case 0:
863                 /* The source could be in the get_sha1() format
864                  * not a reference name.  :refs/other is a
865                  * way to delete 'other' ref at the remote end.
866                  */
867                 matched_src = try_explicit_object_name(rs->src);
868                 if (!matched_src)
869                         error("src refspec %s does not match any.", rs->src);
870                 break;
871         default:
872                 matched_src = NULL;
873                 error("src refspec %s matches more than one.", rs->src);
874                 break;
875         }
877         if (!matched_src)
878                 errs = 1;
880         if (!dst_value) {
881                 unsigned char sha1[20];
882                 int flag;
884                 if (!matched_src)
885                         return errs;
886                 dst_value = resolve_ref(matched_src->name, sha1, 1, &flag);
887                 if (!dst_value ||
888                     ((flag & REF_ISSYMREF) &&
889                      prefixcmp(dst_value, "refs/heads/")))
890                         die("%s cannot be resolved to branch.",
891                             matched_src->name);
892         }
894         switch (count_refspec_match(dst_value, dst, &matched_dst)) {
895         case 1:
896                 break;
897         case 0:
898                 if (!memcmp(dst_value, "refs/", 5))
899                         matched_dst = make_linked_ref(dst_value, dst_tail);
900                 else if((dst_guess = guess_ref(dst_value, matched_src)))
901                         matched_dst = make_linked_ref(dst_guess, dst_tail);
902                 else
903                         error("unable to push to unqualified destination: %s\n"
904                               "The destination refspec neither matches an "
905                               "existing ref on the remote nor\n"
906                               "begins with refs/, and we are unable to "
907                               "guess a prefix based on the source ref.",
908                               dst_value);
909                 break;
910         default:
911                 matched_dst = NULL;
912                 error("dst refspec %s matches more than one.",
913                       dst_value);
914                 break;
915         }
916         if (errs || !matched_dst)
917                 return 1;
918         if (matched_dst->peer_ref) {
919                 errs = 1;
920                 error("dst ref %s receives from more than one src.",
921                       matched_dst->name);
922         }
923         else {
924                 matched_dst->peer_ref = matched_src;
925                 matched_dst->force = rs->force;
926         }
927         return errs;
930 static int match_explicit_refs(struct ref *src, struct ref *dst,
931                                struct ref ***dst_tail, struct refspec *rs,
932                                int rs_nr)
934         int i, errs;
935         for (i = errs = 0; i < rs_nr; i++)
936                 errs |= match_explicit(src, dst, dst_tail, &rs[i], errs);
937         return -errs;
940 static const struct refspec *check_pattern_match(const struct refspec *rs,
941                                                  int rs_nr,
942                                                  const struct ref *src)
944         int i;
945         int matching_refs = -1;
946         for (i = 0; i < rs_nr; i++) {
947                 if (rs[i].matching &&
948                     (matching_refs == -1 || rs[i].force)) {
949                         matching_refs = i;
950                         continue;
951                 }
953                 if (rs[i].pattern &&
954                     !prefixcmp(src->name, rs[i].src) &&
955                     src->name[strlen(rs[i].src)] == '/')
956                         return rs + i;
957         }
958         if (matching_refs != -1)
959                 return rs + matching_refs;
960         else
961                 return NULL;
964 /*
965  * Note. This is used only by "push"; refspec matching rules for
966  * push and fetch are subtly different, so do not try to reuse it
967  * without thinking.
968  */
969 int match_refs(struct ref *src, struct ref *dst, struct ref ***dst_tail,
970                int nr_refspec, const char **refspec, int flags)
972         struct refspec *rs;
973         int send_all = flags & MATCH_REFS_ALL;
974         int send_mirror = flags & MATCH_REFS_MIRROR;
975         static const char *default_refspec[] = { ":", 0 };
977         if (!nr_refspec) {
978                 nr_refspec = 1;
979                 refspec = default_refspec;
980         }
981         rs = parse_push_refspec(nr_refspec, (const char **) refspec);
982         if (match_explicit_refs(src, dst, dst_tail, rs, nr_refspec))
983                 return -1;
985         /* pick the remainder */
986         for ( ; src; src = src->next) {
987                 struct ref *dst_peer;
988                 const struct refspec *pat = NULL;
989                 char *dst_name;
990                 if (src->peer_ref)
991                         continue;
993                 pat = check_pattern_match(rs, nr_refspec, src);
994                 if (!pat)
995                         continue;
997                 if (pat->matching) {
998                         /*
999                          * "matching refs"; traditionally we pushed everything
1000                          * including refs outside refs/heads/ hierarchy, but
1001                          * that does not make much sense these days.
1002                          */
1003                         if (!send_mirror && prefixcmp(src->name, "refs/heads/"))
1004                                 continue;
1005                         dst_name = xstrdup(src->name);
1007                 } else {
1008                         const char *dst_side = pat->dst ? pat->dst : pat->src;
1009                         dst_name = xmalloc(strlen(dst_side) +
1010                                            strlen(src->name) -
1011                                            strlen(pat->src) + 2);
1012                         strcpy(dst_name, dst_side);
1013                         strcat(dst_name, src->name + strlen(pat->src));
1014                 }
1015                 dst_peer = find_ref_by_name(dst, dst_name);
1016                 if (dst_peer) {
1017                         if (dst_peer->peer_ref)
1018                                 /* We're already sending something to this ref. */
1019                                 goto free_name;
1021                 } else {
1022                         if (pat->matching && !(send_all || send_mirror))
1023                                 /*
1024                                  * Remote doesn't have it, and we have no
1025                                  * explicit pattern, and we don't have
1026                                  * --all nor --mirror.
1027                                  */
1028                                 goto free_name;
1030                         /* Create a new one and link it */
1031                         dst_peer = make_linked_ref(dst_name, dst_tail);
1032                         hashcpy(dst_peer->new_sha1, src->new_sha1);
1033                 }
1034                 dst_peer->peer_ref = src;
1035                 dst_peer->force = pat->force;
1036         free_name:
1037                 free(dst_name);
1038         }
1039         return 0;
1042 struct branch *branch_get(const char *name)
1044         struct branch *ret;
1046         read_config();
1047         if (!name || !*name || !strcmp(name, "HEAD"))
1048                 ret = current_branch;
1049         else
1050                 ret = make_branch(name, 0);
1051         if (ret && ret->remote_name) {
1052                 ret->remote = remote_get(ret->remote_name);
1053                 if (ret->merge_nr) {
1054                         int i;
1055                         ret->merge = xcalloc(sizeof(*ret->merge),
1056                                              ret->merge_nr);
1057                         for (i = 0; i < ret->merge_nr; i++) {
1058                                 ret->merge[i] = xcalloc(1, sizeof(**ret->merge));
1059                                 ret->merge[i]->src = xstrdup(ret->merge_name[i]);
1060                                 remote_find_tracking(ret->remote,
1061                                                      ret->merge[i]);
1062                         }
1063                 }
1064         }
1065         return ret;
1068 int branch_has_merge_config(struct branch *branch)
1070         return branch && !!branch->merge;
1073 int branch_merge_matches(struct branch *branch,
1074                                  int i,
1075                                  const char *refname)
1077         if (!branch || i < 0 || i >= branch->merge_nr)
1078                 return 0;
1079         return refname_match(branch->merge[i]->src, refname, ref_fetch_rules);
1082 static struct ref *get_expanded_map(const struct ref *remote_refs,
1083                                     const struct refspec *refspec)
1085         const struct ref *ref;
1086         struct ref *ret = NULL;
1087         struct ref **tail = &ret;
1089         int remote_prefix_len = strlen(refspec->src);
1090         int local_prefix_len = strlen(refspec->dst);
1092         for (ref = remote_refs; ref; ref = ref->next) {
1093                 if (strchr(ref->name, '^'))
1094                         continue; /* a dereference item */
1095                 if (!prefixcmp(ref->name, refspec->src)) {
1096                         const char *match;
1097                         struct ref *cpy = copy_ref(ref);
1098                         match = ref->name + remote_prefix_len;
1100                         cpy->peer_ref = alloc_ref(local_prefix_len +
1101                                                   strlen(match) + 1);
1102                         sprintf(cpy->peer_ref->name, "%s%s",
1103                                 refspec->dst, match);
1104                         if (refspec->force)
1105                                 cpy->peer_ref->force = 1;
1106                         *tail = cpy;
1107                         tail = &cpy->next;
1108                 }
1109         }
1111         return ret;
1114 static const struct ref *find_ref_by_name_abbrev(const struct ref *refs, const char *name)
1116         const struct ref *ref;
1117         for (ref = refs; ref; ref = ref->next) {
1118                 if (refname_match(name, ref->name, ref_fetch_rules))
1119                         return ref;
1120         }
1121         return NULL;
1124 struct ref *get_remote_ref(const struct ref *remote_refs, const char *name)
1126         const struct ref *ref = find_ref_by_name_abbrev(remote_refs, name);
1128         if (!ref)
1129                 return NULL;
1131         return copy_ref(ref);
1134 static struct ref *get_local_ref(const char *name)
1136         struct ref *ret;
1137         if (!name)
1138                 return NULL;
1140         if (!prefixcmp(name, "refs/")) {
1141                 ret = alloc_ref(strlen(name) + 1);
1142                 strcpy(ret->name, name);
1143                 return ret;
1144         }
1146         if (!prefixcmp(name, "heads/") ||
1147             !prefixcmp(name, "tags/") ||
1148             !prefixcmp(name, "remotes/")) {
1149                 ret = alloc_ref(strlen(name) + 6);
1150                 sprintf(ret->name, "refs/%s", name);
1151                 return ret;
1152         }
1154         ret = alloc_ref(strlen(name) + 12);
1155         sprintf(ret->name, "refs/heads/%s", name);
1156         return ret;
1159 int get_fetch_map(const struct ref *remote_refs,
1160                   const struct refspec *refspec,
1161                   struct ref ***tail,
1162                   int missing_ok)
1164         struct ref *ref_map, **rmp;
1166         if (refspec->pattern) {
1167                 ref_map = get_expanded_map(remote_refs, refspec);
1168         } else {
1169                 const char *name = refspec->src[0] ? refspec->src : "HEAD";
1171                 ref_map = get_remote_ref(remote_refs, name);
1172                 if (!missing_ok && !ref_map)
1173                         die("Couldn't find remote ref %s", name);
1174                 if (ref_map) {
1175                         ref_map->peer_ref = get_local_ref(refspec->dst);
1176                         if (ref_map->peer_ref && refspec->force)
1177                                 ref_map->peer_ref->force = 1;
1178                 }
1179         }
1181         for (rmp = &ref_map; *rmp; ) {
1182                 if ((*rmp)->peer_ref) {
1183                         int st = check_ref_format((*rmp)->peer_ref->name + 5);
1184                         if (st && st != CHECK_REF_FORMAT_ONELEVEL) {
1185                                 struct ref *ignore = *rmp;
1186                                 error("* Ignoring funny ref '%s' locally",
1187                                       (*rmp)->peer_ref->name);
1188                                 *rmp = (*rmp)->next;
1189                                 free(ignore->peer_ref);
1190                                 free(ignore);
1191                                 continue;
1192                         }
1193                 }
1194                 rmp = &((*rmp)->next);
1195         }
1197         if (ref_map)
1198                 tail_link_ref(ref_map, tail);
1200         return 0;