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