Sync with 'maint'
[git/gitster.git] / remote.c
blob10104d11e3cba1908cd35f22b54e167755770404
1 #define USE_THE_REPOSITORY_VARIABLE
3 #include "git-compat-util.h"
4 #include "abspath.h"
5 #include "config.h"
6 #include "environment.h"
7 #include "gettext.h"
8 #include "hex.h"
9 #include "remote.h"
10 #include "urlmatch.h"
11 #include "refs.h"
12 #include "refspec.h"
13 #include "object-name.h"
14 #include "object-store-ll.h"
15 #include "path.h"
16 #include "commit.h"
17 #include "diff.h"
18 #include "revision.h"
19 #include "dir.h"
20 #include "setup.h"
21 #include "string-list.h"
22 #include "strvec.h"
23 #include "commit-reach.h"
24 #include "advice.h"
25 #include "connect.h"
26 #include "parse-options.h"
27 #include "transport.h"
29 enum map_direction { FROM_SRC, FROM_DST };
31 struct counted_string {
32 size_t len;
33 const char *s;
36 static int valid_remote(const struct remote *remote)
38 return !!remote->url.nr;
41 static char *alias_url(const char *url, struct rewrites *r)
43 int i, j;
44 struct counted_string *longest;
45 int longest_i;
47 longest = NULL;
48 longest_i = -1;
49 for (i = 0; i < r->rewrite_nr; i++) {
50 if (!r->rewrite[i])
51 continue;
52 for (j = 0; j < r->rewrite[i]->instead_of_nr; j++) {
53 if (starts_with(url, r->rewrite[i]->instead_of[j].s) &&
54 (!longest ||
55 longest->len < r->rewrite[i]->instead_of[j].len)) {
56 longest = &(r->rewrite[i]->instead_of[j]);
57 longest_i = i;
61 if (!longest)
62 return NULL;
64 return xstrfmt("%s%s", r->rewrite[longest_i]->base, url + longest->len);
67 static void add_url(struct remote *remote, const char *url)
69 if (*url)
70 strvec_push(&remote->url, url);
71 else
72 strvec_clear(&remote->url);
75 static void add_pushurl(struct remote *remote, const char *pushurl)
77 if (*pushurl)
78 strvec_push(&remote->pushurl, pushurl);
79 else
80 strvec_clear(&remote->pushurl);
83 static void add_pushurl_alias(struct remote_state *remote_state,
84 struct remote *remote, const char *url)
86 char *alias = alias_url(url, &remote_state->rewrites_push);
87 if (alias)
88 add_pushurl(remote, alias);
89 free(alias);
92 static void add_url_alias(struct remote_state *remote_state,
93 struct remote *remote, const char *url)
95 char *alias = alias_url(url, &remote_state->rewrites);
96 add_url(remote, alias ? alias : url);
97 add_pushurl_alias(remote_state, remote, url);
98 free(alias);
101 struct remotes_hash_key {
102 const char *str;
103 int len;
106 static int remotes_hash_cmp(const void *cmp_data UNUSED,
107 const struct hashmap_entry *eptr,
108 const struct hashmap_entry *entry_or_key,
109 const void *keydata)
111 const struct remote *a, *b;
112 const struct remotes_hash_key *key = keydata;
114 a = container_of(eptr, const struct remote, ent);
115 b = container_of(entry_or_key, const struct remote, ent);
117 if (key)
118 return !!xstrncmpz(a->name, key->str, key->len);
119 else
120 return strcmp(a->name, b->name);
123 static struct remote *make_remote(struct remote_state *remote_state,
124 const char *name, int len)
126 struct remote *ret;
127 struct remotes_hash_key lookup;
128 struct hashmap_entry lookup_entry, *e;
130 if (!len)
131 len = strlen(name);
133 lookup.str = name;
134 lookup.len = len;
135 hashmap_entry_init(&lookup_entry, memhash(name, len));
137 e = hashmap_get(&remote_state->remotes_hash, &lookup_entry, &lookup);
138 if (e)
139 return container_of(e, struct remote, ent);
141 CALLOC_ARRAY(ret, 1);
142 ret->prune = -1; /* unspecified */
143 ret->prune_tags = -1; /* unspecified */
144 ret->name = xstrndup(name, len);
145 refspec_init(&ret->push, REFSPEC_PUSH);
146 refspec_init(&ret->fetch, REFSPEC_FETCH);
147 string_list_init_dup(&ret->server_options);
149 ALLOC_GROW(remote_state->remotes, remote_state->remotes_nr + 1,
150 remote_state->remotes_alloc);
151 remote_state->remotes[remote_state->remotes_nr++] = ret;
153 hashmap_entry_init(&ret->ent, lookup_entry.hash);
154 if (hashmap_put_entry(&remote_state->remotes_hash, ret, ent))
155 BUG("hashmap_put overwrote entry after hashmap_get returned NULL");
156 return ret;
159 static void remote_clear(struct remote *remote)
161 free((char *)remote->name);
162 free((char *)remote->foreign_vcs);
164 strvec_clear(&remote->url);
165 strvec_clear(&remote->pushurl);
167 free((char *)remote->receivepack);
168 free((char *)remote->uploadpack);
169 FREE_AND_NULL(remote->http_proxy);
170 FREE_AND_NULL(remote->http_proxy_authmethod);
171 string_list_clear(&remote->server_options, 0);
174 static void add_merge(struct branch *branch, const char *name)
176 ALLOC_GROW(branch->merge_name, branch->merge_nr + 1,
177 branch->merge_alloc);
178 branch->merge_name[branch->merge_nr++] = name;
181 struct branches_hash_key {
182 const char *str;
183 int len;
186 static int branches_hash_cmp(const void *cmp_data UNUSED,
187 const struct hashmap_entry *eptr,
188 const struct hashmap_entry *entry_or_key,
189 const void *keydata)
191 const struct branch *a, *b;
192 const struct branches_hash_key *key = keydata;
194 a = container_of(eptr, const struct branch, ent);
195 b = container_of(entry_or_key, const struct branch, ent);
197 if (key)
198 return !!xstrncmpz(a->name, key->str, key->len);
199 else
200 return strcmp(a->name, b->name);
203 static struct branch *find_branch(struct remote_state *remote_state,
204 const char *name, size_t len)
206 struct branches_hash_key lookup;
207 struct hashmap_entry lookup_entry, *e;
209 lookup.str = name;
210 lookup.len = len;
211 hashmap_entry_init(&lookup_entry, memhash(name, len));
213 e = hashmap_get(&remote_state->branches_hash, &lookup_entry, &lookup);
214 if (e)
215 return container_of(e, struct branch, ent);
217 return NULL;
220 static void die_on_missing_branch(struct repository *repo,
221 struct branch *branch)
223 /* branch == NULL is always valid because it represents detached HEAD. */
224 if (branch &&
225 branch != find_branch(repo->remote_state, branch->name,
226 strlen(branch->name)))
227 die("branch %s was not found in the repository", branch->name);
230 static struct branch *make_branch(struct remote_state *remote_state,
231 const char *name, size_t len)
233 struct branch *ret;
235 ret = find_branch(remote_state, name, len);
236 if (ret)
237 return ret;
239 CALLOC_ARRAY(ret, 1);
240 ret->name = xstrndup(name, len);
241 ret->refname = xstrfmt("refs/heads/%s", ret->name);
243 hashmap_entry_init(&ret->ent, memhash(name, len));
244 if (hashmap_put_entry(&remote_state->branches_hash, ret, ent))
245 BUG("hashmap_put overwrote entry after hashmap_get returned NULL");
246 return ret;
249 static void branch_release(struct branch *branch)
251 free((char *)branch->name);
252 free((char *)branch->refname);
253 free(branch->remote_name);
254 free(branch->pushremote_name);
255 for (int i = 0; i < branch->merge_nr; i++)
256 refspec_item_clear(branch->merge[i]);
257 free(branch->merge);
260 static struct rewrite *make_rewrite(struct rewrites *r,
261 const char *base, size_t len)
263 struct rewrite *ret;
264 int i;
266 for (i = 0; i < r->rewrite_nr; i++) {
267 if (len == r->rewrite[i]->baselen &&
268 !strncmp(base, r->rewrite[i]->base, len))
269 return r->rewrite[i];
272 ALLOC_GROW(r->rewrite, r->rewrite_nr + 1, r->rewrite_alloc);
273 CALLOC_ARRAY(ret, 1);
274 r->rewrite[r->rewrite_nr++] = ret;
275 ret->base = xstrndup(base, len);
276 ret->baselen = len;
277 return ret;
280 static void rewrites_release(struct rewrites *r)
282 for (int i = 0; i < r->rewrite_nr; i++)
283 free((char *)r->rewrite[i]->base);
284 free(r->rewrite);
285 memset(r, 0, sizeof(*r));
288 static void add_instead_of(struct rewrite *rewrite, const char *instead_of)
290 ALLOC_GROW(rewrite->instead_of, rewrite->instead_of_nr + 1, rewrite->instead_of_alloc);
291 rewrite->instead_of[rewrite->instead_of_nr].s = instead_of;
292 rewrite->instead_of[rewrite->instead_of_nr].len = strlen(instead_of);
293 rewrite->instead_of_nr++;
296 static const char *skip_spaces(const char *s)
298 while (isspace(*s))
299 s++;
300 return s;
303 static void read_remotes_file(struct remote_state *remote_state,
304 struct remote *remote)
306 struct strbuf buf = STRBUF_INIT;
307 FILE *f = fopen_or_warn(git_path("remotes/%s", remote->name), "r");
309 if (!f)
310 return;
311 remote->configured_in_repo = 1;
312 remote->origin = REMOTE_REMOTES;
313 while (strbuf_getline(&buf, f) != EOF) {
314 const char *v;
316 strbuf_rtrim(&buf);
318 if (skip_prefix(buf.buf, "URL:", &v))
319 add_url_alias(remote_state, remote,
320 skip_spaces(v));
321 else if (skip_prefix(buf.buf, "Push:", &v))
322 refspec_append(&remote->push, skip_spaces(v));
323 else if (skip_prefix(buf.buf, "Pull:", &v))
324 refspec_append(&remote->fetch, skip_spaces(v));
326 strbuf_release(&buf);
327 fclose(f);
330 static void read_branches_file(struct remote_state *remote_state,
331 struct remote *remote)
333 char *frag, *to_free = NULL;
334 struct strbuf buf = STRBUF_INIT;
335 FILE *f = fopen_or_warn(git_path("branches/%s", remote->name), "r");
337 if (!f)
338 return;
340 strbuf_getline_lf(&buf, f);
341 fclose(f);
342 strbuf_trim(&buf);
343 if (!buf.len) {
344 strbuf_release(&buf);
345 return;
348 remote->configured_in_repo = 1;
349 remote->origin = REMOTE_BRANCHES;
352 * The branches file would have URL and optionally
353 * #branch specified. The default (or specified) branch is
354 * fetched and stored in the local branch matching the
355 * remote name.
357 frag = strchr(buf.buf, '#');
358 if (frag)
359 *(frag++) = '\0';
360 else
361 frag = to_free = repo_default_branch_name(the_repository, 0);
363 add_url_alias(remote_state, remote, buf.buf);
364 refspec_appendf(&remote->fetch, "refs/heads/%s:refs/heads/%s",
365 frag, remote->name);
368 * Cogito compatible push: push current HEAD to remote #branch
369 * (master if missing)
371 refspec_appendf(&remote->push, "HEAD:refs/heads/%s", frag);
372 remote->fetch_tags = 1; /* always auto-follow */
374 strbuf_release(&buf);
375 free(to_free);
378 static int handle_config(const char *key, const char *value,
379 const struct config_context *ctx, void *cb)
381 const char *name;
382 size_t namelen;
383 const char *subkey;
384 struct remote *remote;
385 struct branch *branch;
386 struct remote_state *remote_state = cb;
387 const struct key_value_info *kvi = ctx->kvi;
389 if (parse_config_key(key, "branch", &name, &namelen, &subkey) >= 0) {
390 /* There is no subsection. */
391 if (!name)
392 return 0;
393 /* There is a subsection, but it is empty. */
394 if (!namelen)
395 return -1;
396 branch = make_branch(remote_state, name, namelen);
397 if (!strcmp(subkey, "remote")) {
398 FREE_AND_NULL(branch->remote_name);
399 return git_config_string(&branch->remote_name, key, value);
400 } else if (!strcmp(subkey, "pushremote")) {
401 FREE_AND_NULL(branch->pushremote_name);
402 return git_config_string(&branch->pushremote_name, key, value);
403 } else if (!strcmp(subkey, "merge")) {
404 if (!value)
405 return config_error_nonbool(key);
406 add_merge(branch, xstrdup(value));
408 return 0;
410 if (parse_config_key(key, "url", &name, &namelen, &subkey) >= 0) {
411 struct rewrite *rewrite;
412 if (!name)
413 return 0;
414 if (!strcmp(subkey, "insteadof")) {
415 if (!value)
416 return config_error_nonbool(key);
417 rewrite = make_rewrite(&remote_state->rewrites, name,
418 namelen);
419 add_instead_of(rewrite, xstrdup(value));
420 } else if (!strcmp(subkey, "pushinsteadof")) {
421 if (!value)
422 return config_error_nonbool(key);
423 rewrite = make_rewrite(&remote_state->rewrites_push,
424 name, namelen);
425 add_instead_of(rewrite, xstrdup(value));
429 if (parse_config_key(key, "remote", &name, &namelen, &subkey) < 0)
430 return 0;
432 /* Handle remote.* variables */
433 if (!name && !strcmp(subkey, "pushdefault")) {
434 FREE_AND_NULL(remote_state->pushremote_name);
435 return git_config_string(&remote_state->pushremote_name, key,
436 value);
439 if (!name)
440 return 0;
441 /* Handle remote.<name>.* variables */
442 if (*name == '/') {
443 warning(_("config remote shorthand cannot begin with '/': %s"),
444 name);
445 return 0;
447 remote = make_remote(remote_state, name, namelen);
448 remote->origin = REMOTE_CONFIG;
449 if (kvi->scope == CONFIG_SCOPE_LOCAL ||
450 kvi->scope == CONFIG_SCOPE_WORKTREE)
451 remote->configured_in_repo = 1;
452 if (!strcmp(subkey, "mirror"))
453 remote->mirror = git_config_bool(key, value);
454 else if (!strcmp(subkey, "skipdefaultupdate"))
455 remote->skip_default_update = git_config_bool(key, value);
456 else if (!strcmp(subkey, "skipfetchall"))
457 remote->skip_default_update = git_config_bool(key, value);
458 else if (!strcmp(subkey, "prune"))
459 remote->prune = git_config_bool(key, value);
460 else if (!strcmp(subkey, "prunetags"))
461 remote->prune_tags = git_config_bool(key, value);
462 else if (!strcmp(subkey, "url")) {
463 if (!value)
464 return config_error_nonbool(key);
465 add_url(remote, value);
466 } else if (!strcmp(subkey, "pushurl")) {
467 if (!value)
468 return config_error_nonbool(key);
469 add_pushurl(remote, value);
470 } else if (!strcmp(subkey, "push")) {
471 char *v;
472 if (git_config_string(&v, key, value))
473 return -1;
474 refspec_append(&remote->push, v);
475 free(v);
476 } else if (!strcmp(subkey, "fetch")) {
477 char *v;
478 if (git_config_string(&v, key, value))
479 return -1;
480 refspec_append(&remote->fetch, v);
481 free(v);
482 } else if (!strcmp(subkey, "receivepack")) {
483 char *v;
484 if (git_config_string(&v, key, value))
485 return -1;
486 if (!remote->receivepack)
487 remote->receivepack = v;
488 else
489 error(_("more than one receivepack given, using the first"));
490 } else if (!strcmp(subkey, "uploadpack")) {
491 char *v;
492 if (git_config_string(&v, key, value))
493 return -1;
494 if (!remote->uploadpack)
495 remote->uploadpack = v;
496 else
497 error(_("more than one uploadpack given, using the first"));
498 } else if (!strcmp(subkey, "tagopt")) {
499 if (!strcmp(value, "--no-tags"))
500 remote->fetch_tags = -1;
501 else if (!strcmp(value, "--tags"))
502 remote->fetch_tags = 2;
503 } else if (!strcmp(subkey, "proxy")) {
504 FREE_AND_NULL(remote->http_proxy);
505 return git_config_string(&remote->http_proxy,
506 key, value);
507 } else if (!strcmp(subkey, "proxyauthmethod")) {
508 FREE_AND_NULL(remote->http_proxy_authmethod);
509 return git_config_string(&remote->http_proxy_authmethod,
510 key, value);
511 } else if (!strcmp(subkey, "vcs")) {
512 FREE_AND_NULL(remote->foreign_vcs);
513 return git_config_string(&remote->foreign_vcs, key, value);
514 } else if (!strcmp(subkey, "serveroption")) {
515 return parse_transport_option(key, value,
516 &remote->server_options);
518 return 0;
521 static void alias_all_urls(struct remote_state *remote_state)
523 int i, j;
524 for (i = 0; i < remote_state->remotes_nr; i++) {
525 int add_pushurl_aliases;
526 if (!remote_state->remotes[i])
527 continue;
528 for (j = 0; j < remote_state->remotes[i]->pushurl.nr; j++) {
529 char *alias = alias_url(remote_state->remotes[i]->pushurl.v[j],
530 &remote_state->rewrites);
531 if (alias)
532 strvec_replace(&remote_state->remotes[i]->pushurl,
533 j, alias);
534 free(alias);
536 add_pushurl_aliases = remote_state->remotes[i]->pushurl.nr == 0;
537 for (j = 0; j < remote_state->remotes[i]->url.nr; j++) {
538 char *alias;
539 if (add_pushurl_aliases)
540 add_pushurl_alias(
541 remote_state, remote_state->remotes[i],
542 remote_state->remotes[i]->url.v[j]);
543 alias = alias_url(remote_state->remotes[i]->url.v[j],
544 &remote_state->rewrites);
545 if (alias)
546 strvec_replace(&remote_state->remotes[i]->url,
547 j, alias);
548 free(alias);
553 static void read_config(struct repository *repo, int early)
555 int flag;
557 if (repo->remote_state->initialized)
558 return;
559 repo->remote_state->initialized = 1;
561 repo->remote_state->current_branch = NULL;
562 if (startup_info->have_repository && !early) {
563 const char *head_ref = refs_resolve_ref_unsafe(
564 get_main_ref_store(repo), "HEAD", 0, NULL, &flag);
565 if (head_ref && (flag & REF_ISSYMREF) &&
566 skip_prefix(head_ref, "refs/heads/", &head_ref)) {
567 repo->remote_state->current_branch = make_branch(
568 repo->remote_state, head_ref, strlen(head_ref));
571 repo_config(repo, handle_config, repo->remote_state);
572 alias_all_urls(repo->remote_state);
575 static int valid_remote_nick(const char *name)
577 if (!name[0] || is_dot_or_dotdot(name))
578 return 0;
580 /* remote nicknames cannot contain slashes */
581 while (*name)
582 if (is_dir_sep(*name++))
583 return 0;
584 return 1;
587 static const char *remotes_remote_for_branch(struct remote_state *remote_state,
588 struct branch *branch,
589 int *explicit)
591 if (branch && branch->remote_name) {
592 if (explicit)
593 *explicit = 1;
594 return branch->remote_name;
596 if (explicit)
597 *explicit = 0;
598 if (remote_state->remotes_nr == 1)
599 return remote_state->remotes[0]->name;
600 return "origin";
603 const char *remote_for_branch(struct branch *branch, int *explicit)
605 read_config(the_repository, 0);
606 die_on_missing_branch(the_repository, branch);
608 return remotes_remote_for_branch(the_repository->remote_state, branch,
609 explicit);
612 static const char *
613 remotes_pushremote_for_branch(struct remote_state *remote_state,
614 struct branch *branch, int *explicit)
616 if (branch && branch->pushremote_name) {
617 if (explicit)
618 *explicit = 1;
619 return branch->pushremote_name;
621 if (remote_state->pushremote_name) {
622 if (explicit)
623 *explicit = 1;
624 return remote_state->pushremote_name;
626 return remotes_remote_for_branch(remote_state, branch, explicit);
629 const char *pushremote_for_branch(struct branch *branch, int *explicit)
631 read_config(the_repository, 0);
632 die_on_missing_branch(the_repository, branch);
634 return remotes_pushremote_for_branch(the_repository->remote_state,
635 branch, explicit);
638 static struct remote *remotes_remote_get(struct remote_state *remote_state,
639 const char *name);
641 char *remote_ref_for_branch(struct branch *branch, int for_push)
643 read_config(the_repository, 0);
644 die_on_missing_branch(the_repository, branch);
646 if (branch) {
647 if (!for_push) {
648 if (branch->merge_nr) {
649 return xstrdup(branch->merge_name[0]);
651 } else {
652 char *dst;
653 const char *remote_name = remotes_pushremote_for_branch(
654 the_repository->remote_state, branch,
655 NULL);
656 struct remote *remote = remotes_remote_get(
657 the_repository->remote_state, remote_name);
659 if (remote && remote->push.nr &&
660 (dst = apply_refspecs(&remote->push,
661 branch->refname))) {
662 return dst;
666 return NULL;
669 static void validate_remote_url(struct remote *remote)
671 int i;
672 const char *value;
673 struct strbuf redacted = STRBUF_INIT;
674 int warn_not_die;
676 if (git_config_get_string_tmp("transfer.credentialsinurl", &value))
677 return;
679 if (!strcmp("warn", value))
680 warn_not_die = 1;
681 else if (!strcmp("die", value))
682 warn_not_die = 0;
683 else if (!strcmp("allow", value))
684 return;
685 else
686 die(_("unrecognized value transfer.credentialsInUrl: '%s'"), value);
688 for (i = 0; i < remote->url.nr; i++) {
689 struct url_info url_info = { 0 };
691 if (!url_normalize(remote->url.v[i], &url_info) ||
692 !url_info.passwd_off)
693 goto loop_cleanup;
695 strbuf_reset(&redacted);
696 strbuf_add(&redacted, url_info.url, url_info.passwd_off);
697 strbuf_addstr(&redacted, "<redacted>");
698 strbuf_addstr(&redacted,
699 url_info.url + url_info.passwd_off + url_info.passwd_len);
701 if (warn_not_die)
702 warning(_("URL '%s' uses plaintext credentials"), redacted.buf);
703 else
704 die(_("URL '%s' uses plaintext credentials"), redacted.buf);
706 loop_cleanup:
707 free(url_info.url);
710 strbuf_release(&redacted);
713 static struct remote *
714 remotes_remote_get_1(struct remote_state *remote_state, const char *name,
715 const char *(*get_default)(struct remote_state *,
716 struct branch *, int *))
718 struct remote *ret;
719 int name_given = 0;
721 if (name)
722 name_given = 1;
723 else
724 name = get_default(remote_state, remote_state->current_branch,
725 &name_given);
727 ret = make_remote(remote_state, name, 0);
728 if (valid_remote_nick(name) && have_git_dir()) {
729 if (!valid_remote(ret))
730 read_remotes_file(remote_state, ret);
731 if (!valid_remote(ret))
732 read_branches_file(remote_state, ret);
734 if (name_given && !valid_remote(ret))
735 add_url_alias(remote_state, ret, name);
736 if (!valid_remote(ret))
737 return NULL;
739 validate_remote_url(ret);
741 return ret;
744 static inline struct remote *
745 remotes_remote_get(struct remote_state *remote_state, const char *name)
747 return remotes_remote_get_1(remote_state, name,
748 remotes_remote_for_branch);
751 struct remote *remote_get(const char *name)
753 read_config(the_repository, 0);
754 return remotes_remote_get(the_repository->remote_state, name);
757 struct remote *remote_get_early(const char *name)
759 read_config(the_repository, 1);
760 return remotes_remote_get(the_repository->remote_state, name);
763 static inline struct remote *
764 remotes_pushremote_get(struct remote_state *remote_state, const char *name)
766 return remotes_remote_get_1(remote_state, name,
767 remotes_pushremote_for_branch);
770 struct remote *pushremote_get(const char *name)
772 read_config(the_repository, 0);
773 return remotes_pushremote_get(the_repository->remote_state, name);
776 int remote_is_configured(struct remote *remote, int in_repo)
778 if (!remote)
779 return 0;
780 if (in_repo)
781 return remote->configured_in_repo;
782 return !!remote->origin;
785 int for_each_remote(each_remote_fn fn, void *priv)
787 int i, result = 0;
788 read_config(the_repository, 0);
789 for (i = 0; i < the_repository->remote_state->remotes_nr && !result;
790 i++) {
791 struct remote *remote =
792 the_repository->remote_state->remotes[i];
793 if (!remote)
794 continue;
795 result = fn(remote, priv);
797 return result;
800 static void handle_duplicate(struct ref *ref1, struct ref *ref2)
802 if (strcmp(ref1->name, ref2->name)) {
803 if (ref1->fetch_head_status != FETCH_HEAD_IGNORE &&
804 ref2->fetch_head_status != FETCH_HEAD_IGNORE) {
805 die(_("Cannot fetch both %s and %s to %s"),
806 ref1->name, ref2->name, ref2->peer_ref->name);
807 } else if (ref1->fetch_head_status != FETCH_HEAD_IGNORE &&
808 ref2->fetch_head_status == FETCH_HEAD_IGNORE) {
809 warning(_("%s usually tracks %s, not %s"),
810 ref2->peer_ref->name, ref2->name, ref1->name);
811 } else if (ref1->fetch_head_status == FETCH_HEAD_IGNORE &&
812 ref2->fetch_head_status == FETCH_HEAD_IGNORE) {
813 die(_("%s tracks both %s and %s"),
814 ref2->peer_ref->name, ref1->name, ref2->name);
815 } else {
817 * This last possibility doesn't occur because
818 * FETCH_HEAD_IGNORE entries always appear at
819 * the end of the list.
821 BUG("Internal error");
824 free(ref2->peer_ref);
825 free(ref2);
828 struct ref *ref_remove_duplicates(struct ref *ref_map)
830 struct string_list refs = STRING_LIST_INIT_NODUP;
831 struct ref *retval = NULL;
832 struct ref **p = &retval;
834 while (ref_map) {
835 struct ref *ref = ref_map;
837 ref_map = ref_map->next;
838 ref->next = NULL;
840 if (!ref->peer_ref) {
841 *p = ref;
842 p = &ref->next;
843 } else {
844 struct string_list_item *item =
845 string_list_insert(&refs, ref->peer_ref->name);
847 if (item->util) {
848 /* Entry already existed */
849 handle_duplicate((struct ref *)item->util, ref);
850 } else {
851 *p = ref;
852 p = &ref->next;
853 item->util = ref;
858 string_list_clear(&refs, 0);
859 return retval;
862 int remote_has_url(struct remote *remote, const char *url)
864 int i;
865 for (i = 0; i < remote->url.nr; i++) {
866 if (!strcmp(remote->url.v[i], url))
867 return 1;
869 return 0;
872 struct strvec *push_url_of_remote(struct remote *remote)
874 return remote->pushurl.nr ? &remote->pushurl : &remote->url;
877 void ref_push_report_free(struct ref_push_report *report)
879 while (report) {
880 struct ref_push_report *next = report->next;
882 free(report->ref_name);
883 free(report->old_oid);
884 free(report->new_oid);
885 free(report);
887 report = next;
891 static int match_name_with_pattern(const char *key, const char *name,
892 const char *value, char **result)
894 const char *kstar = strchr(key, '*');
895 size_t klen;
896 size_t ksuffixlen;
897 size_t namelen;
898 int ret;
899 if (!kstar)
900 die(_("key '%s' of pattern had no '*'"), key);
901 klen = kstar - key;
902 ksuffixlen = strlen(kstar + 1);
903 namelen = strlen(name);
904 ret = !strncmp(name, key, klen) && namelen >= klen + ksuffixlen &&
905 !memcmp(name + namelen - ksuffixlen, kstar + 1, ksuffixlen);
906 if (ret && value) {
907 struct strbuf sb = STRBUF_INIT;
908 const char *vstar = strchr(value, '*');
909 if (!vstar)
910 die(_("value '%s' of pattern has no '*'"), value);
911 strbuf_add(&sb, value, vstar - value);
912 strbuf_add(&sb, name + klen, namelen - klen - ksuffixlen);
913 strbuf_addstr(&sb, vstar + 1);
914 *result = strbuf_detach(&sb, NULL);
916 return ret;
919 static int refspec_match(const struct refspec_item *refspec,
920 const char *name)
922 if (refspec->pattern)
923 return match_name_with_pattern(refspec->src, name, NULL, NULL);
925 return !strcmp(refspec->src, name);
928 int omit_name_by_refspec(const char *name, struct refspec *rs)
930 int i;
932 for (i = 0; i < rs->nr; i++) {
933 if (rs->items[i].negative && refspec_match(&rs->items[i], name))
934 return 1;
936 return 0;
939 struct ref *apply_negative_refspecs(struct ref *ref_map, struct refspec *rs)
941 struct ref **tail;
943 for (tail = &ref_map; *tail; ) {
944 struct ref *ref = *tail;
946 if (omit_name_by_refspec(ref->name, rs)) {
947 *tail = ref->next;
948 free(ref->peer_ref);
949 free(ref);
950 } else
951 tail = &ref->next;
954 return ref_map;
957 static int query_matches_negative_refspec(struct refspec *rs, struct refspec_item *query)
959 int i, matched_negative = 0;
960 int find_src = !query->src;
961 struct string_list reversed = STRING_LIST_INIT_DUP;
962 const char *needle = find_src ? query->dst : query->src;
965 * Check whether the queried ref matches any negative refpsec. If so,
966 * then we should ultimately treat this as not matching the query at
967 * all.
969 * Note that negative refspecs always match the source, but the query
970 * item uses the destination. To handle this, we apply pattern
971 * refspecs in reverse to figure out if the query source matches any
972 * of the negative refspecs.
974 * The first loop finds and expands all positive refspecs
975 * matched by the queried ref.
977 * The second loop checks if any of the results of the first loop
978 * match any negative refspec.
980 for (i = 0; i < rs->nr; i++) {
981 struct refspec_item *refspec = &rs->items[i];
982 char *expn_name;
984 if (refspec->negative)
985 continue;
987 /* Note the reversal of src and dst */
988 if (refspec->pattern) {
989 const char *key = refspec->dst ? refspec->dst : refspec->src;
990 const char *value = refspec->src;
992 if (match_name_with_pattern(key, needle, value, &expn_name))
993 string_list_append_nodup(&reversed, expn_name);
994 } else if (refspec->matching) {
995 /* For the special matching refspec, any query should match */
996 string_list_append(&reversed, needle);
997 } else if (!refspec->src) {
998 BUG("refspec->src should not be null here");
999 } else if (!strcmp(needle, refspec->src)) {
1000 string_list_append(&reversed, refspec->src);
1004 for (i = 0; !matched_negative && i < reversed.nr; i++) {
1005 if (omit_name_by_refspec(reversed.items[i].string, rs))
1006 matched_negative = 1;
1009 string_list_clear(&reversed, 0);
1011 return matched_negative;
1014 static void query_refspecs_multiple(struct refspec *rs,
1015 struct refspec_item *query,
1016 struct string_list *results)
1018 int i;
1019 int find_src = !query->src;
1021 if (find_src && !query->dst)
1022 BUG("query_refspecs_multiple: need either src or dst");
1024 if (query_matches_negative_refspec(rs, query))
1025 return;
1027 for (i = 0; i < rs->nr; i++) {
1028 struct refspec_item *refspec = &rs->items[i];
1029 const char *key = find_src ? refspec->dst : refspec->src;
1030 const char *value = find_src ? refspec->src : refspec->dst;
1031 const char *needle = find_src ? query->dst : query->src;
1032 char **result = find_src ? &query->src : &query->dst;
1034 if (!refspec->dst || refspec->negative)
1035 continue;
1036 if (refspec->pattern) {
1037 if (match_name_with_pattern(key, needle, value, result))
1038 string_list_append_nodup(results, *result);
1039 } else if (!strcmp(needle, key)) {
1040 string_list_append(results, value);
1045 int query_refspecs(struct refspec *rs, struct refspec_item *query)
1047 int i;
1048 int find_src = !query->src;
1049 const char *needle = find_src ? query->dst : query->src;
1050 char **result = find_src ? &query->src : &query->dst;
1052 if (find_src && !query->dst)
1053 BUG("query_refspecs: need either src or dst");
1055 if (query_matches_negative_refspec(rs, query))
1056 return -1;
1058 for (i = 0; i < rs->nr; i++) {
1059 struct refspec_item *refspec = &rs->items[i];
1060 const char *key = find_src ? refspec->dst : refspec->src;
1061 const char *value = find_src ? refspec->src : refspec->dst;
1063 if (!refspec->dst || refspec->negative)
1064 continue;
1065 if (refspec->pattern) {
1066 if (match_name_with_pattern(key, needle, value, result)) {
1067 query->force = refspec->force;
1068 return 0;
1070 } else if (!strcmp(needle, key)) {
1071 *result = xstrdup(value);
1072 query->force = refspec->force;
1073 return 0;
1076 return -1;
1079 char *apply_refspecs(struct refspec *rs, const char *name)
1081 struct refspec_item query;
1083 memset(&query, 0, sizeof(struct refspec_item));
1084 query.src = (char *)name;
1086 if (query_refspecs(rs, &query))
1087 return NULL;
1089 return query.dst;
1092 int remote_find_tracking(struct remote *remote, struct refspec_item *refspec)
1094 return query_refspecs(&remote->fetch, refspec);
1097 static struct ref *alloc_ref_with_prefix(const char *prefix, size_t prefixlen,
1098 const char *name)
1100 size_t len = strlen(name);
1101 struct ref *ref = xcalloc(1, st_add4(sizeof(*ref), prefixlen, len, 1));
1102 memcpy(ref->name, prefix, prefixlen);
1103 memcpy(ref->name + prefixlen, name, len);
1104 return ref;
1107 struct ref *alloc_ref(const char *name)
1109 return alloc_ref_with_prefix("", 0, name);
1112 struct ref *copy_ref(const struct ref *ref)
1114 struct ref *cpy;
1115 size_t len;
1116 if (!ref)
1117 return NULL;
1118 len = st_add3(sizeof(struct ref), strlen(ref->name), 1);
1119 cpy = xmalloc(len);
1120 memcpy(cpy, ref, len);
1121 cpy->next = NULL;
1122 cpy->symref = xstrdup_or_null(ref->symref);
1123 cpy->remote_status = xstrdup_or_null(ref->remote_status);
1124 cpy->peer_ref = copy_ref(ref->peer_ref);
1125 return cpy;
1128 struct ref *copy_ref_list(const struct ref *ref)
1130 struct ref *ret = NULL;
1131 struct ref **tail = &ret;
1132 while (ref) {
1133 *tail = copy_ref(ref);
1134 ref = ref->next;
1135 tail = &((*tail)->next);
1137 return ret;
1140 void free_one_ref(struct ref *ref)
1142 if (!ref)
1143 return;
1144 free_one_ref(ref->peer_ref);
1145 ref_push_report_free(ref->report);
1146 free(ref->remote_status);
1147 free(ref->tracking_ref);
1148 free(ref->symref);
1149 free(ref);
1152 void free_refs(struct ref *ref)
1154 struct ref *next;
1155 while (ref) {
1156 next = ref->next;
1157 free_one_ref(ref);
1158 ref = next;
1162 int count_refspec_match(const char *pattern,
1163 struct ref *refs,
1164 struct ref **matched_ref)
1166 int patlen = strlen(pattern);
1167 struct ref *matched_weak = NULL;
1168 struct ref *matched = NULL;
1169 int weak_match = 0;
1170 int match = 0;
1172 for (weak_match = match = 0; refs; refs = refs->next) {
1173 char *name = refs->name;
1174 int namelen = strlen(name);
1176 if (!refname_match(pattern, name))
1177 continue;
1179 /* A match is "weak" if it is with refs outside
1180 * heads or tags, and did not specify the pattern
1181 * in full (e.g. "refs/remotes/origin/master") or at
1182 * least from the toplevel (e.g. "remotes/origin/master");
1183 * otherwise "git push $URL master" would result in
1184 * ambiguity between remotes/origin/master and heads/master
1185 * at the remote site.
1187 if (namelen != patlen &&
1188 patlen != namelen - 5 &&
1189 !starts_with(name, "refs/heads/") &&
1190 !starts_with(name, "refs/tags/")) {
1191 /* We want to catch the case where only weak
1192 * matches are found and there are multiple
1193 * matches, and where more than one strong
1194 * matches are found, as ambiguous. One
1195 * strong match with zero or more weak matches
1196 * are acceptable as a unique match.
1198 matched_weak = refs;
1199 weak_match++;
1201 else {
1202 matched = refs;
1203 match++;
1206 if (!matched) {
1207 if (matched_ref)
1208 *matched_ref = matched_weak;
1209 return weak_match;
1211 else {
1212 if (matched_ref)
1213 *matched_ref = matched;
1214 return match;
1218 static void tail_link_ref(struct ref *ref, struct ref ***tail)
1220 **tail = ref;
1221 while (ref->next)
1222 ref = ref->next;
1223 *tail = &ref->next;
1226 static struct ref *alloc_delete_ref(void)
1228 struct ref *ref = alloc_ref("(delete)");
1229 oidclr(&ref->new_oid, the_repository->hash_algo);
1230 return ref;
1233 static int try_explicit_object_name(const char *name,
1234 struct ref **match)
1236 struct object_id oid;
1238 if (!*name) {
1239 if (match)
1240 *match = alloc_delete_ref();
1241 return 0;
1244 if (repo_get_oid(the_repository, name, &oid))
1245 return -1;
1247 if (match) {
1248 *match = alloc_ref(name);
1249 oidcpy(&(*match)->new_oid, &oid);
1251 return 0;
1254 static struct ref *make_linked_ref(const char *name, struct ref ***tail)
1256 struct ref *ret = alloc_ref(name);
1257 tail_link_ref(ret, tail);
1258 return ret;
1261 static char *guess_ref(const char *name, struct ref *peer)
1263 struct strbuf buf = STRBUF_INIT;
1265 const char *r = refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
1266 peer->name,
1267 RESOLVE_REF_READING,
1268 NULL, NULL);
1269 if (!r)
1270 return NULL;
1272 if (starts_with(r, "refs/heads/")) {
1273 strbuf_addstr(&buf, "refs/heads/");
1274 } else if (starts_with(r, "refs/tags/")) {
1275 strbuf_addstr(&buf, "refs/tags/");
1276 } else {
1277 return NULL;
1280 strbuf_addstr(&buf, name);
1281 return strbuf_detach(&buf, NULL);
1284 static int match_explicit_lhs(struct ref *src,
1285 struct refspec_item *rs,
1286 struct ref **match,
1287 int *allocated_match)
1289 switch (count_refspec_match(rs->src, src, match)) {
1290 case 1:
1291 if (allocated_match)
1292 *allocated_match = 0;
1293 return 0;
1294 case 0:
1295 /* The source could be in the get_sha1() format
1296 * not a reference name. :refs/other is a
1297 * way to delete 'other' ref at the remote end.
1299 if (try_explicit_object_name(rs->src, match) < 0)
1300 return error(_("src refspec %s does not match any"), rs->src);
1301 if (allocated_match)
1302 *allocated_match = 1;
1303 return 0;
1304 default:
1305 return error(_("src refspec %s matches more than one"), rs->src);
1309 static void show_push_unqualified_ref_name_error(const char *dst_value,
1310 const char *matched_src_name)
1312 struct object_id oid;
1313 enum object_type type;
1316 * TRANSLATORS: "matches '%s'%" is the <dst> part of "git push
1317 * <remote> <src>:<dst>" push, and "being pushed ('%s')" is
1318 * the <src>.
1320 error(_("The destination you provided is not a full refname (i.e.,\n"
1321 "starting with \"refs/\"). We tried to guess what you meant by:\n"
1322 "\n"
1323 "- Looking for a ref that matches '%s' on the remote side.\n"
1324 "- Checking if the <src> being pushed ('%s')\n"
1325 " is a ref in \"refs/{heads,tags}/\". If so we add a corresponding\n"
1326 " refs/{heads,tags}/ prefix on the remote side.\n"
1327 "\n"
1328 "Neither worked, so we gave up. You must fully qualify the ref."),
1329 dst_value, matched_src_name);
1331 if (!advice_enabled(ADVICE_PUSH_UNQUALIFIED_REF_NAME))
1332 return;
1334 if (repo_get_oid(the_repository, matched_src_name, &oid))
1335 BUG("'%s' is not a valid object, "
1336 "match_explicit_lhs() should catch this!",
1337 matched_src_name);
1338 type = oid_object_info(the_repository, &oid, NULL);
1339 if (type == OBJ_COMMIT) {
1340 advise(_("The <src> part of the refspec is a commit object.\n"
1341 "Did you mean to create a new branch by pushing to\n"
1342 "'%s:refs/heads/%s'?"),
1343 matched_src_name, dst_value);
1344 } else if (type == OBJ_TAG) {
1345 advise(_("The <src> part of the refspec is a tag object.\n"
1346 "Did you mean to create a new tag by pushing to\n"
1347 "'%s:refs/tags/%s'?"),
1348 matched_src_name, dst_value);
1349 } else if (type == OBJ_TREE) {
1350 advise(_("The <src> part of the refspec is a tree object.\n"
1351 "Did you mean to tag a new tree by pushing to\n"
1352 "'%s:refs/tags/%s'?"),
1353 matched_src_name, dst_value);
1354 } else if (type == OBJ_BLOB) {
1355 advise(_("The <src> part of the refspec is a blob object.\n"
1356 "Did you mean to tag a new blob by pushing to\n"
1357 "'%s:refs/tags/%s'?"),
1358 matched_src_name, dst_value);
1359 } else {
1360 BUG("'%s' should be commit/tag/tree/blob, is '%d'",
1361 matched_src_name, type);
1365 static int match_explicit(struct ref *src, struct ref *dst,
1366 struct ref ***dst_tail,
1367 struct refspec_item *rs)
1369 struct ref *matched_src = NULL, *matched_dst = NULL;
1370 int allocated_src = 0, ret;
1372 const char *dst_value = rs->dst;
1373 char *dst_guess;
1375 if (rs->pattern || rs->matching || rs->negative) {
1376 ret = 0;
1377 goto out;
1380 if (match_explicit_lhs(src, rs, &matched_src, &allocated_src) < 0) {
1381 ret = -1;
1382 goto out;
1385 if (!dst_value) {
1386 int flag;
1388 dst_value = refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
1389 matched_src->name,
1390 RESOLVE_REF_READING,
1391 NULL, &flag);
1392 if (!dst_value ||
1393 ((flag & REF_ISSYMREF) &&
1394 !starts_with(dst_value, "refs/heads/")))
1395 die(_("%s cannot be resolved to branch"),
1396 matched_src->name);
1399 switch (count_refspec_match(dst_value, dst, &matched_dst)) {
1400 case 1:
1401 break;
1402 case 0:
1403 if (starts_with(dst_value, "refs/")) {
1404 matched_dst = make_linked_ref(dst_value, dst_tail);
1405 } else if (is_null_oid(&matched_src->new_oid)) {
1406 error(_("unable to delete '%s': remote ref does not exist"),
1407 dst_value);
1408 } else if ((dst_guess = guess_ref(dst_value, matched_src))) {
1409 matched_dst = make_linked_ref(dst_guess, dst_tail);
1410 free(dst_guess);
1411 } else {
1412 show_push_unqualified_ref_name_error(dst_value,
1413 matched_src->name);
1415 break;
1416 default:
1417 matched_dst = NULL;
1418 error(_("dst refspec %s matches more than one"),
1419 dst_value);
1420 break;
1423 if (!matched_dst) {
1424 ret = -1;
1425 goto out;
1428 if (matched_dst->peer_ref) {
1429 ret = error(_("dst ref %s receives from more than one src"),
1430 matched_dst->name);
1431 goto out;
1432 } else {
1433 matched_dst->peer_ref = allocated_src ?
1434 matched_src :
1435 copy_ref(matched_src);
1436 matched_dst->force = rs->force;
1437 matched_src = NULL;
1440 ret = 0;
1442 out:
1443 if (allocated_src)
1444 free_one_ref(matched_src);
1445 return ret;
1448 static int match_explicit_refs(struct ref *src, struct ref *dst,
1449 struct ref ***dst_tail, struct refspec *rs)
1451 int i, errs;
1452 for (i = errs = 0; i < rs->nr; i++)
1453 errs += match_explicit(src, dst, dst_tail, &rs->items[i]);
1454 return errs;
1457 static char *get_ref_match(const struct refspec *rs, const struct ref *ref,
1458 int send_mirror, int direction,
1459 const struct refspec_item **ret_pat)
1461 const struct refspec_item *pat;
1462 char *name;
1463 int i;
1464 int matching_refs = -1;
1465 for (i = 0; i < rs->nr; i++) {
1466 const struct refspec_item *item = &rs->items[i];
1468 if (item->negative)
1469 continue;
1471 if (item->matching &&
1472 (matching_refs == -1 || item->force)) {
1473 matching_refs = i;
1474 continue;
1477 if (item->pattern) {
1478 const char *dst_side = item->dst ? item->dst : item->src;
1479 int match;
1480 if (direction == FROM_SRC)
1481 match = match_name_with_pattern(item->src, ref->name, dst_side, &name);
1482 else
1483 match = match_name_with_pattern(dst_side, ref->name, item->src, &name);
1484 if (match) {
1485 matching_refs = i;
1486 break;
1490 if (matching_refs == -1)
1491 return NULL;
1493 pat = &rs->items[matching_refs];
1494 if (pat->matching) {
1496 * "matching refs"; traditionally we pushed everything
1497 * including refs outside refs/heads/ hierarchy, but
1498 * that does not make much sense these days.
1500 if (!send_mirror && !starts_with(ref->name, "refs/heads/"))
1501 return NULL;
1502 name = xstrdup(ref->name);
1504 if (ret_pat)
1505 *ret_pat = pat;
1506 return name;
1509 static struct ref **tail_ref(struct ref **head)
1511 struct ref **tail = head;
1512 while (*tail)
1513 tail = &((*tail)->next);
1514 return tail;
1517 struct tips {
1518 struct commit **tip;
1519 int nr, alloc;
1522 static void add_to_tips(struct tips *tips, const struct object_id *oid)
1524 struct commit *commit;
1526 if (is_null_oid(oid))
1527 return;
1528 commit = lookup_commit_reference_gently(the_repository, oid, 1);
1529 if (!commit || (commit->object.flags & TMP_MARK))
1530 return;
1531 commit->object.flags |= TMP_MARK;
1532 ALLOC_GROW(tips->tip, tips->nr + 1, tips->alloc);
1533 tips->tip[tips->nr++] = commit;
1536 static void add_missing_tags(struct ref *src, struct ref **dst, struct ref ***dst_tail)
1538 struct string_list dst_tag = STRING_LIST_INIT_NODUP;
1539 struct string_list src_tag = STRING_LIST_INIT_NODUP;
1540 struct string_list_item *item;
1541 struct ref *ref;
1542 struct tips sent_tips;
1545 * Collect everything we know they would have at the end of
1546 * this push, and collect all tags they have.
1548 memset(&sent_tips, 0, sizeof(sent_tips));
1549 for (ref = *dst; ref; ref = ref->next) {
1550 if (ref->peer_ref &&
1551 !is_null_oid(&ref->peer_ref->new_oid))
1552 add_to_tips(&sent_tips, &ref->peer_ref->new_oid);
1553 else
1554 add_to_tips(&sent_tips, &ref->old_oid);
1555 if (starts_with(ref->name, "refs/tags/"))
1556 string_list_append(&dst_tag, ref->name);
1558 clear_commit_marks_many(sent_tips.nr, sent_tips.tip, TMP_MARK);
1560 string_list_sort(&dst_tag);
1562 /* Collect tags they do not have. */
1563 for (ref = src; ref; ref = ref->next) {
1564 if (!starts_with(ref->name, "refs/tags/"))
1565 continue; /* not a tag */
1566 if (string_list_has_string(&dst_tag, ref->name))
1567 continue; /* they already have it */
1568 if (oid_object_info(the_repository, &ref->new_oid, NULL) != OBJ_TAG)
1569 continue; /* be conservative */
1570 item = string_list_append(&src_tag, ref->name);
1571 item->util = ref;
1573 string_list_clear(&dst_tag, 0);
1576 * At this point, src_tag lists tags that are missing from
1577 * dst, and sent_tips lists the tips we are pushing or those
1578 * that we know they already have. An element in the src_tag
1579 * that is an ancestor of any of the sent_tips needs to be
1580 * sent to the other side.
1582 if (sent_tips.nr) {
1583 const int reachable_flag = 1;
1584 struct commit_list *found_commits;
1585 struct commit **src_commits;
1586 int nr_src_commits = 0, alloc_src_commits = 16;
1587 ALLOC_ARRAY(src_commits, alloc_src_commits);
1589 for_each_string_list_item(item, &src_tag) {
1590 struct ref *ref = item->util;
1591 struct commit *commit;
1593 if (is_null_oid(&ref->new_oid))
1594 continue;
1595 commit = lookup_commit_reference_gently(the_repository,
1596 &ref->new_oid,
1598 if (!commit)
1599 /* not pushing a commit, which is not an error */
1600 continue;
1602 ALLOC_GROW(src_commits, nr_src_commits + 1, alloc_src_commits);
1603 src_commits[nr_src_commits++] = commit;
1606 found_commits = get_reachable_subset(sent_tips.tip, sent_tips.nr,
1607 src_commits, nr_src_commits,
1608 reachable_flag);
1610 for_each_string_list_item(item, &src_tag) {
1611 struct ref *dst_ref;
1612 struct ref *ref = item->util;
1613 struct commit *commit;
1615 if (is_null_oid(&ref->new_oid))
1616 continue;
1617 commit = lookup_commit_reference_gently(the_repository,
1618 &ref->new_oid,
1620 if (!commit)
1621 /* not pushing a commit, which is not an error */
1622 continue;
1625 * Is this tag, which they do not have, reachable from
1626 * any of the commits we are sending?
1628 if (!(commit->object.flags & reachable_flag))
1629 continue;
1631 /* Add it in */
1632 dst_ref = make_linked_ref(ref->name, dst_tail);
1633 oidcpy(&dst_ref->new_oid, &ref->new_oid);
1634 dst_ref->peer_ref = copy_ref(ref);
1637 clear_commit_marks_many(nr_src_commits, src_commits, reachable_flag);
1638 free(src_commits);
1639 free_commit_list(found_commits);
1642 string_list_clear(&src_tag, 0);
1643 free(sent_tips.tip);
1646 struct ref *find_ref_by_name(const struct ref *list, const char *name)
1648 for ( ; list; list = list->next)
1649 if (!strcmp(list->name, name))
1650 return (struct ref *)list;
1651 return NULL;
1654 static void prepare_ref_index(struct string_list *ref_index, struct ref *ref)
1656 for ( ; ref; ref = ref->next)
1657 string_list_append_nodup(ref_index, ref->name)->util = ref;
1659 string_list_sort(ref_index);
1663 * Given only the set of local refs, sanity-check the set of push
1664 * refspecs. We can't catch all errors that match_push_refs would,
1665 * but we can catch some errors early before even talking to the
1666 * remote side.
1668 int check_push_refs(struct ref *src, struct refspec *rs)
1670 int ret = 0;
1671 int i;
1673 for (i = 0; i < rs->nr; i++) {
1674 struct refspec_item *item = &rs->items[i];
1676 if (item->pattern || item->matching || item->negative)
1677 continue;
1679 ret |= match_explicit_lhs(src, item, NULL, NULL);
1682 return ret;
1686 * Given the set of refs the local repository has, the set of refs the
1687 * remote repository has, and the refspec used for push, determine
1688 * what remote refs we will update and with what value by setting
1689 * peer_ref (which object is being pushed) and force (if the push is
1690 * forced) in elements of "dst". The function may add new elements to
1691 * dst (e.g. pushing to a new branch, done in match_explicit_refs).
1693 int match_push_refs(struct ref *src, struct ref **dst,
1694 struct refspec *rs, int flags)
1696 int send_all = flags & MATCH_REFS_ALL;
1697 int send_mirror = flags & MATCH_REFS_MIRROR;
1698 int send_prune = flags & MATCH_REFS_PRUNE;
1699 int errs;
1700 struct ref *ref, **dst_tail = tail_ref(dst);
1701 struct string_list dst_ref_index = STRING_LIST_INIT_NODUP;
1703 /* If no refspec is provided, use the default ":" */
1704 if (!rs->nr)
1705 refspec_append(rs, ":");
1707 errs = match_explicit_refs(src, *dst, &dst_tail, rs);
1709 /* pick the remainder */
1710 for (ref = src; ref; ref = ref->next) {
1711 struct string_list_item *dst_item;
1712 struct ref *dst_peer;
1713 const struct refspec_item *pat = NULL;
1714 char *dst_name;
1716 dst_name = get_ref_match(rs, ref, send_mirror, FROM_SRC, &pat);
1717 if (!dst_name)
1718 continue;
1720 if (!dst_ref_index.nr)
1721 prepare_ref_index(&dst_ref_index, *dst);
1723 dst_item = string_list_lookup(&dst_ref_index, dst_name);
1724 dst_peer = dst_item ? dst_item->util : NULL;
1725 if (dst_peer) {
1726 if (dst_peer->peer_ref)
1727 /* We're already sending something to this ref. */
1728 goto free_name;
1729 } else {
1730 if (pat->matching && !(send_all || send_mirror))
1732 * Remote doesn't have it, and we have no
1733 * explicit pattern, and we don't have
1734 * --all or --mirror.
1736 goto free_name;
1738 /* Create a new one and link it */
1739 dst_peer = make_linked_ref(dst_name, &dst_tail);
1740 oidcpy(&dst_peer->new_oid, &ref->new_oid);
1741 string_list_insert(&dst_ref_index,
1742 dst_peer->name)->util = dst_peer;
1744 dst_peer->peer_ref = copy_ref(ref);
1745 dst_peer->force = pat->force;
1746 free_name:
1747 free(dst_name);
1750 string_list_clear(&dst_ref_index, 0);
1752 if (flags & MATCH_REFS_FOLLOW_TAGS)
1753 add_missing_tags(src, dst, &dst_tail);
1755 if (send_prune) {
1756 struct string_list src_ref_index = STRING_LIST_INIT_NODUP;
1757 /* check for missing refs on the remote */
1758 for (ref = *dst; ref; ref = ref->next) {
1759 char *src_name;
1761 if (ref->peer_ref)
1762 /* We're already sending something to this ref. */
1763 continue;
1765 src_name = get_ref_match(rs, ref, send_mirror, FROM_DST, NULL);
1766 if (src_name) {
1767 if (!src_ref_index.nr)
1768 prepare_ref_index(&src_ref_index, src);
1769 if (!string_list_has_string(&src_ref_index,
1770 src_name))
1771 ref->peer_ref = alloc_delete_ref();
1772 free(src_name);
1775 string_list_clear(&src_ref_index, 0);
1778 *dst = apply_negative_refspecs(*dst, rs);
1780 if (errs)
1781 return -1;
1782 return 0;
1785 void set_ref_status_for_push(struct ref *remote_refs, int send_mirror,
1786 int force_update)
1788 struct ref *ref;
1790 for (ref = remote_refs; ref; ref = ref->next) {
1791 int force_ref_update = ref->force || force_update;
1792 int reject_reason = 0;
1794 if (ref->peer_ref)
1795 oidcpy(&ref->new_oid, &ref->peer_ref->new_oid);
1796 else if (!send_mirror)
1797 continue;
1799 ref->deletion = is_null_oid(&ref->new_oid);
1800 if (!ref->deletion &&
1801 oideq(&ref->old_oid, &ref->new_oid)) {
1802 ref->status = REF_STATUS_UPTODATE;
1803 continue;
1807 * If the remote ref has moved and is now different
1808 * from what we expect, reject any push.
1810 * It also is an error if the user told us to check
1811 * with the remote-tracking branch to find the value
1812 * to expect, but we did not have such a tracking
1813 * branch.
1815 * If the tip of the remote-tracking ref is unreachable
1816 * from any reflog entry of its local ref indicating a
1817 * possible update since checkout; reject the push.
1819 if (ref->expect_old_sha1) {
1820 if (!oideq(&ref->old_oid, &ref->old_oid_expect))
1821 reject_reason = REF_STATUS_REJECT_STALE;
1822 else if (ref->check_reachable && ref->unreachable)
1823 reject_reason =
1824 REF_STATUS_REJECT_REMOTE_UPDATED;
1825 else
1827 * If the ref isn't stale, and is reachable
1828 * from one of the reflog entries of
1829 * the local branch, force the update.
1831 force_ref_update = 1;
1835 * If the update isn't already rejected then check
1836 * the usual "must fast-forward" rules.
1838 * Decide whether an individual refspec A:B can be
1839 * pushed. The push will succeed if any of the
1840 * following are true:
1842 * (1) the remote reference B does not exist
1844 * (2) the remote reference B is being removed (i.e.,
1845 * pushing :B where no source is specified)
1847 * (3) the destination is not under refs/tags/, and
1848 * if the old and new value is a commit, the new
1849 * is a descendant of the old.
1851 * (4) it is forced using the +A:B notation, or by
1852 * passing the --force argument
1855 if (!reject_reason && !ref->deletion && !is_null_oid(&ref->old_oid)) {
1856 if (starts_with(ref->name, "refs/tags/"))
1857 reject_reason = REF_STATUS_REJECT_ALREADY_EXISTS;
1858 else if (!repo_has_object_file_with_flags(the_repository, &ref->old_oid, OBJECT_INFO_SKIP_FETCH_OBJECT))
1859 reject_reason = REF_STATUS_REJECT_FETCH_FIRST;
1860 else if (!lookup_commit_reference_gently(the_repository, &ref->old_oid, 1) ||
1861 !lookup_commit_reference_gently(the_repository, &ref->new_oid, 1))
1862 reject_reason = REF_STATUS_REJECT_NEEDS_FORCE;
1863 else if (!ref_newer(&ref->new_oid, &ref->old_oid))
1864 reject_reason = REF_STATUS_REJECT_NONFASTFORWARD;
1868 * "--force" will defeat any rejection implemented
1869 * by the rules above.
1871 if (!force_ref_update)
1872 ref->status = reject_reason;
1873 else if (reject_reason)
1874 ref->forced_update = 1;
1878 static void set_merge(struct remote_state *remote_state, struct branch *ret)
1880 struct remote *remote;
1881 char *ref;
1882 struct object_id oid;
1883 int i;
1885 if (!ret)
1886 return; /* no branch */
1887 if (ret->merge)
1888 return; /* already run */
1889 if (!ret->remote_name || !ret->merge_nr) {
1891 * no merge config; let's make sure we don't confuse callers
1892 * with a non-zero merge_nr but a NULL merge
1894 ret->merge_nr = 0;
1895 return;
1898 remote = remotes_remote_get(remote_state, ret->remote_name);
1900 CALLOC_ARRAY(ret->merge, ret->merge_nr);
1901 for (i = 0; i < ret->merge_nr; i++) {
1902 ret->merge[i] = xcalloc(1, sizeof(**ret->merge));
1903 ret->merge[i]->src = xstrdup(ret->merge_name[i]);
1904 if (!remote_find_tracking(remote, ret->merge[i]) ||
1905 strcmp(ret->remote_name, "."))
1906 continue;
1907 if (repo_dwim_ref(the_repository, ret->merge_name[i],
1908 strlen(ret->merge_name[i]), &oid, &ref,
1909 0) == 1)
1910 ret->merge[i]->dst = ref;
1911 else
1912 ret->merge[i]->dst = xstrdup(ret->merge_name[i]);
1916 struct branch *branch_get(const char *name)
1918 struct branch *ret;
1920 read_config(the_repository, 0);
1921 if (!name || !*name || !strcmp(name, "HEAD"))
1922 ret = the_repository->remote_state->current_branch;
1923 else
1924 ret = make_branch(the_repository->remote_state, name,
1925 strlen(name));
1926 set_merge(the_repository->remote_state, ret);
1927 return ret;
1930 int branch_has_merge_config(struct branch *branch)
1932 return branch && !!branch->merge;
1935 int branch_merge_matches(struct branch *branch,
1936 int i,
1937 const char *refname)
1939 if (!branch || i < 0 || i >= branch->merge_nr)
1940 return 0;
1941 return refname_match(branch->merge[i]->src, refname);
1944 __attribute__((format (printf,2,3)))
1945 static const char *error_buf(struct strbuf *err, const char *fmt, ...)
1947 if (err) {
1948 va_list ap;
1949 va_start(ap, fmt);
1950 strbuf_vaddf(err, fmt, ap);
1951 va_end(ap);
1953 return NULL;
1956 const char *branch_get_upstream(struct branch *branch, struct strbuf *err)
1958 if (!branch)
1959 return error_buf(err, _("HEAD does not point to a branch"));
1961 if (!branch->merge || !branch->merge[0]) {
1963 * no merge config; is it because the user didn't define any,
1964 * or because it is not a real branch, and get_branch
1965 * auto-vivified it?
1967 if (!refs_ref_exists(get_main_ref_store(the_repository), branch->refname))
1968 return error_buf(err, _("no such branch: '%s'"),
1969 branch->name);
1970 return error_buf(err,
1971 _("no upstream configured for branch '%s'"),
1972 branch->name);
1975 if (!branch->merge[0]->dst)
1976 return error_buf(err,
1977 _("upstream branch '%s' not stored as a remote-tracking branch"),
1978 branch->merge[0]->src);
1980 return branch->merge[0]->dst;
1983 static const char *tracking_for_push_dest(struct remote *remote,
1984 const char *refname,
1985 struct strbuf *err)
1987 char *ret;
1989 ret = apply_refspecs(&remote->fetch, refname);
1990 if (!ret)
1991 return error_buf(err,
1992 _("push destination '%s' on remote '%s' has no local tracking branch"),
1993 refname, remote->name);
1994 return ret;
1997 static const char *branch_get_push_1(struct remote_state *remote_state,
1998 struct branch *branch, struct strbuf *err)
2000 struct remote *remote;
2002 remote = remotes_remote_get(
2003 remote_state,
2004 remotes_pushremote_for_branch(remote_state, branch, NULL));
2005 if (!remote)
2006 return error_buf(err,
2007 _("branch '%s' has no remote for pushing"),
2008 branch->name);
2010 if (remote->push.nr) {
2011 char *dst;
2012 const char *ret;
2014 dst = apply_refspecs(&remote->push, branch->refname);
2015 if (!dst)
2016 return error_buf(err,
2017 _("push refspecs for '%s' do not include '%s'"),
2018 remote->name, branch->name);
2020 ret = tracking_for_push_dest(remote, dst, err);
2021 free(dst);
2022 return ret;
2025 if (remote->mirror)
2026 return tracking_for_push_dest(remote, branch->refname, err);
2028 switch (push_default) {
2029 case PUSH_DEFAULT_NOTHING:
2030 return error_buf(err, _("push has no destination (push.default is 'nothing')"));
2032 case PUSH_DEFAULT_MATCHING:
2033 case PUSH_DEFAULT_CURRENT:
2034 return tracking_for_push_dest(remote, branch->refname, err);
2036 case PUSH_DEFAULT_UPSTREAM:
2037 return branch_get_upstream(branch, err);
2039 case PUSH_DEFAULT_UNSPECIFIED:
2040 case PUSH_DEFAULT_SIMPLE:
2042 const char *up, *cur;
2044 up = branch_get_upstream(branch, err);
2045 if (!up)
2046 return NULL;
2047 cur = tracking_for_push_dest(remote, branch->refname, err);
2048 if (!cur)
2049 return NULL;
2050 if (strcmp(cur, up))
2051 return error_buf(err,
2052 _("cannot resolve 'simple' push to a single destination"));
2053 return cur;
2057 BUG("unhandled push situation");
2060 const char *branch_get_push(struct branch *branch, struct strbuf *err)
2062 read_config(the_repository, 0);
2063 die_on_missing_branch(the_repository, branch);
2065 if (!branch)
2066 return error_buf(err, _("HEAD does not point to a branch"));
2068 if (!branch->push_tracking_ref)
2069 branch->push_tracking_ref = branch_get_push_1(
2070 the_repository->remote_state, branch, err);
2071 return branch->push_tracking_ref;
2074 static int ignore_symref_update(const char *refname, struct strbuf *scratch)
2076 return !refs_read_symbolic_ref(get_main_ref_store(the_repository), refname, scratch);
2080 * Create and return a list of (struct ref) consisting of copies of
2081 * each remote_ref that matches refspec. refspec must be a pattern.
2082 * Fill in the copies' peer_ref to describe the local tracking refs to
2083 * which they map. Omit any references that would map to an existing
2084 * local symbolic ref.
2086 static struct ref *get_expanded_map(const struct ref *remote_refs,
2087 const struct refspec_item *refspec)
2089 struct strbuf scratch = STRBUF_INIT;
2090 const struct ref *ref;
2091 struct ref *ret = NULL;
2092 struct ref **tail = &ret;
2094 for (ref = remote_refs; ref; ref = ref->next) {
2095 char *expn_name = NULL;
2097 strbuf_reset(&scratch);
2099 if (strchr(ref->name, '^'))
2100 continue; /* a dereference item */
2101 if (match_name_with_pattern(refspec->src, ref->name,
2102 refspec->dst, &expn_name) &&
2103 !ignore_symref_update(expn_name, &scratch)) {
2104 struct ref *cpy = copy_ref(ref);
2106 if (cpy->peer_ref)
2107 free_one_ref(cpy->peer_ref);
2108 cpy->peer_ref = alloc_ref(expn_name);
2109 if (refspec->force)
2110 cpy->peer_ref->force = 1;
2111 *tail = cpy;
2112 tail = &cpy->next;
2114 free(expn_name);
2117 strbuf_release(&scratch);
2118 return ret;
2121 static const struct ref *find_ref_by_name_abbrev(const struct ref *refs, const char *name)
2123 const struct ref *ref;
2124 const struct ref *best_match = NULL;
2125 int best_score = 0;
2127 for (ref = refs; ref; ref = ref->next) {
2128 int score = refname_match(name, ref->name);
2130 if (best_score < score) {
2131 best_match = ref;
2132 best_score = score;
2135 return best_match;
2138 struct ref *get_remote_ref(const struct ref *remote_refs, const char *name)
2140 const struct ref *ref = find_ref_by_name_abbrev(remote_refs, name);
2142 if (!ref)
2143 return NULL;
2145 return copy_ref(ref);
2148 static struct ref *get_local_ref(const char *name)
2150 if (!name || name[0] == '\0')
2151 return NULL;
2153 if (starts_with(name, "refs/"))
2154 return alloc_ref(name);
2156 if (starts_with(name, "heads/") ||
2157 starts_with(name, "tags/") ||
2158 starts_with(name, "remotes/"))
2159 return alloc_ref_with_prefix("refs/", 5, name);
2161 return alloc_ref_with_prefix("refs/heads/", 11, name);
2164 int get_fetch_map(const struct ref *remote_refs,
2165 const struct refspec_item *refspec,
2166 struct ref ***tail,
2167 int missing_ok)
2169 struct ref *ref_map, **rmp;
2171 if (refspec->negative)
2172 return 0;
2174 if (refspec->pattern) {
2175 ref_map = get_expanded_map(remote_refs, refspec);
2176 } else {
2177 const char *name = refspec->src[0] ? refspec->src : "HEAD";
2179 if (refspec->exact_sha1) {
2180 ref_map = alloc_ref(name);
2181 get_oid_hex(name, &ref_map->old_oid);
2182 ref_map->exact_oid = 1;
2183 } else {
2184 ref_map = get_remote_ref(remote_refs, name);
2186 if (!missing_ok && !ref_map)
2187 die(_("couldn't find remote ref %s"), name);
2188 if (ref_map) {
2189 ref_map->peer_ref = get_local_ref(refspec->dst);
2190 if (ref_map->peer_ref && refspec->force)
2191 ref_map->peer_ref->force = 1;
2195 for (rmp = &ref_map; *rmp; ) {
2196 if ((*rmp)->peer_ref) {
2197 if (!starts_with((*rmp)->peer_ref->name, "refs/") ||
2198 check_refname_format((*rmp)->peer_ref->name, 0)) {
2199 struct ref *ignore = *rmp;
2200 error(_("* Ignoring funny ref '%s' locally"),
2201 (*rmp)->peer_ref->name);
2202 *rmp = (*rmp)->next;
2203 free(ignore->peer_ref);
2204 free(ignore);
2205 continue;
2208 rmp = &((*rmp)->next);
2211 if (ref_map)
2212 tail_link_ref(ref_map, tail);
2214 return 0;
2217 int resolve_remote_symref(struct ref *ref, struct ref *list)
2219 if (!ref->symref)
2220 return 0;
2221 for (; list; list = list->next)
2222 if (!strcmp(ref->symref, list->name)) {
2223 oidcpy(&ref->old_oid, &list->old_oid);
2224 return 0;
2226 return 1;
2230 * Compute the commit ahead/behind values for the pair branch_name, base.
2232 * If abf is AHEAD_BEHIND_FULL, compute the full ahead/behind and return the
2233 * counts in *num_ours and *num_theirs. If abf is AHEAD_BEHIND_QUICK, skip
2234 * the (potentially expensive) a/b computation (*num_ours and *num_theirs are
2235 * set to zero).
2237 * Returns -1 if num_ours and num_theirs could not be filled in (e.g., ref
2238 * does not exist). Returns 0 if the commits are identical. Returns 1 if
2239 * commits are different.
2242 static int stat_branch_pair(const char *branch_name, const char *base,
2243 int *num_ours, int *num_theirs,
2244 enum ahead_behind_flags abf)
2246 struct object_id oid;
2247 struct commit *ours, *theirs;
2248 struct rev_info revs;
2249 struct setup_revision_opt opt = {
2250 .free_removed_argv_elements = 1,
2252 struct strvec argv = STRVEC_INIT;
2254 /* Cannot stat if what we used to build on no longer exists */
2255 if (refs_read_ref(get_main_ref_store(the_repository), base, &oid))
2256 return -1;
2257 theirs = lookup_commit_reference(the_repository, &oid);
2258 if (!theirs)
2259 return -1;
2261 if (refs_read_ref(get_main_ref_store(the_repository), branch_name, &oid))
2262 return -1;
2263 ours = lookup_commit_reference(the_repository, &oid);
2264 if (!ours)
2265 return -1;
2267 *num_theirs = *num_ours = 0;
2269 /* are we the same? */
2270 if (theirs == ours)
2271 return 0;
2272 if (abf == AHEAD_BEHIND_QUICK)
2273 return 1;
2274 if (abf != AHEAD_BEHIND_FULL)
2275 BUG("stat_branch_pair: invalid abf '%d'", abf);
2277 /* Run "rev-list --left-right ours...theirs" internally... */
2278 strvec_push(&argv, ""); /* ignored */
2279 strvec_push(&argv, "--left-right");
2280 strvec_pushf(&argv, "%s...%s",
2281 oid_to_hex(&ours->object.oid),
2282 oid_to_hex(&theirs->object.oid));
2283 strvec_push(&argv, "--");
2285 repo_init_revisions(the_repository, &revs, NULL);
2286 setup_revisions(argv.nr, argv.v, &revs, &opt);
2287 if (prepare_revision_walk(&revs))
2288 die(_("revision walk setup failed"));
2290 /* ... and count the commits on each side. */
2291 while (1) {
2292 struct commit *c = get_revision(&revs);
2293 if (!c)
2294 break;
2295 if (c->object.flags & SYMMETRIC_LEFT)
2296 (*num_ours)++;
2297 else
2298 (*num_theirs)++;
2301 /* clear object flags smudged by the above traversal */
2302 clear_commit_marks(ours, ALL_REV_FLAGS);
2303 clear_commit_marks(theirs, ALL_REV_FLAGS);
2305 strvec_clear(&argv);
2306 release_revisions(&revs);
2307 return 1;
2311 * Lookup the tracking branch for the given branch and if present, optionally
2312 * compute the commit ahead/behind values for the pair.
2314 * If for_push is true, the tracking branch refers to the push branch,
2315 * otherwise it refers to the upstream branch.
2317 * The name of the tracking branch (or NULL if it is not defined) is
2318 * returned via *tracking_name, if it is not itself NULL.
2320 * If abf is AHEAD_BEHIND_FULL, compute the full ahead/behind and return the
2321 * counts in *num_ours and *num_theirs. If abf is AHEAD_BEHIND_QUICK, skip
2322 * the (potentially expensive) a/b computation (*num_ours and *num_theirs are
2323 * set to zero).
2325 * Returns -1 if num_ours and num_theirs could not be filled in (e.g., no
2326 * upstream defined, or ref does not exist). Returns 0 if the commits are
2327 * identical. Returns 1 if commits are different.
2329 int stat_tracking_info(struct branch *branch, int *num_ours, int *num_theirs,
2330 const char **tracking_name, int for_push,
2331 enum ahead_behind_flags abf)
2333 const char *base;
2335 /* Cannot stat unless we are marked to build on top of somebody else. */
2336 base = for_push ? branch_get_push(branch, NULL) :
2337 branch_get_upstream(branch, NULL);
2338 if (tracking_name)
2339 *tracking_name = base;
2340 if (!base)
2341 return -1;
2343 return stat_branch_pair(branch->refname, base, num_ours, num_theirs, abf);
2347 * Return true when there is anything to report, otherwise false.
2349 int format_tracking_info(struct branch *branch, struct strbuf *sb,
2350 enum ahead_behind_flags abf,
2351 int show_divergence_advice)
2353 int ours, theirs, sti;
2354 const char *full_base;
2355 char *base;
2356 int upstream_is_gone = 0;
2358 sti = stat_tracking_info(branch, &ours, &theirs, &full_base, 0, abf);
2359 if (sti < 0) {
2360 if (!full_base)
2361 return 0;
2362 upstream_is_gone = 1;
2365 base = refs_shorten_unambiguous_ref(get_main_ref_store(the_repository),
2366 full_base, 0);
2367 if (upstream_is_gone) {
2368 strbuf_addf(sb,
2369 _("Your branch is based on '%s', but the upstream is gone.\n"),
2370 base);
2371 if (advice_enabled(ADVICE_STATUS_HINTS))
2372 strbuf_addstr(sb,
2373 _(" (use \"git branch --unset-upstream\" to fixup)\n"));
2374 } else if (!sti) {
2375 strbuf_addf(sb,
2376 _("Your branch is up to date with '%s'.\n"),
2377 base);
2378 } else if (abf == AHEAD_BEHIND_QUICK) {
2379 strbuf_addf(sb,
2380 _("Your branch and '%s' refer to different commits.\n"),
2381 base);
2382 if (advice_enabled(ADVICE_STATUS_HINTS))
2383 strbuf_addf(sb, _(" (use \"%s\" for details)\n"),
2384 "git status --ahead-behind");
2385 } else if (!theirs) {
2386 strbuf_addf(sb,
2387 Q_("Your branch is ahead of '%s' by %d commit.\n",
2388 "Your branch is ahead of '%s' by %d commits.\n",
2389 ours),
2390 base, ours);
2391 if (advice_enabled(ADVICE_STATUS_HINTS))
2392 strbuf_addstr(sb,
2393 _(" (use \"git push\" to publish your local commits)\n"));
2394 } else if (!ours) {
2395 strbuf_addf(sb,
2396 Q_("Your branch is behind '%s' by %d commit, "
2397 "and can be fast-forwarded.\n",
2398 "Your branch is behind '%s' by %d commits, "
2399 "and can be fast-forwarded.\n",
2400 theirs),
2401 base, theirs);
2402 if (advice_enabled(ADVICE_STATUS_HINTS))
2403 strbuf_addstr(sb,
2404 _(" (use \"git pull\" to update your local branch)\n"));
2405 } else {
2406 strbuf_addf(sb,
2407 Q_("Your branch and '%s' have diverged,\n"
2408 "and have %d and %d different commit each, "
2409 "respectively.\n",
2410 "Your branch and '%s' have diverged,\n"
2411 "and have %d and %d different commits each, "
2412 "respectively.\n",
2413 ours + theirs),
2414 base, ours, theirs);
2415 if (show_divergence_advice &&
2416 advice_enabled(ADVICE_STATUS_HINTS))
2417 strbuf_addstr(sb,
2418 _(" (use \"git pull\" if you want to integrate the remote branch with yours)\n"));
2420 free(base);
2421 return 1;
2424 static int one_local_ref(const char *refname, const char *referent UNUSED, const struct object_id *oid,
2425 int flag UNUSED,
2426 void *cb_data)
2428 struct ref ***local_tail = cb_data;
2429 struct ref *ref;
2431 /* we already know it starts with refs/ to get here */
2432 if (check_refname_format(refname + 5, 0))
2433 return 0;
2435 ref = alloc_ref(refname);
2436 oidcpy(&ref->new_oid, oid);
2437 **local_tail = ref;
2438 *local_tail = &ref->next;
2439 return 0;
2442 struct ref *get_local_heads(void)
2444 struct ref *local_refs = NULL, **local_tail = &local_refs;
2446 refs_for_each_ref(get_main_ref_store(the_repository), one_local_ref,
2447 &local_tail);
2448 return local_refs;
2451 struct ref *guess_remote_head(const struct ref *head,
2452 const struct ref *refs,
2453 int all)
2455 const struct ref *r;
2456 struct ref *list = NULL;
2457 struct ref **tail = &list;
2459 if (!head)
2460 return NULL;
2463 * Some transports support directly peeking at
2464 * where HEAD points; if that is the case, then
2465 * we don't have to guess.
2467 if (head->symref)
2468 return copy_ref(find_ref_by_name(refs, head->symref));
2470 /* If a remote branch exists with the default branch name, let's use it. */
2471 if (!all) {
2472 char *default_branch = repo_default_branch_name(the_repository, 0);
2473 char *ref = xstrfmt("refs/heads/%s", default_branch);
2475 r = find_ref_by_name(refs, ref);
2476 free(ref);
2477 free(default_branch);
2479 if (r && oideq(&r->old_oid, &head->old_oid))
2480 return copy_ref(r);
2482 /* Fall back to the hard-coded historical default */
2483 r = find_ref_by_name(refs, "refs/heads/master");
2484 if (r && oideq(&r->old_oid, &head->old_oid))
2485 return copy_ref(r);
2488 /* Look for another ref that points there */
2489 for (r = refs; r; r = r->next) {
2490 if (r != head &&
2491 starts_with(r->name, "refs/heads/") &&
2492 oideq(&r->old_oid, &head->old_oid)) {
2493 *tail = copy_ref(r);
2494 tail = &((*tail)->next);
2495 if (!all)
2496 break;
2500 return list;
2503 struct stale_heads_info {
2504 struct string_list *ref_names;
2505 struct ref **stale_refs_tail;
2506 struct refspec *rs;
2509 static int get_stale_heads_cb(const char *refname, const char *referent UNUSED, const struct object_id *oid,
2510 int flags, void *cb_data)
2512 struct stale_heads_info *info = cb_data;
2513 struct string_list matches = STRING_LIST_INIT_DUP;
2514 struct refspec_item query;
2515 int i, stale = 1;
2516 memset(&query, 0, sizeof(struct refspec_item));
2517 query.dst = (char *)refname;
2519 query_refspecs_multiple(info->rs, &query, &matches);
2520 if (matches.nr == 0)
2521 goto clean_exit; /* No matches */
2524 * If we did find a suitable refspec and it's not a symref and
2525 * it's not in the list of refs that currently exist in that
2526 * remote, we consider it to be stale. In order to deal with
2527 * overlapping refspecs, we need to go over all of the
2528 * matching refs.
2530 if (flags & REF_ISSYMREF)
2531 goto clean_exit;
2533 for (i = 0; stale && i < matches.nr; i++)
2534 if (string_list_has_string(info->ref_names, matches.items[i].string))
2535 stale = 0;
2537 if (stale) {
2538 struct ref *ref = make_linked_ref(refname, &info->stale_refs_tail);
2539 oidcpy(&ref->new_oid, oid);
2542 clean_exit:
2543 string_list_clear(&matches, 0);
2544 return 0;
2547 struct ref *get_stale_heads(struct refspec *rs, struct ref *fetch_map)
2549 struct ref *ref, *stale_refs = NULL;
2550 struct string_list ref_names = STRING_LIST_INIT_NODUP;
2551 struct stale_heads_info info;
2553 info.ref_names = &ref_names;
2554 info.stale_refs_tail = &stale_refs;
2555 info.rs = rs;
2556 for (ref = fetch_map; ref; ref = ref->next)
2557 string_list_append(&ref_names, ref->name);
2558 string_list_sort(&ref_names);
2559 refs_for_each_ref(get_main_ref_store(the_repository),
2560 get_stale_heads_cb, &info);
2561 string_list_clear(&ref_names, 0);
2562 return stale_refs;
2566 * Compare-and-swap
2568 void clear_cas_option(struct push_cas_option *cas)
2570 int i;
2572 for (i = 0; i < cas->nr; i++)
2573 free(cas->entry[i].refname);
2574 free(cas->entry);
2575 memset(cas, 0, sizeof(*cas));
2578 static struct push_cas *add_cas_entry(struct push_cas_option *cas,
2579 const char *refname,
2580 size_t refnamelen)
2582 struct push_cas *entry;
2583 ALLOC_GROW(cas->entry, cas->nr + 1, cas->alloc);
2584 entry = &cas->entry[cas->nr++];
2585 memset(entry, 0, sizeof(*entry));
2586 entry->refname = xmemdupz(refname, refnamelen);
2587 return entry;
2590 static int parse_push_cas_option(struct push_cas_option *cas, const char *arg, int unset)
2592 const char *colon;
2593 struct push_cas *entry;
2595 if (unset) {
2596 /* "--no-<option>" */
2597 clear_cas_option(cas);
2598 return 0;
2601 if (!arg) {
2602 /* just "--<option>" */
2603 cas->use_tracking_for_rest = 1;
2604 return 0;
2607 /* "--<option>=refname" or "--<option>=refname:value" */
2608 colon = strchrnul(arg, ':');
2609 entry = add_cas_entry(cas, arg, colon - arg);
2610 if (!*colon)
2611 entry->use_tracking = 1;
2612 else if (!colon[1])
2613 oidclr(&entry->expect, the_repository->hash_algo);
2614 else if (repo_get_oid(the_repository, colon + 1, &entry->expect))
2615 return error(_("cannot parse expected object name '%s'"),
2616 colon + 1);
2617 return 0;
2620 int parseopt_push_cas_option(const struct option *opt, const char *arg, int unset)
2622 return parse_push_cas_option(opt->value, arg, unset);
2625 int is_empty_cas(const struct push_cas_option *cas)
2627 return !cas->use_tracking_for_rest && !cas->nr;
2631 * Look at remote.fetch refspec and see if we have a remote
2632 * tracking branch for the refname there. Fill the name of
2633 * the remote-tracking branch in *dst_refname, and the name
2634 * of the commit object at its tip in oid[].
2635 * If we cannot do so, return negative to signal an error.
2637 static int remote_tracking(struct remote *remote, const char *refname,
2638 struct object_id *oid, char **dst_refname)
2640 char *dst;
2642 dst = apply_refspecs(&remote->fetch, refname);
2643 if (!dst)
2644 return -1; /* no tracking ref for refname at remote */
2645 if (refs_read_ref(get_main_ref_store(the_repository), dst, oid)) {
2646 free(dst);
2647 return -1; /* we know what the tracking ref is but we cannot read it */
2650 *dst_refname = dst;
2651 return 0;
2655 * The struct "reflog_commit_array" and related helper functions
2656 * are used for collecting commits into an array during reflog
2657 * traversals in "check_and_collect_until()".
2659 struct reflog_commit_array {
2660 struct commit **item;
2661 size_t nr, alloc;
2664 #define REFLOG_COMMIT_ARRAY_INIT { 0 }
2666 /* Append a commit to the array. */
2667 static void append_commit(struct reflog_commit_array *arr,
2668 struct commit *commit)
2670 ALLOC_GROW(arr->item, arr->nr + 1, arr->alloc);
2671 arr->item[arr->nr++] = commit;
2674 /* Free and reset the array. */
2675 static void free_commit_array(struct reflog_commit_array *arr)
2677 FREE_AND_NULL(arr->item);
2678 arr->nr = arr->alloc = 0;
2681 struct check_and_collect_until_cb_data {
2682 struct commit *remote_commit;
2683 struct reflog_commit_array *local_commits;
2684 timestamp_t remote_reflog_timestamp;
2687 /* Get the timestamp of the latest entry. */
2688 static int peek_reflog(struct object_id *o_oid UNUSED,
2689 struct object_id *n_oid UNUSED,
2690 const char *ident UNUSED,
2691 timestamp_t timestamp, int tz UNUSED,
2692 const char *message UNUSED, void *cb_data)
2694 timestamp_t *ts = cb_data;
2695 *ts = timestamp;
2696 return 1;
2699 static int check_and_collect_until(struct object_id *o_oid UNUSED,
2700 struct object_id *n_oid,
2701 const char *ident UNUSED,
2702 timestamp_t timestamp, int tz UNUSED,
2703 const char *message UNUSED, void *cb_data)
2705 struct commit *commit;
2706 struct check_and_collect_until_cb_data *cb = cb_data;
2708 /* An entry was found. */
2709 if (oideq(n_oid, &cb->remote_commit->object.oid))
2710 return 1;
2712 if ((commit = lookup_commit_reference(the_repository, n_oid)))
2713 append_commit(cb->local_commits, commit);
2716 * If the reflog entry timestamp is older than the remote ref's
2717 * latest reflog entry, there is no need to check or collect
2718 * entries older than this one.
2720 if (timestamp < cb->remote_reflog_timestamp)
2721 return -1;
2723 return 0;
2726 #define MERGE_BASES_BATCH_SIZE 8
2729 * Iterate through the reflog of the local ref to check if there is an entry
2730 * for the given remote-tracking ref; runs until the timestamp of an entry is
2731 * older than latest timestamp of remote-tracking ref's reflog. Any commits
2732 * are that seen along the way are collected into an array to check if the
2733 * remote-tracking ref is reachable from any of them.
2735 static int is_reachable_in_reflog(const char *local, const struct ref *remote)
2737 timestamp_t date;
2738 struct commit *commit;
2739 struct commit **chunk;
2740 struct check_and_collect_until_cb_data cb;
2741 struct reflog_commit_array arr = REFLOG_COMMIT_ARRAY_INIT;
2742 size_t size = 0;
2743 int ret = 0;
2745 commit = lookup_commit_reference(the_repository, &remote->old_oid);
2746 if (!commit)
2747 goto cleanup_return;
2750 * Get the timestamp from the latest entry
2751 * of the remote-tracking ref's reflog.
2753 refs_for_each_reflog_ent_reverse(get_main_ref_store(the_repository),
2754 remote->tracking_ref, peek_reflog,
2755 &date);
2757 cb.remote_commit = commit;
2758 cb.local_commits = &arr;
2759 cb.remote_reflog_timestamp = date;
2760 ret = refs_for_each_reflog_ent_reverse(get_main_ref_store(the_repository),
2761 local, check_and_collect_until,
2762 &cb);
2764 /* We found an entry in the reflog. */
2765 if (ret > 0)
2766 goto cleanup_return;
2769 * Check if the remote commit is reachable from any
2770 * of the commits in the collected array, in batches.
2772 for (chunk = arr.item; chunk < arr.item + arr.nr; chunk += size) {
2773 size = arr.item + arr.nr - chunk;
2774 if (MERGE_BASES_BATCH_SIZE < size)
2775 size = MERGE_BASES_BATCH_SIZE;
2777 if ((ret = repo_in_merge_bases_many(the_repository, commit, size, chunk, 0)))
2778 break;
2781 cleanup_return:
2782 free_commit_array(&arr);
2783 return ret;
2787 * Check for reachability of a remote-tracking
2788 * ref in the reflog entries of its local ref.
2790 static void check_if_includes_upstream(struct ref *remote)
2792 struct ref *local = get_local_ref(remote->name);
2793 if (!local)
2794 return;
2796 if (is_reachable_in_reflog(local->name, remote) <= 0)
2797 remote->unreachable = 1;
2798 free_one_ref(local);
2801 static void apply_cas(struct push_cas_option *cas,
2802 struct remote *remote,
2803 struct ref *ref)
2805 int i;
2807 /* Find an explicit --<option>=<name>[:<value>] entry */
2808 for (i = 0; i < cas->nr; i++) {
2809 struct push_cas *entry = &cas->entry[i];
2810 if (!refname_match(entry->refname, ref->name))
2811 continue;
2812 ref->expect_old_sha1 = 1;
2813 if (!entry->use_tracking)
2814 oidcpy(&ref->old_oid_expect, &entry->expect);
2815 else if (remote_tracking(remote, ref->name,
2816 &ref->old_oid_expect,
2817 &ref->tracking_ref))
2818 oidclr(&ref->old_oid_expect, the_repository->hash_algo);
2819 else
2820 ref->check_reachable = cas->use_force_if_includes;
2821 return;
2824 /* Are we using "--<option>" to cover all? */
2825 if (!cas->use_tracking_for_rest)
2826 return;
2828 ref->expect_old_sha1 = 1;
2829 if (remote_tracking(remote, ref->name,
2830 &ref->old_oid_expect,
2831 &ref->tracking_ref))
2832 oidclr(&ref->old_oid_expect, the_repository->hash_algo);
2833 else
2834 ref->check_reachable = cas->use_force_if_includes;
2837 void apply_push_cas(struct push_cas_option *cas,
2838 struct remote *remote,
2839 struct ref *remote_refs)
2841 struct ref *ref;
2842 for (ref = remote_refs; ref; ref = ref->next) {
2843 apply_cas(cas, remote, ref);
2846 * If "compare-and-swap" is in "use_tracking[_for_rest]"
2847 * mode, and if "--force-if-includes" was specified, run
2848 * the check.
2850 if (ref->check_reachable)
2851 check_if_includes_upstream(ref);
2855 struct remote_state *remote_state_new(void)
2857 struct remote_state *r = xmalloc(sizeof(*r));
2859 memset(r, 0, sizeof(*r));
2861 hashmap_init(&r->remotes_hash, remotes_hash_cmp, NULL, 0);
2862 hashmap_init(&r->branches_hash, branches_hash_cmp, NULL, 0);
2863 return r;
2866 void remote_state_clear(struct remote_state *remote_state)
2868 struct hashmap_iter iter;
2869 struct branch *b;
2870 int i;
2872 for (i = 0; i < remote_state->remotes_nr; i++)
2873 remote_clear(remote_state->remotes[i]);
2874 FREE_AND_NULL(remote_state->remotes);
2875 FREE_AND_NULL(remote_state->pushremote_name);
2876 remote_state->remotes_alloc = 0;
2877 remote_state->remotes_nr = 0;
2879 rewrites_release(&remote_state->rewrites);
2880 rewrites_release(&remote_state->rewrites_push);
2882 hashmap_clear_and_free(&remote_state->remotes_hash, struct remote, ent);
2883 hashmap_for_each_entry(&remote_state->branches_hash, &iter, b, ent) {
2884 branch_release(b);
2885 free(b);
2887 hashmap_clear(&remote_state->branches_hash);
2891 * Returns 1 if it was the last chop before ':'.
2893 static int chop_last_dir(char **remoteurl, int is_relative)
2895 char *rfind = find_last_dir_sep(*remoteurl);
2896 if (rfind) {
2897 *rfind = '\0';
2898 return 0;
2901 rfind = strrchr(*remoteurl, ':');
2902 if (rfind) {
2903 *rfind = '\0';
2904 return 1;
2907 if (is_relative || !strcmp(".", *remoteurl))
2908 die(_("cannot strip one component off url '%s'"),
2909 *remoteurl);
2911 free(*remoteurl);
2912 *remoteurl = xstrdup(".");
2913 return 0;
2916 char *relative_url(const char *remote_url, const char *url,
2917 const char *up_path)
2919 int is_relative = 0;
2920 int colonsep = 0;
2921 char *out;
2922 char *remoteurl;
2923 struct strbuf sb = STRBUF_INIT;
2924 size_t len;
2926 if (!url_is_local_not_ssh(url) || is_absolute_path(url))
2927 return xstrdup(url);
2929 len = strlen(remote_url);
2930 if (!len)
2931 BUG("invalid empty remote_url");
2933 remoteurl = xstrdup(remote_url);
2934 if (is_dir_sep(remoteurl[len-1]))
2935 remoteurl[len-1] = '\0';
2937 if (!url_is_local_not_ssh(remoteurl) || is_absolute_path(remoteurl))
2938 is_relative = 0;
2939 else {
2940 is_relative = 1;
2942 * Prepend a './' to ensure all relative
2943 * remoteurls start with './' or '../'
2945 if (!starts_with_dot_slash_native(remoteurl) &&
2946 !starts_with_dot_dot_slash_native(remoteurl)) {
2947 strbuf_reset(&sb);
2948 strbuf_addf(&sb, "./%s", remoteurl);
2949 free(remoteurl);
2950 remoteurl = strbuf_detach(&sb, NULL);
2954 * When the url starts with '../', remove that and the
2955 * last directory in remoteurl.
2957 while (*url) {
2958 if (starts_with_dot_dot_slash_native(url)) {
2959 url += 3;
2960 colonsep |= chop_last_dir(&remoteurl, is_relative);
2961 } else if (starts_with_dot_slash_native(url))
2962 url += 2;
2963 else
2964 break;
2966 strbuf_reset(&sb);
2967 strbuf_addf(&sb, "%s%s%s", remoteurl, colonsep ? ":" : "/", url);
2968 if (ends_with(url, "/"))
2969 strbuf_setlen(&sb, sb.len - 1);
2970 free(remoteurl);
2972 if (starts_with_dot_slash_native(sb.buf))
2973 out = xstrdup(sb.buf + 2);
2974 else
2975 out = xstrdup(sb.buf);
2977 if (!up_path || !is_relative) {
2978 strbuf_release(&sb);
2979 return out;
2982 strbuf_reset(&sb);
2983 strbuf_addf(&sb, "%s%s", up_path, out);
2984 free(out);
2985 return strbuf_detach(&sb, NULL);