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