Merge branch 'dd/send-email-reedit'
[git] / remote.c
1 #include "cache.h"
2 #include "config.h"
3 #include "remote.h"
4 #include "refs.h"
5 #include "commit.h"
6 #include "diff.h"
7 #include "revision.h"
8 #include "dir.h"
9 #include "tag.h"
10 #include "string-list.h"
11 #include "mergesort.h"
12 #include "argv-array.h"
13
14 enum map_direction { FROM_SRC, FROM_DST };
15
16 static struct refspec s_tag_refspec = {
17         0,
18         1,
19         0,
20         0,
21         "refs/tags/*",
22         "refs/tags/*"
23 };
24
25 /* See TAG_REFSPEC for the string version */
26 const struct refspec *tag_refspec = &s_tag_refspec;
27
28 struct counted_string {
29         size_t len;
30         const char *s;
31 };
32 struct rewrite {
33         const char *base;
34         size_t baselen;
35         struct counted_string *instead_of;
36         int instead_of_nr;
37         int instead_of_alloc;
38 };
39 struct rewrites {
40         struct rewrite **rewrite;
41         int rewrite_alloc;
42         int rewrite_nr;
43 };
44
45 static struct remote **remotes;
46 static int remotes_alloc;
47 static int remotes_nr;
48 static struct hashmap remotes_hash;
49
50 static struct branch **branches;
51 static int branches_alloc;
52 static int branches_nr;
53
54 static struct branch *current_branch;
55 static const char *pushremote_name;
56
57 static struct rewrites rewrites;
58 static struct rewrites rewrites_push;
59
60 static int valid_remote(const struct remote *remote)
61 {
62         return (!!remote->url) || (!!remote->foreign_vcs);
63 }
64
65 static const char *alias_url(const char *url, struct rewrites *r)
66 {
67         int i, j;
68         struct counted_string *longest;
69         int longest_i;
70
71         longest = NULL;
72         longest_i = -1;
73         for (i = 0; i < r->rewrite_nr; i++) {
74                 if (!r->rewrite[i])
75                         continue;
76                 for (j = 0; j < r->rewrite[i]->instead_of_nr; j++) {
77                         if (starts_with(url, r->rewrite[i]->instead_of[j].s) &&
78                             (!longest ||
79                              longest->len < r->rewrite[i]->instead_of[j].len)) {
80                                 longest = &(r->rewrite[i]->instead_of[j]);
81                                 longest_i = i;
82                         }
83                 }
84         }
85         if (!longest)
86                 return url;
87
88         return xstrfmt("%s%s", r->rewrite[longest_i]->base, url + longest->len);
89 }
90
91 static void add_push_refspec(struct remote *remote, const char *ref)
92 {
93         ALLOC_GROW(remote->push_refspec,
94                    remote->push_refspec_nr + 1,
95                    remote->push_refspec_alloc);
96         remote->push_refspec[remote->push_refspec_nr++] = ref;
97 }
98
99 static void add_fetch_refspec(struct remote *remote, const char *ref)
100 {
101         ALLOC_GROW(remote->fetch_refspec,
102                    remote->fetch_refspec_nr + 1,
103                    remote->fetch_refspec_alloc);
104         remote->fetch_refspec[remote->fetch_refspec_nr++] = ref;
105 }
106
107 void add_prune_tags_to_fetch_refspec(struct remote *remote)
108 {
109         int nr = remote->fetch_refspec_nr;
110         int bufsize = nr  + 1;
111         int size = sizeof(struct refspec);
112
113         remote->fetch = xrealloc(remote->fetch, size  * bufsize);
114         memcpy(&remote->fetch[nr], tag_refspec, size);
115         add_fetch_refspec(remote, xstrdup(TAG_REFSPEC));
116 }
117
118 static void add_url(struct remote *remote, const char *url)
119 {
120         ALLOC_GROW(remote->url, remote->url_nr + 1, remote->url_alloc);
121         remote->url[remote->url_nr++] = url;
122 }
123
124 static void add_pushurl(struct remote *remote, const char *pushurl)
125 {
126         ALLOC_GROW(remote->pushurl, remote->pushurl_nr + 1, remote->pushurl_alloc);
127         remote->pushurl[remote->pushurl_nr++] = pushurl;
128 }
129
130 static void add_pushurl_alias(struct remote *remote, const char *url)
131 {
132         const char *pushurl = alias_url(url, &rewrites_push);
133         if (pushurl != url)
134                 add_pushurl(remote, pushurl);
135 }
136
137 static void add_url_alias(struct remote *remote, const char *url)
138 {
139         add_url(remote, alias_url(url, &rewrites));
140         add_pushurl_alias(remote, url);
141 }
142
143 struct remotes_hash_key {
144         const char *str;
145         int len;
146 };
147
148 static int remotes_hash_cmp(const void *unused_cmp_data,
149                             const void *entry,
150                             const void *entry_or_key,
151                             const void *keydata)
152 {
153         const struct remote *a = entry;
154         const struct remote *b = entry_or_key;
155         const struct remotes_hash_key *key = keydata;
156
157         if (key)
158                 return strncmp(a->name, key->str, key->len) || a->name[key->len];
159         else
160                 return strcmp(a->name, b->name);
161 }
162
163 static inline void init_remotes_hash(void)
164 {
165         if (!remotes_hash.cmpfn)
166                 hashmap_init(&remotes_hash, remotes_hash_cmp, NULL, 0);
167 }
168
169 static struct remote *make_remote(const char *name, int len)
170 {
171         struct remote *ret, *replaced;
172         struct remotes_hash_key lookup;
173         struct hashmap_entry lookup_entry;
174
175         if (!len)
176                 len = strlen(name);
177
178         init_remotes_hash();
179         lookup.str = name;
180         lookup.len = len;
181         hashmap_entry_init(&lookup_entry, memhash(name, len));
182
183         if ((ret = hashmap_get(&remotes_hash, &lookup_entry, &lookup)) != NULL)
184                 return ret;
185
186         ret = xcalloc(1, sizeof(struct remote));
187         ret->prune = -1;  /* unspecified */
188         ret->prune_tags = -1;  /* unspecified */
189         ALLOC_GROW(remotes, remotes_nr + 1, remotes_alloc);
190         remotes[remotes_nr++] = ret;
191         ret->name = xstrndup(name, len);
192
193         hashmap_entry_init(ret, lookup_entry.hash);
194         replaced = hashmap_put(&remotes_hash, ret);
195         assert(replaced == NULL);  /* no previous entry overwritten */
196         return ret;
197 }
198
199 static void add_merge(struct branch *branch, const char *name)
200 {
201         ALLOC_GROW(branch->merge_name, branch->merge_nr + 1,
202                    branch->merge_alloc);
203         branch->merge_name[branch->merge_nr++] = name;
204 }
205
206 static struct branch *make_branch(const char *name, int len)
207 {
208         struct branch *ret;
209         int i;
210
211         for (i = 0; i < branches_nr; i++) {
212                 if (len ? (!strncmp(name, branches[i]->name, len) &&
213                            !branches[i]->name[len]) :
214                     !strcmp(name, branches[i]->name))
215                         return branches[i];
216         }
217
218         ALLOC_GROW(branches, branches_nr + 1, branches_alloc);
219         ret = xcalloc(1, sizeof(struct branch));
220         branches[branches_nr++] = ret;
221         if (len)
222                 ret->name = xstrndup(name, len);
223         else
224                 ret->name = xstrdup(name);
225         ret->refname = xstrfmt("refs/heads/%s", ret->name);
226
227         return ret;
228 }
229
230 static struct rewrite *make_rewrite(struct rewrites *r, const char *base, int len)
231 {
232         struct rewrite *ret;
233         int i;
234
235         for (i = 0; i < r->rewrite_nr; i++) {
236                 if (len
237                     ? (len == r->rewrite[i]->baselen &&
238                        !strncmp(base, r->rewrite[i]->base, len))
239                     : !strcmp(base, r->rewrite[i]->base))
240                         return r->rewrite[i];
241         }
242
243         ALLOC_GROW(r->rewrite, r->rewrite_nr + 1, r->rewrite_alloc);
244         ret = xcalloc(1, sizeof(struct rewrite));
245         r->rewrite[r->rewrite_nr++] = ret;
246         if (len) {
247                 ret->base = xstrndup(base, len);
248                 ret->baselen = len;
249         }
250         else {
251                 ret->base = xstrdup(base);
252                 ret->baselen = strlen(base);
253         }
254         return ret;
255 }
256
257 static void add_instead_of(struct rewrite *rewrite, const char *instead_of)
258 {
259         ALLOC_GROW(rewrite->instead_of, rewrite->instead_of_nr + 1, rewrite->instead_of_alloc);
260         rewrite->instead_of[rewrite->instead_of_nr].s = instead_of;
261         rewrite->instead_of[rewrite->instead_of_nr].len = strlen(instead_of);
262         rewrite->instead_of_nr++;
263 }
264
265 static const char *skip_spaces(const char *s)
266 {
267         while (isspace(*s))
268                 s++;
269         return s;
270 }
271
272 static void read_remotes_file(struct remote *remote)
273 {
274         struct strbuf buf = STRBUF_INIT;
275         FILE *f = fopen_or_warn(git_path("remotes/%s", remote->name), "r");
276
277         if (!f)
278                 return;
279         remote->configured_in_repo = 1;
280         remote->origin = REMOTE_REMOTES;
281         while (strbuf_getline(&buf, f) != EOF) {
282                 const char *v;
283
284                 strbuf_rtrim(&buf);
285
286                 if (skip_prefix(buf.buf, "URL:", &v))
287                         add_url_alias(remote, xstrdup(skip_spaces(v)));
288                 else if (skip_prefix(buf.buf, "Push:", &v))
289                         add_push_refspec(remote, xstrdup(skip_spaces(v)));
290                 else if (skip_prefix(buf.buf, "Pull:", &v))
291                         add_fetch_refspec(remote, xstrdup(skip_spaces(v)));
292         }
293         strbuf_release(&buf);
294         fclose(f);
295 }
296
297 static void read_branches_file(struct remote *remote)
298 {
299         char *frag;
300         struct strbuf buf = STRBUF_INIT;
301         FILE *f = fopen_or_warn(git_path("branches/%s", remote->name), "r");
302
303         if (!f)
304                 return;
305
306         strbuf_getline_lf(&buf, f);
307         fclose(f);
308         strbuf_trim(&buf);
309         if (!buf.len) {
310                 strbuf_release(&buf);
311                 return;
312         }
313
314         remote->configured_in_repo = 1;
315         remote->origin = REMOTE_BRANCHES;
316
317         /*
318          * The branches file would have URL and optionally
319          * #branch specified.  The "master" (or specified) branch is
320          * fetched and stored in the local branch matching the
321          * remote name.
322          */
323         frag = strchr(buf.buf, '#');
324         if (frag)
325                 *(frag++) = '\0';
326         else
327                 frag = "master";
328
329         add_url_alias(remote, strbuf_detach(&buf, NULL));
330         add_fetch_refspec(remote, xstrfmt("refs/heads/%s:refs/heads/%s",
331                                           frag, remote->name));
332
333         /*
334          * Cogito compatible push: push current HEAD to remote #branch
335          * (master if missing)
336          */
337         add_push_refspec(remote, xstrfmt("HEAD:refs/heads/%s", frag));
338         remote->fetch_tags = 1; /* always auto-follow */
339 }
340
341 static int handle_config(const char *key, const char *value, void *cb)
342 {
343         const char *name;
344         int namelen;
345         const char *subkey;
346         struct remote *remote;
347         struct branch *branch;
348         if (parse_config_key(key, "branch", &name, &namelen, &subkey) >= 0) {
349                 if (!name)
350                         return 0;
351                 branch = make_branch(name, namelen);
352                 if (!strcmp(subkey, "remote")) {
353                         return git_config_string(&branch->remote_name, key, value);
354                 } else if (!strcmp(subkey, "pushremote")) {
355                         return git_config_string(&branch->pushremote_name, key, value);
356                 } else if (!strcmp(subkey, "merge")) {
357                         if (!value)
358                                 return config_error_nonbool(key);
359                         add_merge(branch, xstrdup(value));
360                 }
361                 return 0;
362         }
363         if (parse_config_key(key, "url", &name, &namelen, &subkey) >= 0) {
364                 struct rewrite *rewrite;
365                 if (!name)
366                         return 0;
367                 if (!strcmp(subkey, "insteadof")) {
368                         rewrite = make_rewrite(&rewrites, name, namelen);
369                         if (!value)
370                                 return config_error_nonbool(key);
371                         add_instead_of(rewrite, xstrdup(value));
372                 } else if (!strcmp(subkey, "pushinsteadof")) {
373                         rewrite = make_rewrite(&rewrites_push, name, namelen);
374                         if (!value)
375                                 return config_error_nonbool(key);
376                         add_instead_of(rewrite, xstrdup(value));
377                 }
378         }
379
380         if (parse_config_key(key, "remote", &name, &namelen, &subkey) < 0)
381                 return 0;
382
383         /* Handle remote.* variables */
384         if (!name && !strcmp(subkey, "pushdefault"))
385                 return git_config_string(&pushremote_name, key, value);
386
387         if (!name)
388                 return 0;
389         /* Handle remote.<name>.* variables */
390         if (*name == '/') {
391                 warning("Config remote shorthand cannot begin with '/': %s",
392                         name);
393                 return 0;
394         }
395         remote = make_remote(name, namelen);
396         remote->origin = REMOTE_CONFIG;
397         if (current_config_scope() == CONFIG_SCOPE_REPO)
398                 remote->configured_in_repo = 1;
399         if (!strcmp(subkey, "mirror"))
400                 remote->mirror = git_config_bool(key, value);
401         else if (!strcmp(subkey, "skipdefaultupdate"))
402                 remote->skip_default_update = git_config_bool(key, value);
403         else if (!strcmp(subkey, "skipfetchall"))
404                 remote->skip_default_update = git_config_bool(key, value);
405         else if (!strcmp(subkey, "prune"))
406                 remote->prune = git_config_bool(key, value);
407         else if (!strcmp(subkey, "prunetags"))
408                 remote->prune_tags = git_config_bool(key, value);
409         else if (!strcmp(subkey, "url")) {
410                 const char *v;
411                 if (git_config_string(&v, key, value))
412                         return -1;
413                 add_url(remote, v);
414         } else if (!strcmp(subkey, "pushurl")) {
415                 const char *v;
416                 if (git_config_string(&v, key, value))
417                         return -1;
418                 add_pushurl(remote, v);
419         } else if (!strcmp(subkey, "push")) {
420                 const char *v;
421                 if (git_config_string(&v, key, value))
422                         return -1;
423                 add_push_refspec(remote, v);
424         } else if (!strcmp(subkey, "fetch")) {
425                 const char *v;
426                 if (git_config_string(&v, key, value))
427                         return -1;
428                 add_fetch_refspec(remote, v);
429         } else if (!strcmp(subkey, "receivepack")) {
430                 const char *v;
431                 if (git_config_string(&v, key, value))
432                         return -1;
433                 if (!remote->receivepack)
434                         remote->receivepack = v;
435                 else
436                         error("more than one receivepack given, using the first");
437         } else if (!strcmp(subkey, "uploadpack")) {
438                 const char *v;
439                 if (git_config_string(&v, key, value))
440                         return -1;
441                 if (!remote->uploadpack)
442                         remote->uploadpack = v;
443                 else
444                         error("more than one uploadpack given, using the first");
445         } else if (!strcmp(subkey, "tagopt")) {
446                 if (!strcmp(value, "--no-tags"))
447                         remote->fetch_tags = -1;
448                 else if (!strcmp(value, "--tags"))
449                         remote->fetch_tags = 2;
450         } else if (!strcmp(subkey, "proxy")) {
451                 return git_config_string((const char **)&remote->http_proxy,
452                                          key, value);
453         } else if (!strcmp(subkey, "proxyauthmethod")) {
454                 return git_config_string((const char **)&remote->http_proxy_authmethod,
455                                          key, value);
456         } else if (!strcmp(subkey, "vcs")) {
457                 return git_config_string(&remote->foreign_vcs, key, value);
458         }
459         return 0;
460 }
461
462 static void alias_all_urls(void)
463 {
464         int i, j;
465         for (i = 0; i < remotes_nr; i++) {
466                 int add_pushurl_aliases;
467                 if (!remotes[i])
468                         continue;
469                 for (j = 0; j < remotes[i]->pushurl_nr; j++) {
470                         remotes[i]->pushurl[j] = alias_url(remotes[i]->pushurl[j], &rewrites);
471                 }
472                 add_pushurl_aliases = remotes[i]->pushurl_nr == 0;
473                 for (j = 0; j < remotes[i]->url_nr; j++) {
474                         if (add_pushurl_aliases)
475                                 add_pushurl_alias(remotes[i], remotes[i]->url[j]);
476                         remotes[i]->url[j] = alias_url(remotes[i]->url[j], &rewrites);
477                 }
478         }
479 }
480
481 static void read_config(void)
482 {
483         static int loaded;
484         int flag;
485
486         if (loaded)
487                 return;
488         loaded = 1;
489
490         current_branch = NULL;
491         if (startup_info->have_repository) {
492                 const char *head_ref = resolve_ref_unsafe("HEAD", 0, NULL, &flag);
493                 if (head_ref && (flag & REF_ISSYMREF) &&
494                     skip_prefix(head_ref, "refs/heads/", &head_ref)) {
495                         current_branch = make_branch(head_ref, 0);
496                 }
497         }
498         git_config(handle_config, NULL);
499         alias_all_urls();
500 }
501
502 static struct refspec *parse_refspec_internal(int nr_refspec, const char **refspec, int fetch, int verify)
503 {
504         int i;
505         struct refspec *rs = xcalloc(nr_refspec, sizeof(*rs));
506
507         for (i = 0; i < nr_refspec; i++) {
508                 size_t llen;
509                 int is_glob;
510                 const char *lhs, *rhs;
511                 int flags;
512
513                 is_glob = 0;
514
515                 lhs = refspec[i];
516                 if (*lhs == '+') {
517                         rs[i].force = 1;
518                         lhs++;
519                 }
520
521                 rhs = strrchr(lhs, ':');
522
523                 /*
524                  * Before going on, special case ":" (or "+:") as a refspec
525                  * for pushing matching refs.
526                  */
527                 if (!fetch && rhs == lhs && rhs[1] == '\0') {
528                         rs[i].matching = 1;
529                         continue;
530                 }
531
532                 if (rhs) {
533                         size_t rlen = strlen(++rhs);
534                         is_glob = (1 <= rlen && strchr(rhs, '*'));
535                         rs[i].dst = xstrndup(rhs, rlen);
536                 }
537
538                 llen = (rhs ? (rhs - lhs - 1) : strlen(lhs));
539                 if (1 <= llen && memchr(lhs, '*', llen)) {
540                         if ((rhs && !is_glob) || (!rhs && fetch))
541                                 goto invalid;
542                         is_glob = 1;
543                 } else if (rhs && is_glob) {
544                         goto invalid;
545                 }
546
547                 rs[i].pattern = is_glob;
548                 rs[i].src = xstrndup(lhs, llen);
549                 flags = REFNAME_ALLOW_ONELEVEL | (is_glob ? REFNAME_REFSPEC_PATTERN : 0);
550
551                 if (fetch) {
552                         struct object_id unused;
553
554                         /* LHS */
555                         if (!*rs[i].src)
556                                 ; /* empty is ok; it means "HEAD" */
557                         else if (llen == GIT_SHA1_HEXSZ && !get_oid_hex(rs[i].src, &unused))
558                                 rs[i].exact_sha1 = 1; /* ok */
559                         else if (!check_refname_format(rs[i].src, flags))
560                                 ; /* valid looking ref is ok */
561                         else
562                                 goto invalid;
563                         /* RHS */
564                         if (!rs[i].dst)
565                                 ; /* missing is ok; it is the same as empty */
566                         else if (!*rs[i].dst)
567                                 ; /* empty is ok; it means "do not store" */
568                         else if (!check_refname_format(rs[i].dst, flags))
569                                 ; /* valid looking ref is ok */
570                         else
571                                 goto invalid;
572                 } else {
573                         /*
574                          * LHS
575                          * - empty is allowed; it means delete.
576                          * - when wildcarded, it must be a valid looking ref.
577                          * - otherwise, it must be an extended SHA-1, but
578                          *   there is no existing way to validate this.
579                          */
580                         if (!*rs[i].src)
581                                 ; /* empty is ok */
582                         else if (is_glob) {
583                                 if (check_refname_format(rs[i].src, flags))
584                                         goto invalid;
585                         }
586                         else
587                                 ; /* anything goes, for now */
588                         /*
589                          * RHS
590                          * - missing is allowed, but LHS then must be a
591                          *   valid looking ref.
592                          * - empty is not allowed.
593                          * - otherwise it must be a valid looking ref.
594                          */
595                         if (!rs[i].dst) {
596                                 if (check_refname_format(rs[i].src, flags))
597                                         goto invalid;
598                         } else if (!*rs[i].dst) {
599                                 goto invalid;
600                         } else {
601                                 if (check_refname_format(rs[i].dst, flags))
602                                         goto invalid;
603                         }
604                 }
605         }
606         return rs;
607
608  invalid:
609         if (verify) {
610                 /*
611                  * nr_refspec must be greater than zero and i must be valid
612                  * since it is only possible to reach this point from within
613                  * the for loop above.
614                  */
615                 free_refspec(i+1, rs);
616                 return NULL;
617         }
618         die("Invalid refspec '%s'", refspec[i]);
619 }
620
621 int valid_fetch_refspec(const char *fetch_refspec_str)
622 {
623         struct refspec *refspec;
624
625         refspec = parse_refspec_internal(1, &fetch_refspec_str, 1, 1);
626         free_refspec(1, refspec);
627         return !!refspec;
628 }
629
630 struct refspec *parse_fetch_refspec(int nr_refspec, const char **refspec)
631 {
632         return parse_refspec_internal(nr_refspec, refspec, 1, 0);
633 }
634
635 struct refspec *parse_push_refspec(int nr_refspec, const char **refspec)
636 {
637         return parse_refspec_internal(nr_refspec, refspec, 0, 0);
638 }
639
640 void free_refspec(int nr_refspec, struct refspec *refspec)
641 {
642         int i;
643
644         if (!refspec)
645                 return;
646
647         for (i = 0; i < nr_refspec; i++) {
648                 free(refspec[i].src);
649                 free(refspec[i].dst);
650         }
651         free(refspec);
652 }
653
654 static int valid_remote_nick(const char *name)
655 {
656         if (!name[0] || is_dot_or_dotdot(name))
657                 return 0;
658
659         /* remote nicknames cannot contain slashes */
660         while (*name)
661                 if (is_dir_sep(*name++))
662                         return 0;
663         return 1;
664 }
665
666 const char *remote_for_branch(struct branch *branch, int *explicit)
667 {
668         if (branch && branch->remote_name) {
669                 if (explicit)
670                         *explicit = 1;
671                 return branch->remote_name;
672         }
673         if (explicit)
674                 *explicit = 0;
675         return "origin";
676 }
677
678 const char *pushremote_for_branch(struct branch *branch, int *explicit)
679 {
680         if (branch && branch->pushremote_name) {
681                 if (explicit)
682                         *explicit = 1;
683                 return branch->pushremote_name;
684         }
685         if (pushremote_name) {
686                 if (explicit)
687                         *explicit = 1;
688                 return pushremote_name;
689         }
690         return remote_for_branch(branch, explicit);
691 }
692
693 const char *remote_ref_for_branch(struct branch *branch, int for_push,
694                                   int *explicit)
695 {
696         if (branch) {
697                 if (!for_push) {
698                         if (branch->merge_nr) {
699                                 if (explicit)
700                                         *explicit = 1;
701                                 return branch->merge_name[0];
702                         }
703                 } else {
704                         const char *dst, *remote_name =
705                                 pushremote_for_branch(branch, NULL);
706                         struct remote *remote = remote_get(remote_name);
707
708                         if (remote && remote->push_refspec_nr &&
709                             (dst = apply_refspecs(remote->push,
710                                                   remote->push_refspec_nr,
711                                                   branch->refname))) {
712                                 if (explicit)
713                                         *explicit = 1;
714                                 return dst;
715                         }
716                 }
717         }
718         if (explicit)
719                 *explicit = 0;
720         return "";
721 }
722
723 static struct remote *remote_get_1(const char *name,
724                                    const char *(*get_default)(struct branch *, int *))
725 {
726         struct remote *ret;
727         int name_given = 0;
728
729         read_config();
730
731         if (name)
732                 name_given = 1;
733         else
734                 name = get_default(current_branch, &name_given);
735
736         ret = make_remote(name, 0);
737         if (valid_remote_nick(name) && have_git_dir()) {
738                 if (!valid_remote(ret))
739                         read_remotes_file(ret);
740                 if (!valid_remote(ret))
741                         read_branches_file(ret);
742         }
743         if (name_given && !valid_remote(ret))
744                 add_url_alias(ret, name);
745         if (!valid_remote(ret))
746                 return NULL;
747         ret->fetch = parse_fetch_refspec(ret->fetch_refspec_nr, ret->fetch_refspec);
748         ret->push = parse_push_refspec(ret->push_refspec_nr, ret->push_refspec);
749         return ret;
750 }
751
752 struct remote *remote_get(const char *name)
753 {
754         return remote_get_1(name, remote_for_branch);
755 }
756
757 struct remote *pushremote_get(const char *name)
758 {
759         return remote_get_1(name, pushremote_for_branch);
760 }
761
762 int remote_is_configured(struct remote *remote, int in_repo)
763 {
764         if (!remote)
765                 return 0;
766         if (in_repo)
767                 return remote->configured_in_repo;
768         return !!remote->origin;
769 }
770
771 int for_each_remote(each_remote_fn fn, void *priv)
772 {
773         int i, result = 0;
774         read_config();
775         for (i = 0; i < remotes_nr && !result; i++) {
776                 struct remote *r = remotes[i];
777                 if (!r)
778                         continue;
779                 if (!r->fetch)
780                         r->fetch = parse_fetch_refspec(r->fetch_refspec_nr,
781                                                        r->fetch_refspec);
782                 if (!r->push)
783                         r->push = parse_push_refspec(r->push_refspec_nr,
784                                                      r->push_refspec);
785                 result = fn(r, priv);
786         }
787         return result;
788 }
789
790 static void handle_duplicate(struct ref *ref1, struct ref *ref2)
791 {
792         if (strcmp(ref1->name, ref2->name)) {
793                 if (ref1->fetch_head_status != FETCH_HEAD_IGNORE &&
794                     ref2->fetch_head_status != FETCH_HEAD_IGNORE) {
795                         die(_("Cannot fetch both %s and %s to %s"),
796                             ref1->name, ref2->name, ref2->peer_ref->name);
797                 } else if (ref1->fetch_head_status != FETCH_HEAD_IGNORE &&
798                            ref2->fetch_head_status == FETCH_HEAD_IGNORE) {
799                         warning(_("%s usually tracks %s, not %s"),
800                                 ref2->peer_ref->name, ref2->name, ref1->name);
801                 } else if (ref1->fetch_head_status == FETCH_HEAD_IGNORE &&
802                            ref2->fetch_head_status == FETCH_HEAD_IGNORE) {
803                         die(_("%s tracks both %s and %s"),
804                             ref2->peer_ref->name, ref1->name, ref2->name);
805                 } else {
806                         /*
807                          * This last possibility doesn't occur because
808                          * FETCH_HEAD_IGNORE entries always appear at
809                          * the end of the list.
810                          */
811                         die(_("Internal error"));
812                 }
813         }
814         free(ref2->peer_ref);
815         free(ref2);
816 }
817
818 struct ref *ref_remove_duplicates(struct ref *ref_map)
819 {
820         struct string_list refs = STRING_LIST_INIT_NODUP;
821         struct ref *retval = NULL;
822         struct ref **p = &retval;
823
824         while (ref_map) {
825                 struct ref *ref = ref_map;
826
827                 ref_map = ref_map->next;
828                 ref->next = NULL;
829
830                 if (!ref->peer_ref) {
831                         *p = ref;
832                         p = &ref->next;
833                 } else {
834                         struct string_list_item *item =
835                                 string_list_insert(&refs, ref->peer_ref->name);
836
837                         if (item->util) {
838                                 /* Entry already existed */
839                                 handle_duplicate((struct ref *)item->util, ref);
840                         } else {
841                                 *p = ref;
842                                 p = &ref->next;
843                                 item->util = ref;
844                         }
845                 }
846         }
847
848         string_list_clear(&refs, 0);
849         return retval;
850 }
851
852 int remote_has_url(struct remote *remote, const char *url)
853 {
854         int i;
855         for (i = 0; i < remote->url_nr; i++) {
856                 if (!strcmp(remote->url[i], url))
857                         return 1;
858         }
859         return 0;
860 }
861
862 static int match_name_with_pattern(const char *key, const char *name,
863                                    const char *value, char **result)
864 {
865         const char *kstar = strchr(key, '*');
866         size_t klen;
867         size_t ksuffixlen;
868         size_t namelen;
869         int ret;
870         if (!kstar)
871                 die("Key '%s' of pattern had no '*'", key);
872         klen = kstar - key;
873         ksuffixlen = strlen(kstar + 1);
874         namelen = strlen(name);
875         ret = !strncmp(name, key, klen) && namelen >= klen + ksuffixlen &&
876                 !memcmp(name + namelen - ksuffixlen, kstar + 1, ksuffixlen);
877         if (ret && value) {
878                 struct strbuf sb = STRBUF_INIT;
879                 const char *vstar = strchr(value, '*');
880                 if (!vstar)
881                         die("Value '%s' of pattern has no '*'", value);
882                 strbuf_add(&sb, value, vstar - value);
883                 strbuf_add(&sb, name + klen, namelen - klen - ksuffixlen);
884                 strbuf_addstr(&sb, vstar + 1);
885                 *result = strbuf_detach(&sb, NULL);
886         }
887         return ret;
888 }
889
890 static void query_refspecs_multiple(struct refspec *refs, int ref_count, struct refspec *query, struct string_list *results)
891 {
892         int i;
893         int find_src = !query->src;
894
895         if (find_src && !query->dst)
896                 error("query_refspecs_multiple: need either src or dst");
897
898         for (i = 0; i < ref_count; i++) {
899                 struct refspec *refspec = &refs[i];
900                 const char *key = find_src ? refspec->dst : refspec->src;
901                 const char *value = find_src ? refspec->src : refspec->dst;
902                 const char *needle = find_src ? query->dst : query->src;
903                 char **result = find_src ? &query->src : &query->dst;
904
905                 if (!refspec->dst)
906                         continue;
907                 if (refspec->pattern) {
908                         if (match_name_with_pattern(key, needle, value, result))
909                                 string_list_append_nodup(results, *result);
910                 } else if (!strcmp(needle, key)) {
911                         string_list_append(results, value);
912                 }
913         }
914 }
915
916 int query_refspecs(struct refspec *refs, int ref_count, struct refspec *query)
917 {
918         int i;
919         int find_src = !query->src;
920         const char *needle = find_src ? query->dst : query->src;
921         char **result = find_src ? &query->src : &query->dst;
922
923         if (find_src && !query->dst)
924                 return error("query_refspecs: need either src or dst");
925
926         for (i = 0; i < ref_count; i++) {
927                 struct refspec *refspec = &refs[i];
928                 const char *key = find_src ? refspec->dst : refspec->src;
929                 const char *value = find_src ? refspec->src : refspec->dst;
930
931                 if (!refspec->dst)
932                         continue;
933                 if (refspec->pattern) {
934                         if (match_name_with_pattern(key, needle, value, result)) {
935                                 query->force = refspec->force;
936                                 return 0;
937                         }
938                 } else if (!strcmp(needle, key)) {
939                         *result = xstrdup(value);
940                         query->force = refspec->force;
941                         return 0;
942                 }
943         }
944         return -1;
945 }
946
947 char *apply_refspecs(struct refspec *refspecs, int nr_refspec,
948                      const char *name)
949 {
950         struct refspec query;
951
952         memset(&query, 0, sizeof(struct refspec));
953         query.src = (char *)name;
954
955         if (query_refspecs(refspecs, nr_refspec, &query))
956                 return NULL;
957
958         return query.dst;
959 }
960
961 int remote_find_tracking(struct remote *remote, struct refspec *refspec)
962 {
963         return query_refspecs(remote->fetch, remote->fetch_refspec_nr, refspec);
964 }
965
966 static struct ref *alloc_ref_with_prefix(const char *prefix, size_t prefixlen,
967                 const char *name)
968 {
969         size_t len = strlen(name);
970         struct ref *ref = xcalloc(1, st_add4(sizeof(*ref), prefixlen, len, 1));
971         memcpy(ref->name, prefix, prefixlen);
972         memcpy(ref->name + prefixlen, name, len);
973         return ref;
974 }
975
976 struct ref *alloc_ref(const char *name)
977 {
978         return alloc_ref_with_prefix("", 0, name);
979 }
980
981 struct ref *copy_ref(const struct ref *ref)
982 {
983         struct ref *cpy;
984         size_t len;
985         if (!ref)
986                 return NULL;
987         len = st_add3(sizeof(struct ref), strlen(ref->name), 1);
988         cpy = xmalloc(len);
989         memcpy(cpy, ref, len);
990         cpy->next = NULL;
991         cpy->symref = xstrdup_or_null(ref->symref);
992         cpy->remote_status = xstrdup_or_null(ref->remote_status);
993         cpy->peer_ref = copy_ref(ref->peer_ref);
994         return cpy;
995 }
996
997 struct ref *copy_ref_list(const struct ref *ref)
998 {
999         struct ref *ret = NULL;
1000         struct ref **tail = &ret;
1001         while (ref) {
1002                 *tail = copy_ref(ref);
1003                 ref = ref->next;
1004                 tail = &((*tail)->next);
1005         }
1006         return ret;
1007 }
1008
1009 static void free_ref(struct ref *ref)
1010 {
1011         if (!ref)
1012                 return;
1013         free_ref(ref->peer_ref);
1014         free(ref->remote_status);
1015         free(ref->symref);
1016         free(ref);
1017 }
1018
1019 void free_refs(struct ref *ref)
1020 {
1021         struct ref *next;
1022         while (ref) {
1023                 next = ref->next;
1024                 free_ref(ref);
1025                 ref = next;
1026         }
1027 }
1028
1029 int ref_compare_name(const void *va, const void *vb)
1030 {
1031         const struct ref *a = va, *b = vb;
1032         return strcmp(a->name, b->name);
1033 }
1034
1035 static void *ref_list_get_next(const void *a)
1036 {
1037         return ((const struct ref *)a)->next;
1038 }
1039
1040 static void ref_list_set_next(void *a, void *next)
1041 {
1042         ((struct ref *)a)->next = next;
1043 }
1044
1045 void sort_ref_list(struct ref **l, int (*cmp)(const void *, const void *))
1046 {
1047         *l = llist_mergesort(*l, ref_list_get_next, ref_list_set_next, cmp);
1048 }
1049
1050 int count_refspec_match(const char *pattern,
1051                         struct ref *refs,
1052                         struct ref **matched_ref)
1053 {
1054         int patlen = strlen(pattern);
1055         struct ref *matched_weak = NULL;
1056         struct ref *matched = NULL;
1057         int weak_match = 0;
1058         int match = 0;
1059
1060         for (weak_match = match = 0; refs; refs = refs->next) {
1061                 char *name = refs->name;
1062                 int namelen = strlen(name);
1063
1064                 if (!refname_match(pattern, name))
1065                         continue;
1066
1067                 /* A match is "weak" if it is with refs outside
1068                  * heads or tags, and did not specify the pattern
1069                  * in full (e.g. "refs/remotes/origin/master") or at
1070                  * least from the toplevel (e.g. "remotes/origin/master");
1071                  * otherwise "git push $URL master" would result in
1072                  * ambiguity between remotes/origin/master and heads/master
1073                  * at the remote site.
1074                  */
1075                 if (namelen != patlen &&
1076                     patlen != namelen - 5 &&
1077                     !starts_with(name, "refs/heads/") &&
1078                     !starts_with(name, "refs/tags/")) {
1079                         /* We want to catch the case where only weak
1080                          * matches are found and there are multiple
1081                          * matches, and where more than one strong
1082                          * matches are found, as ambiguous.  One
1083                          * strong match with zero or more weak matches
1084                          * are acceptable as a unique match.
1085                          */
1086                         matched_weak = refs;
1087                         weak_match++;
1088                 }
1089                 else {
1090                         matched = refs;
1091                         match++;
1092                 }
1093         }
1094         if (!matched) {
1095                 if (matched_ref)
1096                         *matched_ref = matched_weak;
1097                 return weak_match;
1098         }
1099         else {
1100                 if (matched_ref)
1101                         *matched_ref = matched;
1102                 return match;
1103         }
1104 }
1105
1106 static void tail_link_ref(struct ref *ref, struct ref ***tail)
1107 {
1108         **tail = ref;
1109         while (ref->next)
1110                 ref = ref->next;
1111         *tail = &ref->next;
1112 }
1113
1114 static struct ref *alloc_delete_ref(void)
1115 {
1116         struct ref *ref = alloc_ref("(delete)");
1117         oidclr(&ref->new_oid);
1118         return ref;
1119 }
1120
1121 static int try_explicit_object_name(const char *name,
1122                                     struct ref **match)
1123 {
1124         struct object_id oid;
1125
1126         if (!*name) {
1127                 if (match)
1128                         *match = alloc_delete_ref();
1129                 return 0;
1130         }
1131
1132         if (get_oid(name, &oid))
1133                 return -1;
1134
1135         if (match) {
1136                 *match = alloc_ref(name);
1137                 oidcpy(&(*match)->new_oid, &oid);
1138         }
1139         return 0;
1140 }
1141
1142 static struct ref *make_linked_ref(const char *name, struct ref ***tail)
1143 {
1144         struct ref *ret = alloc_ref(name);
1145         tail_link_ref(ret, tail);
1146         return ret;
1147 }
1148
1149 static char *guess_ref(const char *name, struct ref *peer)
1150 {
1151         struct strbuf buf = STRBUF_INIT;
1152
1153         const char *r = resolve_ref_unsafe(peer->name, RESOLVE_REF_READING,
1154                                            NULL, NULL);
1155         if (!r)
1156                 return NULL;
1157
1158         if (starts_with(r, "refs/heads/"))
1159                 strbuf_addstr(&buf, "refs/heads/");
1160         else if (starts_with(r, "refs/tags/"))
1161                 strbuf_addstr(&buf, "refs/tags/");
1162         else
1163                 return NULL;
1164
1165         strbuf_addstr(&buf, name);
1166         return strbuf_detach(&buf, NULL);
1167 }
1168
1169 static int match_explicit_lhs(struct ref *src,
1170                               struct refspec *rs,
1171                               struct ref **match,
1172                               int *allocated_match)
1173 {
1174         switch (count_refspec_match(rs->src, src, match)) {
1175         case 1:
1176                 if (allocated_match)
1177                         *allocated_match = 0;
1178                 return 0;
1179         case 0:
1180                 /* The source could be in the get_sha1() format
1181                  * not a reference name.  :refs/other is a
1182                  * way to delete 'other' ref at the remote end.
1183                  */
1184                 if (try_explicit_object_name(rs->src, match) < 0)
1185                         return error("src refspec %s does not match any.", rs->src);
1186                 if (allocated_match)
1187                         *allocated_match = 1;
1188                 return 0;
1189         default:
1190                 return error("src refspec %s matches more than one.", rs->src);
1191         }
1192 }
1193
1194 static int match_explicit(struct ref *src, struct ref *dst,
1195                           struct ref ***dst_tail,
1196                           struct refspec *rs)
1197 {
1198         struct ref *matched_src, *matched_dst;
1199         int allocated_src;
1200
1201         const char *dst_value = rs->dst;
1202         char *dst_guess;
1203
1204         if (rs->pattern || rs->matching)
1205                 return 0;
1206
1207         matched_src = matched_dst = NULL;
1208         if (match_explicit_lhs(src, rs, &matched_src, &allocated_src) < 0)
1209                 return -1;
1210
1211         if (!dst_value) {
1212                 int flag;
1213
1214                 dst_value = resolve_ref_unsafe(matched_src->name,
1215                                                RESOLVE_REF_READING,
1216                                                NULL, &flag);
1217                 if (!dst_value ||
1218                     ((flag & REF_ISSYMREF) &&
1219                      !starts_with(dst_value, "refs/heads/")))
1220                         die("%s cannot be resolved to branch.",
1221                             matched_src->name);
1222         }
1223
1224         switch (count_refspec_match(dst_value, dst, &matched_dst)) {
1225         case 1:
1226                 break;
1227         case 0:
1228                 if (starts_with(dst_value, "refs/"))
1229                         matched_dst = make_linked_ref(dst_value, dst_tail);
1230                 else if (is_null_oid(&matched_src->new_oid))
1231                         error("unable to delete '%s': remote ref does not exist",
1232                               dst_value);
1233                 else if ((dst_guess = guess_ref(dst_value, matched_src))) {
1234                         matched_dst = make_linked_ref(dst_guess, dst_tail);
1235                         free(dst_guess);
1236                 } else
1237                         error("unable to push to unqualified destination: %s\n"
1238                               "The destination refspec neither matches an "
1239                               "existing ref on the remote nor\n"
1240                               "begins with refs/, and we are unable to "
1241                               "guess a prefix based on the source ref.",
1242                               dst_value);
1243                 break;
1244         default:
1245                 matched_dst = NULL;
1246                 error("dst refspec %s matches more than one.",
1247                       dst_value);
1248                 break;
1249         }
1250         if (!matched_dst)
1251                 return -1;
1252         if (matched_dst->peer_ref)
1253                 return error("dst ref %s receives from more than one src.",
1254                       matched_dst->name);
1255         else {
1256                 matched_dst->peer_ref = allocated_src ?
1257                                         matched_src :
1258                                         copy_ref(matched_src);
1259                 matched_dst->force = rs->force;
1260         }
1261         return 0;
1262 }
1263
1264 static int match_explicit_refs(struct ref *src, struct ref *dst,
1265                                struct ref ***dst_tail, struct refspec *rs,
1266                                int rs_nr)
1267 {
1268         int i, errs;
1269         for (i = errs = 0; i < rs_nr; i++)
1270                 errs += match_explicit(src, dst, dst_tail, &rs[i]);
1271         return errs;
1272 }
1273
1274 static char *get_ref_match(const struct refspec *rs, int rs_nr, const struct ref *ref,
1275                 int send_mirror, int direction, const struct refspec **ret_pat)
1276 {
1277         const struct refspec *pat;
1278         char *name;
1279         int i;
1280         int matching_refs = -1;
1281         for (i = 0; i < rs_nr; i++) {
1282                 if (rs[i].matching &&
1283                     (matching_refs == -1 || rs[i].force)) {
1284                         matching_refs = i;
1285                         continue;
1286                 }
1287
1288                 if (rs[i].pattern) {
1289                         const char *dst_side = rs[i].dst ? rs[i].dst : rs[i].src;
1290                         int match;
1291                         if (direction == FROM_SRC)
1292                                 match = match_name_with_pattern(rs[i].src, ref->name, dst_side, &name);
1293                         else
1294                                 match = match_name_with_pattern(dst_side, ref->name, rs[i].src, &name);
1295                         if (match) {
1296                                 matching_refs = i;
1297                                 break;
1298                         }
1299                 }
1300         }
1301         if (matching_refs == -1)
1302                 return NULL;
1303
1304         pat = rs + matching_refs;
1305         if (pat->matching) {
1306                 /*
1307                  * "matching refs"; traditionally we pushed everything
1308                  * including refs outside refs/heads/ hierarchy, but
1309                  * that does not make much sense these days.
1310                  */
1311                 if (!send_mirror && !starts_with(ref->name, "refs/heads/"))
1312                         return NULL;
1313                 name = xstrdup(ref->name);
1314         }
1315         if (ret_pat)
1316                 *ret_pat = pat;
1317         return name;
1318 }
1319
1320 static struct ref **tail_ref(struct ref **head)
1321 {
1322         struct ref **tail = head;
1323         while (*tail)
1324                 tail = &((*tail)->next);
1325         return tail;
1326 }
1327
1328 struct tips {
1329         struct commit **tip;
1330         int nr, alloc;
1331 };
1332
1333 static void add_to_tips(struct tips *tips, const struct object_id *oid)
1334 {
1335         struct commit *commit;
1336
1337         if (is_null_oid(oid))
1338                 return;
1339         commit = lookup_commit_reference_gently(oid, 1);
1340         if (!commit || (commit->object.flags & TMP_MARK))
1341                 return;
1342         commit->object.flags |= TMP_MARK;
1343         ALLOC_GROW(tips->tip, tips->nr + 1, tips->alloc);
1344         tips->tip[tips->nr++] = commit;
1345 }
1346
1347 static void add_missing_tags(struct ref *src, struct ref **dst, struct ref ***dst_tail)
1348 {
1349         struct string_list dst_tag = STRING_LIST_INIT_NODUP;
1350         struct string_list src_tag = STRING_LIST_INIT_NODUP;
1351         struct string_list_item *item;
1352         struct ref *ref;
1353         struct tips sent_tips;
1354
1355         /*
1356          * Collect everything we know they would have at the end of
1357          * this push, and collect all tags they have.
1358          */
1359         memset(&sent_tips, 0, sizeof(sent_tips));
1360         for (ref = *dst; ref; ref = ref->next) {
1361                 if (ref->peer_ref &&
1362                     !is_null_oid(&ref->peer_ref->new_oid))
1363                         add_to_tips(&sent_tips, &ref->peer_ref->new_oid);
1364                 else
1365                         add_to_tips(&sent_tips, &ref->old_oid);
1366                 if (starts_with(ref->name, "refs/tags/"))
1367                         string_list_append(&dst_tag, ref->name);
1368         }
1369         clear_commit_marks_many(sent_tips.nr, sent_tips.tip, TMP_MARK);
1370
1371         string_list_sort(&dst_tag);
1372
1373         /* Collect tags they do not have. */
1374         for (ref = src; ref; ref = ref->next) {
1375                 if (!starts_with(ref->name, "refs/tags/"))
1376                         continue; /* not a tag */
1377                 if (string_list_has_string(&dst_tag, ref->name))
1378                         continue; /* they already have it */
1379                 if (oid_object_info(the_repository, &ref->new_oid, NULL) != OBJ_TAG)
1380                         continue; /* be conservative */
1381                 item = string_list_append(&src_tag, ref->name);
1382                 item->util = ref;
1383         }
1384         string_list_clear(&dst_tag, 0);
1385
1386         /*
1387          * At this point, src_tag lists tags that are missing from
1388          * dst, and sent_tips lists the tips we are pushing or those
1389          * that we know they already have. An element in the src_tag
1390          * that is an ancestor of any of the sent_tips needs to be
1391          * sent to the other side.
1392          */
1393         if (sent_tips.nr) {
1394                 for_each_string_list_item(item, &src_tag) {
1395                         struct ref *ref = item->util;
1396                         struct ref *dst_ref;
1397                         struct commit *commit;
1398
1399                         if (is_null_oid(&ref->new_oid))
1400                                 continue;
1401                         commit = lookup_commit_reference_gently(&ref->new_oid,
1402                                                                 1);
1403                         if (!commit)
1404                                 /* not pushing a commit, which is not an error */
1405                                 continue;
1406
1407                         /*
1408                          * Is this tag, which they do not have, reachable from
1409                          * any of the commits we are sending?
1410                          */
1411                         if (!in_merge_bases_many(commit, sent_tips.nr, sent_tips.tip))
1412                                 continue;
1413
1414                         /* Add it in */
1415                         dst_ref = make_linked_ref(ref->name, dst_tail);
1416                         oidcpy(&dst_ref->new_oid, &ref->new_oid);
1417                         dst_ref->peer_ref = copy_ref(ref);
1418                 }
1419         }
1420         string_list_clear(&src_tag, 0);
1421         free(sent_tips.tip);
1422 }
1423
1424 struct ref *find_ref_by_name(const struct ref *list, const char *name)
1425 {
1426         for ( ; list; list = list->next)
1427                 if (!strcmp(list->name, name))
1428                         return (struct ref *)list;
1429         return NULL;
1430 }
1431
1432 static void prepare_ref_index(struct string_list *ref_index, struct ref *ref)
1433 {
1434         for ( ; ref; ref = ref->next)
1435                 string_list_append_nodup(ref_index, ref->name)->util = ref;
1436
1437         string_list_sort(ref_index);
1438 }
1439
1440 /*
1441  * Given only the set of local refs, sanity-check the set of push
1442  * refspecs. We can't catch all errors that match_push_refs would,
1443  * but we can catch some errors early before even talking to the
1444  * remote side.
1445  */
1446 int check_push_refs(struct ref *src, int nr_refspec, const char **refspec_names)
1447 {
1448         struct refspec *refspec = parse_push_refspec(nr_refspec, refspec_names);
1449         int ret = 0;
1450         int i;
1451
1452         for (i = 0; i < nr_refspec; i++) {
1453                 struct refspec *rs = refspec + i;
1454
1455                 if (rs->pattern || rs->matching)
1456                         continue;
1457
1458                 ret |= match_explicit_lhs(src, rs, NULL, NULL);
1459         }
1460
1461         free_refspec(nr_refspec, refspec);
1462         return ret;
1463 }
1464
1465 /*
1466  * Given the set of refs the local repository has, the set of refs the
1467  * remote repository has, and the refspec used for push, determine
1468  * what remote refs we will update and with what value by setting
1469  * peer_ref (which object is being pushed) and force (if the push is
1470  * forced) in elements of "dst". The function may add new elements to
1471  * dst (e.g. pushing to a new branch, done in match_explicit_refs).
1472  */
1473 int match_push_refs(struct ref *src, struct ref **dst,
1474                     int nr_refspec, const char **refspec, int flags)
1475 {
1476         struct refspec *rs;
1477         int send_all = flags & MATCH_REFS_ALL;
1478         int send_mirror = flags & MATCH_REFS_MIRROR;
1479         int send_prune = flags & MATCH_REFS_PRUNE;
1480         int errs;
1481         static const char *default_refspec[] = { ":", NULL };
1482         struct ref *ref, **dst_tail = tail_ref(dst);
1483         struct string_list dst_ref_index = STRING_LIST_INIT_NODUP;
1484
1485         if (!nr_refspec) {
1486                 nr_refspec = 1;
1487                 refspec = default_refspec;
1488         }
1489         rs = parse_push_refspec(nr_refspec, (const char **) refspec);
1490         errs = match_explicit_refs(src, *dst, &dst_tail, rs, nr_refspec);
1491
1492         /* pick the remainder */
1493         for (ref = src; ref; ref = ref->next) {
1494                 struct string_list_item *dst_item;
1495                 struct ref *dst_peer;
1496                 const struct refspec *pat = NULL;
1497                 char *dst_name;
1498
1499                 dst_name = get_ref_match(rs, nr_refspec, ref, send_mirror, FROM_SRC, &pat);
1500                 if (!dst_name)
1501                         continue;
1502
1503                 if (!dst_ref_index.nr)
1504                         prepare_ref_index(&dst_ref_index, *dst);
1505
1506                 dst_item = string_list_lookup(&dst_ref_index, dst_name);
1507                 dst_peer = dst_item ? dst_item->util : NULL;
1508                 if (dst_peer) {
1509                         if (dst_peer->peer_ref)
1510                                 /* We're already sending something to this ref. */
1511                                 goto free_name;
1512                 } else {
1513                         if (pat->matching && !(send_all || send_mirror))
1514                                 /*
1515                                  * Remote doesn't have it, and we have no
1516                                  * explicit pattern, and we don't have
1517                                  * --all or --mirror.
1518                                  */
1519                                 goto free_name;
1520
1521                         /* Create a new one and link it */
1522                         dst_peer = make_linked_ref(dst_name, &dst_tail);
1523                         oidcpy(&dst_peer->new_oid, &ref->new_oid);
1524                         string_list_insert(&dst_ref_index,
1525                                 dst_peer->name)->util = dst_peer;
1526                 }
1527                 dst_peer->peer_ref = copy_ref(ref);
1528                 dst_peer->force = pat->force;
1529         free_name:
1530                 free(dst_name);
1531         }
1532
1533         string_list_clear(&dst_ref_index, 0);
1534
1535         if (flags & MATCH_REFS_FOLLOW_TAGS)
1536                 add_missing_tags(src, dst, &dst_tail);
1537
1538         if (send_prune) {
1539                 struct string_list src_ref_index = STRING_LIST_INIT_NODUP;
1540                 /* check for missing refs on the remote */
1541                 for (ref = *dst; ref; ref = ref->next) {
1542                         char *src_name;
1543
1544                         if (ref->peer_ref)
1545                                 /* We're already sending something to this ref. */
1546                                 continue;
1547
1548                         src_name = get_ref_match(rs, nr_refspec, ref, send_mirror, FROM_DST, NULL);
1549                         if (src_name) {
1550                                 if (!src_ref_index.nr)
1551                                         prepare_ref_index(&src_ref_index, src);
1552                                 if (!string_list_has_string(&src_ref_index,
1553                                             src_name))
1554                                         ref->peer_ref = alloc_delete_ref();
1555                                 free(src_name);
1556                         }
1557                 }
1558                 string_list_clear(&src_ref_index, 0);
1559         }
1560         if (errs)
1561                 return -1;
1562         return 0;
1563 }
1564
1565 void set_ref_status_for_push(struct ref *remote_refs, int send_mirror,
1566                              int force_update)
1567 {
1568         struct ref *ref;
1569
1570         for (ref = remote_refs; ref; ref = ref->next) {
1571                 int force_ref_update = ref->force || force_update;
1572                 int reject_reason = 0;
1573
1574                 if (ref->peer_ref)
1575                         oidcpy(&ref->new_oid, &ref->peer_ref->new_oid);
1576                 else if (!send_mirror)
1577                         continue;
1578
1579                 ref->deletion = is_null_oid(&ref->new_oid);
1580                 if (!ref->deletion &&
1581                         !oidcmp(&ref->old_oid, &ref->new_oid)) {
1582                         ref->status = REF_STATUS_UPTODATE;
1583                         continue;
1584                 }
1585
1586                 /*
1587                  * If the remote ref has moved and is now different
1588                  * from what we expect, reject any push.
1589                  *
1590                  * It also is an error if the user told us to check
1591                  * with the remote-tracking branch to find the value
1592                  * to expect, but we did not have such a tracking
1593                  * branch.
1594                  */
1595                 if (ref->expect_old_sha1) {
1596                         if (oidcmp(&ref->old_oid, &ref->old_oid_expect))
1597                                 reject_reason = REF_STATUS_REJECT_STALE;
1598                         else
1599                                 /* If the ref isn't stale then force the update. */
1600                                 force_ref_update = 1;
1601                 }
1602
1603                 /*
1604                  * If the update isn't already rejected then check
1605                  * the usual "must fast-forward" rules.
1606                  *
1607                  * Decide whether an individual refspec A:B can be
1608                  * pushed.  The push will succeed if any of the
1609                  * following are true:
1610                  *
1611                  * (1) the remote reference B does not exist
1612                  *
1613                  * (2) the remote reference B is being removed (i.e.,
1614                  *     pushing :B where no source is specified)
1615                  *
1616                  * (3) the destination is not under refs/tags/, and
1617                  *     if the old and new value is a commit, the new
1618                  *     is a descendant of the old.
1619                  *
1620                  * (4) it is forced using the +A:B notation, or by
1621                  *     passing the --force argument
1622                  */
1623
1624                 if (!reject_reason && !ref->deletion && !is_null_oid(&ref->old_oid)) {
1625                         if (starts_with(ref->name, "refs/tags/"))
1626                                 reject_reason = REF_STATUS_REJECT_ALREADY_EXISTS;
1627                         else if (!has_object_file(&ref->old_oid))
1628                                 reject_reason = REF_STATUS_REJECT_FETCH_FIRST;
1629                         else if (!lookup_commit_reference_gently(&ref->old_oid, 1) ||
1630                                  !lookup_commit_reference_gently(&ref->new_oid, 1))
1631                                 reject_reason = REF_STATUS_REJECT_NEEDS_FORCE;
1632                         else if (!ref_newer(&ref->new_oid, &ref->old_oid))
1633                                 reject_reason = REF_STATUS_REJECT_NONFASTFORWARD;
1634                 }
1635
1636                 /*
1637                  * "--force" will defeat any rejection implemented
1638                  * by the rules above.
1639                  */
1640                 if (!force_ref_update)
1641                         ref->status = reject_reason;
1642                 else if (reject_reason)
1643                         ref->forced_update = 1;
1644         }
1645 }
1646
1647 static void set_merge(struct branch *ret)
1648 {
1649         struct remote *remote;
1650         char *ref;
1651         struct object_id oid;
1652         int i;
1653
1654         if (!ret)
1655                 return; /* no branch */
1656         if (ret->merge)
1657                 return; /* already run */
1658         if (!ret->remote_name || !ret->merge_nr) {
1659                 /*
1660                  * no merge config; let's make sure we don't confuse callers
1661                  * with a non-zero merge_nr but a NULL merge
1662                  */
1663                 ret->merge_nr = 0;
1664                 return;
1665         }
1666
1667         remote = remote_get(ret->remote_name);
1668
1669         ret->merge = xcalloc(ret->merge_nr, sizeof(*ret->merge));
1670         for (i = 0; i < ret->merge_nr; i++) {
1671                 ret->merge[i] = xcalloc(1, sizeof(**ret->merge));
1672                 ret->merge[i]->src = xstrdup(ret->merge_name[i]);
1673                 if (!remote_find_tracking(remote, ret->merge[i]) ||
1674                     strcmp(ret->remote_name, "."))
1675                         continue;
1676                 if (dwim_ref(ret->merge_name[i], strlen(ret->merge_name[i]),
1677                              &oid, &ref) == 1)
1678                         ret->merge[i]->dst = ref;
1679                 else
1680                         ret->merge[i]->dst = xstrdup(ret->merge_name[i]);
1681         }
1682 }
1683
1684 struct branch *branch_get(const char *name)
1685 {
1686         struct branch *ret;
1687
1688         read_config();
1689         if (!name || !*name || !strcmp(name, "HEAD"))
1690                 ret = current_branch;
1691         else
1692                 ret = make_branch(name, 0);
1693         set_merge(ret);
1694         return ret;
1695 }
1696
1697 int branch_has_merge_config(struct branch *branch)
1698 {
1699         return branch && !!branch->merge;
1700 }
1701
1702 int branch_merge_matches(struct branch *branch,
1703                                  int i,
1704                                  const char *refname)
1705 {
1706         if (!branch || i < 0 || i >= branch->merge_nr)
1707                 return 0;
1708         return refname_match(branch->merge[i]->src, refname);
1709 }
1710
1711 __attribute__((format (printf,2,3)))
1712 static const char *error_buf(struct strbuf *err, const char *fmt, ...)
1713 {
1714         if (err) {
1715                 va_list ap;
1716                 va_start(ap, fmt);
1717                 strbuf_vaddf(err, fmt, ap);
1718                 va_end(ap);
1719         }
1720         return NULL;
1721 }
1722
1723 const char *branch_get_upstream(struct branch *branch, struct strbuf *err)
1724 {
1725         if (!branch)
1726                 return error_buf(err, _("HEAD does not point to a branch"));
1727
1728         if (!branch->merge || !branch->merge[0]) {
1729                 /*
1730                  * no merge config; is it because the user didn't define any,
1731                  * or because it is not a real branch, and get_branch
1732                  * auto-vivified it?
1733                  */
1734                 if (!ref_exists(branch->refname))
1735                         return error_buf(err, _("no such branch: '%s'"),
1736                                          branch->name);
1737                 return error_buf(err,
1738                                  _("no upstream configured for branch '%s'"),
1739                                  branch->name);
1740         }
1741
1742         if (!branch->merge[0]->dst)
1743                 return error_buf(err,
1744                                  _("upstream branch '%s' not stored as a remote-tracking branch"),
1745                                  branch->merge[0]->src);
1746
1747         return branch->merge[0]->dst;
1748 }
1749
1750 static const char *tracking_for_push_dest(struct remote *remote,
1751                                           const char *refname,
1752                                           struct strbuf *err)
1753 {
1754         char *ret;
1755
1756         ret = apply_refspecs(remote->fetch, remote->fetch_refspec_nr, refname);
1757         if (!ret)
1758                 return error_buf(err,
1759                                  _("push destination '%s' on remote '%s' has no local tracking branch"),
1760                                  refname, remote->name);
1761         return ret;
1762 }
1763
1764 static const char *branch_get_push_1(struct branch *branch, struct strbuf *err)
1765 {
1766         struct remote *remote;
1767
1768         remote = remote_get(pushremote_for_branch(branch, NULL));
1769         if (!remote)
1770                 return error_buf(err,
1771                                  _("branch '%s' has no remote for pushing"),
1772                                  branch->name);
1773
1774         if (remote->push_refspec_nr) {
1775                 char *dst;
1776                 const char *ret;
1777
1778                 dst = apply_refspecs(remote->push, remote->push_refspec_nr,
1779                                      branch->refname);
1780                 if (!dst)
1781                         return error_buf(err,
1782                                          _("push refspecs for '%s' do not include '%s'"),
1783                                          remote->name, branch->name);
1784
1785                 ret = tracking_for_push_dest(remote, dst, err);
1786                 free(dst);
1787                 return ret;
1788         }
1789
1790         if (remote->mirror)
1791                 return tracking_for_push_dest(remote, branch->refname, err);
1792
1793         switch (push_default) {
1794         case PUSH_DEFAULT_NOTHING:
1795                 return error_buf(err, _("push has no destination (push.default is 'nothing')"));
1796
1797         case PUSH_DEFAULT_MATCHING:
1798         case PUSH_DEFAULT_CURRENT:
1799                 return tracking_for_push_dest(remote, branch->refname, err);
1800
1801         case PUSH_DEFAULT_UPSTREAM:
1802                 return branch_get_upstream(branch, err);
1803
1804         case PUSH_DEFAULT_UNSPECIFIED:
1805         case PUSH_DEFAULT_SIMPLE:
1806                 {
1807                         const char *up, *cur;
1808
1809                         up = branch_get_upstream(branch, err);
1810                         if (!up)
1811                                 return NULL;
1812                         cur = tracking_for_push_dest(remote, branch->refname, err);
1813                         if (!cur)
1814                                 return NULL;
1815                         if (strcmp(cur, up))
1816                                 return error_buf(err,
1817                                                  _("cannot resolve 'simple' push to a single destination"));
1818                         return cur;
1819                 }
1820         }
1821
1822         die("BUG: unhandled push situation");
1823 }
1824
1825 const char *branch_get_push(struct branch *branch, struct strbuf *err)
1826 {
1827         if (!branch)
1828                 return error_buf(err, _("HEAD does not point to a branch"));
1829
1830         if (!branch->push_tracking_ref)
1831                 branch->push_tracking_ref = branch_get_push_1(branch, err);
1832         return branch->push_tracking_ref;
1833 }
1834
1835 static int ignore_symref_update(const char *refname)
1836 {
1837         int flag;
1838
1839         if (!resolve_ref_unsafe(refname, 0, NULL, &flag))
1840                 return 0; /* non-existing refs are OK */
1841         return (flag & REF_ISSYMREF);
1842 }
1843
1844 /*
1845  * Create and return a list of (struct ref) consisting of copies of
1846  * each remote_ref that matches refspec.  refspec must be a pattern.
1847  * Fill in the copies' peer_ref to describe the local tracking refs to
1848  * which they map.  Omit any references that would map to an existing
1849  * local symbolic ref.
1850  */
1851 static struct ref *get_expanded_map(const struct ref *remote_refs,
1852                                     const struct refspec *refspec)
1853 {
1854         const struct ref *ref;
1855         struct ref *ret = NULL;
1856         struct ref **tail = &ret;
1857
1858         for (ref = remote_refs; ref; ref = ref->next) {
1859                 char *expn_name = NULL;
1860
1861                 if (strchr(ref->name, '^'))
1862                         continue; /* a dereference item */
1863                 if (match_name_with_pattern(refspec->src, ref->name,
1864                                             refspec->dst, &expn_name) &&
1865                     !ignore_symref_update(expn_name)) {
1866                         struct ref *cpy = copy_ref(ref);
1867
1868                         cpy->peer_ref = alloc_ref(expn_name);
1869                         if (refspec->force)
1870                                 cpy->peer_ref->force = 1;
1871                         *tail = cpy;
1872                         tail = &cpy->next;
1873                 }
1874                 free(expn_name);
1875         }
1876
1877         return ret;
1878 }
1879
1880 static const struct ref *find_ref_by_name_abbrev(const struct ref *refs, const char *name)
1881 {
1882         const struct ref *ref;
1883         for (ref = refs; ref; ref = ref->next) {
1884                 if (refname_match(name, ref->name))
1885                         return ref;
1886         }
1887         return NULL;
1888 }
1889
1890 struct ref *get_remote_ref(const struct ref *remote_refs, const char *name)
1891 {
1892         const struct ref *ref = find_ref_by_name_abbrev(remote_refs, name);
1893
1894         if (!ref)
1895                 return NULL;
1896
1897         return copy_ref(ref);
1898 }
1899
1900 static struct ref *get_local_ref(const char *name)
1901 {
1902         if (!name || name[0] == '\0')
1903                 return NULL;
1904
1905         if (starts_with(name, "refs/"))
1906                 return alloc_ref(name);
1907
1908         if (starts_with(name, "heads/") ||
1909             starts_with(name, "tags/") ||
1910             starts_with(name, "remotes/"))
1911                 return alloc_ref_with_prefix("refs/", 5, name);
1912
1913         return alloc_ref_with_prefix("refs/heads/", 11, name);
1914 }
1915
1916 int get_fetch_map(const struct ref *remote_refs,
1917                   const struct refspec *refspec,
1918                   struct ref ***tail,
1919                   int missing_ok)
1920 {
1921         struct ref *ref_map, **rmp;
1922
1923         if (refspec->pattern) {
1924                 ref_map = get_expanded_map(remote_refs, refspec);
1925         } else {
1926                 const char *name = refspec->src[0] ? refspec->src : "HEAD";
1927
1928                 if (refspec->exact_sha1) {
1929                         ref_map = alloc_ref(name);
1930                         get_oid_hex(name, &ref_map->old_oid);
1931                 } else {
1932                         ref_map = get_remote_ref(remote_refs, name);
1933                 }
1934                 if (!missing_ok && !ref_map)
1935                         die("Couldn't find remote ref %s", name);
1936                 if (ref_map) {
1937                         ref_map->peer_ref = get_local_ref(refspec->dst);
1938                         if (ref_map->peer_ref && refspec->force)
1939                                 ref_map->peer_ref->force = 1;
1940                 }
1941         }
1942
1943         for (rmp = &ref_map; *rmp; ) {
1944                 if ((*rmp)->peer_ref) {
1945                         if (!starts_with((*rmp)->peer_ref->name, "refs/") ||
1946                             check_refname_format((*rmp)->peer_ref->name, 0)) {
1947                                 struct ref *ignore = *rmp;
1948                                 error("* Ignoring funny ref '%s' locally",
1949                                       (*rmp)->peer_ref->name);
1950                                 *rmp = (*rmp)->next;
1951                                 free(ignore->peer_ref);
1952                                 free(ignore);
1953                                 continue;
1954                         }
1955                 }
1956                 rmp = &((*rmp)->next);
1957         }
1958
1959         if (ref_map)
1960                 tail_link_ref(ref_map, tail);
1961
1962         return 0;
1963 }
1964
1965 int resolve_remote_symref(struct ref *ref, struct ref *list)
1966 {
1967         if (!ref->symref)
1968                 return 0;
1969         for (; list; list = list->next)
1970                 if (!strcmp(ref->symref, list->name)) {
1971                         oidcpy(&ref->old_oid, &list->old_oid);
1972                         return 0;
1973                 }
1974         return 1;
1975 }
1976
1977 static void unmark_and_free(struct commit_list *list, unsigned int mark)
1978 {
1979         while (list) {
1980                 struct commit *commit = pop_commit(&list);
1981                 commit->object.flags &= ~mark;
1982         }
1983 }
1984
1985 int ref_newer(const struct object_id *new_oid, const struct object_id *old_oid)
1986 {
1987         struct object *o;
1988         struct commit *old_commit, *new_commit;
1989         struct commit_list *list, *used;
1990         int found = 0;
1991
1992         /*
1993          * Both new_commit and old_commit must be commit-ish and new_commit is descendant of
1994          * old_commit.  Otherwise we require --force.
1995          */
1996         o = deref_tag(parse_object(old_oid), NULL, 0);
1997         if (!o || o->type != OBJ_COMMIT)
1998                 return 0;
1999         old_commit = (struct commit *) o;
2000
2001         o = deref_tag(parse_object(new_oid), NULL, 0);
2002         if (!o || o->type != OBJ_COMMIT)
2003                 return 0;
2004         new_commit = (struct commit *) o;
2005
2006         if (parse_commit(new_commit) < 0)
2007                 return 0;
2008
2009         used = list = NULL;
2010         commit_list_insert(new_commit, &list);
2011         while (list) {
2012                 new_commit = pop_most_recent_commit(&list, TMP_MARK);
2013                 commit_list_insert(new_commit, &used);
2014                 if (new_commit == old_commit) {
2015                         found = 1;
2016                         break;
2017                 }
2018         }
2019         unmark_and_free(list, TMP_MARK);
2020         unmark_and_free(used, TMP_MARK);
2021         return found;
2022 }
2023
2024 /*
2025  * Lookup the upstream branch for the given branch and if present, optionally
2026  * compute the commit ahead/behind values for the pair.
2027  *
2028  * If abf is AHEAD_BEHIND_FULL, compute the full ahead/behind and return the
2029  * counts in *num_ours and *num_theirs.  If abf is AHEAD_BEHIND_QUICK, skip
2030  * the (potentially expensive) a/b computation (*num_ours and *num_theirs are
2031  * set to zero).
2032  *
2033  * The name of the upstream branch (or NULL if no upstream is defined) is
2034  * returned via *upstream_name, if it is not itself NULL.
2035  *
2036  * Returns -1 if num_ours and num_theirs could not be filled in (e.g., no
2037  * upstream defined, or ref does not exist).  Returns 0 if the commits are
2038  * identical.  Returns 1 if commits are different.
2039  */
2040 int stat_tracking_info(struct branch *branch, int *num_ours, int *num_theirs,
2041                        const char **upstream_name, enum ahead_behind_flags abf)
2042 {
2043         struct object_id oid;
2044         struct commit *ours, *theirs;
2045         struct rev_info revs;
2046         const char *base;
2047         struct argv_array argv = ARGV_ARRAY_INIT;
2048
2049         /* Cannot stat unless we are marked to build on top of somebody else. */
2050         base = branch_get_upstream(branch, NULL);
2051         if (upstream_name)
2052                 *upstream_name = base;
2053         if (!base)
2054                 return -1;
2055
2056         /* Cannot stat if what we used to build on no longer exists */
2057         if (read_ref(base, &oid))
2058                 return -1;
2059         theirs = lookup_commit_reference(&oid);
2060         if (!theirs)
2061                 return -1;
2062
2063         if (read_ref(branch->refname, &oid))
2064                 return -1;
2065         ours = lookup_commit_reference(&oid);
2066         if (!ours)
2067                 return -1;
2068
2069         *num_theirs = *num_ours = 0;
2070
2071         /* are we the same? */
2072         if (theirs == ours)
2073                 return 0;
2074         if (abf == AHEAD_BEHIND_QUICK)
2075                 return 1;
2076         if (abf != AHEAD_BEHIND_FULL)
2077                 BUG("stat_tracking_info: invalid abf '%d'", abf);
2078
2079         /* Run "rev-list --left-right ours...theirs" internally... */
2080         argv_array_push(&argv, ""); /* ignored */
2081         argv_array_push(&argv, "--left-right");
2082         argv_array_pushf(&argv, "%s...%s",
2083                          oid_to_hex(&ours->object.oid),
2084                          oid_to_hex(&theirs->object.oid));
2085         argv_array_push(&argv, "--");
2086
2087         init_revisions(&revs, NULL);
2088         setup_revisions(argv.argc, argv.argv, &revs, NULL);
2089         if (prepare_revision_walk(&revs))
2090                 die("revision walk setup failed");
2091
2092         /* ... and count the commits on each side. */
2093         while (1) {
2094                 struct commit *c = get_revision(&revs);
2095                 if (!c)
2096                         break;
2097                 if (c->object.flags & SYMMETRIC_LEFT)
2098                         (*num_ours)++;
2099                 else
2100                         (*num_theirs)++;
2101         }
2102
2103         /* clear object flags smudged by the above traversal */
2104         clear_commit_marks(ours, ALL_REV_FLAGS);
2105         clear_commit_marks(theirs, ALL_REV_FLAGS);
2106
2107         argv_array_clear(&argv);
2108         return 1;
2109 }
2110
2111 /*
2112  * Return true when there is anything to report, otherwise false.
2113  */
2114 int format_tracking_info(struct branch *branch, struct strbuf *sb,
2115                          enum ahead_behind_flags abf)
2116 {
2117         int ours, theirs, sti;
2118         const char *full_base;
2119         char *base;
2120         int upstream_is_gone = 0;
2121
2122         sti = stat_tracking_info(branch, &ours, &theirs, &full_base, abf);
2123         if (sti < 0) {
2124                 if (!full_base)
2125                         return 0;
2126                 upstream_is_gone = 1;
2127         }
2128
2129         base = shorten_unambiguous_ref(full_base, 0);
2130         if (upstream_is_gone) {
2131                 strbuf_addf(sb,
2132                         _("Your branch is based on '%s', but the upstream is gone.\n"),
2133                         base);
2134                 if (advice_status_hints)
2135                         strbuf_addstr(sb,
2136                                 _("  (use \"git branch --unset-upstream\" to fixup)\n"));
2137         } else if (!sti) {
2138                 strbuf_addf(sb,
2139                         _("Your branch is up to date with '%s'.\n"),
2140                         base);
2141         } else if (abf == AHEAD_BEHIND_QUICK) {
2142                 strbuf_addf(sb,
2143                             _("Your branch and '%s' refer to different commits.\n"),
2144                             base);
2145                 if (advice_status_hints)
2146                         strbuf_addf(sb, _("  (use \"%s\" for details)\n"),
2147                                     "git status --ahead-behind");
2148         } else if (!theirs) {
2149                 strbuf_addf(sb,
2150                         Q_("Your branch is ahead of '%s' by %d commit.\n",
2151                            "Your branch is ahead of '%s' by %d commits.\n",
2152                            ours),
2153                         base, ours);
2154                 if (advice_status_hints)
2155                         strbuf_addstr(sb,
2156                                 _("  (use \"git push\" to publish your local commits)\n"));
2157         } else if (!ours) {
2158                 strbuf_addf(sb,
2159                         Q_("Your branch is behind '%s' by %d commit, "
2160                                "and can be fast-forwarded.\n",
2161                            "Your branch is behind '%s' by %d commits, "
2162                                "and can be fast-forwarded.\n",
2163                            theirs),
2164                         base, theirs);
2165                 if (advice_status_hints)
2166                         strbuf_addstr(sb,
2167                                 _("  (use \"git pull\" to update your local branch)\n"));
2168         } else {
2169                 strbuf_addf(sb,
2170                         Q_("Your branch and '%s' have diverged,\n"
2171                                "and have %d and %d different commit each, "
2172                                "respectively.\n",
2173                            "Your branch and '%s' have diverged,\n"
2174                                "and have %d and %d different commits each, "
2175                                "respectively.\n",
2176                            ours + theirs),
2177                         base, ours, theirs);
2178                 if (advice_status_hints)
2179                         strbuf_addstr(sb,
2180                                 _("  (use \"git pull\" to merge the remote branch into yours)\n"));
2181         }
2182         free(base);
2183         return 1;
2184 }
2185
2186 static int one_local_ref(const char *refname, const struct object_id *oid,
2187                          int flag, void *cb_data)
2188 {
2189         struct ref ***local_tail = cb_data;
2190         struct ref *ref;
2191
2192         /* we already know it starts with refs/ to get here */
2193         if (check_refname_format(refname + 5, 0))
2194                 return 0;
2195
2196         ref = alloc_ref(refname);
2197         oidcpy(&ref->new_oid, oid);
2198         **local_tail = ref;
2199         *local_tail = &ref->next;
2200         return 0;
2201 }
2202
2203 struct ref *get_local_heads(void)
2204 {
2205         struct ref *local_refs = NULL, **local_tail = &local_refs;
2206
2207         for_each_ref(one_local_ref, &local_tail);
2208         return local_refs;
2209 }
2210
2211 struct ref *guess_remote_head(const struct ref *head,
2212                               const struct ref *refs,
2213                               int all)
2214 {
2215         const struct ref *r;
2216         struct ref *list = NULL;
2217         struct ref **tail = &list;
2218
2219         if (!head)
2220                 return NULL;
2221
2222         /*
2223          * Some transports support directly peeking at
2224          * where HEAD points; if that is the case, then
2225          * we don't have to guess.
2226          */
2227         if (head->symref)
2228                 return copy_ref(find_ref_by_name(refs, head->symref));
2229
2230         /* If refs/heads/master could be right, it is. */
2231         if (!all) {
2232                 r = find_ref_by_name(refs, "refs/heads/master");
2233                 if (r && !oidcmp(&r->old_oid, &head->old_oid))
2234                         return copy_ref(r);
2235         }
2236
2237         /* Look for another ref that points there */
2238         for (r = refs; r; r = r->next) {
2239                 if (r != head &&
2240                     starts_with(r->name, "refs/heads/") &&
2241                     !oidcmp(&r->old_oid, &head->old_oid)) {
2242                         *tail = copy_ref(r);
2243                         tail = &((*tail)->next);
2244                         if (!all)
2245                                 break;
2246                 }
2247         }
2248
2249         return list;
2250 }
2251
2252 struct stale_heads_info {
2253         struct string_list *ref_names;
2254         struct ref **stale_refs_tail;
2255         struct refspec *refs;
2256         int ref_count;
2257 };
2258
2259 static int get_stale_heads_cb(const char *refname, const struct object_id *oid,
2260                               int flags, void *cb_data)
2261 {
2262         struct stale_heads_info *info = cb_data;
2263         struct string_list matches = STRING_LIST_INIT_DUP;
2264         struct refspec query;
2265         int i, stale = 1;
2266         memset(&query, 0, sizeof(struct refspec));
2267         query.dst = (char *)refname;
2268
2269         query_refspecs_multiple(info->refs, info->ref_count, &query, &matches);
2270         if (matches.nr == 0)
2271                 goto clean_exit; /* No matches */
2272
2273         /*
2274          * If we did find a suitable refspec and it's not a symref and
2275          * it's not in the list of refs that currently exist in that
2276          * remote, we consider it to be stale. In order to deal with
2277          * overlapping refspecs, we need to go over all of the
2278          * matching refs.
2279          */
2280         if (flags & REF_ISSYMREF)
2281                 goto clean_exit;
2282
2283         for (i = 0; stale && i < matches.nr; i++)
2284                 if (string_list_has_string(info->ref_names, matches.items[i].string))
2285                         stale = 0;
2286
2287         if (stale) {
2288                 struct ref *ref = make_linked_ref(refname, &info->stale_refs_tail);
2289                 oidcpy(&ref->new_oid, oid);
2290         }
2291
2292 clean_exit:
2293         string_list_clear(&matches, 0);
2294         return 0;
2295 }
2296
2297 struct ref *get_stale_heads(struct refspec *refs, int ref_count, struct ref *fetch_map)
2298 {
2299         struct ref *ref, *stale_refs = NULL;
2300         struct string_list ref_names = STRING_LIST_INIT_NODUP;
2301         struct stale_heads_info info;
2302
2303         info.ref_names = &ref_names;
2304         info.stale_refs_tail = &stale_refs;
2305         info.refs = refs;
2306         info.ref_count = ref_count;
2307         for (ref = fetch_map; ref; ref = ref->next)
2308                 string_list_append(&ref_names, ref->name);
2309         string_list_sort(&ref_names);
2310         for_each_ref(get_stale_heads_cb, &info);
2311         string_list_clear(&ref_names, 0);
2312         return stale_refs;
2313 }
2314
2315 /*
2316  * Compare-and-swap
2317  */
2318 static void clear_cas_option(struct push_cas_option *cas)
2319 {
2320         int i;
2321
2322         for (i = 0; i < cas->nr; i++)
2323                 free(cas->entry[i].refname);
2324         free(cas->entry);
2325         memset(cas, 0, sizeof(*cas));
2326 }
2327
2328 static struct push_cas *add_cas_entry(struct push_cas_option *cas,
2329                                       const char *refname,
2330                                       size_t refnamelen)
2331 {
2332         struct push_cas *entry;
2333         ALLOC_GROW(cas->entry, cas->nr + 1, cas->alloc);
2334         entry = &cas->entry[cas->nr++];
2335         memset(entry, 0, sizeof(*entry));
2336         entry->refname = xmemdupz(refname, refnamelen);
2337         return entry;
2338 }
2339
2340 static int parse_push_cas_option(struct push_cas_option *cas, const char *arg, int unset)
2341 {
2342         const char *colon;
2343         struct push_cas *entry;
2344
2345         if (unset) {
2346                 /* "--no-<option>" */
2347                 clear_cas_option(cas);
2348                 return 0;
2349         }
2350
2351         if (!arg) {
2352                 /* just "--<option>" */
2353                 cas->use_tracking_for_rest = 1;
2354                 return 0;
2355         }
2356
2357         /* "--<option>=refname" or "--<option>=refname:value" */
2358         colon = strchrnul(arg, ':');
2359         entry = add_cas_entry(cas, arg, colon - arg);
2360         if (!*colon)
2361                 entry->use_tracking = 1;
2362         else if (!colon[1])
2363                 oidclr(&entry->expect);
2364         else if (get_oid(colon + 1, &entry->expect))
2365                 return error("cannot parse expected object name '%s'", colon + 1);
2366         return 0;
2367 }
2368
2369 int parseopt_push_cas_option(const struct option *opt, const char *arg, int unset)
2370 {
2371         return parse_push_cas_option(opt->value, arg, unset);
2372 }
2373
2374 int is_empty_cas(const struct push_cas_option *cas)
2375 {
2376         return !cas->use_tracking_for_rest && !cas->nr;
2377 }
2378
2379 /*
2380  * Look at remote.fetch refspec and see if we have a remote
2381  * tracking branch for the refname there.  Fill its current
2382  * value in sha1[].
2383  * If we cannot do so, return negative to signal an error.
2384  */
2385 static int remote_tracking(struct remote *remote, const char *refname,
2386                            struct object_id *oid)
2387 {
2388         char *dst;
2389
2390         dst = apply_refspecs(remote->fetch, remote->fetch_refspec_nr, refname);
2391         if (!dst)
2392                 return -1; /* no tracking ref for refname at remote */
2393         if (read_ref(dst, oid))
2394                 return -1; /* we know what the tracking ref is but we cannot read it */
2395         return 0;
2396 }
2397
2398 static void apply_cas(struct push_cas_option *cas,
2399                       struct remote *remote,
2400                       struct ref *ref)
2401 {
2402         int i;
2403
2404         /* Find an explicit --<option>=<name>[:<value>] entry */
2405         for (i = 0; i < cas->nr; i++) {
2406                 struct push_cas *entry = &cas->entry[i];
2407                 if (!refname_match(entry->refname, ref->name))
2408                         continue;
2409                 ref->expect_old_sha1 = 1;
2410                 if (!entry->use_tracking)
2411                         oidcpy(&ref->old_oid_expect, &entry->expect);
2412                 else if (remote_tracking(remote, ref->name, &ref->old_oid_expect))
2413                         oidclr(&ref->old_oid_expect);
2414                 return;
2415         }
2416
2417         /* Are we using "--<option>" to cover all? */
2418         if (!cas->use_tracking_for_rest)
2419                 return;
2420
2421         ref->expect_old_sha1 = 1;
2422         if (remote_tracking(remote, ref->name, &ref->old_oid_expect))
2423                 oidclr(&ref->old_oid_expect);
2424 }
2425
2426 void apply_push_cas(struct push_cas_option *cas,
2427                     struct remote *remote,
2428                     struct ref *remote_refs)
2429 {
2430         struct ref *ref;
2431         for (ref = remote_refs; ref; ref = ref->next)
2432                 apply_cas(cas, remote, ref);
2433 }