Merge branch 'jk/ref-filter-trailer-fixes'
[git.git] / remote.c
blob539e5ceae30ed7294f1733d4b9ac000bb671245b
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"
28 enum map_direction { FROM_SRC, FROM_DST };
30 struct counted_string {
31 size_t len;
32 const char *s;
35 static int valid_remote(const struct remote *remote)
37 return !!remote->url.nr;
40 static char *alias_url(const char *url, struct rewrites *r)
42 int i, j;
43 struct counted_string *longest;
44 int longest_i;
46 longest = NULL;
47 longest_i = -1;
48 for (i = 0; i < r->rewrite_nr; i++) {
49 if (!r->rewrite[i])
50 continue;
51 for (j = 0; j < r->rewrite[i]->instead_of_nr; j++) {
52 if (starts_with(url, r->rewrite[i]->instead_of[j].s) &&
53 (!longest ||
54 longest->len < r->rewrite[i]->instead_of[j].len)) {
55 longest = &(r->rewrite[i]->instead_of[j]);
56 longest_i = i;
60 if (!longest)
61 return NULL;
63 return xstrfmt("%s%s", r->rewrite[longest_i]->base, url + longest->len);
66 static void add_url(struct remote *remote, const char *url)
68 if (*url)
69 strvec_push(&remote->url, url);
70 else
71 strvec_clear(&remote->url);
74 static void add_pushurl(struct remote *remote, const char *pushurl)
76 if (*pushurl)
77 strvec_push(&remote->pushurl, pushurl);
78 else
79 strvec_clear(&remote->pushurl);
82 static void add_pushurl_alias(struct remote_state *remote_state,
83 struct remote *remote, const char *url)
85 char *alias = alias_url(url, &remote_state->rewrites_push);
86 if (alias)
87 add_pushurl(remote, alias);
88 free(alias);
91 static void add_url_alias(struct remote_state *remote_state,
92 struct remote *remote, const char *url)
94 char *alias = alias_url(url, &remote_state->rewrites);
95 add_url(remote, alias ? alias : url);
96 add_pushurl_alias(remote_state, remote, url);
97 free(alias);
100 struct remotes_hash_key {
101 const char *str;
102 int len;
105 static int remotes_hash_cmp(const void *cmp_data UNUSED,
106 const struct hashmap_entry *eptr,
107 const struct hashmap_entry *entry_or_key,
108 const void *keydata)
110 const struct remote *a, *b;
111 const struct remotes_hash_key *key = keydata;
113 a = container_of(eptr, const struct remote, ent);
114 b = container_of(entry_or_key, const struct remote, ent);
116 if (key)
117 return !!xstrncmpz(a->name, key->str, key->len);
118 else
119 return strcmp(a->name, b->name);
122 static struct remote *make_remote(struct remote_state *remote_state,
123 const char *name, int len)
125 struct remote *ret;
126 struct remotes_hash_key lookup;
127 struct hashmap_entry lookup_entry, *e;
129 if (!len)
130 len = strlen(name);
132 lookup.str = name;
133 lookup.len = len;
134 hashmap_entry_init(&lookup_entry, memhash(name, len));
136 e = hashmap_get(&remote_state->remotes_hash, &lookup_entry, &lookup);
137 if (e)
138 return container_of(e, struct remote, ent);
140 CALLOC_ARRAY(ret, 1);
141 ret->prune = -1; /* unspecified */
142 ret->prune_tags = -1; /* unspecified */
143 ret->name = xstrndup(name, len);
144 refspec_init(&ret->push, REFSPEC_PUSH);
145 refspec_init(&ret->fetch, REFSPEC_FETCH);
147 ALLOC_GROW(remote_state->remotes, remote_state->remotes_nr + 1,
148 remote_state->remotes_alloc);
149 remote_state->remotes[remote_state->remotes_nr++] = ret;
151 hashmap_entry_init(&ret->ent, lookup_entry.hash);
152 if (hashmap_put_entry(&remote_state->remotes_hash, ret, ent))
153 BUG("hashmap_put overwrote entry after hashmap_get returned NULL");
154 return ret;
157 static void remote_clear(struct remote *remote)
159 free((char *)remote->name);
160 free((char *)remote->foreign_vcs);
162 strvec_clear(&remote->url);
163 strvec_clear(&remote->pushurl);
165 free((char *)remote->receivepack);
166 free((char *)remote->uploadpack);
167 FREE_AND_NULL(remote->http_proxy);
168 FREE_AND_NULL(remote->http_proxy_authmethod);
171 static void add_merge(struct branch *branch, const char *name)
173 ALLOC_GROW(branch->merge_name, branch->merge_nr + 1,
174 branch->merge_alloc);
175 branch->merge_name[branch->merge_nr++] = name;
178 struct branches_hash_key {
179 const char *str;
180 int len;
183 static int branches_hash_cmp(const void *cmp_data UNUSED,
184 const struct hashmap_entry *eptr,
185 const struct hashmap_entry *entry_or_key,
186 const void *keydata)
188 const struct branch *a, *b;
189 const struct branches_hash_key *key = keydata;
191 a = container_of(eptr, const struct branch, ent);
192 b = container_of(entry_or_key, const struct branch, ent);
194 if (key)
195 return !!xstrncmpz(a->name, key->str, key->len);
196 else
197 return strcmp(a->name, b->name);
200 static struct branch *find_branch(struct remote_state *remote_state,
201 const char *name, size_t len)
203 struct branches_hash_key lookup;
204 struct hashmap_entry lookup_entry, *e;
206 lookup.str = name;
207 lookup.len = len;
208 hashmap_entry_init(&lookup_entry, memhash(name, len));
210 e = hashmap_get(&remote_state->branches_hash, &lookup_entry, &lookup);
211 if (e)
212 return container_of(e, struct branch, ent);
214 return NULL;
217 static void die_on_missing_branch(struct repository *repo,
218 struct branch *branch)
220 /* branch == NULL is always valid because it represents detached HEAD. */
221 if (branch &&
222 branch != find_branch(repo->remote_state, branch->name,
223 strlen(branch->name)))
224 die("branch %s was not found in the repository", branch->name);
227 static struct branch *make_branch(struct remote_state *remote_state,
228 const char *name, size_t len)
230 struct branch *ret;
232 ret = find_branch(remote_state, name, len);
233 if (ret)
234 return ret;
236 CALLOC_ARRAY(ret, 1);
237 ret->name = xstrndup(name, len);
238 ret->refname = xstrfmt("refs/heads/%s", ret->name);
240 hashmap_entry_init(&ret->ent, memhash(name, len));
241 if (hashmap_put_entry(&remote_state->branches_hash, ret, ent))
242 BUG("hashmap_put overwrote entry after hashmap_get returned NULL");
243 return ret;
246 static void branch_release(struct branch *branch)
248 free((char *)branch->name);
249 free((char *)branch->refname);
250 free(branch->remote_name);
251 free(branch->pushremote_name);
252 for (int i = 0; i < branch->merge_nr; i++)
253 refspec_item_clear(branch->merge[i]);
254 free(branch->merge);
257 static struct rewrite *make_rewrite(struct rewrites *r,
258 const char *base, size_t len)
260 struct rewrite *ret;
261 int i;
263 for (i = 0; i < r->rewrite_nr; i++) {
264 if (len == r->rewrite[i]->baselen &&
265 !strncmp(base, r->rewrite[i]->base, len))
266 return r->rewrite[i];
269 ALLOC_GROW(r->rewrite, r->rewrite_nr + 1, r->rewrite_alloc);
270 CALLOC_ARRAY(ret, 1);
271 r->rewrite[r->rewrite_nr++] = ret;
272 ret->base = xstrndup(base, len);
273 ret->baselen = len;
274 return ret;
277 static void rewrites_release(struct rewrites *r)
279 for (int i = 0; i < r->rewrite_nr; i++)
280 free((char *)r->rewrite[i]->base);
281 free(r->rewrite);
282 memset(r, 0, sizeof(*r));
285 static void add_instead_of(struct rewrite *rewrite, const char *instead_of)
287 ALLOC_GROW(rewrite->instead_of, rewrite->instead_of_nr + 1, rewrite->instead_of_alloc);
288 rewrite->instead_of[rewrite->instead_of_nr].s = instead_of;
289 rewrite->instead_of[rewrite->instead_of_nr].len = strlen(instead_of);
290 rewrite->instead_of_nr++;
293 static const char *skip_spaces(const char *s)
295 while (isspace(*s))
296 s++;
297 return s;
300 static void read_remotes_file(struct remote_state *remote_state,
301 struct remote *remote)
303 struct strbuf buf = STRBUF_INIT;
304 FILE *f = fopen_or_warn(git_path("remotes/%s", remote->name), "r");
306 if (!f)
307 return;
308 remote->configured_in_repo = 1;
309 remote->origin = REMOTE_REMOTES;
310 while (strbuf_getline(&buf, f) != EOF) {
311 const char *v;
313 strbuf_rtrim(&buf);
315 if (skip_prefix(buf.buf, "URL:", &v))
316 add_url_alias(remote_state, remote,
317 skip_spaces(v));
318 else if (skip_prefix(buf.buf, "Push:", &v))
319 refspec_append(&remote->push, skip_spaces(v));
320 else if (skip_prefix(buf.buf, "Pull:", &v))
321 refspec_append(&remote->fetch, skip_spaces(v));
323 strbuf_release(&buf);
324 fclose(f);
327 static void read_branches_file(struct remote_state *remote_state,
328 struct remote *remote)
330 char *frag, *to_free = NULL;
331 struct strbuf buf = STRBUF_INIT;
332 FILE *f = fopen_or_warn(git_path("branches/%s", remote->name), "r");
334 if (!f)
335 return;
337 strbuf_getline_lf(&buf, f);
338 fclose(f);
339 strbuf_trim(&buf);
340 if (!buf.len) {
341 strbuf_release(&buf);
342 return;
345 remote->configured_in_repo = 1;
346 remote->origin = REMOTE_BRANCHES;
349 * The branches file would have URL and optionally
350 * #branch specified. The default (or specified) branch is
351 * fetched and stored in the local branch matching the
352 * remote name.
354 frag = strchr(buf.buf, '#');
355 if (frag)
356 *(frag++) = '\0';
357 else
358 frag = to_free = repo_default_branch_name(the_repository, 0);
360 add_url_alias(remote_state, remote, buf.buf);
361 refspec_appendf(&remote->fetch, "refs/heads/%s:refs/heads/%s",
362 frag, remote->name);
365 * Cogito compatible push: push current HEAD to remote #branch
366 * (master if missing)
368 refspec_appendf(&remote->push, "HEAD:refs/heads/%s", frag);
369 remote->fetch_tags = 1; /* always auto-follow */
371 strbuf_release(&buf);
372 free(to_free);
375 static int handle_config(const char *key, const char *value,
376 const struct config_context *ctx, void *cb)
378 const char *name;
379 size_t namelen;
380 const char *subkey;
381 struct remote *remote;
382 struct branch *branch;
383 struct remote_state *remote_state = cb;
384 const struct key_value_info *kvi = ctx->kvi;
386 if (parse_config_key(key, "branch", &name, &namelen, &subkey) >= 0) {
387 /* There is no subsection. */
388 if (!name)
389 return 0;
390 /* There is a subsection, but it is empty. */
391 if (!namelen)
392 return -1;
393 branch = make_branch(remote_state, name, namelen);
394 if (!strcmp(subkey, "remote")) {
395 FREE_AND_NULL(branch->remote_name);
396 return git_config_string(&branch->remote_name, key, value);
397 } else if (!strcmp(subkey, "pushremote")) {
398 FREE_AND_NULL(branch->pushremote_name);
399 return git_config_string(&branch->pushremote_name, key, value);
400 } else if (!strcmp(subkey, "merge")) {
401 if (!value)
402 return config_error_nonbool(key);
403 add_merge(branch, xstrdup(value));
405 return 0;
407 if (parse_config_key(key, "url", &name, &namelen, &subkey) >= 0) {
408 struct rewrite *rewrite;
409 if (!name)
410 return 0;
411 if (!strcmp(subkey, "insteadof")) {
412 if (!value)
413 return config_error_nonbool(key);
414 rewrite = make_rewrite(&remote_state->rewrites, name,
415 namelen);
416 add_instead_of(rewrite, xstrdup(value));
417 } else if (!strcmp(subkey, "pushinsteadof")) {
418 if (!value)
419 return config_error_nonbool(key);
420 rewrite = make_rewrite(&remote_state->rewrites_push,
421 name, namelen);
422 add_instead_of(rewrite, xstrdup(value));
426 if (parse_config_key(key, "remote", &name, &namelen, &subkey) < 0)
427 return 0;
429 /* Handle remote.* variables */
430 if (!name && !strcmp(subkey, "pushdefault")) {
431 FREE_AND_NULL(remote_state->pushremote_name);
432 return git_config_string(&remote_state->pushremote_name, key,
433 value);
436 if (!name)
437 return 0;
438 /* Handle remote.<name>.* variables */
439 if (*name == '/') {
440 warning(_("config remote shorthand cannot begin with '/': %s"),
441 name);
442 return 0;
444 remote = make_remote(remote_state, name, namelen);
445 remote->origin = REMOTE_CONFIG;
446 if (kvi->scope == CONFIG_SCOPE_LOCAL ||
447 kvi->scope == CONFIG_SCOPE_WORKTREE)
448 remote->configured_in_repo = 1;
449 if (!strcmp(subkey, "mirror"))
450 remote->mirror = git_config_bool(key, value);
451 else if (!strcmp(subkey, "skipdefaultupdate"))
452 remote->skip_default_update = git_config_bool(key, value);
453 else if (!strcmp(subkey, "skipfetchall"))
454 remote->skip_default_update = git_config_bool(key, value);
455 else if (!strcmp(subkey, "prune"))
456 remote->prune = git_config_bool(key, value);
457 else if (!strcmp(subkey, "prunetags"))
458 remote->prune_tags = git_config_bool(key, value);
459 else if (!strcmp(subkey, "url")) {
460 if (!value)
461 return config_error_nonbool(key);
462 add_url(remote, value);
463 } else if (!strcmp(subkey, "pushurl")) {
464 if (!value)
465 return config_error_nonbool(key);
466 add_pushurl(remote, value);
467 } else if (!strcmp(subkey, "push")) {
468 char *v;
469 if (git_config_string(&v, key, value))
470 return -1;
471 refspec_append(&remote->push, v);
472 free(v);
473 } else if (!strcmp(subkey, "fetch")) {
474 char *v;
475 if (git_config_string(&v, key, value))
476 return -1;
477 refspec_append(&remote->fetch, v);
478 free(v);
479 } else if (!strcmp(subkey, "receivepack")) {
480 char *v;
481 if (git_config_string(&v, key, value))
482 return -1;
483 if (!remote->receivepack)
484 remote->receivepack = v;
485 else
486 error(_("more than one receivepack given, using the first"));
487 } else if (!strcmp(subkey, "uploadpack")) {
488 char *v;
489 if (git_config_string(&v, key, value))
490 return -1;
491 if (!remote->uploadpack)
492 remote->uploadpack = v;
493 else
494 error(_("more than one uploadpack given, using the first"));
495 } else if (!strcmp(subkey, "tagopt")) {
496 if (!strcmp(value, "--no-tags"))
497 remote->fetch_tags = -1;
498 else if (!strcmp(value, "--tags"))
499 remote->fetch_tags = 2;
500 } else if (!strcmp(subkey, "proxy")) {
501 FREE_AND_NULL(remote->http_proxy);
502 return git_config_string(&remote->http_proxy,
503 key, value);
504 } else if (!strcmp(subkey, "proxyauthmethod")) {
505 FREE_AND_NULL(remote->http_proxy_authmethod);
506 return git_config_string(&remote->http_proxy_authmethod,
507 key, value);
508 } else if (!strcmp(subkey, "vcs")) {
509 FREE_AND_NULL(remote->foreign_vcs);
510 return git_config_string(&remote->foreign_vcs, key, value);
512 return 0;
515 static void alias_all_urls(struct remote_state *remote_state)
517 int i, j;
518 for (i = 0; i < remote_state->remotes_nr; i++) {
519 int add_pushurl_aliases;
520 if (!remote_state->remotes[i])
521 continue;
522 for (j = 0; j < remote_state->remotes[i]->pushurl.nr; j++) {
523 char *alias = alias_url(remote_state->remotes[i]->pushurl.v[j],
524 &remote_state->rewrites);
525 if (alias)
526 strvec_replace(&remote_state->remotes[i]->pushurl,
527 j, alias);
528 free(alias);
530 add_pushurl_aliases = remote_state->remotes[i]->pushurl.nr == 0;
531 for (j = 0; j < remote_state->remotes[i]->url.nr; j++) {
532 char *alias;
533 if (add_pushurl_aliases)
534 add_pushurl_alias(
535 remote_state, remote_state->remotes[i],
536 remote_state->remotes[i]->url.v[j]);
537 alias = alias_url(remote_state->remotes[i]->url.v[j],
538 &remote_state->rewrites);
539 if (alias)
540 strvec_replace(&remote_state->remotes[i]->url,
541 j, alias);
542 free(alias);
547 static void read_config(struct repository *repo, int early)
549 int flag;
551 if (repo->remote_state->initialized)
552 return;
553 repo->remote_state->initialized = 1;
555 repo->remote_state->current_branch = NULL;
556 if (startup_info->have_repository && !early) {
557 const char *head_ref = refs_resolve_ref_unsafe(
558 get_main_ref_store(repo), "HEAD", 0, NULL, &flag);
559 if (head_ref && (flag & REF_ISSYMREF) &&
560 skip_prefix(head_ref, "refs/heads/", &head_ref)) {
561 repo->remote_state->current_branch = make_branch(
562 repo->remote_state, head_ref, strlen(head_ref));
565 repo_config(repo, handle_config, repo->remote_state);
566 alias_all_urls(repo->remote_state);
569 static int valid_remote_nick(const char *name)
571 if (!name[0] || is_dot_or_dotdot(name))
572 return 0;
574 /* remote nicknames cannot contain slashes */
575 while (*name)
576 if (is_dir_sep(*name++))
577 return 0;
578 return 1;
581 static const char *remotes_remote_for_branch(struct remote_state *remote_state,
582 struct branch *branch,
583 int *explicit)
585 if (branch && branch->remote_name) {
586 if (explicit)
587 *explicit = 1;
588 return branch->remote_name;
590 if (explicit)
591 *explicit = 0;
592 if (remote_state->remotes_nr == 1)
593 return remote_state->remotes[0]->name;
594 return "origin";
597 const char *remote_for_branch(struct branch *branch, int *explicit)
599 read_config(the_repository, 0);
600 die_on_missing_branch(the_repository, branch);
602 return remotes_remote_for_branch(the_repository->remote_state, branch,
603 explicit);
606 static const char *
607 remotes_pushremote_for_branch(struct remote_state *remote_state,
608 struct branch *branch, int *explicit)
610 if (branch && branch->pushremote_name) {
611 if (explicit)
612 *explicit = 1;
613 return branch->pushremote_name;
615 if (remote_state->pushremote_name) {
616 if (explicit)
617 *explicit = 1;
618 return remote_state->pushremote_name;
620 return remotes_remote_for_branch(remote_state, branch, explicit);
623 const char *pushremote_for_branch(struct branch *branch, int *explicit)
625 read_config(the_repository, 0);
626 die_on_missing_branch(the_repository, branch);
628 return remotes_pushremote_for_branch(the_repository->remote_state,
629 branch, explicit);
632 static struct remote *remotes_remote_get(struct remote_state *remote_state,
633 const char *name);
635 char *remote_ref_for_branch(struct branch *branch, int for_push)
637 read_config(the_repository, 0);
638 die_on_missing_branch(the_repository, branch);
640 if (branch) {
641 if (!for_push) {
642 if (branch->merge_nr) {
643 return xstrdup(branch->merge_name[0]);
645 } else {
646 char *dst;
647 const char *remote_name = remotes_pushremote_for_branch(
648 the_repository->remote_state, branch,
649 NULL);
650 struct remote *remote = remotes_remote_get(
651 the_repository->remote_state, remote_name);
653 if (remote && remote->push.nr &&
654 (dst = apply_refspecs(&remote->push,
655 branch->refname))) {
656 return dst;
660 return NULL;
663 static void validate_remote_url(struct remote *remote)
665 int i;
666 const char *value;
667 struct strbuf redacted = STRBUF_INIT;
668 int warn_not_die;
670 if (git_config_get_string_tmp("transfer.credentialsinurl", &value))
671 return;
673 if (!strcmp("warn", value))
674 warn_not_die = 1;
675 else if (!strcmp("die", value))
676 warn_not_die = 0;
677 else if (!strcmp("allow", value))
678 return;
679 else
680 die(_("unrecognized value transfer.credentialsInUrl: '%s'"), value);
682 for (i = 0; i < remote->url.nr; i++) {
683 struct url_info url_info = { 0 };
685 if (!url_normalize(remote->url.v[i], &url_info) ||
686 !url_info.passwd_off)
687 goto loop_cleanup;
689 strbuf_reset(&redacted);
690 strbuf_add(&redacted, url_info.url, url_info.passwd_off);
691 strbuf_addstr(&redacted, "<redacted>");
692 strbuf_addstr(&redacted,
693 url_info.url + url_info.passwd_off + url_info.passwd_len);
695 if (warn_not_die)
696 warning(_("URL '%s' uses plaintext credentials"), redacted.buf);
697 else
698 die(_("URL '%s' uses plaintext credentials"), redacted.buf);
700 loop_cleanup:
701 free(url_info.url);
704 strbuf_release(&redacted);
707 static struct remote *
708 remotes_remote_get_1(struct remote_state *remote_state, const char *name,
709 const char *(*get_default)(struct remote_state *,
710 struct branch *, int *))
712 struct remote *ret;
713 int name_given = 0;
715 if (name)
716 name_given = 1;
717 else
718 name = get_default(remote_state, remote_state->current_branch,
719 &name_given);
721 ret = make_remote(remote_state, name, 0);
722 if (valid_remote_nick(name) && have_git_dir()) {
723 if (!valid_remote(ret))
724 read_remotes_file(remote_state, ret);
725 if (!valid_remote(ret))
726 read_branches_file(remote_state, ret);
728 if (name_given && !valid_remote(ret))
729 add_url_alias(remote_state, ret, name);
730 if (!valid_remote(ret))
731 return NULL;
733 validate_remote_url(ret);
735 return ret;
738 static inline struct remote *
739 remotes_remote_get(struct remote_state *remote_state, const char *name)
741 return remotes_remote_get_1(remote_state, name,
742 remotes_remote_for_branch);
745 struct remote *remote_get(const char *name)
747 read_config(the_repository, 0);
748 return remotes_remote_get(the_repository->remote_state, name);
751 struct remote *remote_get_early(const char *name)
753 read_config(the_repository, 1);
754 return remotes_remote_get(the_repository->remote_state, name);
757 static inline struct remote *
758 remotes_pushremote_get(struct remote_state *remote_state, const char *name)
760 return remotes_remote_get_1(remote_state, name,
761 remotes_pushremote_for_branch);
764 struct remote *pushremote_get(const char *name)
766 read_config(the_repository, 0);
767 return remotes_pushremote_get(the_repository->remote_state, name);
770 int remote_is_configured(struct remote *remote, int in_repo)
772 if (!remote)
773 return 0;
774 if (in_repo)
775 return remote->configured_in_repo;
776 return !!remote->origin;
779 int for_each_remote(each_remote_fn fn, void *priv)
781 int i, result = 0;
782 read_config(the_repository, 0);
783 for (i = 0; i < the_repository->remote_state->remotes_nr && !result;
784 i++) {
785 struct remote *remote =
786 the_repository->remote_state->remotes[i];
787 if (!remote)
788 continue;
789 result = fn(remote, priv);
791 return result;
794 static void handle_duplicate(struct ref *ref1, struct ref *ref2)
796 if (strcmp(ref1->name, ref2->name)) {
797 if (ref1->fetch_head_status != FETCH_HEAD_IGNORE &&
798 ref2->fetch_head_status != FETCH_HEAD_IGNORE) {
799 die(_("Cannot fetch both %s and %s to %s"),
800 ref1->name, ref2->name, ref2->peer_ref->name);
801 } else if (ref1->fetch_head_status != FETCH_HEAD_IGNORE &&
802 ref2->fetch_head_status == FETCH_HEAD_IGNORE) {
803 warning(_("%s usually tracks %s, not %s"),
804 ref2->peer_ref->name, ref2->name, ref1->name);
805 } else if (ref1->fetch_head_status == FETCH_HEAD_IGNORE &&
806 ref2->fetch_head_status == FETCH_HEAD_IGNORE) {
807 die(_("%s tracks both %s and %s"),
808 ref2->peer_ref->name, ref1->name, ref2->name);
809 } else {
811 * This last possibility doesn't occur because
812 * FETCH_HEAD_IGNORE entries always appear at
813 * the end of the list.
815 BUG("Internal error");
818 free(ref2->peer_ref);
819 free(ref2);
822 struct ref *ref_remove_duplicates(struct ref *ref_map)
824 struct string_list refs = STRING_LIST_INIT_NODUP;
825 struct ref *retval = NULL;
826 struct ref **p = &retval;
828 while (ref_map) {
829 struct ref *ref = ref_map;
831 ref_map = ref_map->next;
832 ref->next = NULL;
834 if (!ref->peer_ref) {
835 *p = ref;
836 p = &ref->next;
837 } else {
838 struct string_list_item *item =
839 string_list_insert(&refs, ref->peer_ref->name);
841 if (item->util) {
842 /* Entry already existed */
843 handle_duplicate((struct ref *)item->util, ref);
844 } else {
845 *p = ref;
846 p = &ref->next;
847 item->util = ref;
852 string_list_clear(&refs, 0);
853 return retval;
856 int remote_has_url(struct remote *remote, const char *url)
858 int i;
859 for (i = 0; i < remote->url.nr; i++) {
860 if (!strcmp(remote->url.v[i], url))
861 return 1;
863 return 0;
866 struct strvec *push_url_of_remote(struct remote *remote)
868 return remote->pushurl.nr ? &remote->pushurl : &remote->url;
871 static int match_name_with_pattern(const char *key, const char *name,
872 const char *value, char **result)
874 const char *kstar = strchr(key, '*');
875 size_t klen;
876 size_t ksuffixlen;
877 size_t namelen;
878 int ret;
879 if (!kstar)
880 die(_("key '%s' of pattern had no '*'"), key);
881 klen = kstar - key;
882 ksuffixlen = strlen(kstar + 1);
883 namelen = strlen(name);
884 ret = !strncmp(name, key, klen) && namelen >= klen + ksuffixlen &&
885 !memcmp(name + namelen - ksuffixlen, kstar + 1, ksuffixlen);
886 if (ret && value) {
887 struct strbuf sb = STRBUF_INIT;
888 const char *vstar = strchr(value, '*');
889 if (!vstar)
890 die(_("value '%s' of pattern has no '*'"), value);
891 strbuf_add(&sb, value, vstar - value);
892 strbuf_add(&sb, name + klen, namelen - klen - ksuffixlen);
893 strbuf_addstr(&sb, vstar + 1);
894 *result = strbuf_detach(&sb, NULL);
896 return ret;
899 static int refspec_match(const struct refspec_item *refspec,
900 const char *name)
902 if (refspec->pattern)
903 return match_name_with_pattern(refspec->src, name, NULL, NULL);
905 return !strcmp(refspec->src, name);
908 int omit_name_by_refspec(const char *name, struct refspec *rs)
910 int i;
912 for (i = 0; i < rs->nr; i++) {
913 if (rs->items[i].negative && refspec_match(&rs->items[i], name))
914 return 1;
916 return 0;
919 struct ref *apply_negative_refspecs(struct ref *ref_map, struct refspec *rs)
921 struct ref **tail;
923 for (tail = &ref_map; *tail; ) {
924 struct ref *ref = *tail;
926 if (omit_name_by_refspec(ref->name, rs)) {
927 *tail = ref->next;
928 free(ref->peer_ref);
929 free(ref);
930 } else
931 tail = &ref->next;
934 return ref_map;
937 static int query_matches_negative_refspec(struct refspec *rs, struct refspec_item *query)
939 int i, matched_negative = 0;
940 int find_src = !query->src;
941 struct string_list reversed = STRING_LIST_INIT_DUP;
942 const char *needle = find_src ? query->dst : query->src;
945 * Check whether the queried ref matches any negative refpsec. If so,
946 * then we should ultimately treat this as not matching the query at
947 * all.
949 * Note that negative refspecs always match the source, but the query
950 * item uses the destination. To handle this, we apply pattern
951 * refspecs in reverse to figure out if the query source matches any
952 * of the negative refspecs.
954 * The first loop finds and expands all positive refspecs
955 * matched by the queried ref.
957 * The second loop checks if any of the results of the first loop
958 * match any negative refspec.
960 for (i = 0; i < rs->nr; i++) {
961 struct refspec_item *refspec = &rs->items[i];
962 char *expn_name;
964 if (refspec->negative)
965 continue;
967 /* Note the reversal of src and dst */
968 if (refspec->pattern) {
969 const char *key = refspec->dst ? refspec->dst : refspec->src;
970 const char *value = refspec->src;
972 if (match_name_with_pattern(key, needle, value, &expn_name))
973 string_list_append_nodup(&reversed, expn_name);
974 } else if (refspec->matching) {
975 /* For the special matching refspec, any query should match */
976 string_list_append(&reversed, needle);
977 } else if (!refspec->src) {
978 BUG("refspec->src should not be null here");
979 } else if (!strcmp(needle, refspec->src)) {
980 string_list_append(&reversed, refspec->src);
984 for (i = 0; !matched_negative && i < reversed.nr; i++) {
985 if (omit_name_by_refspec(reversed.items[i].string, rs))
986 matched_negative = 1;
989 string_list_clear(&reversed, 0);
991 return matched_negative;
994 static void query_refspecs_multiple(struct refspec *rs,
995 struct refspec_item *query,
996 struct string_list *results)
998 int i;
999 int find_src = !query->src;
1001 if (find_src && !query->dst)
1002 BUG("query_refspecs_multiple: need either src or dst");
1004 if (query_matches_negative_refspec(rs, query))
1005 return;
1007 for (i = 0; i < rs->nr; i++) {
1008 struct refspec_item *refspec = &rs->items[i];
1009 const char *key = find_src ? refspec->dst : refspec->src;
1010 const char *value = find_src ? refspec->src : refspec->dst;
1011 const char *needle = find_src ? query->dst : query->src;
1012 char **result = find_src ? &query->src : &query->dst;
1014 if (!refspec->dst || refspec->negative)
1015 continue;
1016 if (refspec->pattern) {
1017 if (match_name_with_pattern(key, needle, value, result))
1018 string_list_append_nodup(results, *result);
1019 } else if (!strcmp(needle, key)) {
1020 string_list_append(results, value);
1025 int query_refspecs(struct refspec *rs, struct refspec_item *query)
1027 int i;
1028 int find_src = !query->src;
1029 const char *needle = find_src ? query->dst : query->src;
1030 char **result = find_src ? &query->src : &query->dst;
1032 if (find_src && !query->dst)
1033 BUG("query_refspecs: need either src or dst");
1035 if (query_matches_negative_refspec(rs, query))
1036 return -1;
1038 for (i = 0; i < rs->nr; i++) {
1039 struct refspec_item *refspec = &rs->items[i];
1040 const char *key = find_src ? refspec->dst : refspec->src;
1041 const char *value = find_src ? refspec->src : refspec->dst;
1043 if (!refspec->dst || refspec->negative)
1044 continue;
1045 if (refspec->pattern) {
1046 if (match_name_with_pattern(key, needle, value, result)) {
1047 query->force = refspec->force;
1048 return 0;
1050 } else if (!strcmp(needle, key)) {
1051 *result = xstrdup(value);
1052 query->force = refspec->force;
1053 return 0;
1056 return -1;
1059 char *apply_refspecs(struct refspec *rs, const char *name)
1061 struct refspec_item query;
1063 memset(&query, 0, sizeof(struct refspec_item));
1064 query.src = (char *)name;
1066 if (query_refspecs(rs, &query))
1067 return NULL;
1069 return query.dst;
1072 int remote_find_tracking(struct remote *remote, struct refspec_item *refspec)
1074 return query_refspecs(&remote->fetch, refspec);
1077 static struct ref *alloc_ref_with_prefix(const char *prefix, size_t prefixlen,
1078 const char *name)
1080 size_t len = strlen(name);
1081 struct ref *ref = xcalloc(1, st_add4(sizeof(*ref), prefixlen, len, 1));
1082 memcpy(ref->name, prefix, prefixlen);
1083 memcpy(ref->name + prefixlen, name, len);
1084 return ref;
1087 struct ref *alloc_ref(const char *name)
1089 return alloc_ref_with_prefix("", 0, name);
1092 struct ref *copy_ref(const struct ref *ref)
1094 struct ref *cpy;
1095 size_t len;
1096 if (!ref)
1097 return NULL;
1098 len = st_add3(sizeof(struct ref), strlen(ref->name), 1);
1099 cpy = xmalloc(len);
1100 memcpy(cpy, ref, len);
1101 cpy->next = NULL;
1102 cpy->symref = xstrdup_or_null(ref->symref);
1103 cpy->remote_status = xstrdup_or_null(ref->remote_status);
1104 cpy->peer_ref = copy_ref(ref->peer_ref);
1105 return cpy;
1108 struct ref *copy_ref_list(const struct ref *ref)
1110 struct ref *ret = NULL;
1111 struct ref **tail = &ret;
1112 while (ref) {
1113 *tail = copy_ref(ref);
1114 ref = ref->next;
1115 tail = &((*tail)->next);
1117 return ret;
1120 void free_one_ref(struct ref *ref)
1122 if (!ref)
1123 return;
1124 free_one_ref(ref->peer_ref);
1125 free(ref->remote_status);
1126 free(ref->symref);
1127 free(ref);
1130 void free_refs(struct ref *ref)
1132 struct ref *next;
1133 while (ref) {
1134 next = ref->next;
1135 free_one_ref(ref);
1136 ref = next;
1140 int count_refspec_match(const char *pattern,
1141 struct ref *refs,
1142 struct ref **matched_ref)
1144 int patlen = strlen(pattern);
1145 struct ref *matched_weak = NULL;
1146 struct ref *matched = NULL;
1147 int weak_match = 0;
1148 int match = 0;
1150 for (weak_match = match = 0; refs; refs = refs->next) {
1151 char *name = refs->name;
1152 int namelen = strlen(name);
1154 if (!refname_match(pattern, name))
1155 continue;
1157 /* A match is "weak" if it is with refs outside
1158 * heads or tags, and did not specify the pattern
1159 * in full (e.g. "refs/remotes/origin/master") or at
1160 * least from the toplevel (e.g. "remotes/origin/master");
1161 * otherwise "git push $URL master" would result in
1162 * ambiguity between remotes/origin/master and heads/master
1163 * at the remote site.
1165 if (namelen != patlen &&
1166 patlen != namelen - 5 &&
1167 !starts_with(name, "refs/heads/") &&
1168 !starts_with(name, "refs/tags/")) {
1169 /* We want to catch the case where only weak
1170 * matches are found and there are multiple
1171 * matches, and where more than one strong
1172 * matches are found, as ambiguous. One
1173 * strong match with zero or more weak matches
1174 * are acceptable as a unique match.
1176 matched_weak = refs;
1177 weak_match++;
1179 else {
1180 matched = refs;
1181 match++;
1184 if (!matched) {
1185 if (matched_ref)
1186 *matched_ref = matched_weak;
1187 return weak_match;
1189 else {
1190 if (matched_ref)
1191 *matched_ref = matched;
1192 return match;
1196 static void tail_link_ref(struct ref *ref, struct ref ***tail)
1198 **tail = ref;
1199 while (ref->next)
1200 ref = ref->next;
1201 *tail = &ref->next;
1204 static struct ref *alloc_delete_ref(void)
1206 struct ref *ref = alloc_ref("(delete)");
1207 oidclr(&ref->new_oid, the_repository->hash_algo);
1208 return ref;
1211 static int try_explicit_object_name(const char *name,
1212 struct ref **match)
1214 struct object_id oid;
1216 if (!*name) {
1217 if (match)
1218 *match = alloc_delete_ref();
1219 return 0;
1222 if (repo_get_oid(the_repository, name, &oid))
1223 return -1;
1225 if (match) {
1226 *match = alloc_ref(name);
1227 oidcpy(&(*match)->new_oid, &oid);
1229 return 0;
1232 static struct ref *make_linked_ref(const char *name, struct ref ***tail)
1234 struct ref *ret = alloc_ref(name);
1235 tail_link_ref(ret, tail);
1236 return ret;
1239 static char *guess_ref(const char *name, struct ref *peer)
1241 struct strbuf buf = STRBUF_INIT;
1243 const char *r = refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
1244 peer->name,
1245 RESOLVE_REF_READING,
1246 NULL, NULL);
1247 if (!r)
1248 return NULL;
1250 if (starts_with(r, "refs/heads/")) {
1251 strbuf_addstr(&buf, "refs/heads/");
1252 } else if (starts_with(r, "refs/tags/")) {
1253 strbuf_addstr(&buf, "refs/tags/");
1254 } else {
1255 return NULL;
1258 strbuf_addstr(&buf, name);
1259 return strbuf_detach(&buf, NULL);
1262 static int match_explicit_lhs(struct ref *src,
1263 struct refspec_item *rs,
1264 struct ref **match,
1265 int *allocated_match)
1267 switch (count_refspec_match(rs->src, src, match)) {
1268 case 1:
1269 if (allocated_match)
1270 *allocated_match = 0;
1271 return 0;
1272 case 0:
1273 /* The source could be in the get_sha1() format
1274 * not a reference name. :refs/other is a
1275 * way to delete 'other' ref at the remote end.
1277 if (try_explicit_object_name(rs->src, match) < 0)
1278 return error(_("src refspec %s does not match any"), rs->src);
1279 if (allocated_match)
1280 *allocated_match = 1;
1281 return 0;
1282 default:
1283 return error(_("src refspec %s matches more than one"), rs->src);
1287 static void show_push_unqualified_ref_name_error(const char *dst_value,
1288 const char *matched_src_name)
1290 struct object_id oid;
1291 enum object_type type;
1294 * TRANSLATORS: "matches '%s'%" is the <dst> part of "git push
1295 * <remote> <src>:<dst>" push, and "being pushed ('%s')" is
1296 * the <src>.
1298 error(_("The destination you provided is not a full refname (i.e.,\n"
1299 "starting with \"refs/\"). We tried to guess what you meant by:\n"
1300 "\n"
1301 "- Looking for a ref that matches '%s' on the remote side.\n"
1302 "- Checking if the <src> being pushed ('%s')\n"
1303 " is a ref in \"refs/{heads,tags}/\". If so we add a corresponding\n"
1304 " refs/{heads,tags}/ prefix on the remote side.\n"
1305 "\n"
1306 "Neither worked, so we gave up. You must fully qualify the ref."),
1307 dst_value, matched_src_name);
1309 if (!advice_enabled(ADVICE_PUSH_UNQUALIFIED_REF_NAME))
1310 return;
1312 if (repo_get_oid(the_repository, matched_src_name, &oid))
1313 BUG("'%s' is not a valid object, "
1314 "match_explicit_lhs() should catch this!",
1315 matched_src_name);
1316 type = oid_object_info(the_repository, &oid, NULL);
1317 if (type == OBJ_COMMIT) {
1318 advise(_("The <src> part of the refspec is a commit object.\n"
1319 "Did you mean to create a new branch by pushing to\n"
1320 "'%s:refs/heads/%s'?"),
1321 matched_src_name, dst_value);
1322 } else if (type == OBJ_TAG) {
1323 advise(_("The <src> part of the refspec is a tag object.\n"
1324 "Did you mean to create a new tag by pushing to\n"
1325 "'%s:refs/tags/%s'?"),
1326 matched_src_name, dst_value);
1327 } else if (type == OBJ_TREE) {
1328 advise(_("The <src> part of the refspec is a tree object.\n"
1329 "Did you mean to tag a new tree by pushing to\n"
1330 "'%s:refs/tags/%s'?"),
1331 matched_src_name, dst_value);
1332 } else if (type == OBJ_BLOB) {
1333 advise(_("The <src> part of the refspec is a blob object.\n"
1334 "Did you mean to tag a new blob by pushing to\n"
1335 "'%s:refs/tags/%s'?"),
1336 matched_src_name, dst_value);
1337 } else {
1338 BUG("'%s' should be commit/tag/tree/blob, is '%d'",
1339 matched_src_name, type);
1343 static int match_explicit(struct ref *src, struct ref *dst,
1344 struct ref ***dst_tail,
1345 struct refspec_item *rs)
1347 struct ref *matched_src = NULL, *matched_dst = NULL;
1348 int allocated_src = 0, ret;
1350 const char *dst_value = rs->dst;
1351 char *dst_guess;
1353 if (rs->pattern || rs->matching || rs->negative) {
1354 ret = 0;
1355 goto out;
1358 if (match_explicit_lhs(src, rs, &matched_src, &allocated_src) < 0) {
1359 ret = -1;
1360 goto out;
1363 if (!dst_value) {
1364 int flag;
1366 dst_value = refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
1367 matched_src->name,
1368 RESOLVE_REF_READING,
1369 NULL, &flag);
1370 if (!dst_value ||
1371 ((flag & REF_ISSYMREF) &&
1372 !starts_with(dst_value, "refs/heads/")))
1373 die(_("%s cannot be resolved to branch"),
1374 matched_src->name);
1377 switch (count_refspec_match(dst_value, dst, &matched_dst)) {
1378 case 1:
1379 break;
1380 case 0:
1381 if (starts_with(dst_value, "refs/")) {
1382 matched_dst = make_linked_ref(dst_value, dst_tail);
1383 } else if (is_null_oid(&matched_src->new_oid)) {
1384 error(_("unable to delete '%s': remote ref does not exist"),
1385 dst_value);
1386 } else if ((dst_guess = guess_ref(dst_value, matched_src))) {
1387 matched_dst = make_linked_ref(dst_guess, dst_tail);
1388 free(dst_guess);
1389 } else {
1390 show_push_unqualified_ref_name_error(dst_value,
1391 matched_src->name);
1393 break;
1394 default:
1395 matched_dst = NULL;
1396 error(_("dst refspec %s matches more than one"),
1397 dst_value);
1398 break;
1401 if (!matched_dst) {
1402 ret = -1;
1403 goto out;
1406 if (matched_dst->peer_ref) {
1407 ret = error(_("dst ref %s receives from more than one src"),
1408 matched_dst->name);
1409 goto out;
1410 } else {
1411 matched_dst->peer_ref = allocated_src ?
1412 matched_src :
1413 copy_ref(matched_src);
1414 matched_dst->force = rs->force;
1415 matched_src = NULL;
1418 ret = 0;
1420 out:
1421 if (allocated_src)
1422 free_one_ref(matched_src);
1423 return ret;
1426 static int match_explicit_refs(struct ref *src, struct ref *dst,
1427 struct ref ***dst_tail, struct refspec *rs)
1429 int i, errs;
1430 for (i = errs = 0; i < rs->nr; i++)
1431 errs += match_explicit(src, dst, dst_tail, &rs->items[i]);
1432 return errs;
1435 static char *get_ref_match(const struct refspec *rs, const struct ref *ref,
1436 int send_mirror, int direction,
1437 const struct refspec_item **ret_pat)
1439 const struct refspec_item *pat;
1440 char *name;
1441 int i;
1442 int matching_refs = -1;
1443 for (i = 0; i < rs->nr; i++) {
1444 const struct refspec_item *item = &rs->items[i];
1446 if (item->negative)
1447 continue;
1449 if (item->matching &&
1450 (matching_refs == -1 || item->force)) {
1451 matching_refs = i;
1452 continue;
1455 if (item->pattern) {
1456 const char *dst_side = item->dst ? item->dst : item->src;
1457 int match;
1458 if (direction == FROM_SRC)
1459 match = match_name_with_pattern(item->src, ref->name, dst_side, &name);
1460 else
1461 match = match_name_with_pattern(dst_side, ref->name, item->src, &name);
1462 if (match) {
1463 matching_refs = i;
1464 break;
1468 if (matching_refs == -1)
1469 return NULL;
1471 pat = &rs->items[matching_refs];
1472 if (pat->matching) {
1474 * "matching refs"; traditionally we pushed everything
1475 * including refs outside refs/heads/ hierarchy, but
1476 * that does not make much sense these days.
1478 if (!send_mirror && !starts_with(ref->name, "refs/heads/"))
1479 return NULL;
1480 name = xstrdup(ref->name);
1482 if (ret_pat)
1483 *ret_pat = pat;
1484 return name;
1487 static struct ref **tail_ref(struct ref **head)
1489 struct ref **tail = head;
1490 while (*tail)
1491 tail = &((*tail)->next);
1492 return tail;
1495 struct tips {
1496 struct commit **tip;
1497 int nr, alloc;
1500 static void add_to_tips(struct tips *tips, const struct object_id *oid)
1502 struct commit *commit;
1504 if (is_null_oid(oid))
1505 return;
1506 commit = lookup_commit_reference_gently(the_repository, oid, 1);
1507 if (!commit || (commit->object.flags & TMP_MARK))
1508 return;
1509 commit->object.flags |= TMP_MARK;
1510 ALLOC_GROW(tips->tip, tips->nr + 1, tips->alloc);
1511 tips->tip[tips->nr++] = commit;
1514 static void add_missing_tags(struct ref *src, struct ref **dst, struct ref ***dst_tail)
1516 struct string_list dst_tag = STRING_LIST_INIT_NODUP;
1517 struct string_list src_tag = STRING_LIST_INIT_NODUP;
1518 struct string_list_item *item;
1519 struct ref *ref;
1520 struct tips sent_tips;
1523 * Collect everything we know they would have at the end of
1524 * this push, and collect all tags they have.
1526 memset(&sent_tips, 0, sizeof(sent_tips));
1527 for (ref = *dst; ref; ref = ref->next) {
1528 if (ref->peer_ref &&
1529 !is_null_oid(&ref->peer_ref->new_oid))
1530 add_to_tips(&sent_tips, &ref->peer_ref->new_oid);
1531 else
1532 add_to_tips(&sent_tips, &ref->old_oid);
1533 if (starts_with(ref->name, "refs/tags/"))
1534 string_list_append(&dst_tag, ref->name);
1536 clear_commit_marks_many(sent_tips.nr, sent_tips.tip, TMP_MARK);
1538 string_list_sort(&dst_tag);
1540 /* Collect tags they do not have. */
1541 for (ref = src; ref; ref = ref->next) {
1542 if (!starts_with(ref->name, "refs/tags/"))
1543 continue; /* not a tag */
1544 if (string_list_has_string(&dst_tag, ref->name))
1545 continue; /* they already have it */
1546 if (oid_object_info(the_repository, &ref->new_oid, NULL) != OBJ_TAG)
1547 continue; /* be conservative */
1548 item = string_list_append(&src_tag, ref->name);
1549 item->util = ref;
1551 string_list_clear(&dst_tag, 0);
1554 * At this point, src_tag lists tags that are missing from
1555 * dst, and sent_tips lists the tips we are pushing or those
1556 * that we know they already have. An element in the src_tag
1557 * that is an ancestor of any of the sent_tips needs to be
1558 * sent to the other side.
1560 if (sent_tips.nr) {
1561 const int reachable_flag = 1;
1562 struct commit_list *found_commits;
1563 struct commit **src_commits;
1564 int nr_src_commits = 0, alloc_src_commits = 16;
1565 ALLOC_ARRAY(src_commits, alloc_src_commits);
1567 for_each_string_list_item(item, &src_tag) {
1568 struct ref *ref = item->util;
1569 struct commit *commit;
1571 if (is_null_oid(&ref->new_oid))
1572 continue;
1573 commit = lookup_commit_reference_gently(the_repository,
1574 &ref->new_oid,
1576 if (!commit)
1577 /* not pushing a commit, which is not an error */
1578 continue;
1580 ALLOC_GROW(src_commits, nr_src_commits + 1, alloc_src_commits);
1581 src_commits[nr_src_commits++] = commit;
1584 found_commits = get_reachable_subset(sent_tips.tip, sent_tips.nr,
1585 src_commits, nr_src_commits,
1586 reachable_flag);
1588 for_each_string_list_item(item, &src_tag) {
1589 struct ref *dst_ref;
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;
1603 * Is this tag, which they do not have, reachable from
1604 * any of the commits we are sending?
1606 if (!(commit->object.flags & reachable_flag))
1607 continue;
1609 /* Add it in */
1610 dst_ref = make_linked_ref(ref->name, dst_tail);
1611 oidcpy(&dst_ref->new_oid, &ref->new_oid);
1612 dst_ref->peer_ref = copy_ref(ref);
1615 clear_commit_marks_many(nr_src_commits, src_commits, reachable_flag);
1616 free(src_commits);
1617 free_commit_list(found_commits);
1620 string_list_clear(&src_tag, 0);
1621 free(sent_tips.tip);
1624 struct ref *find_ref_by_name(const struct ref *list, const char *name)
1626 for ( ; list; list = list->next)
1627 if (!strcmp(list->name, name))
1628 return (struct ref *)list;
1629 return NULL;
1632 static void prepare_ref_index(struct string_list *ref_index, struct ref *ref)
1634 for ( ; ref; ref = ref->next)
1635 string_list_append_nodup(ref_index, ref->name)->util = ref;
1637 string_list_sort(ref_index);
1641 * Given only the set of local refs, sanity-check the set of push
1642 * refspecs. We can't catch all errors that match_push_refs would,
1643 * but we can catch some errors early before even talking to the
1644 * remote side.
1646 int check_push_refs(struct ref *src, struct refspec *rs)
1648 int ret = 0;
1649 int i;
1651 for (i = 0; i < rs->nr; i++) {
1652 struct refspec_item *item = &rs->items[i];
1654 if (item->pattern || item->matching || item->negative)
1655 continue;
1657 ret |= match_explicit_lhs(src, item, NULL, NULL);
1660 return ret;
1664 * Given the set of refs the local repository has, the set of refs the
1665 * remote repository has, and the refspec used for push, determine
1666 * what remote refs we will update and with what value by setting
1667 * peer_ref (which object is being pushed) and force (if the push is
1668 * forced) in elements of "dst". The function may add new elements to
1669 * dst (e.g. pushing to a new branch, done in match_explicit_refs).
1671 int match_push_refs(struct ref *src, struct ref **dst,
1672 struct refspec *rs, int flags)
1674 int send_all = flags & MATCH_REFS_ALL;
1675 int send_mirror = flags & MATCH_REFS_MIRROR;
1676 int send_prune = flags & MATCH_REFS_PRUNE;
1677 int errs;
1678 struct ref *ref, **dst_tail = tail_ref(dst);
1679 struct string_list dst_ref_index = STRING_LIST_INIT_NODUP;
1681 /* If no refspec is provided, use the default ":" */
1682 if (!rs->nr)
1683 refspec_append(rs, ":");
1685 errs = match_explicit_refs(src, *dst, &dst_tail, rs);
1687 /* pick the remainder */
1688 for (ref = src; ref; ref = ref->next) {
1689 struct string_list_item *dst_item;
1690 struct ref *dst_peer;
1691 const struct refspec_item *pat = NULL;
1692 char *dst_name;
1694 dst_name = get_ref_match(rs, ref, send_mirror, FROM_SRC, &pat);
1695 if (!dst_name)
1696 continue;
1698 if (!dst_ref_index.nr)
1699 prepare_ref_index(&dst_ref_index, *dst);
1701 dst_item = string_list_lookup(&dst_ref_index, dst_name);
1702 dst_peer = dst_item ? dst_item->util : NULL;
1703 if (dst_peer) {
1704 if (dst_peer->peer_ref)
1705 /* We're already sending something to this ref. */
1706 goto free_name;
1707 } else {
1708 if (pat->matching && !(send_all || send_mirror))
1710 * Remote doesn't have it, and we have no
1711 * explicit pattern, and we don't have
1712 * --all or --mirror.
1714 goto free_name;
1716 /* Create a new one and link it */
1717 dst_peer = make_linked_ref(dst_name, &dst_tail);
1718 oidcpy(&dst_peer->new_oid, &ref->new_oid);
1719 string_list_insert(&dst_ref_index,
1720 dst_peer->name)->util = dst_peer;
1722 dst_peer->peer_ref = copy_ref(ref);
1723 dst_peer->force = pat->force;
1724 free_name:
1725 free(dst_name);
1728 string_list_clear(&dst_ref_index, 0);
1730 if (flags & MATCH_REFS_FOLLOW_TAGS)
1731 add_missing_tags(src, dst, &dst_tail);
1733 if (send_prune) {
1734 struct string_list src_ref_index = STRING_LIST_INIT_NODUP;
1735 /* check for missing refs on the remote */
1736 for (ref = *dst; ref; ref = ref->next) {
1737 char *src_name;
1739 if (ref->peer_ref)
1740 /* We're already sending something to this ref. */
1741 continue;
1743 src_name = get_ref_match(rs, ref, send_mirror, FROM_DST, NULL);
1744 if (src_name) {
1745 if (!src_ref_index.nr)
1746 prepare_ref_index(&src_ref_index, src);
1747 if (!string_list_has_string(&src_ref_index,
1748 src_name))
1749 ref->peer_ref = alloc_delete_ref();
1750 free(src_name);
1753 string_list_clear(&src_ref_index, 0);
1756 *dst = apply_negative_refspecs(*dst, rs);
1758 if (errs)
1759 return -1;
1760 return 0;
1763 void set_ref_status_for_push(struct ref *remote_refs, int send_mirror,
1764 int force_update)
1766 struct ref *ref;
1768 for (ref = remote_refs; ref; ref = ref->next) {
1769 int force_ref_update = ref->force || force_update;
1770 int reject_reason = 0;
1772 if (ref->peer_ref)
1773 oidcpy(&ref->new_oid, &ref->peer_ref->new_oid);
1774 else if (!send_mirror)
1775 continue;
1777 ref->deletion = is_null_oid(&ref->new_oid);
1778 if (!ref->deletion &&
1779 oideq(&ref->old_oid, &ref->new_oid)) {
1780 ref->status = REF_STATUS_UPTODATE;
1781 continue;
1785 * If the remote ref has moved and is now different
1786 * from what we expect, reject any push.
1788 * It also is an error if the user told us to check
1789 * with the remote-tracking branch to find the value
1790 * to expect, but we did not have such a tracking
1791 * branch.
1793 * If the tip of the remote-tracking ref is unreachable
1794 * from any reflog entry of its local ref indicating a
1795 * possible update since checkout; reject the push.
1797 if (ref->expect_old_sha1) {
1798 if (!oideq(&ref->old_oid, &ref->old_oid_expect))
1799 reject_reason = REF_STATUS_REJECT_STALE;
1800 else if (ref->check_reachable && ref->unreachable)
1801 reject_reason =
1802 REF_STATUS_REJECT_REMOTE_UPDATED;
1803 else
1805 * If the ref isn't stale, and is reachable
1806 * from one of the reflog entries of
1807 * the local branch, force the update.
1809 force_ref_update = 1;
1813 * If the update isn't already rejected then check
1814 * the usual "must fast-forward" rules.
1816 * Decide whether an individual refspec A:B can be
1817 * pushed. The push will succeed if any of the
1818 * following are true:
1820 * (1) the remote reference B does not exist
1822 * (2) the remote reference B is being removed (i.e.,
1823 * pushing :B where no source is specified)
1825 * (3) the destination is not under refs/tags/, and
1826 * if the old and new value is a commit, the new
1827 * is a descendant of the old.
1829 * (4) it is forced using the +A:B notation, or by
1830 * passing the --force argument
1833 if (!reject_reason && !ref->deletion && !is_null_oid(&ref->old_oid)) {
1834 if (starts_with(ref->name, "refs/tags/"))
1835 reject_reason = REF_STATUS_REJECT_ALREADY_EXISTS;
1836 else if (!repo_has_object_file_with_flags(the_repository, &ref->old_oid, OBJECT_INFO_SKIP_FETCH_OBJECT))
1837 reject_reason = REF_STATUS_REJECT_FETCH_FIRST;
1838 else if (!lookup_commit_reference_gently(the_repository, &ref->old_oid, 1) ||
1839 !lookup_commit_reference_gently(the_repository, &ref->new_oid, 1))
1840 reject_reason = REF_STATUS_REJECT_NEEDS_FORCE;
1841 else if (!ref_newer(&ref->new_oid, &ref->old_oid))
1842 reject_reason = REF_STATUS_REJECT_NONFASTFORWARD;
1846 * "--force" will defeat any rejection implemented
1847 * by the rules above.
1849 if (!force_ref_update)
1850 ref->status = reject_reason;
1851 else if (reject_reason)
1852 ref->forced_update = 1;
1856 static void set_merge(struct remote_state *remote_state, struct branch *ret)
1858 struct remote *remote;
1859 char *ref;
1860 struct object_id oid;
1861 int i;
1863 if (!ret)
1864 return; /* no branch */
1865 if (ret->merge)
1866 return; /* already run */
1867 if (!ret->remote_name || !ret->merge_nr) {
1869 * no merge config; let's make sure we don't confuse callers
1870 * with a non-zero merge_nr but a NULL merge
1872 ret->merge_nr = 0;
1873 return;
1876 remote = remotes_remote_get(remote_state, ret->remote_name);
1878 CALLOC_ARRAY(ret->merge, ret->merge_nr);
1879 for (i = 0; i < ret->merge_nr; i++) {
1880 ret->merge[i] = xcalloc(1, sizeof(**ret->merge));
1881 ret->merge[i]->src = xstrdup(ret->merge_name[i]);
1882 if (!remote_find_tracking(remote, ret->merge[i]) ||
1883 strcmp(ret->remote_name, "."))
1884 continue;
1885 if (repo_dwim_ref(the_repository, ret->merge_name[i],
1886 strlen(ret->merge_name[i]), &oid, &ref,
1887 0) == 1)
1888 ret->merge[i]->dst = ref;
1889 else
1890 ret->merge[i]->dst = xstrdup(ret->merge_name[i]);
1894 struct branch *branch_get(const char *name)
1896 struct branch *ret;
1898 read_config(the_repository, 0);
1899 if (!name || !*name || !strcmp(name, "HEAD"))
1900 ret = the_repository->remote_state->current_branch;
1901 else
1902 ret = make_branch(the_repository->remote_state, name,
1903 strlen(name));
1904 set_merge(the_repository->remote_state, ret);
1905 return ret;
1908 int branch_has_merge_config(struct branch *branch)
1910 return branch && !!branch->merge;
1913 int branch_merge_matches(struct branch *branch,
1914 int i,
1915 const char *refname)
1917 if (!branch || i < 0 || i >= branch->merge_nr)
1918 return 0;
1919 return refname_match(branch->merge[i]->src, refname);
1922 __attribute__((format (printf,2,3)))
1923 static const char *error_buf(struct strbuf *err, const char *fmt, ...)
1925 if (err) {
1926 va_list ap;
1927 va_start(ap, fmt);
1928 strbuf_vaddf(err, fmt, ap);
1929 va_end(ap);
1931 return NULL;
1934 const char *branch_get_upstream(struct branch *branch, struct strbuf *err)
1936 if (!branch)
1937 return error_buf(err, _("HEAD does not point to a branch"));
1939 if (!branch->merge || !branch->merge[0]) {
1941 * no merge config; is it because the user didn't define any,
1942 * or because it is not a real branch, and get_branch
1943 * auto-vivified it?
1945 if (!refs_ref_exists(get_main_ref_store(the_repository), branch->refname))
1946 return error_buf(err, _("no such branch: '%s'"),
1947 branch->name);
1948 return error_buf(err,
1949 _("no upstream configured for branch '%s'"),
1950 branch->name);
1953 if (!branch->merge[0]->dst)
1954 return error_buf(err,
1955 _("upstream branch '%s' not stored as a remote-tracking branch"),
1956 branch->merge[0]->src);
1958 return branch->merge[0]->dst;
1961 static const char *tracking_for_push_dest(struct remote *remote,
1962 const char *refname,
1963 struct strbuf *err)
1965 char *ret;
1967 ret = apply_refspecs(&remote->fetch, refname);
1968 if (!ret)
1969 return error_buf(err,
1970 _("push destination '%s' on remote '%s' has no local tracking branch"),
1971 refname, remote->name);
1972 return ret;
1975 static const char *branch_get_push_1(struct remote_state *remote_state,
1976 struct branch *branch, struct strbuf *err)
1978 struct remote *remote;
1980 remote = remotes_remote_get(
1981 remote_state,
1982 remotes_pushremote_for_branch(remote_state, branch, NULL));
1983 if (!remote)
1984 return error_buf(err,
1985 _("branch '%s' has no remote for pushing"),
1986 branch->name);
1988 if (remote->push.nr) {
1989 char *dst;
1990 const char *ret;
1992 dst = apply_refspecs(&remote->push, branch->refname);
1993 if (!dst)
1994 return error_buf(err,
1995 _("push refspecs for '%s' do not include '%s'"),
1996 remote->name, branch->name);
1998 ret = tracking_for_push_dest(remote, dst, err);
1999 free(dst);
2000 return ret;
2003 if (remote->mirror)
2004 return tracking_for_push_dest(remote, branch->refname, err);
2006 switch (push_default) {
2007 case PUSH_DEFAULT_NOTHING:
2008 return error_buf(err, _("push has no destination (push.default is 'nothing')"));
2010 case PUSH_DEFAULT_MATCHING:
2011 case PUSH_DEFAULT_CURRENT:
2012 return tracking_for_push_dest(remote, branch->refname, err);
2014 case PUSH_DEFAULT_UPSTREAM:
2015 return branch_get_upstream(branch, err);
2017 case PUSH_DEFAULT_UNSPECIFIED:
2018 case PUSH_DEFAULT_SIMPLE:
2020 const char *up, *cur;
2022 up = branch_get_upstream(branch, err);
2023 if (!up)
2024 return NULL;
2025 cur = tracking_for_push_dest(remote, branch->refname, err);
2026 if (!cur)
2027 return NULL;
2028 if (strcmp(cur, up))
2029 return error_buf(err,
2030 _("cannot resolve 'simple' push to a single destination"));
2031 return cur;
2035 BUG("unhandled push situation");
2038 const char *branch_get_push(struct branch *branch, struct strbuf *err)
2040 read_config(the_repository, 0);
2041 die_on_missing_branch(the_repository, branch);
2043 if (!branch)
2044 return error_buf(err, _("HEAD does not point to a branch"));
2046 if (!branch->push_tracking_ref)
2047 branch->push_tracking_ref = branch_get_push_1(
2048 the_repository->remote_state, branch, err);
2049 return branch->push_tracking_ref;
2052 static int ignore_symref_update(const char *refname, struct strbuf *scratch)
2054 return !refs_read_symbolic_ref(get_main_ref_store(the_repository), refname, scratch);
2058 * Create and return a list of (struct ref) consisting of copies of
2059 * each remote_ref that matches refspec. refspec must be a pattern.
2060 * Fill in the copies' peer_ref to describe the local tracking refs to
2061 * which they map. Omit any references that would map to an existing
2062 * local symbolic ref.
2064 static struct ref *get_expanded_map(const struct ref *remote_refs,
2065 const struct refspec_item *refspec)
2067 struct strbuf scratch = STRBUF_INIT;
2068 const struct ref *ref;
2069 struct ref *ret = NULL;
2070 struct ref **tail = &ret;
2072 for (ref = remote_refs; ref; ref = ref->next) {
2073 char *expn_name = NULL;
2075 strbuf_reset(&scratch);
2077 if (strchr(ref->name, '^'))
2078 continue; /* a dereference item */
2079 if (match_name_with_pattern(refspec->src, ref->name,
2080 refspec->dst, &expn_name) &&
2081 !ignore_symref_update(expn_name, &scratch)) {
2082 struct ref *cpy = copy_ref(ref);
2084 if (cpy->peer_ref)
2085 free_one_ref(cpy->peer_ref);
2086 cpy->peer_ref = alloc_ref(expn_name);
2087 if (refspec->force)
2088 cpy->peer_ref->force = 1;
2089 *tail = cpy;
2090 tail = &cpy->next;
2092 free(expn_name);
2095 strbuf_release(&scratch);
2096 return ret;
2099 static const struct ref *find_ref_by_name_abbrev(const struct ref *refs, const char *name)
2101 const struct ref *ref;
2102 const struct ref *best_match = NULL;
2103 int best_score = 0;
2105 for (ref = refs; ref; ref = ref->next) {
2106 int score = refname_match(name, ref->name);
2108 if (best_score < score) {
2109 best_match = ref;
2110 best_score = score;
2113 return best_match;
2116 struct ref *get_remote_ref(const struct ref *remote_refs, const char *name)
2118 const struct ref *ref = find_ref_by_name_abbrev(remote_refs, name);
2120 if (!ref)
2121 return NULL;
2123 return copy_ref(ref);
2126 static struct ref *get_local_ref(const char *name)
2128 if (!name || name[0] == '\0')
2129 return NULL;
2131 if (starts_with(name, "refs/"))
2132 return alloc_ref(name);
2134 if (starts_with(name, "heads/") ||
2135 starts_with(name, "tags/") ||
2136 starts_with(name, "remotes/"))
2137 return alloc_ref_with_prefix("refs/", 5, name);
2139 return alloc_ref_with_prefix("refs/heads/", 11, name);
2142 int get_fetch_map(const struct ref *remote_refs,
2143 const struct refspec_item *refspec,
2144 struct ref ***tail,
2145 int missing_ok)
2147 struct ref *ref_map, **rmp;
2149 if (refspec->negative)
2150 return 0;
2152 if (refspec->pattern) {
2153 ref_map = get_expanded_map(remote_refs, refspec);
2154 } else {
2155 const char *name = refspec->src[0] ? refspec->src : "HEAD";
2157 if (refspec->exact_sha1) {
2158 ref_map = alloc_ref(name);
2159 get_oid_hex(name, &ref_map->old_oid);
2160 ref_map->exact_oid = 1;
2161 } else {
2162 ref_map = get_remote_ref(remote_refs, name);
2164 if (!missing_ok && !ref_map)
2165 die(_("couldn't find remote ref %s"), name);
2166 if (ref_map) {
2167 ref_map->peer_ref = get_local_ref(refspec->dst);
2168 if (ref_map->peer_ref && refspec->force)
2169 ref_map->peer_ref->force = 1;
2173 for (rmp = &ref_map; *rmp; ) {
2174 if ((*rmp)->peer_ref) {
2175 if (!starts_with((*rmp)->peer_ref->name, "refs/") ||
2176 check_refname_format((*rmp)->peer_ref->name, 0)) {
2177 struct ref *ignore = *rmp;
2178 error(_("* Ignoring funny ref '%s' locally"),
2179 (*rmp)->peer_ref->name);
2180 *rmp = (*rmp)->next;
2181 free(ignore->peer_ref);
2182 free(ignore);
2183 continue;
2186 rmp = &((*rmp)->next);
2189 if (ref_map)
2190 tail_link_ref(ref_map, tail);
2192 return 0;
2195 int resolve_remote_symref(struct ref *ref, struct ref *list)
2197 if (!ref->symref)
2198 return 0;
2199 for (; list; list = list->next)
2200 if (!strcmp(ref->symref, list->name)) {
2201 oidcpy(&ref->old_oid, &list->old_oid);
2202 return 0;
2204 return 1;
2208 * Compute the commit ahead/behind values for the pair branch_name, base.
2210 * If abf is AHEAD_BEHIND_FULL, compute the full ahead/behind and return the
2211 * counts in *num_ours and *num_theirs. If abf is AHEAD_BEHIND_QUICK, skip
2212 * the (potentially expensive) a/b computation (*num_ours and *num_theirs are
2213 * set to zero).
2215 * Returns -1 if num_ours and num_theirs could not be filled in (e.g., ref
2216 * does not exist). Returns 0 if the commits are identical. Returns 1 if
2217 * commits are different.
2220 static int stat_branch_pair(const char *branch_name, const char *base,
2221 int *num_ours, int *num_theirs,
2222 enum ahead_behind_flags abf)
2224 struct object_id oid;
2225 struct commit *ours, *theirs;
2226 struct rev_info revs;
2227 struct setup_revision_opt opt = {
2228 .free_removed_argv_elements = 1,
2230 struct strvec argv = STRVEC_INIT;
2232 /* Cannot stat if what we used to build on no longer exists */
2233 if (refs_read_ref(get_main_ref_store(the_repository), base, &oid))
2234 return -1;
2235 theirs = lookup_commit_reference(the_repository, &oid);
2236 if (!theirs)
2237 return -1;
2239 if (refs_read_ref(get_main_ref_store(the_repository), branch_name, &oid))
2240 return -1;
2241 ours = lookup_commit_reference(the_repository, &oid);
2242 if (!ours)
2243 return -1;
2245 *num_theirs = *num_ours = 0;
2247 /* are we the same? */
2248 if (theirs == ours)
2249 return 0;
2250 if (abf == AHEAD_BEHIND_QUICK)
2251 return 1;
2252 if (abf != AHEAD_BEHIND_FULL)
2253 BUG("stat_branch_pair: invalid abf '%d'", abf);
2255 /* Run "rev-list --left-right ours...theirs" internally... */
2256 strvec_push(&argv, ""); /* ignored */
2257 strvec_push(&argv, "--left-right");
2258 strvec_pushf(&argv, "%s...%s",
2259 oid_to_hex(&ours->object.oid),
2260 oid_to_hex(&theirs->object.oid));
2261 strvec_push(&argv, "--");
2263 repo_init_revisions(the_repository, &revs, NULL);
2264 setup_revisions(argv.nr, argv.v, &revs, &opt);
2265 if (prepare_revision_walk(&revs))
2266 die(_("revision walk setup failed"));
2268 /* ... and count the commits on each side. */
2269 while (1) {
2270 struct commit *c = get_revision(&revs);
2271 if (!c)
2272 break;
2273 if (c->object.flags & SYMMETRIC_LEFT)
2274 (*num_ours)++;
2275 else
2276 (*num_theirs)++;
2279 /* clear object flags smudged by the above traversal */
2280 clear_commit_marks(ours, ALL_REV_FLAGS);
2281 clear_commit_marks(theirs, ALL_REV_FLAGS);
2283 strvec_clear(&argv);
2284 release_revisions(&revs);
2285 return 1;
2289 * Lookup the tracking branch for the given branch and if present, optionally
2290 * compute the commit ahead/behind values for the pair.
2292 * If for_push is true, the tracking branch refers to the push branch,
2293 * otherwise it refers to the upstream branch.
2295 * The name of the tracking branch (or NULL if it is not defined) is
2296 * returned via *tracking_name, if it is not itself NULL.
2298 * If abf is AHEAD_BEHIND_FULL, compute the full ahead/behind and return the
2299 * counts in *num_ours and *num_theirs. If abf is AHEAD_BEHIND_QUICK, skip
2300 * the (potentially expensive) a/b computation (*num_ours and *num_theirs are
2301 * set to zero).
2303 * Returns -1 if num_ours and num_theirs could not be filled in (e.g., no
2304 * upstream defined, or ref does not exist). Returns 0 if the commits are
2305 * identical. Returns 1 if commits are different.
2307 int stat_tracking_info(struct branch *branch, int *num_ours, int *num_theirs,
2308 const char **tracking_name, int for_push,
2309 enum ahead_behind_flags abf)
2311 const char *base;
2313 /* Cannot stat unless we are marked to build on top of somebody else. */
2314 base = for_push ? branch_get_push(branch, NULL) :
2315 branch_get_upstream(branch, NULL);
2316 if (tracking_name)
2317 *tracking_name = base;
2318 if (!base)
2319 return -1;
2321 return stat_branch_pair(branch->refname, base, num_ours, num_theirs, abf);
2325 * Return true when there is anything to report, otherwise false.
2327 int format_tracking_info(struct branch *branch, struct strbuf *sb,
2328 enum ahead_behind_flags abf,
2329 int show_divergence_advice)
2331 int ours, theirs, sti;
2332 const char *full_base;
2333 char *base;
2334 int upstream_is_gone = 0;
2336 sti = stat_tracking_info(branch, &ours, &theirs, &full_base, 0, abf);
2337 if (sti < 0) {
2338 if (!full_base)
2339 return 0;
2340 upstream_is_gone = 1;
2343 base = refs_shorten_unambiguous_ref(get_main_ref_store(the_repository),
2344 full_base, 0);
2345 if (upstream_is_gone) {
2346 strbuf_addf(sb,
2347 _("Your branch is based on '%s', but the upstream is gone.\n"),
2348 base);
2349 if (advice_enabled(ADVICE_STATUS_HINTS))
2350 strbuf_addstr(sb,
2351 _(" (use \"git branch --unset-upstream\" to fixup)\n"));
2352 } else if (!sti) {
2353 strbuf_addf(sb,
2354 _("Your branch is up to date with '%s'.\n"),
2355 base);
2356 } else if (abf == AHEAD_BEHIND_QUICK) {
2357 strbuf_addf(sb,
2358 _("Your branch and '%s' refer to different commits.\n"),
2359 base);
2360 if (advice_enabled(ADVICE_STATUS_HINTS))
2361 strbuf_addf(sb, _(" (use \"%s\" for details)\n"),
2362 "git status --ahead-behind");
2363 } else if (!theirs) {
2364 strbuf_addf(sb,
2365 Q_("Your branch is ahead of '%s' by %d commit.\n",
2366 "Your branch is ahead of '%s' by %d commits.\n",
2367 ours),
2368 base, ours);
2369 if (advice_enabled(ADVICE_STATUS_HINTS))
2370 strbuf_addstr(sb,
2371 _(" (use \"git push\" to publish your local commits)\n"));
2372 } else if (!ours) {
2373 strbuf_addf(sb,
2374 Q_("Your branch is behind '%s' by %d commit, "
2375 "and can be fast-forwarded.\n",
2376 "Your branch is behind '%s' by %d commits, "
2377 "and can be fast-forwarded.\n",
2378 theirs),
2379 base, theirs);
2380 if (advice_enabled(ADVICE_STATUS_HINTS))
2381 strbuf_addstr(sb,
2382 _(" (use \"git pull\" to update your local branch)\n"));
2383 } else {
2384 strbuf_addf(sb,
2385 Q_("Your branch and '%s' have diverged,\n"
2386 "and have %d and %d different commit each, "
2387 "respectively.\n",
2388 "Your branch and '%s' have diverged,\n"
2389 "and have %d and %d different commits each, "
2390 "respectively.\n",
2391 ours + theirs),
2392 base, ours, theirs);
2393 if (show_divergence_advice &&
2394 advice_enabled(ADVICE_STATUS_HINTS))
2395 strbuf_addstr(sb,
2396 _(" (use \"git pull\" if you want to integrate the remote branch with yours)\n"));
2398 free(base);
2399 return 1;
2402 static int one_local_ref(const char *refname, const char *referent UNUSED, const struct object_id *oid,
2403 int flag UNUSED,
2404 void *cb_data)
2406 struct ref ***local_tail = cb_data;
2407 struct ref *ref;
2409 /* we already know it starts with refs/ to get here */
2410 if (check_refname_format(refname + 5, 0))
2411 return 0;
2413 ref = alloc_ref(refname);
2414 oidcpy(&ref->new_oid, oid);
2415 **local_tail = ref;
2416 *local_tail = &ref->next;
2417 return 0;
2420 struct ref *get_local_heads(void)
2422 struct ref *local_refs = NULL, **local_tail = &local_refs;
2424 refs_for_each_ref(get_main_ref_store(the_repository), one_local_ref,
2425 &local_tail);
2426 return local_refs;
2429 struct ref *guess_remote_head(const struct ref *head,
2430 const struct ref *refs,
2431 int all)
2433 const struct ref *r;
2434 struct ref *list = NULL;
2435 struct ref **tail = &list;
2437 if (!head)
2438 return NULL;
2441 * Some transports support directly peeking at
2442 * where HEAD points; if that is the case, then
2443 * we don't have to guess.
2445 if (head->symref)
2446 return copy_ref(find_ref_by_name(refs, head->symref));
2448 /* If a remote branch exists with the default branch name, let's use it. */
2449 if (!all) {
2450 char *default_branch = repo_default_branch_name(the_repository, 0);
2451 char *ref = xstrfmt("refs/heads/%s", default_branch);
2453 r = find_ref_by_name(refs, ref);
2454 free(ref);
2455 free(default_branch);
2457 if (r && oideq(&r->old_oid, &head->old_oid))
2458 return copy_ref(r);
2460 /* Fall back to the hard-coded historical default */
2461 r = find_ref_by_name(refs, "refs/heads/master");
2462 if (r && oideq(&r->old_oid, &head->old_oid))
2463 return copy_ref(r);
2466 /* Look for another ref that points there */
2467 for (r = refs; r; r = r->next) {
2468 if (r != head &&
2469 starts_with(r->name, "refs/heads/") &&
2470 oideq(&r->old_oid, &head->old_oid)) {
2471 *tail = copy_ref(r);
2472 tail = &((*tail)->next);
2473 if (!all)
2474 break;
2478 return list;
2481 struct stale_heads_info {
2482 struct string_list *ref_names;
2483 struct ref **stale_refs_tail;
2484 struct refspec *rs;
2487 static int get_stale_heads_cb(const char *refname, const char *referent UNUSED, const struct object_id *oid,
2488 int flags, void *cb_data)
2490 struct stale_heads_info *info = cb_data;
2491 struct string_list matches = STRING_LIST_INIT_DUP;
2492 struct refspec_item query;
2493 int i, stale = 1;
2494 memset(&query, 0, sizeof(struct refspec_item));
2495 query.dst = (char *)refname;
2497 query_refspecs_multiple(info->rs, &query, &matches);
2498 if (matches.nr == 0)
2499 goto clean_exit; /* No matches */
2502 * If we did find a suitable refspec and it's not a symref and
2503 * it's not in the list of refs that currently exist in that
2504 * remote, we consider it to be stale. In order to deal with
2505 * overlapping refspecs, we need to go over all of the
2506 * matching refs.
2508 if (flags & REF_ISSYMREF)
2509 goto clean_exit;
2511 for (i = 0; stale && i < matches.nr; i++)
2512 if (string_list_has_string(info->ref_names, matches.items[i].string))
2513 stale = 0;
2515 if (stale) {
2516 struct ref *ref = make_linked_ref(refname, &info->stale_refs_tail);
2517 oidcpy(&ref->new_oid, oid);
2520 clean_exit:
2521 string_list_clear(&matches, 0);
2522 return 0;
2525 struct ref *get_stale_heads(struct refspec *rs, struct ref *fetch_map)
2527 struct ref *ref, *stale_refs = NULL;
2528 struct string_list ref_names = STRING_LIST_INIT_NODUP;
2529 struct stale_heads_info info;
2531 info.ref_names = &ref_names;
2532 info.stale_refs_tail = &stale_refs;
2533 info.rs = rs;
2534 for (ref = fetch_map; ref; ref = ref->next)
2535 string_list_append(&ref_names, ref->name);
2536 string_list_sort(&ref_names);
2537 refs_for_each_ref(get_main_ref_store(the_repository),
2538 get_stale_heads_cb, &info);
2539 string_list_clear(&ref_names, 0);
2540 return stale_refs;
2544 * Compare-and-swap
2546 static void clear_cas_option(struct push_cas_option *cas)
2548 int i;
2550 for (i = 0; i < cas->nr; i++)
2551 free(cas->entry[i].refname);
2552 free(cas->entry);
2553 memset(cas, 0, sizeof(*cas));
2556 static struct push_cas *add_cas_entry(struct push_cas_option *cas,
2557 const char *refname,
2558 size_t refnamelen)
2560 struct push_cas *entry;
2561 ALLOC_GROW(cas->entry, cas->nr + 1, cas->alloc);
2562 entry = &cas->entry[cas->nr++];
2563 memset(entry, 0, sizeof(*entry));
2564 entry->refname = xmemdupz(refname, refnamelen);
2565 return entry;
2568 static int parse_push_cas_option(struct push_cas_option *cas, const char *arg, int unset)
2570 const char *colon;
2571 struct push_cas *entry;
2573 if (unset) {
2574 /* "--no-<option>" */
2575 clear_cas_option(cas);
2576 return 0;
2579 if (!arg) {
2580 /* just "--<option>" */
2581 cas->use_tracking_for_rest = 1;
2582 return 0;
2585 /* "--<option>=refname" or "--<option>=refname:value" */
2586 colon = strchrnul(arg, ':');
2587 entry = add_cas_entry(cas, arg, colon - arg);
2588 if (!*colon)
2589 entry->use_tracking = 1;
2590 else if (!colon[1])
2591 oidclr(&entry->expect, the_repository->hash_algo);
2592 else if (repo_get_oid(the_repository, colon + 1, &entry->expect))
2593 return error(_("cannot parse expected object name '%s'"),
2594 colon + 1);
2595 return 0;
2598 int parseopt_push_cas_option(const struct option *opt, const char *arg, int unset)
2600 return parse_push_cas_option(opt->value, arg, unset);
2603 int is_empty_cas(const struct push_cas_option *cas)
2605 return !cas->use_tracking_for_rest && !cas->nr;
2609 * Look at remote.fetch refspec and see if we have a remote
2610 * tracking branch for the refname there. Fill the name of
2611 * the remote-tracking branch in *dst_refname, and the name
2612 * of the commit object at its tip in oid[].
2613 * If we cannot do so, return negative to signal an error.
2615 static int remote_tracking(struct remote *remote, const char *refname,
2616 struct object_id *oid, char **dst_refname)
2618 char *dst;
2620 dst = apply_refspecs(&remote->fetch, refname);
2621 if (!dst)
2622 return -1; /* no tracking ref for refname at remote */
2623 if (refs_read_ref(get_main_ref_store(the_repository), dst, oid))
2624 return -1; /* we know what the tracking ref is but we cannot read it */
2626 *dst_refname = dst;
2627 return 0;
2631 * The struct "reflog_commit_array" and related helper functions
2632 * are used for collecting commits into an array during reflog
2633 * traversals in "check_and_collect_until()".
2635 struct reflog_commit_array {
2636 struct commit **item;
2637 size_t nr, alloc;
2640 #define REFLOG_COMMIT_ARRAY_INIT { 0 }
2642 /* Append a commit to the array. */
2643 static void append_commit(struct reflog_commit_array *arr,
2644 struct commit *commit)
2646 ALLOC_GROW(arr->item, arr->nr + 1, arr->alloc);
2647 arr->item[arr->nr++] = commit;
2650 /* Free and reset the array. */
2651 static void free_commit_array(struct reflog_commit_array *arr)
2653 FREE_AND_NULL(arr->item);
2654 arr->nr = arr->alloc = 0;
2657 struct check_and_collect_until_cb_data {
2658 struct commit *remote_commit;
2659 struct reflog_commit_array *local_commits;
2660 timestamp_t remote_reflog_timestamp;
2663 /* Get the timestamp of the latest entry. */
2664 static int peek_reflog(struct object_id *o_oid UNUSED,
2665 struct object_id *n_oid UNUSED,
2666 const char *ident UNUSED,
2667 timestamp_t timestamp, int tz UNUSED,
2668 const char *message UNUSED, void *cb_data)
2670 timestamp_t *ts = cb_data;
2671 *ts = timestamp;
2672 return 1;
2675 static int check_and_collect_until(struct object_id *o_oid UNUSED,
2676 struct object_id *n_oid,
2677 const char *ident UNUSED,
2678 timestamp_t timestamp, int tz UNUSED,
2679 const char *message UNUSED, void *cb_data)
2681 struct commit *commit;
2682 struct check_and_collect_until_cb_data *cb = cb_data;
2684 /* An entry was found. */
2685 if (oideq(n_oid, &cb->remote_commit->object.oid))
2686 return 1;
2688 if ((commit = lookup_commit_reference(the_repository, n_oid)))
2689 append_commit(cb->local_commits, commit);
2692 * If the reflog entry timestamp is older than the remote ref's
2693 * latest reflog entry, there is no need to check or collect
2694 * entries older than this one.
2696 if (timestamp < cb->remote_reflog_timestamp)
2697 return -1;
2699 return 0;
2702 #define MERGE_BASES_BATCH_SIZE 8
2705 * Iterate through the reflog of the local ref to check if there is an entry
2706 * for the given remote-tracking ref; runs until the timestamp of an entry is
2707 * older than latest timestamp of remote-tracking ref's reflog. Any commits
2708 * are that seen along the way are collected into an array to check if the
2709 * remote-tracking ref is reachable from any of them.
2711 static int is_reachable_in_reflog(const char *local, const struct ref *remote)
2713 timestamp_t date;
2714 struct commit *commit;
2715 struct commit **chunk;
2716 struct check_and_collect_until_cb_data cb;
2717 struct reflog_commit_array arr = REFLOG_COMMIT_ARRAY_INIT;
2718 size_t size = 0;
2719 int ret = 0;
2721 commit = lookup_commit_reference(the_repository, &remote->old_oid);
2722 if (!commit)
2723 goto cleanup_return;
2726 * Get the timestamp from the latest entry
2727 * of the remote-tracking ref's reflog.
2729 refs_for_each_reflog_ent_reverse(get_main_ref_store(the_repository),
2730 remote->tracking_ref, peek_reflog,
2731 &date);
2733 cb.remote_commit = commit;
2734 cb.local_commits = &arr;
2735 cb.remote_reflog_timestamp = date;
2736 ret = refs_for_each_reflog_ent_reverse(get_main_ref_store(the_repository),
2737 local, check_and_collect_until,
2738 &cb);
2740 /* We found an entry in the reflog. */
2741 if (ret > 0)
2742 goto cleanup_return;
2745 * Check if the remote commit is reachable from any
2746 * of the commits in the collected array, in batches.
2748 for (chunk = arr.item; chunk < arr.item + arr.nr; chunk += size) {
2749 size = arr.item + arr.nr - chunk;
2750 if (MERGE_BASES_BATCH_SIZE < size)
2751 size = MERGE_BASES_BATCH_SIZE;
2753 if ((ret = repo_in_merge_bases_many(the_repository, commit, size, chunk, 0)))
2754 break;
2757 cleanup_return:
2758 free_commit_array(&arr);
2759 return ret;
2763 * Check for reachability of a remote-tracking
2764 * ref in the reflog entries of its local ref.
2766 static void check_if_includes_upstream(struct ref *remote)
2768 struct ref *local = get_local_ref(remote->name);
2769 if (!local)
2770 return;
2772 if (is_reachable_in_reflog(local->name, remote) <= 0)
2773 remote->unreachable = 1;
2776 static void apply_cas(struct push_cas_option *cas,
2777 struct remote *remote,
2778 struct ref *ref)
2780 int i;
2782 /* Find an explicit --<option>=<name>[:<value>] entry */
2783 for (i = 0; i < cas->nr; i++) {
2784 struct push_cas *entry = &cas->entry[i];
2785 if (!refname_match(entry->refname, ref->name))
2786 continue;
2787 ref->expect_old_sha1 = 1;
2788 if (!entry->use_tracking)
2789 oidcpy(&ref->old_oid_expect, &entry->expect);
2790 else if (remote_tracking(remote, ref->name,
2791 &ref->old_oid_expect,
2792 &ref->tracking_ref))
2793 oidclr(&ref->old_oid_expect, the_repository->hash_algo);
2794 else
2795 ref->check_reachable = cas->use_force_if_includes;
2796 return;
2799 /* Are we using "--<option>" to cover all? */
2800 if (!cas->use_tracking_for_rest)
2801 return;
2803 ref->expect_old_sha1 = 1;
2804 if (remote_tracking(remote, ref->name,
2805 &ref->old_oid_expect,
2806 &ref->tracking_ref))
2807 oidclr(&ref->old_oid_expect, the_repository->hash_algo);
2808 else
2809 ref->check_reachable = cas->use_force_if_includes;
2812 void apply_push_cas(struct push_cas_option *cas,
2813 struct remote *remote,
2814 struct ref *remote_refs)
2816 struct ref *ref;
2817 for (ref = remote_refs; ref; ref = ref->next) {
2818 apply_cas(cas, remote, ref);
2821 * If "compare-and-swap" is in "use_tracking[_for_rest]"
2822 * mode, and if "--force-if-includes" was specified, run
2823 * the check.
2825 if (ref->check_reachable)
2826 check_if_includes_upstream(ref);
2830 struct remote_state *remote_state_new(void)
2832 struct remote_state *r = xmalloc(sizeof(*r));
2834 memset(r, 0, sizeof(*r));
2836 hashmap_init(&r->remotes_hash, remotes_hash_cmp, NULL, 0);
2837 hashmap_init(&r->branches_hash, branches_hash_cmp, NULL, 0);
2838 return r;
2841 void remote_state_clear(struct remote_state *remote_state)
2843 struct hashmap_iter iter;
2844 struct branch *b;
2845 int i;
2847 for (i = 0; i < remote_state->remotes_nr; i++)
2848 remote_clear(remote_state->remotes[i]);
2849 FREE_AND_NULL(remote_state->remotes);
2850 FREE_AND_NULL(remote_state->pushremote_name);
2851 remote_state->remotes_alloc = 0;
2852 remote_state->remotes_nr = 0;
2854 rewrites_release(&remote_state->rewrites);
2855 rewrites_release(&remote_state->rewrites_push);
2857 hashmap_clear_and_free(&remote_state->remotes_hash, struct remote, ent);
2858 hashmap_for_each_entry(&remote_state->branches_hash, &iter, b, ent) {
2859 branch_release(b);
2860 free(b);
2862 hashmap_clear(&remote_state->branches_hash);
2866 * Returns 1 if it was the last chop before ':'.
2868 static int chop_last_dir(char **remoteurl, int is_relative)
2870 char *rfind = find_last_dir_sep(*remoteurl);
2871 if (rfind) {
2872 *rfind = '\0';
2873 return 0;
2876 rfind = strrchr(*remoteurl, ':');
2877 if (rfind) {
2878 *rfind = '\0';
2879 return 1;
2882 if (is_relative || !strcmp(".", *remoteurl))
2883 die(_("cannot strip one component off url '%s'"),
2884 *remoteurl);
2886 free(*remoteurl);
2887 *remoteurl = xstrdup(".");
2888 return 0;
2891 char *relative_url(const char *remote_url, const char *url,
2892 const char *up_path)
2894 int is_relative = 0;
2895 int colonsep = 0;
2896 char *out;
2897 char *remoteurl;
2898 struct strbuf sb = STRBUF_INIT;
2899 size_t len;
2901 if (!url_is_local_not_ssh(url) || is_absolute_path(url))
2902 return xstrdup(url);
2904 len = strlen(remote_url);
2905 if (!len)
2906 BUG("invalid empty remote_url");
2908 remoteurl = xstrdup(remote_url);
2909 if (is_dir_sep(remoteurl[len-1]))
2910 remoteurl[len-1] = '\0';
2912 if (!url_is_local_not_ssh(remoteurl) || is_absolute_path(remoteurl))
2913 is_relative = 0;
2914 else {
2915 is_relative = 1;
2917 * Prepend a './' to ensure all relative
2918 * remoteurls start with './' or '../'
2920 if (!starts_with_dot_slash_native(remoteurl) &&
2921 !starts_with_dot_dot_slash_native(remoteurl)) {
2922 strbuf_reset(&sb);
2923 strbuf_addf(&sb, "./%s", remoteurl);
2924 free(remoteurl);
2925 remoteurl = strbuf_detach(&sb, NULL);
2929 * When the url starts with '../', remove that and the
2930 * last directory in remoteurl.
2932 while (*url) {
2933 if (starts_with_dot_dot_slash_native(url)) {
2934 url += 3;
2935 colonsep |= chop_last_dir(&remoteurl, is_relative);
2936 } else if (starts_with_dot_slash_native(url))
2937 url += 2;
2938 else
2939 break;
2941 strbuf_reset(&sb);
2942 strbuf_addf(&sb, "%s%s%s", remoteurl, colonsep ? ":" : "/", url);
2943 if (ends_with(url, "/"))
2944 strbuf_setlen(&sb, sb.len - 1);
2945 free(remoteurl);
2947 if (starts_with_dot_slash_native(sb.buf))
2948 out = xstrdup(sb.buf + 2);
2949 else
2950 out = xstrdup(sb.buf);
2952 if (!up_path || !is_relative) {
2953 strbuf_release(&sb);
2954 return out;
2957 strbuf_reset(&sb);
2958 strbuf_addf(&sb, "%s%s", up_path, out);
2959 free(out);
2960 return strbuf_detach(&sb, NULL);