]> git.scripts.mit.edu Git - git.git/blob - remote.c
The sixteenth batch
[git.git] / remote.c
1 #include "git-compat-util.h"
2 #include "abspath.h"
3 #include "config.h"
4 #include "environment.h"
5 #include "gettext.h"
6 #include "hex.h"
7 #include "remote.h"
8 #include "urlmatch.h"
9 #include "refs.h"
10 #include "refspec.h"
11 #include "object-name.h"
12 #include "object-store-ll.h"
13 #include "path.h"
14 #include "commit.h"
15 #include "diff.h"
16 #include "revision.h"
17 #include "dir.h"
18 #include "setup.h"
19 #include "string-list.h"
20 #include "strvec.h"
21 #include "commit-reach.h"
22 #include "advice.h"
23 #include "connect.h"
24 #include "parse-options.h"
25
26 enum map_direction { FROM_SRC, FROM_DST };
27
28 struct counted_string {
29         size_t len;
30         const char *s;
31 };
32
33 static int valid_remote(const struct remote *remote)
34 {
35         return (!!remote->url) || (!!remote->foreign_vcs);
36 }
37
38 static const char *alias_url(const char *url, struct rewrites *r)
39 {
40         int i, j;
41         struct counted_string *longest;
42         int longest_i;
43
44         longest = NULL;
45         longest_i = -1;
46         for (i = 0; i < r->rewrite_nr; i++) {
47                 if (!r->rewrite[i])
48                         continue;
49                 for (j = 0; j < r->rewrite[i]->instead_of_nr; j++) {
50                         if (starts_with(url, r->rewrite[i]->instead_of[j].s) &&
51                             (!longest ||
52                              longest->len < r->rewrite[i]->instead_of[j].len)) {
53                                 longest = &(r->rewrite[i]->instead_of[j]);
54                                 longest_i = i;
55                         }
56                 }
57         }
58         if (!longest)
59                 return url;
60
61         return xstrfmt("%s%s", r->rewrite[longest_i]->base, url + longest->len);
62 }
63
64 static void add_url(struct remote *remote, const char *url)
65 {
66         ALLOC_GROW(remote->url, remote->url_nr + 1, remote->url_alloc);
67         remote->url[remote->url_nr++] = url;
68 }
69
70 static void add_pushurl(struct remote *remote, const char *pushurl)
71 {
72         ALLOC_GROW(remote->pushurl, remote->pushurl_nr + 1, remote->pushurl_alloc);
73         remote->pushurl[remote->pushurl_nr++] = pushurl;
74 }
75
76 static void add_pushurl_alias(struct remote_state *remote_state,
77                               struct remote *remote, const char *url)
78 {
79         const char *pushurl = alias_url(url, &remote_state->rewrites_push);
80         if (pushurl != url)
81                 add_pushurl(remote, pushurl);
82 }
83
84 static void add_url_alias(struct remote_state *remote_state,
85                           struct remote *remote, const char *url)
86 {
87         add_url(remote, alias_url(url, &remote_state->rewrites));
88         add_pushurl_alias(remote_state, remote, url);
89 }
90
91 struct remotes_hash_key {
92         const char *str;
93         int len;
94 };
95
96 static int remotes_hash_cmp(const void *cmp_data UNUSED,
97                             const struct hashmap_entry *eptr,
98                             const struct hashmap_entry *entry_or_key,
99                             const void *keydata)
100 {
101         const struct remote *a, *b;
102         const struct remotes_hash_key *key = keydata;
103
104         a = container_of(eptr, const struct remote, ent);
105         b = container_of(entry_or_key, const struct remote, ent);
106
107         if (key)
108                 return !!xstrncmpz(a->name, key->str, key->len);
109         else
110                 return strcmp(a->name, b->name);
111 }
112
113 static struct remote *make_remote(struct remote_state *remote_state,
114                                   const char *name, int len)
115 {
116         struct remote *ret;
117         struct remotes_hash_key lookup;
118         struct hashmap_entry lookup_entry, *e;
119
120         if (!len)
121                 len = strlen(name);
122
123         lookup.str = name;
124         lookup.len = len;
125         hashmap_entry_init(&lookup_entry, memhash(name, len));
126
127         e = hashmap_get(&remote_state->remotes_hash, &lookup_entry, &lookup);
128         if (e)
129                 return container_of(e, struct remote, ent);
130
131         CALLOC_ARRAY(ret, 1);
132         ret->prune = -1;  /* unspecified */
133         ret->prune_tags = -1;  /* unspecified */
134         ret->name = xstrndup(name, len);
135         refspec_init(&ret->push, REFSPEC_PUSH);
136         refspec_init(&ret->fetch, REFSPEC_FETCH);
137
138         ALLOC_GROW(remote_state->remotes, remote_state->remotes_nr + 1,
139                    remote_state->remotes_alloc);
140         remote_state->remotes[remote_state->remotes_nr++] = ret;
141
142         hashmap_entry_init(&ret->ent, lookup_entry.hash);
143         if (hashmap_put_entry(&remote_state->remotes_hash, ret, ent))
144                 BUG("hashmap_put overwrote entry after hashmap_get returned NULL");
145         return ret;
146 }
147
148 static void remote_clear(struct remote *remote)
149 {
150         int i;
151
152         free((char *)remote->name);
153         free((char *)remote->foreign_vcs);
154
155         for (i = 0; i < remote->url_nr; i++)
156                 free((char *)remote->url[i]);
157         FREE_AND_NULL(remote->url);
158
159         for (i = 0; i < remote->pushurl_nr; i++)
160                 free((char *)remote->pushurl[i]);
161         FREE_AND_NULL(remote->pushurl);
162         free((char *)remote->receivepack);
163         free((char *)remote->uploadpack);
164         FREE_AND_NULL(remote->http_proxy);
165         FREE_AND_NULL(remote->http_proxy_authmethod);
166 }
167
168 static void add_merge(struct branch *branch, const char *name)
169 {
170         ALLOC_GROW(branch->merge_name, branch->merge_nr + 1,
171                    branch->merge_alloc);
172         branch->merge_name[branch->merge_nr++] = name;
173 }
174
175 struct branches_hash_key {
176         const char *str;
177         int len;
178 };
179
180 static int branches_hash_cmp(const void *cmp_data UNUSED,
181                              const struct hashmap_entry *eptr,
182                              const struct hashmap_entry *entry_or_key,
183                              const void *keydata)
184 {
185         const struct branch *a, *b;
186         const struct branches_hash_key *key = keydata;
187
188         a = container_of(eptr, const struct branch, ent);
189         b = container_of(entry_or_key, const struct branch, ent);
190
191         if (key)
192                 return !!xstrncmpz(a->name, key->str, key->len);
193         else
194                 return strcmp(a->name, b->name);
195 }
196
197 static struct branch *find_branch(struct remote_state *remote_state,
198                                   const char *name, size_t len)
199 {
200         struct branches_hash_key lookup;
201         struct hashmap_entry lookup_entry, *e;
202
203         lookup.str = name;
204         lookup.len = len;
205         hashmap_entry_init(&lookup_entry, memhash(name, len));
206
207         e = hashmap_get(&remote_state->branches_hash, &lookup_entry, &lookup);
208         if (e)
209                 return container_of(e, struct branch, ent);
210
211         return NULL;
212 }
213
214 static void die_on_missing_branch(struct repository *repo,
215                                   struct branch *branch)
216 {
217         /* branch == NULL is always valid because it represents detached HEAD. */
218         if (branch &&
219             branch != find_branch(repo->remote_state, branch->name,
220                                   strlen(branch->name)))
221                 die("branch %s was not found in the repository", branch->name);
222 }
223
224 static struct branch *make_branch(struct remote_state *remote_state,
225                                   const char *name, size_t len)
226 {
227         struct branch *ret;
228
229         ret = find_branch(remote_state, name, len);
230         if (ret)
231                 return ret;
232
233         CALLOC_ARRAY(ret, 1);
234         ret->name = xstrndup(name, len);
235         ret->refname = xstrfmt("refs/heads/%s", ret->name);
236
237         hashmap_entry_init(&ret->ent, memhash(name, len));
238         if (hashmap_put_entry(&remote_state->branches_hash, ret, ent))
239                 BUG("hashmap_put overwrote entry after hashmap_get returned NULL");
240         return ret;
241 }
242
243 static struct rewrite *make_rewrite(struct rewrites *r,
244                                     const char *base, size_t len)
245 {
246         struct rewrite *ret;
247         int i;
248
249         for (i = 0; i < r->rewrite_nr; i++) {
250                 if (len == r->rewrite[i]->baselen &&
251                     !strncmp(base, r->rewrite[i]->base, len))
252                         return r->rewrite[i];
253         }
254
255         ALLOC_GROW(r->rewrite, r->rewrite_nr + 1, r->rewrite_alloc);
256         CALLOC_ARRAY(ret, 1);
257         r->rewrite[r->rewrite_nr++] = ret;
258         ret->base = xstrndup(base, len);
259         ret->baselen = len;
260         return ret;
261 }
262
263 static void add_instead_of(struct rewrite *rewrite, const char *instead_of)
264 {
265         ALLOC_GROW(rewrite->instead_of, rewrite->instead_of_nr + 1, rewrite->instead_of_alloc);
266         rewrite->instead_of[rewrite->instead_of_nr].s = instead_of;
267         rewrite->instead_of[rewrite->instead_of_nr].len = strlen(instead_of);
268         rewrite->instead_of_nr++;
269 }
270
271 static const char *skip_spaces(const char *s)
272 {
273         while (isspace(*s))
274                 s++;
275         return s;
276 }
277
278 static void read_remotes_file(struct remote_state *remote_state,
279                               struct remote *remote)
280 {
281         struct strbuf buf = STRBUF_INIT;
282         FILE *f = fopen_or_warn(git_path("remotes/%s", remote->name), "r");
283
284         if (!f)
285                 return;
286         remote->configured_in_repo = 1;
287         remote->origin = REMOTE_REMOTES;
288         while (strbuf_getline(&buf, f) != EOF) {
289                 const char *v;
290
291                 strbuf_rtrim(&buf);
292
293                 if (skip_prefix(buf.buf, "URL:", &v))
294                         add_url_alias(remote_state, remote,
295                                       xstrdup(skip_spaces(v)));
296                 else if (skip_prefix(buf.buf, "Push:", &v))
297                         refspec_append(&remote->push, skip_spaces(v));
298                 else if (skip_prefix(buf.buf, "Pull:", &v))
299                         refspec_append(&remote->fetch, skip_spaces(v));
300         }
301         strbuf_release(&buf);
302         fclose(f);
303 }
304
305 static void read_branches_file(struct remote_state *remote_state,
306                                struct remote *remote)
307 {
308         char *frag, *to_free = NULL;
309         struct strbuf buf = STRBUF_INIT;
310         FILE *f = fopen_or_warn(git_path("branches/%s", remote->name), "r");
311
312         if (!f)
313                 return;
314
315         strbuf_getline_lf(&buf, f);
316         fclose(f);
317         strbuf_trim(&buf);
318         if (!buf.len) {
319                 strbuf_release(&buf);
320                 return;
321         }
322
323         remote->configured_in_repo = 1;
324         remote->origin = REMOTE_BRANCHES;
325
326         /*
327          * The branches file would have URL and optionally
328          * #branch specified.  The default (or specified) branch is
329          * fetched and stored in the local branch matching the
330          * remote name.
331          */
332         frag = strchr(buf.buf, '#');
333         if (frag)
334                 *(frag++) = '\0';
335         else
336                 frag = to_free = repo_default_branch_name(the_repository, 0);
337
338         add_url_alias(remote_state, remote, strbuf_detach(&buf, NULL));
339         refspec_appendf(&remote->fetch, "refs/heads/%s:refs/heads/%s",
340                         frag, remote->name);
341
342         /*
343          * Cogito compatible push: push current HEAD to remote #branch
344          * (master if missing)
345          */
346         refspec_appendf(&remote->push, "HEAD:refs/heads/%s", frag);
347         remote->fetch_tags = 1; /* always auto-follow */
348
349         free(to_free);
350 }
351
352 static int handle_config(const char *key, const char *value,
353                          const struct config_context *ctx, void *cb)
354 {
355         const char *name;
356         size_t namelen;
357         const char *subkey;
358         struct remote *remote;
359         struct branch *branch;
360         struct remote_state *remote_state = cb;
361         const struct key_value_info *kvi = ctx->kvi;
362
363         if (parse_config_key(key, "branch", &name, &namelen, &subkey) >= 0) {
364                 /* There is no subsection. */
365                 if (!name)
366                         return 0;
367                 /* There is a subsection, but it is empty. */
368                 if (!namelen)
369                         return -1;
370                 branch = make_branch(remote_state, name, namelen);
371                 if (!strcmp(subkey, "remote")) {
372                         return git_config_string(&branch->remote_name, key, value);
373                 } else if (!strcmp(subkey, "pushremote")) {
374                         return git_config_string(&branch->pushremote_name, key, value);
375                 } else if (!strcmp(subkey, "merge")) {
376                         if (!value)
377                                 return config_error_nonbool(key);
378                         add_merge(branch, xstrdup(value));
379                 }
380                 return 0;
381         }
382         if (parse_config_key(key, "url", &name, &namelen, &subkey) >= 0) {
383                 struct rewrite *rewrite;
384                 if (!name)
385                         return 0;
386                 if (!strcmp(subkey, "insteadof")) {
387                         if (!value)
388                                 return config_error_nonbool(key);
389                         rewrite = make_rewrite(&remote_state->rewrites, name,
390                                                namelen);
391                         add_instead_of(rewrite, xstrdup(value));
392                 } else if (!strcmp(subkey, "pushinsteadof")) {
393                         if (!value)
394                                 return config_error_nonbool(key);
395                         rewrite = make_rewrite(&remote_state->rewrites_push,
396                                                name, namelen);
397                         add_instead_of(rewrite, xstrdup(value));
398                 }
399         }
400
401         if (parse_config_key(key, "remote", &name, &namelen, &subkey) < 0)
402                 return 0;
403
404         /* Handle remote.* variables */
405         if (!name && !strcmp(subkey, "pushdefault"))
406                 return git_config_string(&remote_state->pushremote_name, key,
407                                          value);
408
409         if (!name)
410                 return 0;
411         /* Handle remote.<name>.* variables */
412         if (*name == '/') {
413                 warning(_("config remote shorthand cannot begin with '/': %s"),
414                         name);
415                 return 0;
416         }
417         remote = make_remote(remote_state, name, namelen);
418         remote->origin = REMOTE_CONFIG;
419         if (kvi->scope == CONFIG_SCOPE_LOCAL ||
420             kvi->scope == CONFIG_SCOPE_WORKTREE)
421                 remote->configured_in_repo = 1;
422         if (!strcmp(subkey, "mirror"))
423                 remote->mirror = git_config_bool(key, value);
424         else if (!strcmp(subkey, "skipdefaultupdate"))
425                 remote->skip_default_update = git_config_bool(key, value);
426         else if (!strcmp(subkey, "skipfetchall"))
427                 remote->skip_default_update = git_config_bool(key, value);
428         else if (!strcmp(subkey, "prune"))
429                 remote->prune = git_config_bool(key, value);
430         else if (!strcmp(subkey, "prunetags"))
431                 remote->prune_tags = git_config_bool(key, value);
432         else if (!strcmp(subkey, "url")) {
433                 char *v;
434                 if (git_config_string(&v, key, value))
435                         return -1;
436                 add_url(remote, v);
437         } else if (!strcmp(subkey, "pushurl")) {
438                 char *v;
439                 if (git_config_string(&v, key, value))
440                         return -1;
441                 add_pushurl(remote, v);
442         } else if (!strcmp(subkey, "push")) {
443                 char *v;
444                 if (git_config_string(&v, key, value))
445                         return -1;
446                 refspec_append(&remote->push, v);
447                 free(v);
448         } else if (!strcmp(subkey, "fetch")) {
449                 char *v;
450                 if (git_config_string(&v, key, value))
451                         return -1;
452                 refspec_append(&remote->fetch, v);
453                 free(v);
454         } else if (!strcmp(subkey, "receivepack")) {
455                 char *v;
456                 if (git_config_string(&v, key, value))
457                         return -1;
458                 if (!remote->receivepack)
459                         remote->receivepack = v;
460                 else
461                         error(_("more than one receivepack given, using the first"));
462         } else if (!strcmp(subkey, "uploadpack")) {
463                 char *v;
464                 if (git_config_string(&v, key, value))
465                         return -1;
466                 if (!remote->uploadpack)
467                         remote->uploadpack = v;
468                 else
469                         error(_("more than one uploadpack given, using the first"));
470         } else if (!strcmp(subkey, "tagopt")) {
471                 if (!strcmp(value, "--no-tags"))
472                         remote->fetch_tags = -1;
473                 else if (!strcmp(value, "--tags"))
474                         remote->fetch_tags = 2;
475         } else if (!strcmp(subkey, "proxy")) {
476                 return git_config_string(&remote->http_proxy,
477                                          key, value);
478         } else if (!strcmp(subkey, "proxyauthmethod")) {
479                 return git_config_string(&remote->http_proxy_authmethod,
480                                          key, value);
481         } else if (!strcmp(subkey, "vcs")) {
482                 return git_config_string(&remote->foreign_vcs, key, value);
483         }
484         return 0;
485 }
486
487 static void alias_all_urls(struct remote_state *remote_state)
488 {
489         int i, j;
490         for (i = 0; i < remote_state->remotes_nr; i++) {
491                 int add_pushurl_aliases;
492                 if (!remote_state->remotes[i])
493                         continue;
494                 for (j = 0; j < remote_state->remotes[i]->pushurl_nr; j++) {
495                         remote_state->remotes[i]->pushurl[j] =
496                                 alias_url(remote_state->remotes[i]->pushurl[j],
497                                           &remote_state->rewrites);
498                 }
499                 add_pushurl_aliases = remote_state->remotes[i]->pushurl_nr == 0;
500                 for (j = 0; j < remote_state->remotes[i]->url_nr; j++) {
501                         if (add_pushurl_aliases)
502                                 add_pushurl_alias(
503                                         remote_state, remote_state->remotes[i],
504                                         remote_state->remotes[i]->url[j]);
505                         remote_state->remotes[i]->url[j] =
506                                 alias_url(remote_state->remotes[i]->url[j],
507                                           &remote_state->rewrites);
508                 }
509         }
510 }
511
512 static void read_config(struct repository *repo, int early)
513 {
514         int flag;
515
516         if (repo->remote_state->initialized)
517                 return;
518         repo->remote_state->initialized = 1;
519
520         repo->remote_state->current_branch = NULL;
521         if (startup_info->have_repository && !early) {
522                 const char *head_ref = refs_resolve_ref_unsafe(
523                         get_main_ref_store(repo), "HEAD", 0, NULL, &flag);
524                 if (head_ref && (flag & REF_ISSYMREF) &&
525                     skip_prefix(head_ref, "refs/heads/", &head_ref)) {
526                         repo->remote_state->current_branch = make_branch(
527                                 repo->remote_state, head_ref, strlen(head_ref));
528                 }
529         }
530         repo_config(repo, handle_config, repo->remote_state);
531         alias_all_urls(repo->remote_state);
532 }
533
534 static int valid_remote_nick(const char *name)
535 {
536         if (!name[0] || is_dot_or_dotdot(name))
537                 return 0;
538
539         /* remote nicknames cannot contain slashes */
540         while (*name)
541                 if (is_dir_sep(*name++))
542                         return 0;
543         return 1;
544 }
545
546 static const char *remotes_remote_for_branch(struct remote_state *remote_state,
547                                              struct branch *branch,
548                                              int *explicit)
549 {
550         if (branch && branch->remote_name) {
551                 if (explicit)
552                         *explicit = 1;
553                 return branch->remote_name;
554         }
555         if (explicit)
556                 *explicit = 0;
557         if (remote_state->remotes_nr == 1)
558                 return remote_state->remotes[0]->name;
559         return "origin";
560 }
561
562 const char *remote_for_branch(struct branch *branch, int *explicit)
563 {
564         read_config(the_repository, 0);
565         die_on_missing_branch(the_repository, branch);
566
567         return remotes_remote_for_branch(the_repository->remote_state, branch,
568                                          explicit);
569 }
570
571 static const char *
572 remotes_pushremote_for_branch(struct remote_state *remote_state,
573                               struct branch *branch, int *explicit)
574 {
575         if (branch && branch->pushremote_name) {
576                 if (explicit)
577                         *explicit = 1;
578                 return branch->pushremote_name;
579         }
580         if (remote_state->pushremote_name) {
581                 if (explicit)
582                         *explicit = 1;
583                 return remote_state->pushremote_name;
584         }
585         return remotes_remote_for_branch(remote_state, branch, explicit);
586 }
587
588 const char *pushremote_for_branch(struct branch *branch, int *explicit)
589 {
590         read_config(the_repository, 0);
591         die_on_missing_branch(the_repository, branch);
592
593         return remotes_pushremote_for_branch(the_repository->remote_state,
594                                              branch, explicit);
595 }
596
597 static struct remote *remotes_remote_get(struct remote_state *remote_state,
598                                          const char *name);
599
600 const char *remote_ref_for_branch(struct branch *branch, int for_push)
601 {
602         read_config(the_repository, 0);
603         die_on_missing_branch(the_repository, branch);
604
605         if (branch) {
606                 if (!for_push) {
607                         if (branch->merge_nr) {
608                                 return branch->merge_name[0];
609                         }
610                 } else {
611                         const char *dst,
612                                 *remote_name = remotes_pushremote_for_branch(
613                                         the_repository->remote_state, branch,
614                                         NULL);
615                         struct remote *remote = remotes_remote_get(
616                                 the_repository->remote_state, remote_name);
617
618                         if (remote && remote->push.nr &&
619                             (dst = apply_refspecs(&remote->push,
620                                                   branch->refname))) {
621                                 return dst;
622                         }
623                 }
624         }
625         return NULL;
626 }
627
628 static void validate_remote_url(struct remote *remote)
629 {
630         int i;
631         const char *value;
632         struct strbuf redacted = STRBUF_INIT;
633         int warn_not_die;
634
635         if (git_config_get_string_tmp("transfer.credentialsinurl", &value))
636                 return;
637
638         if (!strcmp("warn", value))
639                 warn_not_die = 1;
640         else if (!strcmp("die", value))
641                 warn_not_die = 0;
642         else if (!strcmp("allow", value))
643                 return;
644         else
645                 die(_("unrecognized value transfer.credentialsInUrl: '%s'"), value);
646
647         for (i = 0; i < remote->url_nr; i++) {
648                 struct url_info url_info = { 0 };
649
650                 if (!url_normalize(remote->url[i], &url_info) ||
651                     !url_info.passwd_off)
652                         goto loop_cleanup;
653
654                 strbuf_reset(&redacted);
655                 strbuf_add(&redacted, url_info.url, url_info.passwd_off);
656                 strbuf_addstr(&redacted, "<redacted>");
657                 strbuf_addstr(&redacted,
658                               url_info.url + url_info.passwd_off + url_info.passwd_len);
659
660                 if (warn_not_die)
661                         warning(_("URL '%s' uses plaintext credentials"), redacted.buf);
662                 else
663                         die(_("URL '%s' uses plaintext credentials"), redacted.buf);
664
665 loop_cleanup:
666                 free(url_info.url);
667         }
668
669         strbuf_release(&redacted);
670 }
671
672 static struct remote *
673 remotes_remote_get_1(struct remote_state *remote_state, const char *name,
674                      const char *(*get_default)(struct remote_state *,
675                                                 struct branch *, int *))
676 {
677         struct remote *ret;
678         int name_given = 0;
679
680         if (name)
681                 name_given = 1;
682         else
683                 name = get_default(remote_state, remote_state->current_branch,
684                                    &name_given);
685
686         ret = make_remote(remote_state, name, 0);
687         if (valid_remote_nick(name) && have_git_dir()) {
688                 if (!valid_remote(ret))
689                         read_remotes_file(remote_state, ret);
690                 if (!valid_remote(ret))
691                         read_branches_file(remote_state, ret);
692         }
693         if (name_given && !valid_remote(ret))
694                 add_url_alias(remote_state, ret, name);
695         if (!valid_remote(ret))
696                 return NULL;
697
698         validate_remote_url(ret);
699
700         return ret;
701 }
702
703 static inline struct remote *
704 remotes_remote_get(struct remote_state *remote_state, const char *name)
705 {
706         return remotes_remote_get_1(remote_state, name,
707                                     remotes_remote_for_branch);
708 }
709
710 struct remote *remote_get(const char *name)
711 {
712         read_config(the_repository, 0);
713         return remotes_remote_get(the_repository->remote_state, name);
714 }
715
716 struct remote *remote_get_early(const char *name)
717 {
718         read_config(the_repository, 1);
719         return remotes_remote_get(the_repository->remote_state, name);
720 }
721
722 static inline struct remote *
723 remotes_pushremote_get(struct remote_state *remote_state, const char *name)
724 {
725         return remotes_remote_get_1(remote_state, name,
726                                     remotes_pushremote_for_branch);
727 }
728
729 struct remote *pushremote_get(const char *name)
730 {
731         read_config(the_repository, 0);
732         return remotes_pushremote_get(the_repository->remote_state, name);
733 }
734
735 int remote_is_configured(struct remote *remote, int in_repo)
736 {
737         if (!remote)
738                 return 0;
739         if (in_repo)
740                 return remote->configured_in_repo;
741         return !!remote->origin;
742 }
743
744 int for_each_remote(each_remote_fn fn, void *priv)
745 {
746         int i, result = 0;
747         read_config(the_repository, 0);
748         for (i = 0; i < the_repository->remote_state->remotes_nr && !result;
749              i++) {
750                 struct remote *remote =
751                         the_repository->remote_state->remotes[i];
752                 if (!remote)
753                         continue;
754                 result = fn(remote, priv);
755         }
756         return result;
757 }
758
759 static void handle_duplicate(struct ref *ref1, struct ref *ref2)
760 {
761         if (strcmp(ref1->name, ref2->name)) {
762                 if (ref1->fetch_head_status != FETCH_HEAD_IGNORE &&
763                     ref2->fetch_head_status != FETCH_HEAD_IGNORE) {
764                         die(_("Cannot fetch both %s and %s to %s"),
765                             ref1->name, ref2->name, ref2->peer_ref->name);
766                 } else if (ref1->fetch_head_status != FETCH_HEAD_IGNORE &&
767                            ref2->fetch_head_status == FETCH_HEAD_IGNORE) {
768                         warning(_("%s usually tracks %s, not %s"),
769                                 ref2->peer_ref->name, ref2->name, ref1->name);
770                 } else if (ref1->fetch_head_status == FETCH_HEAD_IGNORE &&
771                            ref2->fetch_head_status == FETCH_HEAD_IGNORE) {
772                         die(_("%s tracks both %s and %s"),
773                             ref2->peer_ref->name, ref1->name, ref2->name);
774                 } else {
775                         /*
776                          * This last possibility doesn't occur because
777                          * FETCH_HEAD_IGNORE entries always appear at
778                          * the end of the list.
779                          */
780                         BUG("Internal error");
781                 }
782         }
783         free(ref2->peer_ref);
784         free(ref2);
785 }
786
787 struct ref *ref_remove_duplicates(struct ref *ref_map)
788 {
789         struct string_list refs = STRING_LIST_INIT_NODUP;
790         struct ref *retval = NULL;
791         struct ref **p = &retval;
792
793         while (ref_map) {
794                 struct ref *ref = ref_map;
795
796                 ref_map = ref_map->next;
797                 ref->next = NULL;
798
799                 if (!ref->peer_ref) {
800                         *p = ref;
801                         p = &ref->next;
802                 } else {
803                         struct string_list_item *item =
804                                 string_list_insert(&refs, ref->peer_ref->name);
805
806                         if (item->util) {
807                                 /* Entry already existed */
808                                 handle_duplicate((struct ref *)item->util, ref);
809                         } else {
810                                 *p = ref;
811                                 p = &ref->next;
812                                 item->util = ref;
813                         }
814                 }
815         }
816
817         string_list_clear(&refs, 0);
818         return retval;
819 }
820
821 int remote_has_url(struct remote *remote, const char *url)
822 {
823         int i;
824         for (i = 0; i < remote->url_nr; i++) {
825                 if (!strcmp(remote->url[i], url))
826                         return 1;
827         }
828         return 0;
829 }
830
831 static int match_name_with_pattern(const char *key, const char *name,
832                                    const char *value, char **result)
833 {
834         const char *kstar = strchr(key, '*');
835         size_t klen;
836         size_t ksuffixlen;
837         size_t namelen;
838         int ret;
839         if (!kstar)
840                 die(_("key '%s' of pattern had no '*'"), key);
841         klen = kstar - key;
842         ksuffixlen = strlen(kstar + 1);
843         namelen = strlen(name);
844         ret = !strncmp(name, key, klen) && namelen >= klen + ksuffixlen &&
845                 !memcmp(name + namelen - ksuffixlen, kstar + 1, ksuffixlen);
846         if (ret && value) {
847                 struct strbuf sb = STRBUF_INIT;
848                 const char *vstar = strchr(value, '*');
849                 if (!vstar)
850                         die(_("value '%s' of pattern has no '*'"), value);
851                 strbuf_add(&sb, value, vstar - value);
852                 strbuf_add(&sb, name + klen, namelen - klen - ksuffixlen);
853                 strbuf_addstr(&sb, vstar + 1);
854                 *result = strbuf_detach(&sb, NULL);
855         }
856         return ret;
857 }
858
859 static int refspec_match(const struct refspec_item *refspec,
860                          const char *name)
861 {
862         if (refspec->pattern)
863                 return match_name_with_pattern(refspec->src, name, NULL, NULL);
864
865         return !strcmp(refspec->src, name);
866 }
867
868 int omit_name_by_refspec(const char *name, struct refspec *rs)
869 {
870         int i;
871
872         for (i = 0; i < rs->nr; i++) {
873                 if (rs->items[i].negative && refspec_match(&rs->items[i], name))
874                         return 1;
875         }
876         return 0;
877 }
878
879 struct ref *apply_negative_refspecs(struct ref *ref_map, struct refspec *rs)
880 {
881         struct ref **tail;
882
883         for (tail = &ref_map; *tail; ) {
884                 struct ref *ref = *tail;
885
886                 if (omit_name_by_refspec(ref->name, rs)) {
887                         *tail = ref->next;
888                         free(ref->peer_ref);
889                         free(ref);
890                 } else
891                         tail = &ref->next;
892         }
893
894         return ref_map;
895 }
896
897 static int query_matches_negative_refspec(struct refspec *rs, struct refspec_item *query)
898 {
899         int i, matched_negative = 0;
900         int find_src = !query->src;
901         struct string_list reversed = STRING_LIST_INIT_DUP;
902         const char *needle = find_src ? query->dst : query->src;
903
904         /*
905          * Check whether the queried ref matches any negative refpsec. If so,
906          * then we should ultimately treat this as not matching the query at
907          * all.
908          *
909          * Note that negative refspecs always match the source, but the query
910          * item uses the destination. To handle this, we apply pattern
911          * refspecs in reverse to figure out if the query source matches any
912          * of the negative refspecs.
913          *
914          * The first loop finds and expands all positive refspecs
915          * matched by the queried ref.
916          *
917          * The second loop checks if any of the results of the first loop
918          * match any negative refspec.
919          */
920         for (i = 0; i < rs->nr; i++) {
921                 struct refspec_item *refspec = &rs->items[i];
922                 char *expn_name;
923
924                 if (refspec->negative)
925                         continue;
926
927                 /* Note the reversal of src and dst */
928                 if (refspec->pattern) {
929                         const char *key = refspec->dst ? refspec->dst : refspec->src;
930                         const char *value = refspec->src;
931
932                         if (match_name_with_pattern(key, needle, value, &expn_name))
933                                 string_list_append_nodup(&reversed, expn_name);
934                 } else if (refspec->matching) {
935                         /* For the special matching refspec, any query should match */
936                         string_list_append(&reversed, needle);
937                 } else if (!refspec->src) {
938                         BUG("refspec->src should not be null here");
939                 } else if (!strcmp(needle, refspec->src)) {
940                         string_list_append(&reversed, refspec->src);
941                 }
942         }
943
944         for (i = 0; !matched_negative && i < reversed.nr; i++) {
945                 if (omit_name_by_refspec(reversed.items[i].string, rs))
946                         matched_negative = 1;
947         }
948
949         string_list_clear(&reversed, 0);
950
951         return matched_negative;
952 }
953
954 static void query_refspecs_multiple(struct refspec *rs,
955                                     struct refspec_item *query,
956                                     struct string_list *results)
957 {
958         int i;
959         int find_src = !query->src;
960
961         if (find_src && !query->dst)
962                 BUG("query_refspecs_multiple: need either src or dst");
963
964         if (query_matches_negative_refspec(rs, query))
965                 return;
966
967         for (i = 0; i < rs->nr; i++) {
968                 struct refspec_item *refspec = &rs->items[i];
969                 const char *key = find_src ? refspec->dst : refspec->src;
970                 const char *value = find_src ? refspec->src : refspec->dst;
971                 const char *needle = find_src ? query->dst : query->src;
972                 char **result = find_src ? &query->src : &query->dst;
973
974                 if (!refspec->dst || refspec->negative)
975                         continue;
976                 if (refspec->pattern) {
977                         if (match_name_with_pattern(key, needle, value, result))
978                                 string_list_append_nodup(results, *result);
979                 } else if (!strcmp(needle, key)) {
980                         string_list_append(results, value);
981                 }
982         }
983 }
984
985 int query_refspecs(struct refspec *rs, struct refspec_item *query)
986 {
987         int i;
988         int find_src = !query->src;
989         const char *needle = find_src ? query->dst : query->src;
990         char **result = find_src ? &query->src : &query->dst;
991
992         if (find_src && !query->dst)
993                 BUG("query_refspecs: need either src or dst");
994
995         if (query_matches_negative_refspec(rs, query))
996                 return -1;
997
998         for (i = 0; i < rs->nr; i++) {
999                 struct refspec_item *refspec = &rs->items[i];
1000                 const char *key = find_src ? refspec->dst : refspec->src;
1001                 const char *value = find_src ? refspec->src : refspec->dst;
1002
1003                 if (!refspec->dst || refspec->negative)
1004                         continue;
1005                 if (refspec->pattern) {
1006                         if (match_name_with_pattern(key, needle, value, result)) {
1007                                 query->force = refspec->force;
1008                                 return 0;
1009                         }
1010                 } else if (!strcmp(needle, key)) {
1011                         *result = xstrdup(value);
1012                         query->force = refspec->force;
1013                         return 0;
1014                 }
1015         }
1016         return -1;
1017 }
1018
1019 char *apply_refspecs(struct refspec *rs, const char *name)
1020 {
1021         struct refspec_item query;
1022
1023         memset(&query, 0, sizeof(struct refspec_item));
1024         query.src = (char *)name;
1025
1026         if (query_refspecs(rs, &query))
1027                 return NULL;
1028
1029         return query.dst;
1030 }
1031
1032 int remote_find_tracking(struct remote *remote, struct refspec_item *refspec)
1033 {
1034         return query_refspecs(&remote->fetch, refspec);
1035 }
1036
1037 static struct ref *alloc_ref_with_prefix(const char *prefix, size_t prefixlen,
1038                 const char *name)
1039 {
1040         size_t len = strlen(name);
1041         struct ref *ref = xcalloc(1, st_add4(sizeof(*ref), prefixlen, len, 1));
1042         memcpy(ref->name, prefix, prefixlen);
1043         memcpy(ref->name + prefixlen, name, len);
1044         return ref;
1045 }
1046
1047 struct ref *alloc_ref(const char *name)
1048 {
1049         return alloc_ref_with_prefix("", 0, name);
1050 }
1051
1052 struct ref *copy_ref(const struct ref *ref)
1053 {
1054         struct ref *cpy;
1055         size_t len;
1056         if (!ref)
1057                 return NULL;
1058         len = st_add3(sizeof(struct ref), strlen(ref->name), 1);
1059         cpy = xmalloc(len);
1060         memcpy(cpy, ref, len);
1061         cpy->next = NULL;
1062         cpy->symref = xstrdup_or_null(ref->symref);
1063         cpy->remote_status = xstrdup_or_null(ref->remote_status);
1064         cpy->peer_ref = copy_ref(ref->peer_ref);
1065         return cpy;
1066 }
1067
1068 struct ref *copy_ref_list(const struct ref *ref)
1069 {
1070         struct ref *ret = NULL;
1071         struct ref **tail = &ret;
1072         while (ref) {
1073                 *tail = copy_ref(ref);
1074                 ref = ref->next;
1075                 tail = &((*tail)->next);
1076         }
1077         return ret;
1078 }
1079
1080 void free_one_ref(struct ref *ref)
1081 {
1082         if (!ref)
1083                 return;
1084         free_one_ref(ref->peer_ref);
1085         free(ref->remote_status);
1086         free(ref->symref);
1087         free(ref);
1088 }
1089
1090 void free_refs(struct ref *ref)
1091 {
1092         struct ref *next;
1093         while (ref) {
1094                 next = ref->next;
1095                 free_one_ref(ref);
1096                 ref = next;
1097         }
1098 }
1099
1100 int count_refspec_match(const char *pattern,
1101                         struct ref *refs,
1102                         struct ref **matched_ref)
1103 {
1104         int patlen = strlen(pattern);
1105         struct ref *matched_weak = NULL;
1106         struct ref *matched = NULL;
1107         int weak_match = 0;
1108         int match = 0;
1109
1110         for (weak_match = match = 0; refs; refs = refs->next) {
1111                 char *name = refs->name;
1112                 int namelen = strlen(name);
1113
1114                 if (!refname_match(pattern, name))
1115                         continue;
1116
1117                 /* A match is "weak" if it is with refs outside
1118                  * heads or tags, and did not specify the pattern
1119                  * in full (e.g. "refs/remotes/origin/master") or at
1120                  * least from the toplevel (e.g. "remotes/origin/master");
1121                  * otherwise "git push $URL master" would result in
1122                  * ambiguity between remotes/origin/master and heads/master
1123                  * at the remote site.
1124                  */
1125                 if (namelen != patlen &&
1126                     patlen != namelen - 5 &&
1127                     !starts_with(name, "refs/heads/") &&
1128                     !starts_with(name, "refs/tags/")) {
1129                         /* We want to catch the case where only weak
1130                          * matches are found and there are multiple
1131                          * matches, and where more than one strong
1132                          * matches are found, as ambiguous.  One
1133                          * strong match with zero or more weak matches
1134                          * are acceptable as a unique match.
1135                          */
1136                         matched_weak = refs;
1137                         weak_match++;
1138                 }
1139                 else {
1140                         matched = refs;
1141                         match++;
1142                 }
1143         }
1144         if (!matched) {
1145                 if (matched_ref)
1146                         *matched_ref = matched_weak;
1147                 return weak_match;
1148         }
1149         else {
1150                 if (matched_ref)
1151                         *matched_ref = matched;
1152                 return match;
1153         }
1154 }
1155
1156 static void tail_link_ref(struct ref *ref, struct ref ***tail)
1157 {
1158         **tail = ref;
1159         while (ref->next)
1160                 ref = ref->next;
1161         *tail = &ref->next;
1162 }
1163
1164 static struct ref *alloc_delete_ref(void)
1165 {
1166         struct ref *ref = alloc_ref("(delete)");
1167         oidclr(&ref->new_oid);
1168         return ref;
1169 }
1170
1171 static int try_explicit_object_name(const char *name,
1172                                     struct ref **match)
1173 {
1174         struct object_id oid;
1175
1176         if (!*name) {
1177                 if (match)
1178                         *match = alloc_delete_ref();
1179                 return 0;
1180         }
1181
1182         if (repo_get_oid(the_repository, name, &oid))
1183                 return -1;
1184
1185         if (match) {
1186                 *match = alloc_ref(name);
1187                 oidcpy(&(*match)->new_oid, &oid);
1188         }
1189         return 0;
1190 }
1191
1192 static struct ref *make_linked_ref(const char *name, struct ref ***tail)
1193 {
1194         struct ref *ret = alloc_ref(name);
1195         tail_link_ref(ret, tail);
1196         return ret;
1197 }
1198
1199 static char *guess_ref(const char *name, struct ref *peer)
1200 {
1201         struct strbuf buf = STRBUF_INIT;
1202
1203         const char *r = refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
1204                                                 peer->name,
1205                                                 RESOLVE_REF_READING,
1206                                                 NULL, NULL);
1207         if (!r)
1208                 return NULL;
1209
1210         if (starts_with(r, "refs/heads/")) {
1211                 strbuf_addstr(&buf, "refs/heads/");
1212         } else if (starts_with(r, "refs/tags/")) {
1213                 strbuf_addstr(&buf, "refs/tags/");
1214         } else {
1215                 return NULL;
1216         }
1217
1218         strbuf_addstr(&buf, name);
1219         return strbuf_detach(&buf, NULL);
1220 }
1221
1222 static int match_explicit_lhs(struct ref *src,
1223                               struct refspec_item *rs,
1224                               struct ref **match,
1225                               int *allocated_match)
1226 {
1227         switch (count_refspec_match(rs->src, src, match)) {
1228         case 1:
1229                 if (allocated_match)
1230                         *allocated_match = 0;
1231                 return 0;
1232         case 0:
1233                 /* The source could be in the get_sha1() format
1234                  * not a reference name.  :refs/other is a
1235                  * way to delete 'other' ref at the remote end.
1236                  */
1237                 if (try_explicit_object_name(rs->src, match) < 0)
1238                         return error(_("src refspec %s does not match any"), rs->src);
1239                 if (allocated_match)
1240                         *allocated_match = 1;
1241                 return 0;
1242         default:
1243                 return error(_("src refspec %s matches more than one"), rs->src);
1244         }
1245 }
1246
1247 static void show_push_unqualified_ref_name_error(const char *dst_value,
1248                                                  const char *matched_src_name)
1249 {
1250         struct object_id oid;
1251         enum object_type type;
1252
1253         /*
1254          * TRANSLATORS: "matches '%s'%" is the <dst> part of "git push
1255          * <remote> <src>:<dst>" push, and "being pushed ('%s')" is
1256          * the <src>.
1257          */
1258         error(_("The destination you provided is not a full refname (i.e.,\n"
1259                 "starting with \"refs/\"). We tried to guess what you meant by:\n"
1260                 "\n"
1261                 "- Looking for a ref that matches '%s' on the remote side.\n"
1262                 "- Checking if the <src> being pushed ('%s')\n"
1263                 "  is a ref in \"refs/{heads,tags}/\". If so we add a corresponding\n"
1264                 "  refs/{heads,tags}/ prefix on the remote side.\n"
1265                 "\n"
1266                 "Neither worked, so we gave up. You must fully qualify the ref."),
1267               dst_value, matched_src_name);
1268
1269         if (!advice_enabled(ADVICE_PUSH_UNQUALIFIED_REF_NAME))
1270                 return;
1271
1272         if (repo_get_oid(the_repository, matched_src_name, &oid))
1273                 BUG("'%s' is not a valid object, "
1274                     "match_explicit_lhs() should catch this!",
1275                     matched_src_name);
1276         type = oid_object_info(the_repository, &oid, NULL);
1277         if (type == OBJ_COMMIT) {
1278                 advise(_("The <src> part of the refspec is a commit object.\n"
1279                          "Did you mean to create a new branch by pushing to\n"
1280                          "'%s:refs/heads/%s'?"),
1281                        matched_src_name, dst_value);
1282         } else if (type == OBJ_TAG) {
1283                 advise(_("The <src> part of the refspec is a tag object.\n"
1284                          "Did you mean to create a new tag by pushing to\n"
1285                          "'%s:refs/tags/%s'?"),
1286                        matched_src_name, dst_value);
1287         } else if (type == OBJ_TREE) {
1288                 advise(_("The <src> part of the refspec is a tree object.\n"
1289                          "Did you mean to tag a new tree by pushing to\n"
1290                          "'%s:refs/tags/%s'?"),
1291                        matched_src_name, dst_value);
1292         } else if (type == OBJ_BLOB) {
1293                 advise(_("The <src> part of the refspec is a blob object.\n"
1294                          "Did you mean to tag a new blob by pushing to\n"
1295                          "'%s:refs/tags/%s'?"),
1296                        matched_src_name, dst_value);
1297         } else {
1298                 BUG("'%s' should be commit/tag/tree/blob, is '%d'",
1299                     matched_src_name, type);
1300         }
1301 }
1302
1303 static int match_explicit(struct ref *src, struct ref *dst,
1304                           struct ref ***dst_tail,
1305                           struct refspec_item *rs)
1306 {
1307         struct ref *matched_src, *matched_dst;
1308         int allocated_src;
1309
1310         const char *dst_value = rs->dst;
1311         char *dst_guess;
1312
1313         if (rs->pattern || rs->matching || rs->negative)
1314                 return 0;
1315
1316         matched_src = matched_dst = NULL;
1317         if (match_explicit_lhs(src, rs, &matched_src, &allocated_src) < 0)
1318                 return -1;
1319
1320         if (!dst_value) {
1321                 int flag;
1322
1323                 dst_value = refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
1324                                                     matched_src->name,
1325                                                     RESOLVE_REF_READING,
1326                                                     NULL, &flag);
1327                 if (!dst_value ||
1328                     ((flag & REF_ISSYMREF) &&
1329                      !starts_with(dst_value, "refs/heads/")))
1330                         die(_("%s cannot be resolved to branch"),
1331                             matched_src->name);
1332         }
1333
1334         switch (count_refspec_match(dst_value, dst, &matched_dst)) {
1335         case 1:
1336                 break;
1337         case 0:
1338                 if (starts_with(dst_value, "refs/")) {
1339                         matched_dst = make_linked_ref(dst_value, dst_tail);
1340                 } else if (is_null_oid(&matched_src->new_oid)) {
1341                         error(_("unable to delete '%s': remote ref does not exist"),
1342                               dst_value);
1343                 } else if ((dst_guess = guess_ref(dst_value, matched_src))) {
1344                         matched_dst = make_linked_ref(dst_guess, dst_tail);
1345                         free(dst_guess);
1346                 } else {
1347                         show_push_unqualified_ref_name_error(dst_value,
1348                                                              matched_src->name);
1349                 }
1350                 break;
1351         default:
1352                 matched_dst = NULL;
1353                 error(_("dst refspec %s matches more than one"),
1354                       dst_value);
1355                 break;
1356         }
1357         if (!matched_dst)
1358                 return -1;
1359         if (matched_dst->peer_ref)
1360                 return error(_("dst ref %s receives from more than one src"),
1361                              matched_dst->name);
1362         else {
1363                 matched_dst->peer_ref = allocated_src ?
1364                                         matched_src :
1365                                         copy_ref(matched_src);
1366                 matched_dst->force = rs->force;
1367         }
1368         return 0;
1369 }
1370
1371 static int match_explicit_refs(struct ref *src, struct ref *dst,
1372                                struct ref ***dst_tail, struct refspec *rs)
1373 {
1374         int i, errs;
1375         for (i = errs = 0; i < rs->nr; i++)
1376                 errs += match_explicit(src, dst, dst_tail, &rs->items[i]);
1377         return errs;
1378 }
1379
1380 static char *get_ref_match(const struct refspec *rs, const struct ref *ref,
1381                            int send_mirror, int direction,
1382                            const struct refspec_item **ret_pat)
1383 {
1384         const struct refspec_item *pat;
1385         char *name;
1386         int i;
1387         int matching_refs = -1;
1388         for (i = 0; i < rs->nr; i++) {
1389                 const struct refspec_item *item = &rs->items[i];
1390
1391                 if (item->negative)
1392                         continue;
1393
1394                 if (item->matching &&
1395                     (matching_refs == -1 || item->force)) {
1396                         matching_refs = i;
1397                         continue;
1398                 }
1399
1400                 if (item->pattern) {
1401                         const char *dst_side = item->dst ? item->dst : item->src;
1402                         int match;
1403                         if (direction == FROM_SRC)
1404                                 match = match_name_with_pattern(item->src, ref->name, dst_side, &name);
1405                         else
1406                                 match = match_name_with_pattern(dst_side, ref->name, item->src, &name);
1407                         if (match) {
1408                                 matching_refs = i;
1409                                 break;
1410                         }
1411                 }
1412         }
1413         if (matching_refs == -1)
1414                 return NULL;
1415
1416         pat = &rs->items[matching_refs];
1417         if (pat->matching) {
1418                 /*
1419                  * "matching refs"; traditionally we pushed everything
1420                  * including refs outside refs/heads/ hierarchy, but
1421                  * that does not make much sense these days.
1422                  */
1423                 if (!send_mirror && !starts_with(ref->name, "refs/heads/"))
1424                         return NULL;
1425                 name = xstrdup(ref->name);
1426         }
1427         if (ret_pat)
1428                 *ret_pat = pat;
1429         return name;
1430 }
1431
1432 static struct ref **tail_ref(struct ref **head)
1433 {
1434         struct ref **tail = head;
1435         while (*tail)
1436                 tail = &((*tail)->next);
1437         return tail;
1438 }
1439
1440 struct tips {
1441         struct commit **tip;
1442         int nr, alloc;
1443 };
1444
1445 static void add_to_tips(struct tips *tips, const struct object_id *oid)
1446 {
1447         struct commit *commit;
1448
1449         if (is_null_oid(oid))
1450                 return;
1451         commit = lookup_commit_reference_gently(the_repository, oid, 1);
1452         if (!commit || (commit->object.flags & TMP_MARK))
1453                 return;
1454         commit->object.flags |= TMP_MARK;
1455         ALLOC_GROW(tips->tip, tips->nr + 1, tips->alloc);
1456         tips->tip[tips->nr++] = commit;
1457 }
1458
1459 static void add_missing_tags(struct ref *src, struct ref **dst, struct ref ***dst_tail)
1460 {
1461         struct string_list dst_tag = STRING_LIST_INIT_NODUP;
1462         struct string_list src_tag = STRING_LIST_INIT_NODUP;
1463         struct string_list_item *item;
1464         struct ref *ref;
1465         struct tips sent_tips;
1466
1467         /*
1468          * Collect everything we know they would have at the end of
1469          * this push, and collect all tags they have.
1470          */
1471         memset(&sent_tips, 0, sizeof(sent_tips));
1472         for (ref = *dst; ref; ref = ref->next) {
1473                 if (ref->peer_ref &&
1474                     !is_null_oid(&ref->peer_ref->new_oid))
1475                         add_to_tips(&sent_tips, &ref->peer_ref->new_oid);
1476                 else
1477                         add_to_tips(&sent_tips, &ref->old_oid);
1478                 if (starts_with(ref->name, "refs/tags/"))
1479                         string_list_append(&dst_tag, ref->name);
1480         }
1481         clear_commit_marks_many(sent_tips.nr, sent_tips.tip, TMP_MARK);
1482
1483         string_list_sort(&dst_tag);
1484
1485         /* Collect tags they do not have. */
1486         for (ref = src; ref; ref = ref->next) {
1487                 if (!starts_with(ref->name, "refs/tags/"))
1488                         continue; /* not a tag */
1489                 if (string_list_has_string(&dst_tag, ref->name))
1490                         continue; /* they already have it */
1491                 if (oid_object_info(the_repository, &ref->new_oid, NULL) != OBJ_TAG)
1492                         continue; /* be conservative */
1493                 item = string_list_append(&src_tag, ref->name);
1494                 item->util = ref;
1495         }
1496         string_list_clear(&dst_tag, 0);
1497
1498         /*
1499          * At this point, src_tag lists tags that are missing from
1500          * dst, and sent_tips lists the tips we are pushing or those
1501          * that we know they already have. An element in the src_tag
1502          * that is an ancestor of any of the sent_tips needs to be
1503          * sent to the other side.
1504          */
1505         if (sent_tips.nr) {
1506                 const int reachable_flag = 1;
1507                 struct commit_list *found_commits;
1508                 struct commit **src_commits;
1509                 int nr_src_commits = 0, alloc_src_commits = 16;
1510                 ALLOC_ARRAY(src_commits, alloc_src_commits);
1511
1512                 for_each_string_list_item(item, &src_tag) {
1513                         struct ref *ref = item->util;
1514                         struct commit *commit;
1515
1516                         if (is_null_oid(&ref->new_oid))
1517                                 continue;
1518                         commit = lookup_commit_reference_gently(the_repository,
1519                                                                 &ref->new_oid,
1520                                                                 1);
1521                         if (!commit)
1522                                 /* not pushing a commit, which is not an error */
1523                                 continue;
1524
1525                         ALLOC_GROW(src_commits, nr_src_commits + 1, alloc_src_commits);
1526                         src_commits[nr_src_commits++] = commit;
1527                 }
1528
1529                 found_commits = get_reachable_subset(sent_tips.tip, sent_tips.nr,
1530                                                      src_commits, nr_src_commits,
1531                                                      reachable_flag);
1532
1533                 for_each_string_list_item(item, &src_tag) {
1534                         struct ref *dst_ref;
1535                         struct ref *ref = item->util;
1536                         struct commit *commit;
1537
1538                         if (is_null_oid(&ref->new_oid))
1539                                 continue;
1540                         commit = lookup_commit_reference_gently(the_repository,
1541                                                                 &ref->new_oid,
1542                                                                 1);
1543                         if (!commit)
1544                                 /* not pushing a commit, which is not an error */
1545                                 continue;
1546
1547                         /*
1548                          * Is this tag, which they do not have, reachable from
1549                          * any of the commits we are sending?
1550                          */
1551                         if (!(commit->object.flags & reachable_flag))
1552                                 continue;
1553
1554                         /* Add it in */
1555                         dst_ref = make_linked_ref(ref->name, dst_tail);
1556                         oidcpy(&dst_ref->new_oid, &ref->new_oid);
1557                         dst_ref->peer_ref = copy_ref(ref);
1558                 }
1559
1560                 clear_commit_marks_many(nr_src_commits, src_commits, reachable_flag);
1561                 free(src_commits);
1562                 free_commit_list(found_commits);
1563         }
1564
1565         string_list_clear(&src_tag, 0);
1566         free(sent_tips.tip);
1567 }
1568
1569 struct ref *find_ref_by_name(const struct ref *list, const char *name)
1570 {
1571         for ( ; list; list = list->next)
1572                 if (!strcmp(list->name, name))
1573                         return (struct ref *)list;
1574         return NULL;
1575 }
1576
1577 static void prepare_ref_index(struct string_list *ref_index, struct ref *ref)
1578 {
1579         for ( ; ref; ref = ref->next)
1580                 string_list_append_nodup(ref_index, ref->name)->util = ref;
1581
1582         string_list_sort(ref_index);
1583 }
1584
1585 /*
1586  * Given only the set of local refs, sanity-check the set of push
1587  * refspecs. We can't catch all errors that match_push_refs would,
1588  * but we can catch some errors early before even talking to the
1589  * remote side.
1590  */
1591 int check_push_refs(struct ref *src, struct refspec *rs)
1592 {
1593         int ret = 0;
1594         int i;
1595
1596         for (i = 0; i < rs->nr; i++) {
1597                 struct refspec_item *item = &rs->items[i];
1598
1599                 if (item->pattern || item->matching || item->negative)
1600                         continue;
1601
1602                 ret |= match_explicit_lhs(src, item, NULL, NULL);
1603         }
1604
1605         return ret;
1606 }
1607
1608 /*
1609  * Given the set of refs the local repository has, the set of refs the
1610  * remote repository has, and the refspec used for push, determine
1611  * what remote refs we will update and with what value by setting
1612  * peer_ref (which object is being pushed) and force (if the push is
1613  * forced) in elements of "dst". The function may add new elements to
1614  * dst (e.g. pushing to a new branch, done in match_explicit_refs).
1615  */
1616 int match_push_refs(struct ref *src, struct ref **dst,
1617                     struct refspec *rs, int flags)
1618 {
1619         int send_all = flags & MATCH_REFS_ALL;
1620         int send_mirror = flags & MATCH_REFS_MIRROR;
1621         int send_prune = flags & MATCH_REFS_PRUNE;
1622         int errs;
1623         struct ref *ref, **dst_tail = tail_ref(dst);
1624         struct string_list dst_ref_index = STRING_LIST_INIT_NODUP;
1625
1626         /* If no refspec is provided, use the default ":" */
1627         if (!rs->nr)
1628                 refspec_append(rs, ":");
1629
1630         errs = match_explicit_refs(src, *dst, &dst_tail, rs);
1631
1632         /* pick the remainder */
1633         for (ref = src; ref; ref = ref->next) {
1634                 struct string_list_item *dst_item;
1635                 struct ref *dst_peer;
1636                 const struct refspec_item *pat = NULL;
1637                 char *dst_name;
1638
1639                 dst_name = get_ref_match(rs, ref, send_mirror, FROM_SRC, &pat);
1640                 if (!dst_name)
1641                         continue;
1642
1643                 if (!dst_ref_index.nr)
1644                         prepare_ref_index(&dst_ref_index, *dst);
1645
1646                 dst_item = string_list_lookup(&dst_ref_index, dst_name);
1647                 dst_peer = dst_item ? dst_item->util : NULL;
1648                 if (dst_peer) {
1649                         if (dst_peer->peer_ref)
1650                                 /* We're already sending something to this ref. */
1651                                 goto free_name;
1652                 } else {
1653                         if (pat->matching && !(send_all || send_mirror))
1654                                 /*
1655                                  * Remote doesn't have it, and we have no
1656                                  * explicit pattern, and we don't have
1657                                  * --all or --mirror.
1658                                  */
1659                                 goto free_name;
1660
1661                         /* Create a new one and link it */
1662                         dst_peer = make_linked_ref(dst_name, &dst_tail);
1663                         oidcpy(&dst_peer->new_oid, &ref->new_oid);
1664                         string_list_insert(&dst_ref_index,
1665                                 dst_peer->name)->util = dst_peer;
1666                 }
1667                 dst_peer->peer_ref = copy_ref(ref);
1668                 dst_peer->force = pat->force;
1669         free_name:
1670                 free(dst_name);
1671         }
1672
1673         string_list_clear(&dst_ref_index, 0);
1674
1675         if (flags & MATCH_REFS_FOLLOW_TAGS)
1676                 add_missing_tags(src, dst, &dst_tail);
1677
1678         if (send_prune) {
1679                 struct string_list src_ref_index = STRING_LIST_INIT_NODUP;
1680                 /* check for missing refs on the remote */
1681                 for (ref = *dst; ref; ref = ref->next) {
1682                         char *src_name;
1683
1684                         if (ref->peer_ref)
1685                                 /* We're already sending something to this ref. */
1686                                 continue;
1687
1688                         src_name = get_ref_match(rs, ref, send_mirror, FROM_DST, NULL);
1689                         if (src_name) {
1690                                 if (!src_ref_index.nr)
1691                                         prepare_ref_index(&src_ref_index, src);
1692                                 if (!string_list_has_string(&src_ref_index,
1693                                             src_name))
1694                                         ref->peer_ref = alloc_delete_ref();
1695                                 free(src_name);
1696                         }
1697                 }
1698                 string_list_clear(&src_ref_index, 0);
1699         }
1700
1701         *dst = apply_negative_refspecs(*dst, rs);
1702
1703         if (errs)
1704                 return -1;
1705         return 0;
1706 }
1707
1708 void set_ref_status_for_push(struct ref *remote_refs, int send_mirror,
1709                              int force_update)
1710 {
1711         struct ref *ref;
1712
1713         for (ref = remote_refs; ref; ref = ref->next) {
1714                 int force_ref_update = ref->force || force_update;
1715                 int reject_reason = 0;
1716
1717                 if (ref->peer_ref)
1718                         oidcpy(&ref->new_oid, &ref->peer_ref->new_oid);
1719                 else if (!send_mirror)
1720                         continue;
1721
1722                 ref->deletion = is_null_oid(&ref->new_oid);
1723                 if (!ref->deletion &&
1724                         oideq(&ref->old_oid, &ref->new_oid)) {
1725                         ref->status = REF_STATUS_UPTODATE;
1726                         continue;
1727                 }
1728
1729                 /*
1730                  * If the remote ref has moved and is now different
1731                  * from what we expect, reject any push.
1732                  *
1733                  * It also is an error if the user told us to check
1734                  * with the remote-tracking branch to find the value
1735                  * to expect, but we did not have such a tracking
1736                  * branch.
1737                  *
1738                  * If the tip of the remote-tracking ref is unreachable
1739                  * from any reflog entry of its local ref indicating a
1740                  * possible update since checkout; reject the push.
1741                  */
1742                 if (ref->expect_old_sha1) {
1743                         if (!oideq(&ref->old_oid, &ref->old_oid_expect))
1744                                 reject_reason = REF_STATUS_REJECT_STALE;
1745                         else if (ref->check_reachable && ref->unreachable)
1746                                 reject_reason =
1747                                         REF_STATUS_REJECT_REMOTE_UPDATED;
1748                         else
1749                                 /*
1750                                  * If the ref isn't stale, and is reachable
1751                                  * from one of the reflog entries of
1752                                  * the local branch, force the update.
1753                                  */
1754                                 force_ref_update = 1;
1755                 }
1756
1757                 /*
1758                  * If the update isn't already rejected then check
1759                  * the usual "must fast-forward" rules.
1760                  *
1761                  * Decide whether an individual refspec A:B can be
1762                  * pushed.  The push will succeed if any of the
1763                  * following are true:
1764                  *
1765                  * (1) the remote reference B does not exist
1766                  *
1767                  * (2) the remote reference B is being removed (i.e.,
1768                  *     pushing :B where no source is specified)
1769                  *
1770                  * (3) the destination is not under refs/tags/, and
1771                  *     if the old and new value is a commit, the new
1772                  *     is a descendant of the old.
1773                  *
1774                  * (4) it is forced using the +A:B notation, or by
1775                  *     passing the --force argument
1776                  */
1777
1778                 if (!reject_reason && !ref->deletion && !is_null_oid(&ref->old_oid)) {
1779                         if (starts_with(ref->name, "refs/tags/"))
1780                                 reject_reason = REF_STATUS_REJECT_ALREADY_EXISTS;
1781                         else if (!repo_has_object_file_with_flags(the_repository, &ref->old_oid, OBJECT_INFO_SKIP_FETCH_OBJECT))
1782                                 reject_reason = REF_STATUS_REJECT_FETCH_FIRST;
1783                         else if (!lookup_commit_reference_gently(the_repository, &ref->old_oid, 1) ||
1784                                  !lookup_commit_reference_gently(the_repository, &ref->new_oid, 1))
1785                                 reject_reason = REF_STATUS_REJECT_NEEDS_FORCE;
1786                         else if (!ref_newer(&ref->new_oid, &ref->old_oid))
1787                                 reject_reason = REF_STATUS_REJECT_NONFASTFORWARD;
1788                 }
1789
1790                 /*
1791                  * "--force" will defeat any rejection implemented
1792                  * by the rules above.
1793                  */
1794                 if (!force_ref_update)
1795                         ref->status = reject_reason;
1796                 else if (reject_reason)
1797                         ref->forced_update = 1;
1798         }
1799 }
1800
1801 static void set_merge(struct remote_state *remote_state, struct branch *ret)
1802 {
1803         struct remote *remote;
1804         char *ref;
1805         struct object_id oid;
1806         int i;
1807
1808         if (!ret)
1809                 return; /* no branch */
1810         if (ret->merge)
1811                 return; /* already run */
1812         if (!ret->remote_name || !ret->merge_nr) {
1813                 /*
1814                  * no merge config; let's make sure we don't confuse callers
1815                  * with a non-zero merge_nr but a NULL merge
1816                  */
1817                 ret->merge_nr = 0;
1818                 return;
1819         }
1820
1821         remote = remotes_remote_get(remote_state, ret->remote_name);
1822
1823         CALLOC_ARRAY(ret->merge, ret->merge_nr);
1824         for (i = 0; i < ret->merge_nr; i++) {
1825                 ret->merge[i] = xcalloc(1, sizeof(**ret->merge));
1826                 ret->merge[i]->src = xstrdup(ret->merge_name[i]);
1827                 if (!remote_find_tracking(remote, ret->merge[i]) ||
1828                     strcmp(ret->remote_name, "."))
1829                         continue;
1830                 if (repo_dwim_ref(the_repository, ret->merge_name[i],
1831                                   strlen(ret->merge_name[i]), &oid, &ref,
1832                                   0) == 1)
1833                         ret->merge[i]->dst = ref;
1834                 else
1835                         ret->merge[i]->dst = xstrdup(ret->merge_name[i]);
1836         }
1837 }
1838
1839 struct branch *branch_get(const char *name)
1840 {
1841         struct branch *ret;
1842
1843         read_config(the_repository, 0);
1844         if (!name || !*name || !strcmp(name, "HEAD"))
1845                 ret = the_repository->remote_state->current_branch;
1846         else
1847                 ret = make_branch(the_repository->remote_state, name,
1848                                   strlen(name));
1849         set_merge(the_repository->remote_state, ret);
1850         return ret;
1851 }
1852
1853 int branch_has_merge_config(struct branch *branch)
1854 {
1855         return branch && !!branch->merge;
1856 }
1857
1858 int branch_merge_matches(struct branch *branch,
1859                                  int i,
1860                                  const char *refname)
1861 {
1862         if (!branch || i < 0 || i >= branch->merge_nr)
1863                 return 0;
1864         return refname_match(branch->merge[i]->src, refname);
1865 }
1866
1867 __attribute__((format (printf,2,3)))
1868 static const char *error_buf(struct strbuf *err, const char *fmt, ...)
1869 {
1870         if (err) {
1871                 va_list ap;
1872                 va_start(ap, fmt);
1873                 strbuf_vaddf(err, fmt, ap);
1874                 va_end(ap);
1875         }
1876         return NULL;
1877 }
1878
1879 const char *branch_get_upstream(struct branch *branch, struct strbuf *err)
1880 {
1881         if (!branch)
1882                 return error_buf(err, _("HEAD does not point to a branch"));
1883
1884         if (!branch->merge || !branch->merge[0]) {
1885                 /*
1886                  * no merge config; is it because the user didn't define any,
1887                  * or because it is not a real branch, and get_branch
1888                  * auto-vivified it?
1889                  */
1890                 if (!refs_ref_exists(get_main_ref_store(the_repository), branch->refname))
1891                         return error_buf(err, _("no such branch: '%s'"),
1892                                          branch->name);
1893                 return error_buf(err,
1894                                  _("no upstream configured for branch '%s'"),
1895                                  branch->name);
1896         }
1897
1898         if (!branch->merge[0]->dst)
1899                 return error_buf(err,
1900                                  _("upstream branch '%s' not stored as a remote-tracking branch"),
1901                                  branch->merge[0]->src);
1902
1903         return branch->merge[0]->dst;
1904 }
1905
1906 static const char *tracking_for_push_dest(struct remote *remote,
1907                                           const char *refname,
1908                                           struct strbuf *err)
1909 {
1910         char *ret;
1911
1912         ret = apply_refspecs(&remote->fetch, refname);
1913         if (!ret)
1914                 return error_buf(err,
1915                                  _("push destination '%s' on remote '%s' has no local tracking branch"),
1916                                  refname, remote->name);
1917         return ret;
1918 }
1919
1920 static const char *branch_get_push_1(struct remote_state *remote_state,
1921                                      struct branch *branch, struct strbuf *err)
1922 {
1923         struct remote *remote;
1924
1925         remote = remotes_remote_get(
1926                 remote_state,
1927                 remotes_pushremote_for_branch(remote_state, branch, NULL));
1928         if (!remote)
1929                 return error_buf(err,
1930                                  _("branch '%s' has no remote for pushing"),
1931                                  branch->name);
1932
1933         if (remote->push.nr) {
1934                 char *dst;
1935                 const char *ret;
1936
1937                 dst = apply_refspecs(&remote->push, branch->refname);
1938                 if (!dst)
1939                         return error_buf(err,
1940                                          _("push refspecs for '%s' do not include '%s'"),
1941                                          remote->name, branch->name);
1942
1943                 ret = tracking_for_push_dest(remote, dst, err);
1944                 free(dst);
1945                 return ret;
1946         }
1947
1948         if (remote->mirror)
1949                 return tracking_for_push_dest(remote, branch->refname, err);
1950
1951         switch (push_default) {
1952         case PUSH_DEFAULT_NOTHING:
1953                 return error_buf(err, _("push has no destination (push.default is 'nothing')"));
1954
1955         case PUSH_DEFAULT_MATCHING:
1956         case PUSH_DEFAULT_CURRENT:
1957                 return tracking_for_push_dest(remote, branch->refname, err);
1958
1959         case PUSH_DEFAULT_UPSTREAM:
1960                 return branch_get_upstream(branch, err);
1961
1962         case PUSH_DEFAULT_UNSPECIFIED:
1963         case PUSH_DEFAULT_SIMPLE:
1964                 {
1965                         const char *up, *cur;
1966
1967                         up = branch_get_upstream(branch, err);
1968                         if (!up)
1969                                 return NULL;
1970                         cur = tracking_for_push_dest(remote, branch->refname, err);
1971                         if (!cur)
1972                                 return NULL;
1973                         if (strcmp(cur, up))
1974                                 return error_buf(err,
1975                                                  _("cannot resolve 'simple' push to a single destination"));
1976                         return cur;
1977                 }
1978         }
1979
1980         BUG("unhandled push situation");
1981 }
1982
1983 const char *branch_get_push(struct branch *branch, struct strbuf *err)
1984 {
1985         read_config(the_repository, 0);
1986         die_on_missing_branch(the_repository, branch);
1987
1988         if (!branch)
1989                 return error_buf(err, _("HEAD does not point to a branch"));
1990
1991         if (!branch->push_tracking_ref)
1992                 branch->push_tracking_ref = branch_get_push_1(
1993                         the_repository->remote_state, branch, err);
1994         return branch->push_tracking_ref;
1995 }
1996
1997 static int ignore_symref_update(const char *refname, struct strbuf *scratch)
1998 {
1999         return !refs_read_symbolic_ref(get_main_ref_store(the_repository), refname, scratch);
2000 }
2001
2002 /*
2003  * Create and return a list of (struct ref) consisting of copies of
2004  * each remote_ref that matches refspec.  refspec must be a pattern.
2005  * Fill in the copies' peer_ref to describe the local tracking refs to
2006  * which they map.  Omit any references that would map to an existing
2007  * local symbolic ref.
2008  */
2009 static struct ref *get_expanded_map(const struct ref *remote_refs,
2010                                     const struct refspec_item *refspec)
2011 {
2012         struct strbuf scratch = STRBUF_INIT;
2013         const struct ref *ref;
2014         struct ref *ret = NULL;
2015         struct ref **tail = &ret;
2016
2017         for (ref = remote_refs; ref; ref = ref->next) {
2018                 char *expn_name = NULL;
2019
2020                 strbuf_reset(&scratch);
2021
2022                 if (strchr(ref->name, '^'))
2023                         continue; /* a dereference item */
2024                 if (match_name_with_pattern(refspec->src, ref->name,
2025                                             refspec->dst, &expn_name) &&
2026                     !ignore_symref_update(expn_name, &scratch)) {
2027                         struct ref *cpy = copy_ref(ref);
2028
2029                         cpy->peer_ref = alloc_ref(expn_name);
2030                         if (refspec->force)
2031                                 cpy->peer_ref->force = 1;
2032                         *tail = cpy;
2033                         tail = &cpy->next;
2034                 }
2035                 free(expn_name);
2036         }
2037
2038         strbuf_release(&scratch);
2039         return ret;
2040 }
2041
2042 static const struct ref *find_ref_by_name_abbrev(const struct ref *refs, const char *name)
2043 {
2044         const struct ref *ref;
2045         const struct ref *best_match = NULL;
2046         int best_score = 0;
2047
2048         for (ref = refs; ref; ref = ref->next) {
2049                 int score = refname_match(name, ref->name);
2050
2051                 if (best_score < score) {
2052                         best_match = ref;
2053                         best_score = score;
2054                 }
2055         }
2056         return best_match;
2057 }
2058
2059 struct ref *get_remote_ref(const struct ref *remote_refs, const char *name)
2060 {
2061         const struct ref *ref = find_ref_by_name_abbrev(remote_refs, name);
2062
2063         if (!ref)
2064                 return NULL;
2065
2066         return copy_ref(ref);
2067 }
2068
2069 static struct ref *get_local_ref(const char *name)
2070 {
2071         if (!name || name[0] == '\0')
2072                 return NULL;
2073
2074         if (starts_with(name, "refs/"))
2075                 return alloc_ref(name);
2076
2077         if (starts_with(name, "heads/") ||
2078             starts_with(name, "tags/") ||
2079             starts_with(name, "remotes/"))
2080                 return alloc_ref_with_prefix("refs/", 5, name);
2081
2082         return alloc_ref_with_prefix("refs/heads/", 11, name);
2083 }
2084
2085 int get_fetch_map(const struct ref *remote_refs,
2086                   const struct refspec_item *refspec,
2087                   struct ref ***tail,
2088                   int missing_ok)
2089 {
2090         struct ref *ref_map, **rmp;
2091
2092         if (refspec->negative)
2093                 return 0;
2094
2095         if (refspec->pattern) {
2096                 ref_map = get_expanded_map(remote_refs, refspec);
2097         } else {
2098                 const char *name = refspec->src[0] ? refspec->src : "HEAD";
2099
2100                 if (refspec->exact_sha1) {
2101                         ref_map = alloc_ref(name);
2102                         get_oid_hex(name, &ref_map->old_oid);
2103                         ref_map->exact_oid = 1;
2104                 } else {
2105                         ref_map = get_remote_ref(remote_refs, name);
2106                 }
2107                 if (!missing_ok && !ref_map)
2108                         die(_("couldn't find remote ref %s"), name);
2109                 if (ref_map) {
2110                         ref_map->peer_ref = get_local_ref(refspec->dst);
2111                         if (ref_map->peer_ref && refspec->force)
2112                                 ref_map->peer_ref->force = 1;
2113                 }
2114         }
2115
2116         for (rmp = &ref_map; *rmp; ) {
2117                 if ((*rmp)->peer_ref) {
2118                         if (!starts_with((*rmp)->peer_ref->name, "refs/") ||
2119                             check_refname_format((*rmp)->peer_ref->name, 0)) {
2120                                 struct ref *ignore = *rmp;
2121                                 error(_("* Ignoring funny ref '%s' locally"),
2122                                       (*rmp)->peer_ref->name);
2123                                 *rmp = (*rmp)->next;
2124                                 free(ignore->peer_ref);
2125                                 free(ignore);
2126                                 continue;
2127                         }
2128                 }
2129                 rmp = &((*rmp)->next);
2130         }
2131
2132         if (ref_map)
2133                 tail_link_ref(ref_map, tail);
2134
2135         return 0;
2136 }
2137
2138 int resolve_remote_symref(struct ref *ref, struct ref *list)
2139 {
2140         if (!ref->symref)
2141                 return 0;
2142         for (; list; list = list->next)
2143                 if (!strcmp(ref->symref, list->name)) {
2144                         oidcpy(&ref->old_oid, &list->old_oid);
2145                         return 0;
2146                 }
2147         return 1;
2148 }
2149
2150 /*
2151  * Compute the commit ahead/behind values for the pair branch_name, base.
2152  *
2153  * If abf is AHEAD_BEHIND_FULL, compute the full ahead/behind and return the
2154  * counts in *num_ours and *num_theirs.  If abf is AHEAD_BEHIND_QUICK, skip
2155  * the (potentially expensive) a/b computation (*num_ours and *num_theirs are
2156  * set to zero).
2157  *
2158  * Returns -1 if num_ours and num_theirs could not be filled in (e.g., ref
2159  * does not exist).  Returns 0 if the commits are identical.  Returns 1 if
2160  * commits are different.
2161  */
2162
2163 static int stat_branch_pair(const char *branch_name, const char *base,
2164                              int *num_ours, int *num_theirs,
2165                              enum ahead_behind_flags abf)
2166 {
2167         struct object_id oid;
2168         struct commit *ours, *theirs;
2169         struct rev_info revs;
2170         struct setup_revision_opt opt = {
2171                 .free_removed_argv_elements = 1,
2172         };
2173         struct strvec argv = STRVEC_INIT;
2174
2175         /* Cannot stat if what we used to build on no longer exists */
2176         if (refs_read_ref(get_main_ref_store(the_repository), base, &oid))
2177                 return -1;
2178         theirs = lookup_commit_reference(the_repository, &oid);
2179         if (!theirs)
2180                 return -1;
2181
2182         if (refs_read_ref(get_main_ref_store(the_repository), branch_name, &oid))
2183                 return -1;
2184         ours = lookup_commit_reference(the_repository, &oid);
2185         if (!ours)
2186                 return -1;
2187
2188         *num_theirs = *num_ours = 0;
2189
2190         /* are we the same? */
2191         if (theirs == ours)
2192                 return 0;
2193         if (abf == AHEAD_BEHIND_QUICK)
2194                 return 1;
2195         if (abf != AHEAD_BEHIND_FULL)
2196                 BUG("stat_branch_pair: invalid abf '%d'", abf);
2197
2198         /* Run "rev-list --left-right ours...theirs" internally... */
2199         strvec_push(&argv, ""); /* ignored */
2200         strvec_push(&argv, "--left-right");
2201         strvec_pushf(&argv, "%s...%s",
2202                      oid_to_hex(&ours->object.oid),
2203                      oid_to_hex(&theirs->object.oid));
2204         strvec_push(&argv, "--");
2205
2206         repo_init_revisions(the_repository, &revs, NULL);
2207         setup_revisions(argv.nr, argv.v, &revs, &opt);
2208         if (prepare_revision_walk(&revs))
2209                 die(_("revision walk setup failed"));
2210
2211         /* ... and count the commits on each side. */
2212         while (1) {
2213                 struct commit *c = get_revision(&revs);
2214                 if (!c)
2215                         break;
2216                 if (c->object.flags & SYMMETRIC_LEFT)
2217                         (*num_ours)++;
2218                 else
2219                         (*num_theirs)++;
2220         }
2221
2222         /* clear object flags smudged by the above traversal */
2223         clear_commit_marks(ours, ALL_REV_FLAGS);
2224         clear_commit_marks(theirs, ALL_REV_FLAGS);
2225
2226         strvec_clear(&argv);
2227         release_revisions(&revs);
2228         return 1;
2229 }
2230
2231 /*
2232  * Lookup the tracking branch for the given branch and if present, optionally
2233  * compute the commit ahead/behind values for the pair.
2234  *
2235  * If for_push is true, the tracking branch refers to the push branch,
2236  * otherwise it refers to the upstream branch.
2237  *
2238  * The name of the tracking branch (or NULL if it is not defined) is
2239  * returned via *tracking_name, if it is not itself NULL.
2240  *
2241  * If abf is AHEAD_BEHIND_FULL, compute the full ahead/behind and return the
2242  * counts in *num_ours and *num_theirs.  If abf is AHEAD_BEHIND_QUICK, skip
2243  * the (potentially expensive) a/b computation (*num_ours and *num_theirs are
2244  * set to zero).
2245  *
2246  * Returns -1 if num_ours and num_theirs could not be filled in (e.g., no
2247  * upstream defined, or ref does not exist).  Returns 0 if the commits are
2248  * identical.  Returns 1 if commits are different.
2249  */
2250 int stat_tracking_info(struct branch *branch, int *num_ours, int *num_theirs,
2251                        const char **tracking_name, int for_push,
2252                        enum ahead_behind_flags abf)
2253 {
2254         const char *base;
2255
2256         /* Cannot stat unless we are marked to build on top of somebody else. */
2257         base = for_push ? branch_get_push(branch, NULL) :
2258                 branch_get_upstream(branch, NULL);
2259         if (tracking_name)
2260                 *tracking_name = base;
2261         if (!base)
2262                 return -1;
2263
2264         return stat_branch_pair(branch->refname, base, num_ours, num_theirs, abf);
2265 }
2266
2267 /*
2268  * Return true when there is anything to report, otherwise false.
2269  */
2270 int format_tracking_info(struct branch *branch, struct strbuf *sb,
2271                          enum ahead_behind_flags abf,
2272                          int show_divergence_advice)
2273 {
2274         int ours, theirs, sti;
2275         const char *full_base;
2276         char *base;
2277         int upstream_is_gone = 0;
2278
2279         sti = stat_tracking_info(branch, &ours, &theirs, &full_base, 0, abf);
2280         if (sti < 0) {
2281                 if (!full_base)
2282                         return 0;
2283                 upstream_is_gone = 1;
2284         }
2285
2286         base = refs_shorten_unambiguous_ref(get_main_ref_store(the_repository),
2287                                             full_base, 0);
2288         if (upstream_is_gone) {
2289                 strbuf_addf(sb,
2290                         _("Your branch is based on '%s', but the upstream is gone.\n"),
2291                         base);
2292                 if (advice_enabled(ADVICE_STATUS_HINTS))
2293                         strbuf_addstr(sb,
2294                                 _("  (use \"git branch --unset-upstream\" to fixup)\n"));
2295         } else if (!sti) {
2296                 strbuf_addf(sb,
2297                         _("Your branch is up to date with '%s'.\n"),
2298                         base);
2299         } else if (abf == AHEAD_BEHIND_QUICK) {
2300                 strbuf_addf(sb,
2301                             _("Your branch and '%s' refer to different commits.\n"),
2302                             base);
2303                 if (advice_enabled(ADVICE_STATUS_HINTS))
2304                         strbuf_addf(sb, _("  (use \"%s\" for details)\n"),
2305                                     "git status --ahead-behind");
2306         } else if (!theirs) {
2307                 strbuf_addf(sb,
2308                         Q_("Your branch is ahead of '%s' by %d commit.\n",
2309                            "Your branch is ahead of '%s' by %d commits.\n",
2310                            ours),
2311                         base, ours);
2312                 if (advice_enabled(ADVICE_STATUS_HINTS))
2313                         strbuf_addstr(sb,
2314                                 _("  (use \"git push\" to publish your local commits)\n"));
2315         } else if (!ours) {
2316                 strbuf_addf(sb,
2317                         Q_("Your branch is behind '%s' by %d commit, "
2318                                "and can be fast-forwarded.\n",
2319                            "Your branch is behind '%s' by %d commits, "
2320                                "and can be fast-forwarded.\n",
2321                            theirs),
2322                         base, theirs);
2323                 if (advice_enabled(ADVICE_STATUS_HINTS))
2324                         strbuf_addstr(sb,
2325                                 _("  (use \"git pull\" to update your local branch)\n"));
2326         } else {
2327                 strbuf_addf(sb,
2328                         Q_("Your branch and '%s' have diverged,\n"
2329                                "and have %d and %d different commit each, "
2330                                "respectively.\n",
2331                            "Your branch and '%s' have diverged,\n"
2332                                "and have %d and %d different commits each, "
2333                                "respectively.\n",
2334                            ours + theirs),
2335                         base, ours, theirs);
2336                 if (show_divergence_advice &&
2337                     advice_enabled(ADVICE_STATUS_HINTS))
2338                         strbuf_addstr(sb,
2339                                 _("  (use \"git pull\" if you want to integrate the remote branch with yours)\n"));
2340         }
2341         free(base);
2342         return 1;
2343 }
2344
2345 static int one_local_ref(const char *refname, const struct object_id *oid,
2346                          int flag UNUSED,
2347                          void *cb_data)
2348 {
2349         struct ref ***local_tail = cb_data;
2350         struct ref *ref;
2351
2352         /* we already know it starts with refs/ to get here */
2353         if (check_refname_format(refname + 5, 0))
2354                 return 0;
2355
2356         ref = alloc_ref(refname);
2357         oidcpy(&ref->new_oid, oid);
2358         **local_tail = ref;
2359         *local_tail = &ref->next;
2360         return 0;
2361 }
2362
2363 struct ref *get_local_heads(void)
2364 {
2365         struct ref *local_refs = NULL, **local_tail = &local_refs;
2366
2367         refs_for_each_ref(get_main_ref_store(the_repository), one_local_ref,
2368                           &local_tail);
2369         return local_refs;
2370 }
2371
2372 struct ref *guess_remote_head(const struct ref *head,
2373                               const struct ref *refs,
2374                               int all)
2375 {
2376         const struct ref *r;
2377         struct ref *list = NULL;
2378         struct ref **tail = &list;
2379
2380         if (!head)
2381                 return NULL;
2382
2383         /*
2384          * Some transports support directly peeking at
2385          * where HEAD points; if that is the case, then
2386          * we don't have to guess.
2387          */
2388         if (head->symref)
2389                 return copy_ref(find_ref_by_name(refs, head->symref));
2390
2391         /* If a remote branch exists with the default branch name, let's use it. */
2392         if (!all) {
2393                 char *default_branch = repo_default_branch_name(the_repository, 0);
2394                 char *ref = xstrfmt("refs/heads/%s", default_branch);
2395
2396                 r = find_ref_by_name(refs, ref);
2397                 free(ref);
2398                 free(default_branch);
2399
2400                 if (r && oideq(&r->old_oid, &head->old_oid))
2401                         return copy_ref(r);
2402
2403                 /* Fall back to the hard-coded historical default */
2404                 r = find_ref_by_name(refs, "refs/heads/master");
2405                 if (r && oideq(&r->old_oid, &head->old_oid))
2406                         return copy_ref(r);
2407         }
2408
2409         /* Look for another ref that points there */
2410         for (r = refs; r; r = r->next) {
2411                 if (r != head &&
2412                     starts_with(r->name, "refs/heads/") &&
2413                     oideq(&r->old_oid, &head->old_oid)) {
2414                         *tail = copy_ref(r);
2415                         tail = &((*tail)->next);
2416                         if (!all)
2417                                 break;
2418                 }
2419         }
2420
2421         return list;
2422 }
2423
2424 struct stale_heads_info {
2425         struct string_list *ref_names;
2426         struct ref **stale_refs_tail;
2427         struct refspec *rs;
2428 };
2429
2430 static int get_stale_heads_cb(const char *refname, const struct object_id *oid,
2431                               int flags, void *cb_data)
2432 {
2433         struct stale_heads_info *info = cb_data;
2434         struct string_list matches = STRING_LIST_INIT_DUP;
2435         struct refspec_item query;
2436         int i, stale = 1;
2437         memset(&query, 0, sizeof(struct refspec_item));
2438         query.dst = (char *)refname;
2439
2440         query_refspecs_multiple(info->rs, &query, &matches);
2441         if (matches.nr == 0)
2442                 goto clean_exit; /* No matches */
2443
2444         /*
2445          * If we did find a suitable refspec and it's not a symref and
2446          * it's not in the list of refs that currently exist in that
2447          * remote, we consider it to be stale. In order to deal with
2448          * overlapping refspecs, we need to go over all of the
2449          * matching refs.
2450          */
2451         if (flags & REF_ISSYMREF)
2452                 goto clean_exit;
2453
2454         for (i = 0; stale && i < matches.nr; i++)
2455                 if (string_list_has_string(info->ref_names, matches.items[i].string))
2456                         stale = 0;
2457
2458         if (stale) {
2459                 struct ref *ref = make_linked_ref(refname, &info->stale_refs_tail);
2460                 oidcpy(&ref->new_oid, oid);
2461         }
2462
2463 clean_exit:
2464         string_list_clear(&matches, 0);
2465         return 0;
2466 }
2467
2468 struct ref *get_stale_heads(struct refspec *rs, struct ref *fetch_map)
2469 {
2470         struct ref *ref, *stale_refs = NULL;
2471         struct string_list ref_names = STRING_LIST_INIT_NODUP;
2472         struct stale_heads_info info;
2473
2474         info.ref_names = &ref_names;
2475         info.stale_refs_tail = &stale_refs;
2476         info.rs = rs;
2477         for (ref = fetch_map; ref; ref = ref->next)
2478                 string_list_append(&ref_names, ref->name);
2479         string_list_sort(&ref_names);
2480         refs_for_each_ref(get_main_ref_store(the_repository),
2481                           get_stale_heads_cb, &info);
2482         string_list_clear(&ref_names, 0);
2483         return stale_refs;
2484 }
2485
2486 /*
2487  * Compare-and-swap
2488  */
2489 static void clear_cas_option(struct push_cas_option *cas)
2490 {
2491         int i;
2492
2493         for (i = 0; i < cas->nr; i++)
2494                 free(cas->entry[i].refname);
2495         free(cas->entry);
2496         memset(cas, 0, sizeof(*cas));
2497 }
2498
2499 static struct push_cas *add_cas_entry(struct push_cas_option *cas,
2500                                       const char *refname,
2501                                       size_t refnamelen)
2502 {
2503         struct push_cas *entry;
2504         ALLOC_GROW(cas->entry, cas->nr + 1, cas->alloc);
2505         entry = &cas->entry[cas->nr++];
2506         memset(entry, 0, sizeof(*entry));
2507         entry->refname = xmemdupz(refname, refnamelen);
2508         return entry;
2509 }
2510
2511 static int parse_push_cas_option(struct push_cas_option *cas, const char *arg, int unset)
2512 {
2513         const char *colon;
2514         struct push_cas *entry;
2515
2516         if (unset) {
2517                 /* "--no-<option>" */
2518                 clear_cas_option(cas);
2519                 return 0;
2520         }
2521
2522         if (!arg) {
2523                 /* just "--<option>" */
2524                 cas->use_tracking_for_rest = 1;
2525                 return 0;
2526         }
2527
2528         /* "--<option>=refname" or "--<option>=refname:value" */
2529         colon = strchrnul(arg, ':');
2530         entry = add_cas_entry(cas, arg, colon - arg);
2531         if (!*colon)
2532                 entry->use_tracking = 1;
2533         else if (!colon[1])
2534                 oidclr(&entry->expect);
2535         else if (repo_get_oid(the_repository, colon + 1, &entry->expect))
2536                 return error(_("cannot parse expected object name '%s'"),
2537                              colon + 1);
2538         return 0;
2539 }
2540
2541 int parseopt_push_cas_option(const struct option *opt, const char *arg, int unset)
2542 {
2543         return parse_push_cas_option(opt->value, arg, unset);
2544 }
2545
2546 int is_empty_cas(const struct push_cas_option *cas)
2547 {
2548         return !cas->use_tracking_for_rest && !cas->nr;
2549 }
2550
2551 /*
2552  * Look at remote.fetch refspec and see if we have a remote
2553  * tracking branch for the refname there. Fill the name of
2554  * the remote-tracking branch in *dst_refname, and the name
2555  * of the commit object at its tip in oid[].
2556  * If we cannot do so, return negative to signal an error.
2557  */
2558 static int remote_tracking(struct remote *remote, const char *refname,
2559                            struct object_id *oid, char **dst_refname)
2560 {
2561         char *dst;
2562
2563         dst = apply_refspecs(&remote->fetch, refname);
2564         if (!dst)
2565                 return -1; /* no tracking ref for refname at remote */
2566         if (refs_read_ref(get_main_ref_store(the_repository), dst, oid))
2567                 return -1; /* we know what the tracking ref is but we cannot read it */
2568
2569         *dst_refname = dst;
2570         return 0;
2571 }
2572
2573 /*
2574  * The struct "reflog_commit_array" and related helper functions
2575  * are used for collecting commits into an array during reflog
2576  * traversals in "check_and_collect_until()".
2577  */
2578 struct reflog_commit_array {
2579         struct commit **item;
2580         size_t nr, alloc;
2581 };
2582
2583 #define REFLOG_COMMIT_ARRAY_INIT { 0 }
2584
2585 /* Append a commit to the array. */
2586 static void append_commit(struct reflog_commit_array *arr,
2587                           struct commit *commit)
2588 {
2589         ALLOC_GROW(arr->item, arr->nr + 1, arr->alloc);
2590         arr->item[arr->nr++] = commit;
2591 }
2592
2593 /* Free and reset the array. */
2594 static void free_commit_array(struct reflog_commit_array *arr)
2595 {
2596         FREE_AND_NULL(arr->item);
2597         arr->nr = arr->alloc = 0;
2598 }
2599
2600 struct check_and_collect_until_cb_data {
2601         struct commit *remote_commit;
2602         struct reflog_commit_array *local_commits;
2603         timestamp_t remote_reflog_timestamp;
2604 };
2605
2606 /* Get the timestamp of the latest entry. */
2607 static int peek_reflog(struct object_id *o_oid UNUSED,
2608                        struct object_id *n_oid UNUSED,
2609                        const char *ident UNUSED,
2610                        timestamp_t timestamp, int tz UNUSED,
2611                        const char *message UNUSED, void *cb_data)
2612 {
2613         timestamp_t *ts = cb_data;
2614         *ts = timestamp;
2615         return 1;
2616 }
2617
2618 static int check_and_collect_until(struct object_id *o_oid UNUSED,
2619                                    struct object_id *n_oid,
2620                                    const char *ident UNUSED,
2621                                    timestamp_t timestamp, int tz UNUSED,
2622                                    const char *message UNUSED, void *cb_data)
2623 {
2624         struct commit *commit;
2625         struct check_and_collect_until_cb_data *cb = cb_data;
2626
2627         /* An entry was found. */
2628         if (oideq(n_oid, &cb->remote_commit->object.oid))
2629                 return 1;
2630
2631         if ((commit = lookup_commit_reference(the_repository, n_oid)))
2632                 append_commit(cb->local_commits, commit);
2633
2634         /*
2635          * If the reflog entry timestamp is older than the remote ref's
2636          * latest reflog entry, there is no need to check or collect
2637          * entries older than this one.
2638          */
2639         if (timestamp < cb->remote_reflog_timestamp)
2640                 return -1;
2641
2642         return 0;
2643 }
2644
2645 #define MERGE_BASES_BATCH_SIZE 8
2646
2647 /*
2648  * Iterate through the reflog of the local ref to check if there is an entry
2649  * for the given remote-tracking ref; runs until the timestamp of an entry is
2650  * older than latest timestamp of remote-tracking ref's reflog. Any commits
2651  * are that seen along the way are collected into an array to check if the
2652  * remote-tracking ref is reachable from any of them.
2653  */
2654 static int is_reachable_in_reflog(const char *local, const struct ref *remote)
2655 {
2656         timestamp_t date;
2657         struct commit *commit;
2658         struct commit **chunk;
2659         struct check_and_collect_until_cb_data cb;
2660         struct reflog_commit_array arr = REFLOG_COMMIT_ARRAY_INIT;
2661         size_t size = 0;
2662         int ret = 0;
2663
2664         commit = lookup_commit_reference(the_repository, &remote->old_oid);
2665         if (!commit)
2666                 goto cleanup_return;
2667
2668         /*
2669          * Get the timestamp from the latest entry
2670          * of the remote-tracking ref's reflog.
2671          */
2672         refs_for_each_reflog_ent_reverse(get_main_ref_store(the_repository),
2673                                          remote->tracking_ref, peek_reflog,
2674                                          &date);
2675
2676         cb.remote_commit = commit;
2677         cb.local_commits = &arr;
2678         cb.remote_reflog_timestamp = date;
2679         ret = refs_for_each_reflog_ent_reverse(get_main_ref_store(the_repository),
2680                                                local, check_and_collect_until,
2681                                                &cb);
2682
2683         /* We found an entry in the reflog. */
2684         if (ret > 0)
2685                 goto cleanup_return;
2686
2687         /*
2688          * Check if the remote commit is reachable from any
2689          * of the commits in the collected array, in batches.
2690          */
2691         for (chunk = arr.item; chunk < arr.item + arr.nr; chunk += size) {
2692                 size = arr.item + arr.nr - chunk;
2693                 if (MERGE_BASES_BATCH_SIZE < size)
2694                         size = MERGE_BASES_BATCH_SIZE;
2695
2696                 if ((ret = repo_in_merge_bases_many(the_repository, commit, size, chunk, 0)))
2697                         break;
2698         }
2699
2700 cleanup_return:
2701         free_commit_array(&arr);
2702         return ret;
2703 }
2704
2705 /*
2706  * Check for reachability of a remote-tracking
2707  * ref in the reflog entries of its local ref.
2708  */
2709 static void check_if_includes_upstream(struct ref *remote)
2710 {
2711         struct ref *local = get_local_ref(remote->name);
2712         if (!local)
2713                 return;
2714
2715         if (is_reachable_in_reflog(local->name, remote) <= 0)
2716                 remote->unreachable = 1;
2717 }
2718
2719 static void apply_cas(struct push_cas_option *cas,
2720                       struct remote *remote,
2721                       struct ref *ref)
2722 {
2723         int i;
2724
2725         /* Find an explicit --<option>=<name>[:<value>] entry */
2726         for (i = 0; i < cas->nr; i++) {
2727                 struct push_cas *entry = &cas->entry[i];
2728                 if (!refname_match(entry->refname, ref->name))
2729                         continue;
2730                 ref->expect_old_sha1 = 1;
2731                 if (!entry->use_tracking)
2732                         oidcpy(&ref->old_oid_expect, &entry->expect);
2733                 else if (remote_tracking(remote, ref->name,
2734                                          &ref->old_oid_expect,
2735                                          &ref->tracking_ref))
2736                         oidclr(&ref->old_oid_expect);
2737                 else
2738                         ref->check_reachable = cas->use_force_if_includes;
2739                 return;
2740         }
2741
2742         /* Are we using "--<option>" to cover all? */
2743         if (!cas->use_tracking_for_rest)
2744                 return;
2745
2746         ref->expect_old_sha1 = 1;
2747         if (remote_tracking(remote, ref->name,
2748                             &ref->old_oid_expect,
2749                             &ref->tracking_ref))
2750                 oidclr(&ref->old_oid_expect);
2751         else
2752                 ref->check_reachable = cas->use_force_if_includes;
2753 }
2754
2755 void apply_push_cas(struct push_cas_option *cas,
2756                     struct remote *remote,
2757                     struct ref *remote_refs)
2758 {
2759         struct ref *ref;
2760         for (ref = remote_refs; ref; ref = ref->next) {
2761                 apply_cas(cas, remote, ref);
2762
2763                 /*
2764                  * If "compare-and-swap" is in "use_tracking[_for_rest]"
2765                  * mode, and if "--force-if-includes" was specified, run
2766                  * the check.
2767                  */
2768                 if (ref->check_reachable)
2769                         check_if_includes_upstream(ref);
2770         }
2771 }
2772
2773 struct remote_state *remote_state_new(void)
2774 {
2775         struct remote_state *r = xmalloc(sizeof(*r));
2776
2777         memset(r, 0, sizeof(*r));
2778
2779         hashmap_init(&r->remotes_hash, remotes_hash_cmp, NULL, 0);
2780         hashmap_init(&r->branches_hash, branches_hash_cmp, NULL, 0);
2781         return r;
2782 }
2783
2784 void remote_state_clear(struct remote_state *remote_state)
2785 {
2786         int i;
2787
2788         for (i = 0; i < remote_state->remotes_nr; i++)
2789                 remote_clear(remote_state->remotes[i]);
2790         FREE_AND_NULL(remote_state->remotes);
2791         remote_state->remotes_alloc = 0;
2792         remote_state->remotes_nr = 0;
2793
2794         hashmap_clear_and_free(&remote_state->remotes_hash, struct remote, ent);
2795         hashmap_clear_and_free(&remote_state->branches_hash, struct remote, ent);
2796 }
2797
2798 /*
2799  * Returns 1 if it was the last chop before ':'.
2800  */
2801 static int chop_last_dir(char **remoteurl, int is_relative)
2802 {
2803         char *rfind = find_last_dir_sep(*remoteurl);
2804         if (rfind) {
2805                 *rfind = '\0';
2806                 return 0;
2807         }
2808
2809         rfind = strrchr(*remoteurl, ':');
2810         if (rfind) {
2811                 *rfind = '\0';
2812                 return 1;
2813         }
2814
2815         if (is_relative || !strcmp(".", *remoteurl))
2816                 die(_("cannot strip one component off url '%s'"),
2817                         *remoteurl);
2818
2819         free(*remoteurl);
2820         *remoteurl = xstrdup(".");
2821         return 0;
2822 }
2823
2824 char *relative_url(const char *remote_url, const char *url,
2825                    const char *up_path)
2826 {
2827         int is_relative = 0;
2828         int colonsep = 0;
2829         char *out;
2830         char *remoteurl;
2831         struct strbuf sb = STRBUF_INIT;
2832         size_t len;
2833
2834         if (!url_is_local_not_ssh(url) || is_absolute_path(url))
2835                 return xstrdup(url);
2836
2837         len = strlen(remote_url);
2838         if (!len)
2839                 BUG("invalid empty remote_url");
2840
2841         remoteurl = xstrdup(remote_url);
2842         if (is_dir_sep(remoteurl[len-1]))
2843                 remoteurl[len-1] = '\0';
2844
2845         if (!url_is_local_not_ssh(remoteurl) || is_absolute_path(remoteurl))
2846                 is_relative = 0;
2847         else {
2848                 is_relative = 1;
2849                 /*
2850                  * Prepend a './' to ensure all relative
2851                  * remoteurls start with './' or '../'
2852                  */
2853                 if (!starts_with_dot_slash_native(remoteurl) &&
2854                     !starts_with_dot_dot_slash_native(remoteurl)) {
2855                         strbuf_reset(&sb);
2856                         strbuf_addf(&sb, "./%s", remoteurl);
2857                         free(remoteurl);
2858                         remoteurl = strbuf_detach(&sb, NULL);
2859                 }
2860         }
2861         /*
2862          * When the url starts with '../', remove that and the
2863          * last directory in remoteurl.
2864          */
2865         while (*url) {
2866                 if (starts_with_dot_dot_slash_native(url)) {
2867                         url += 3;
2868                         colonsep |= chop_last_dir(&remoteurl, is_relative);
2869                 } else if (starts_with_dot_slash_native(url))
2870                         url += 2;
2871                 else
2872                         break;
2873         }
2874         strbuf_reset(&sb);
2875         strbuf_addf(&sb, "%s%s%s", remoteurl, colonsep ? ":" : "/", url);
2876         if (ends_with(url, "/"))
2877                 strbuf_setlen(&sb, sb.len - 1);
2878         free(remoteurl);
2879
2880         if (starts_with_dot_slash_native(sb.buf))
2881                 out = xstrdup(sb.buf + 2);
2882         else
2883                 out = xstrdup(sb.buf);
2884
2885         if (!up_path || !is_relative) {
2886                 strbuf_release(&sb);
2887                 return out;
2888         }
2889
2890         strbuf_reset(&sb);
2891         strbuf_addf(&sb, "%s%s", up_path, out);
2892         free(out);
2893         return strbuf_detach(&sb, NULL);
2894 }