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