Merge branch 'ds/read-cache-mempool-leakfix'
[git/gitster.git] / remote.c
blobe291e8ff5cddb25e35063be74097b1965b27000e
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->tracking_ref);
1127 free(ref->symref);
1128 free(ref);
1131 void free_refs(struct ref *ref)
1133 struct ref *next;
1134 while (ref) {
1135 next = ref->next;
1136 free_one_ref(ref);
1137 ref = next;
1141 int count_refspec_match(const char *pattern,
1142 struct ref *refs,
1143 struct ref **matched_ref)
1145 int patlen = strlen(pattern);
1146 struct ref *matched_weak = NULL;
1147 struct ref *matched = NULL;
1148 int weak_match = 0;
1149 int match = 0;
1151 for (weak_match = match = 0; refs; refs = refs->next) {
1152 char *name = refs->name;
1153 int namelen = strlen(name);
1155 if (!refname_match(pattern, name))
1156 continue;
1158 /* A match is "weak" if it is with refs outside
1159 * heads or tags, and did not specify the pattern
1160 * in full (e.g. "refs/remotes/origin/master") or at
1161 * least from the toplevel (e.g. "remotes/origin/master");
1162 * otherwise "git push $URL master" would result in
1163 * ambiguity between remotes/origin/master and heads/master
1164 * at the remote site.
1166 if (namelen != patlen &&
1167 patlen != namelen - 5 &&
1168 !starts_with(name, "refs/heads/") &&
1169 !starts_with(name, "refs/tags/")) {
1170 /* We want to catch the case where only weak
1171 * matches are found and there are multiple
1172 * matches, and where more than one strong
1173 * matches are found, as ambiguous. One
1174 * strong match with zero or more weak matches
1175 * are acceptable as a unique match.
1177 matched_weak = refs;
1178 weak_match++;
1180 else {
1181 matched = refs;
1182 match++;
1185 if (!matched) {
1186 if (matched_ref)
1187 *matched_ref = matched_weak;
1188 return weak_match;
1190 else {
1191 if (matched_ref)
1192 *matched_ref = matched;
1193 return match;
1197 static void tail_link_ref(struct ref *ref, struct ref ***tail)
1199 **tail = ref;
1200 while (ref->next)
1201 ref = ref->next;
1202 *tail = &ref->next;
1205 static struct ref *alloc_delete_ref(void)
1207 struct ref *ref = alloc_ref("(delete)");
1208 oidclr(&ref->new_oid, the_repository->hash_algo);
1209 return ref;
1212 static int try_explicit_object_name(const char *name,
1213 struct ref **match)
1215 struct object_id oid;
1217 if (!*name) {
1218 if (match)
1219 *match = alloc_delete_ref();
1220 return 0;
1223 if (repo_get_oid(the_repository, name, &oid))
1224 return -1;
1226 if (match) {
1227 *match = alloc_ref(name);
1228 oidcpy(&(*match)->new_oid, &oid);
1230 return 0;
1233 static struct ref *make_linked_ref(const char *name, struct ref ***tail)
1235 struct ref *ret = alloc_ref(name);
1236 tail_link_ref(ret, tail);
1237 return ret;
1240 static char *guess_ref(const char *name, struct ref *peer)
1242 struct strbuf buf = STRBUF_INIT;
1244 const char *r = refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
1245 peer->name,
1246 RESOLVE_REF_READING,
1247 NULL, NULL);
1248 if (!r)
1249 return NULL;
1251 if (starts_with(r, "refs/heads/")) {
1252 strbuf_addstr(&buf, "refs/heads/");
1253 } else if (starts_with(r, "refs/tags/")) {
1254 strbuf_addstr(&buf, "refs/tags/");
1255 } else {
1256 return NULL;
1259 strbuf_addstr(&buf, name);
1260 return strbuf_detach(&buf, NULL);
1263 static int match_explicit_lhs(struct ref *src,
1264 struct refspec_item *rs,
1265 struct ref **match,
1266 int *allocated_match)
1268 switch (count_refspec_match(rs->src, src, match)) {
1269 case 1:
1270 if (allocated_match)
1271 *allocated_match = 0;
1272 return 0;
1273 case 0:
1274 /* The source could be in the get_sha1() format
1275 * not a reference name. :refs/other is a
1276 * way to delete 'other' ref at the remote end.
1278 if (try_explicit_object_name(rs->src, match) < 0)
1279 return error(_("src refspec %s does not match any"), rs->src);
1280 if (allocated_match)
1281 *allocated_match = 1;
1282 return 0;
1283 default:
1284 return error(_("src refspec %s matches more than one"), rs->src);
1288 static void show_push_unqualified_ref_name_error(const char *dst_value,
1289 const char *matched_src_name)
1291 struct object_id oid;
1292 enum object_type type;
1295 * TRANSLATORS: "matches '%s'%" is the <dst> part of "git push
1296 * <remote> <src>:<dst>" push, and "being pushed ('%s')" is
1297 * the <src>.
1299 error(_("The destination you provided is not a full refname (i.e.,\n"
1300 "starting with \"refs/\"). We tried to guess what you meant by:\n"
1301 "\n"
1302 "- Looking for a ref that matches '%s' on the remote side.\n"
1303 "- Checking if the <src> being pushed ('%s')\n"
1304 " is a ref in \"refs/{heads,tags}/\". If so we add a corresponding\n"
1305 " refs/{heads,tags}/ prefix on the remote side.\n"
1306 "\n"
1307 "Neither worked, so we gave up. You must fully qualify the ref."),
1308 dst_value, matched_src_name);
1310 if (!advice_enabled(ADVICE_PUSH_UNQUALIFIED_REF_NAME))
1311 return;
1313 if (repo_get_oid(the_repository, matched_src_name, &oid))
1314 BUG("'%s' is not a valid object, "
1315 "match_explicit_lhs() should catch this!",
1316 matched_src_name);
1317 type = oid_object_info(the_repository, &oid, NULL);
1318 if (type == OBJ_COMMIT) {
1319 advise(_("The <src> part of the refspec is a commit object.\n"
1320 "Did you mean to create a new branch by pushing to\n"
1321 "'%s:refs/heads/%s'?"),
1322 matched_src_name, dst_value);
1323 } else if (type == OBJ_TAG) {
1324 advise(_("The <src> part of the refspec is a tag object.\n"
1325 "Did you mean to create a new tag by pushing to\n"
1326 "'%s:refs/tags/%s'?"),
1327 matched_src_name, dst_value);
1328 } else if (type == OBJ_TREE) {
1329 advise(_("The <src> part of the refspec is a tree object.\n"
1330 "Did you mean to tag a new tree by pushing to\n"
1331 "'%s:refs/tags/%s'?"),
1332 matched_src_name, dst_value);
1333 } else if (type == OBJ_BLOB) {
1334 advise(_("The <src> part of the refspec is a blob object.\n"
1335 "Did you mean to tag a new blob by pushing to\n"
1336 "'%s:refs/tags/%s'?"),
1337 matched_src_name, dst_value);
1338 } else {
1339 BUG("'%s' should be commit/tag/tree/blob, is '%d'",
1340 matched_src_name, type);
1344 static int match_explicit(struct ref *src, struct ref *dst,
1345 struct ref ***dst_tail,
1346 struct refspec_item *rs)
1348 struct ref *matched_src = NULL, *matched_dst = NULL;
1349 int allocated_src = 0, ret;
1351 const char *dst_value = rs->dst;
1352 char *dst_guess;
1354 if (rs->pattern || rs->matching || rs->negative) {
1355 ret = 0;
1356 goto out;
1359 if (match_explicit_lhs(src, rs, &matched_src, &allocated_src) < 0) {
1360 ret = -1;
1361 goto out;
1364 if (!dst_value) {
1365 int flag;
1367 dst_value = refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
1368 matched_src->name,
1369 RESOLVE_REF_READING,
1370 NULL, &flag);
1371 if (!dst_value ||
1372 ((flag & REF_ISSYMREF) &&
1373 !starts_with(dst_value, "refs/heads/")))
1374 die(_("%s cannot be resolved to branch"),
1375 matched_src->name);
1378 switch (count_refspec_match(dst_value, dst, &matched_dst)) {
1379 case 1:
1380 break;
1381 case 0:
1382 if (starts_with(dst_value, "refs/")) {
1383 matched_dst = make_linked_ref(dst_value, dst_tail);
1384 } else if (is_null_oid(&matched_src->new_oid)) {
1385 error(_("unable to delete '%s': remote ref does not exist"),
1386 dst_value);
1387 } else if ((dst_guess = guess_ref(dst_value, matched_src))) {
1388 matched_dst = make_linked_ref(dst_guess, dst_tail);
1389 free(dst_guess);
1390 } else {
1391 show_push_unqualified_ref_name_error(dst_value,
1392 matched_src->name);
1394 break;
1395 default:
1396 matched_dst = NULL;
1397 error(_("dst refspec %s matches more than one"),
1398 dst_value);
1399 break;
1402 if (!matched_dst) {
1403 ret = -1;
1404 goto out;
1407 if (matched_dst->peer_ref) {
1408 ret = error(_("dst ref %s receives from more than one src"),
1409 matched_dst->name);
1410 goto out;
1411 } else {
1412 matched_dst->peer_ref = allocated_src ?
1413 matched_src :
1414 copy_ref(matched_src);
1415 matched_dst->force = rs->force;
1416 matched_src = NULL;
1419 ret = 0;
1421 out:
1422 if (allocated_src)
1423 free_one_ref(matched_src);
1424 return ret;
1427 static int match_explicit_refs(struct ref *src, struct ref *dst,
1428 struct ref ***dst_tail, struct refspec *rs)
1430 int i, errs;
1431 for (i = errs = 0; i < rs->nr; i++)
1432 errs += match_explicit(src, dst, dst_tail, &rs->items[i]);
1433 return errs;
1436 static char *get_ref_match(const struct refspec *rs, const struct ref *ref,
1437 int send_mirror, int direction,
1438 const struct refspec_item **ret_pat)
1440 const struct refspec_item *pat;
1441 char *name;
1442 int i;
1443 int matching_refs = -1;
1444 for (i = 0; i < rs->nr; i++) {
1445 const struct refspec_item *item = &rs->items[i];
1447 if (item->negative)
1448 continue;
1450 if (item->matching &&
1451 (matching_refs == -1 || item->force)) {
1452 matching_refs = i;
1453 continue;
1456 if (item->pattern) {
1457 const char *dst_side = item->dst ? item->dst : item->src;
1458 int match;
1459 if (direction == FROM_SRC)
1460 match = match_name_with_pattern(item->src, ref->name, dst_side, &name);
1461 else
1462 match = match_name_with_pattern(dst_side, ref->name, item->src, &name);
1463 if (match) {
1464 matching_refs = i;
1465 break;
1469 if (matching_refs == -1)
1470 return NULL;
1472 pat = &rs->items[matching_refs];
1473 if (pat->matching) {
1475 * "matching refs"; traditionally we pushed everything
1476 * including refs outside refs/heads/ hierarchy, but
1477 * that does not make much sense these days.
1479 if (!send_mirror && !starts_with(ref->name, "refs/heads/"))
1480 return NULL;
1481 name = xstrdup(ref->name);
1483 if (ret_pat)
1484 *ret_pat = pat;
1485 return name;
1488 static struct ref **tail_ref(struct ref **head)
1490 struct ref **tail = head;
1491 while (*tail)
1492 tail = &((*tail)->next);
1493 return tail;
1496 struct tips {
1497 struct commit **tip;
1498 int nr, alloc;
1501 static void add_to_tips(struct tips *tips, const struct object_id *oid)
1503 struct commit *commit;
1505 if (is_null_oid(oid))
1506 return;
1507 commit = lookup_commit_reference_gently(the_repository, oid, 1);
1508 if (!commit || (commit->object.flags & TMP_MARK))
1509 return;
1510 commit->object.flags |= TMP_MARK;
1511 ALLOC_GROW(tips->tip, tips->nr + 1, tips->alloc);
1512 tips->tip[tips->nr++] = commit;
1515 static void add_missing_tags(struct ref *src, struct ref **dst, struct ref ***dst_tail)
1517 struct string_list dst_tag = STRING_LIST_INIT_NODUP;
1518 struct string_list src_tag = STRING_LIST_INIT_NODUP;
1519 struct string_list_item *item;
1520 struct ref *ref;
1521 struct tips sent_tips;
1524 * Collect everything we know they would have at the end of
1525 * this push, and collect all tags they have.
1527 memset(&sent_tips, 0, sizeof(sent_tips));
1528 for (ref = *dst; ref; ref = ref->next) {
1529 if (ref->peer_ref &&
1530 !is_null_oid(&ref->peer_ref->new_oid))
1531 add_to_tips(&sent_tips, &ref->peer_ref->new_oid);
1532 else
1533 add_to_tips(&sent_tips, &ref->old_oid);
1534 if (starts_with(ref->name, "refs/tags/"))
1535 string_list_append(&dst_tag, ref->name);
1537 clear_commit_marks_many(sent_tips.nr, sent_tips.tip, TMP_MARK);
1539 string_list_sort(&dst_tag);
1541 /* Collect tags they do not have. */
1542 for (ref = src; ref; ref = ref->next) {
1543 if (!starts_with(ref->name, "refs/tags/"))
1544 continue; /* not a tag */
1545 if (string_list_has_string(&dst_tag, ref->name))
1546 continue; /* they already have it */
1547 if (oid_object_info(the_repository, &ref->new_oid, NULL) != OBJ_TAG)
1548 continue; /* be conservative */
1549 item = string_list_append(&src_tag, ref->name);
1550 item->util = ref;
1552 string_list_clear(&dst_tag, 0);
1555 * At this point, src_tag lists tags that are missing from
1556 * dst, and sent_tips lists the tips we are pushing or those
1557 * that we know they already have. An element in the src_tag
1558 * that is an ancestor of any of the sent_tips needs to be
1559 * sent to the other side.
1561 if (sent_tips.nr) {
1562 const int reachable_flag = 1;
1563 struct commit_list *found_commits;
1564 struct commit **src_commits;
1565 int nr_src_commits = 0, alloc_src_commits = 16;
1566 ALLOC_ARRAY(src_commits, alloc_src_commits);
1568 for_each_string_list_item(item, &src_tag) {
1569 struct ref *ref = item->util;
1570 struct commit *commit;
1572 if (is_null_oid(&ref->new_oid))
1573 continue;
1574 commit = lookup_commit_reference_gently(the_repository,
1575 &ref->new_oid,
1577 if (!commit)
1578 /* not pushing a commit, which is not an error */
1579 continue;
1581 ALLOC_GROW(src_commits, nr_src_commits + 1, alloc_src_commits);
1582 src_commits[nr_src_commits++] = commit;
1585 found_commits = get_reachable_subset(sent_tips.tip, sent_tips.nr,
1586 src_commits, nr_src_commits,
1587 reachable_flag);
1589 for_each_string_list_item(item, &src_tag) {
1590 struct ref *dst_ref;
1591 struct ref *ref = item->util;
1592 struct commit *commit;
1594 if (is_null_oid(&ref->new_oid))
1595 continue;
1596 commit = lookup_commit_reference_gently(the_repository,
1597 &ref->new_oid,
1599 if (!commit)
1600 /* not pushing a commit, which is not an error */
1601 continue;
1604 * Is this tag, which they do not have, reachable from
1605 * any of the commits we are sending?
1607 if (!(commit->object.flags & reachable_flag))
1608 continue;
1610 /* Add it in */
1611 dst_ref = make_linked_ref(ref->name, dst_tail);
1612 oidcpy(&dst_ref->new_oid, &ref->new_oid);
1613 dst_ref->peer_ref = copy_ref(ref);
1616 clear_commit_marks_many(nr_src_commits, src_commits, reachable_flag);
1617 free(src_commits);
1618 free_commit_list(found_commits);
1621 string_list_clear(&src_tag, 0);
1622 free(sent_tips.tip);
1625 struct ref *find_ref_by_name(const struct ref *list, const char *name)
1627 for ( ; list; list = list->next)
1628 if (!strcmp(list->name, name))
1629 return (struct ref *)list;
1630 return NULL;
1633 static void prepare_ref_index(struct string_list *ref_index, struct ref *ref)
1635 for ( ; ref; ref = ref->next)
1636 string_list_append_nodup(ref_index, ref->name)->util = ref;
1638 string_list_sort(ref_index);
1642 * Given only the set of local refs, sanity-check the set of push
1643 * refspecs. We can't catch all errors that match_push_refs would,
1644 * but we can catch some errors early before even talking to the
1645 * remote side.
1647 int check_push_refs(struct ref *src, struct refspec *rs)
1649 int ret = 0;
1650 int i;
1652 for (i = 0; i < rs->nr; i++) {
1653 struct refspec_item *item = &rs->items[i];
1655 if (item->pattern || item->matching || item->negative)
1656 continue;
1658 ret |= match_explicit_lhs(src, item, NULL, NULL);
1661 return ret;
1665 * Given the set of refs the local repository has, the set of refs the
1666 * remote repository has, and the refspec used for push, determine
1667 * what remote refs we will update and with what value by setting
1668 * peer_ref (which object is being pushed) and force (if the push is
1669 * forced) in elements of "dst". The function may add new elements to
1670 * dst (e.g. pushing to a new branch, done in match_explicit_refs).
1672 int match_push_refs(struct ref *src, struct ref **dst,
1673 struct refspec *rs, int flags)
1675 int send_all = flags & MATCH_REFS_ALL;
1676 int send_mirror = flags & MATCH_REFS_MIRROR;
1677 int send_prune = flags & MATCH_REFS_PRUNE;
1678 int errs;
1679 struct ref *ref, **dst_tail = tail_ref(dst);
1680 struct string_list dst_ref_index = STRING_LIST_INIT_NODUP;
1682 /* If no refspec is provided, use the default ":" */
1683 if (!rs->nr)
1684 refspec_append(rs, ":");
1686 errs = match_explicit_refs(src, *dst, &dst_tail, rs);
1688 /* pick the remainder */
1689 for (ref = src; ref; ref = ref->next) {
1690 struct string_list_item *dst_item;
1691 struct ref *dst_peer;
1692 const struct refspec_item *pat = NULL;
1693 char *dst_name;
1695 dst_name = get_ref_match(rs, ref, send_mirror, FROM_SRC, &pat);
1696 if (!dst_name)
1697 continue;
1699 if (!dst_ref_index.nr)
1700 prepare_ref_index(&dst_ref_index, *dst);
1702 dst_item = string_list_lookup(&dst_ref_index, dst_name);
1703 dst_peer = dst_item ? dst_item->util : NULL;
1704 if (dst_peer) {
1705 if (dst_peer->peer_ref)
1706 /* We're already sending something to this ref. */
1707 goto free_name;
1708 } else {
1709 if (pat->matching && !(send_all || send_mirror))
1711 * Remote doesn't have it, and we have no
1712 * explicit pattern, and we don't have
1713 * --all or --mirror.
1715 goto free_name;
1717 /* Create a new one and link it */
1718 dst_peer = make_linked_ref(dst_name, &dst_tail);
1719 oidcpy(&dst_peer->new_oid, &ref->new_oid);
1720 string_list_insert(&dst_ref_index,
1721 dst_peer->name)->util = dst_peer;
1723 dst_peer->peer_ref = copy_ref(ref);
1724 dst_peer->force = pat->force;
1725 free_name:
1726 free(dst_name);
1729 string_list_clear(&dst_ref_index, 0);
1731 if (flags & MATCH_REFS_FOLLOW_TAGS)
1732 add_missing_tags(src, dst, &dst_tail);
1734 if (send_prune) {
1735 struct string_list src_ref_index = STRING_LIST_INIT_NODUP;
1736 /* check for missing refs on the remote */
1737 for (ref = *dst; ref; ref = ref->next) {
1738 char *src_name;
1740 if (ref->peer_ref)
1741 /* We're already sending something to this ref. */
1742 continue;
1744 src_name = get_ref_match(rs, ref, send_mirror, FROM_DST, NULL);
1745 if (src_name) {
1746 if (!src_ref_index.nr)
1747 prepare_ref_index(&src_ref_index, src);
1748 if (!string_list_has_string(&src_ref_index,
1749 src_name))
1750 ref->peer_ref = alloc_delete_ref();
1751 free(src_name);
1754 string_list_clear(&src_ref_index, 0);
1757 *dst = apply_negative_refspecs(*dst, rs);
1759 if (errs)
1760 return -1;
1761 return 0;
1764 void set_ref_status_for_push(struct ref *remote_refs, int send_mirror,
1765 int force_update)
1767 struct ref *ref;
1769 for (ref = remote_refs; ref; ref = ref->next) {
1770 int force_ref_update = ref->force || force_update;
1771 int reject_reason = 0;
1773 if (ref->peer_ref)
1774 oidcpy(&ref->new_oid, &ref->peer_ref->new_oid);
1775 else if (!send_mirror)
1776 continue;
1778 ref->deletion = is_null_oid(&ref->new_oid);
1779 if (!ref->deletion &&
1780 oideq(&ref->old_oid, &ref->new_oid)) {
1781 ref->status = REF_STATUS_UPTODATE;
1782 continue;
1786 * If the remote ref has moved and is now different
1787 * from what we expect, reject any push.
1789 * It also is an error if the user told us to check
1790 * with the remote-tracking branch to find the value
1791 * to expect, but we did not have such a tracking
1792 * branch.
1794 * If the tip of the remote-tracking ref is unreachable
1795 * from any reflog entry of its local ref indicating a
1796 * possible update since checkout; reject the push.
1798 if (ref->expect_old_sha1) {
1799 if (!oideq(&ref->old_oid, &ref->old_oid_expect))
1800 reject_reason = REF_STATUS_REJECT_STALE;
1801 else if (ref->check_reachable && ref->unreachable)
1802 reject_reason =
1803 REF_STATUS_REJECT_REMOTE_UPDATED;
1804 else
1806 * If the ref isn't stale, and is reachable
1807 * from one of the reflog entries of
1808 * the local branch, force the update.
1810 force_ref_update = 1;
1814 * If the update isn't already rejected then check
1815 * the usual "must fast-forward" rules.
1817 * Decide whether an individual refspec A:B can be
1818 * pushed. The push will succeed if any of the
1819 * following are true:
1821 * (1) the remote reference B does not exist
1823 * (2) the remote reference B is being removed (i.e.,
1824 * pushing :B where no source is specified)
1826 * (3) the destination is not under refs/tags/, and
1827 * if the old and new value is a commit, the new
1828 * is a descendant of the old.
1830 * (4) it is forced using the +A:B notation, or by
1831 * passing the --force argument
1834 if (!reject_reason && !ref->deletion && !is_null_oid(&ref->old_oid)) {
1835 if (starts_with(ref->name, "refs/tags/"))
1836 reject_reason = REF_STATUS_REJECT_ALREADY_EXISTS;
1837 else if (!repo_has_object_file_with_flags(the_repository, &ref->old_oid, OBJECT_INFO_SKIP_FETCH_OBJECT))
1838 reject_reason = REF_STATUS_REJECT_FETCH_FIRST;
1839 else if (!lookup_commit_reference_gently(the_repository, &ref->old_oid, 1) ||
1840 !lookup_commit_reference_gently(the_repository, &ref->new_oid, 1))
1841 reject_reason = REF_STATUS_REJECT_NEEDS_FORCE;
1842 else if (!ref_newer(&ref->new_oid, &ref->old_oid))
1843 reject_reason = REF_STATUS_REJECT_NONFASTFORWARD;
1847 * "--force" will defeat any rejection implemented
1848 * by the rules above.
1850 if (!force_ref_update)
1851 ref->status = reject_reason;
1852 else if (reject_reason)
1853 ref->forced_update = 1;
1857 static void set_merge(struct remote_state *remote_state, struct branch *ret)
1859 struct remote *remote;
1860 char *ref;
1861 struct object_id oid;
1862 int i;
1864 if (!ret)
1865 return; /* no branch */
1866 if (ret->merge)
1867 return; /* already run */
1868 if (!ret->remote_name || !ret->merge_nr) {
1870 * no merge config; let's make sure we don't confuse callers
1871 * with a non-zero merge_nr but a NULL merge
1873 ret->merge_nr = 0;
1874 return;
1877 remote = remotes_remote_get(remote_state, ret->remote_name);
1879 CALLOC_ARRAY(ret->merge, ret->merge_nr);
1880 for (i = 0; i < ret->merge_nr; i++) {
1881 ret->merge[i] = xcalloc(1, sizeof(**ret->merge));
1882 ret->merge[i]->src = xstrdup(ret->merge_name[i]);
1883 if (!remote_find_tracking(remote, ret->merge[i]) ||
1884 strcmp(ret->remote_name, "."))
1885 continue;
1886 if (repo_dwim_ref(the_repository, ret->merge_name[i],
1887 strlen(ret->merge_name[i]), &oid, &ref,
1888 0) == 1)
1889 ret->merge[i]->dst = ref;
1890 else
1891 ret->merge[i]->dst = xstrdup(ret->merge_name[i]);
1895 struct branch *branch_get(const char *name)
1897 struct branch *ret;
1899 read_config(the_repository, 0);
1900 if (!name || !*name || !strcmp(name, "HEAD"))
1901 ret = the_repository->remote_state->current_branch;
1902 else
1903 ret = make_branch(the_repository->remote_state, name,
1904 strlen(name));
1905 set_merge(the_repository->remote_state, ret);
1906 return ret;
1909 int branch_has_merge_config(struct branch *branch)
1911 return branch && !!branch->merge;
1914 int branch_merge_matches(struct branch *branch,
1915 int i,
1916 const char *refname)
1918 if (!branch || i < 0 || i >= branch->merge_nr)
1919 return 0;
1920 return refname_match(branch->merge[i]->src, refname);
1923 __attribute__((format (printf,2,3)))
1924 static const char *error_buf(struct strbuf *err, const char *fmt, ...)
1926 if (err) {
1927 va_list ap;
1928 va_start(ap, fmt);
1929 strbuf_vaddf(err, fmt, ap);
1930 va_end(ap);
1932 return NULL;
1935 const char *branch_get_upstream(struct branch *branch, struct strbuf *err)
1937 if (!branch)
1938 return error_buf(err, _("HEAD does not point to a branch"));
1940 if (!branch->merge || !branch->merge[0]) {
1942 * no merge config; is it because the user didn't define any,
1943 * or because it is not a real branch, and get_branch
1944 * auto-vivified it?
1946 if (!refs_ref_exists(get_main_ref_store(the_repository), branch->refname))
1947 return error_buf(err, _("no such branch: '%s'"),
1948 branch->name);
1949 return error_buf(err,
1950 _("no upstream configured for branch '%s'"),
1951 branch->name);
1954 if (!branch->merge[0]->dst)
1955 return error_buf(err,
1956 _("upstream branch '%s' not stored as a remote-tracking branch"),
1957 branch->merge[0]->src);
1959 return branch->merge[0]->dst;
1962 static const char *tracking_for_push_dest(struct remote *remote,
1963 const char *refname,
1964 struct strbuf *err)
1966 char *ret;
1968 ret = apply_refspecs(&remote->fetch, refname);
1969 if (!ret)
1970 return error_buf(err,
1971 _("push destination '%s' on remote '%s' has no local tracking branch"),
1972 refname, remote->name);
1973 return ret;
1976 static const char *branch_get_push_1(struct remote_state *remote_state,
1977 struct branch *branch, struct strbuf *err)
1979 struct remote *remote;
1981 remote = remotes_remote_get(
1982 remote_state,
1983 remotes_pushremote_for_branch(remote_state, branch, NULL));
1984 if (!remote)
1985 return error_buf(err,
1986 _("branch '%s' has no remote for pushing"),
1987 branch->name);
1989 if (remote->push.nr) {
1990 char *dst;
1991 const char *ret;
1993 dst = apply_refspecs(&remote->push, branch->refname);
1994 if (!dst)
1995 return error_buf(err,
1996 _("push refspecs for '%s' do not include '%s'"),
1997 remote->name, branch->name);
1999 ret = tracking_for_push_dest(remote, dst, err);
2000 free(dst);
2001 return ret;
2004 if (remote->mirror)
2005 return tracking_for_push_dest(remote, branch->refname, err);
2007 switch (push_default) {
2008 case PUSH_DEFAULT_NOTHING:
2009 return error_buf(err, _("push has no destination (push.default is 'nothing')"));
2011 case PUSH_DEFAULT_MATCHING:
2012 case PUSH_DEFAULT_CURRENT:
2013 return tracking_for_push_dest(remote, branch->refname, err);
2015 case PUSH_DEFAULT_UPSTREAM:
2016 return branch_get_upstream(branch, err);
2018 case PUSH_DEFAULT_UNSPECIFIED:
2019 case PUSH_DEFAULT_SIMPLE:
2021 const char *up, *cur;
2023 up = branch_get_upstream(branch, err);
2024 if (!up)
2025 return NULL;
2026 cur = tracking_for_push_dest(remote, branch->refname, err);
2027 if (!cur)
2028 return NULL;
2029 if (strcmp(cur, up))
2030 return error_buf(err,
2031 _("cannot resolve 'simple' push to a single destination"));
2032 return cur;
2036 BUG("unhandled push situation");
2039 const char *branch_get_push(struct branch *branch, struct strbuf *err)
2041 read_config(the_repository, 0);
2042 die_on_missing_branch(the_repository, branch);
2044 if (!branch)
2045 return error_buf(err, _("HEAD does not point to a branch"));
2047 if (!branch->push_tracking_ref)
2048 branch->push_tracking_ref = branch_get_push_1(
2049 the_repository->remote_state, branch, err);
2050 return branch->push_tracking_ref;
2053 static int ignore_symref_update(const char *refname, struct strbuf *scratch)
2055 return !refs_read_symbolic_ref(get_main_ref_store(the_repository), refname, scratch);
2059 * Create and return a list of (struct ref) consisting of copies of
2060 * each remote_ref that matches refspec. refspec must be a pattern.
2061 * Fill in the copies' peer_ref to describe the local tracking refs to
2062 * which they map. Omit any references that would map to an existing
2063 * local symbolic ref.
2065 static struct ref *get_expanded_map(const struct ref *remote_refs,
2066 const struct refspec_item *refspec)
2068 struct strbuf scratch = STRBUF_INIT;
2069 const struct ref *ref;
2070 struct ref *ret = NULL;
2071 struct ref **tail = &ret;
2073 for (ref = remote_refs; ref; ref = ref->next) {
2074 char *expn_name = NULL;
2076 strbuf_reset(&scratch);
2078 if (strchr(ref->name, '^'))
2079 continue; /* a dereference item */
2080 if (match_name_with_pattern(refspec->src, ref->name,
2081 refspec->dst, &expn_name) &&
2082 !ignore_symref_update(expn_name, &scratch)) {
2083 struct ref *cpy = copy_ref(ref);
2085 if (cpy->peer_ref)
2086 free_one_ref(cpy->peer_ref);
2087 cpy->peer_ref = alloc_ref(expn_name);
2088 if (refspec->force)
2089 cpy->peer_ref->force = 1;
2090 *tail = cpy;
2091 tail = &cpy->next;
2093 free(expn_name);
2096 strbuf_release(&scratch);
2097 return ret;
2100 static const struct ref *find_ref_by_name_abbrev(const struct ref *refs, const char *name)
2102 const struct ref *ref;
2103 const struct ref *best_match = NULL;
2104 int best_score = 0;
2106 for (ref = refs; ref; ref = ref->next) {
2107 int score = refname_match(name, ref->name);
2109 if (best_score < score) {
2110 best_match = ref;
2111 best_score = score;
2114 return best_match;
2117 struct ref *get_remote_ref(const struct ref *remote_refs, const char *name)
2119 const struct ref *ref = find_ref_by_name_abbrev(remote_refs, name);
2121 if (!ref)
2122 return NULL;
2124 return copy_ref(ref);
2127 static struct ref *get_local_ref(const char *name)
2129 if (!name || name[0] == '\0')
2130 return NULL;
2132 if (starts_with(name, "refs/"))
2133 return alloc_ref(name);
2135 if (starts_with(name, "heads/") ||
2136 starts_with(name, "tags/") ||
2137 starts_with(name, "remotes/"))
2138 return alloc_ref_with_prefix("refs/", 5, name);
2140 return alloc_ref_with_prefix("refs/heads/", 11, name);
2143 int get_fetch_map(const struct ref *remote_refs,
2144 const struct refspec_item *refspec,
2145 struct ref ***tail,
2146 int missing_ok)
2148 struct ref *ref_map, **rmp;
2150 if (refspec->negative)
2151 return 0;
2153 if (refspec->pattern) {
2154 ref_map = get_expanded_map(remote_refs, refspec);
2155 } else {
2156 const char *name = refspec->src[0] ? refspec->src : "HEAD";
2158 if (refspec->exact_sha1) {
2159 ref_map = alloc_ref(name);
2160 get_oid_hex(name, &ref_map->old_oid);
2161 ref_map->exact_oid = 1;
2162 } else {
2163 ref_map = get_remote_ref(remote_refs, name);
2165 if (!missing_ok && !ref_map)
2166 die(_("couldn't find remote ref %s"), name);
2167 if (ref_map) {
2168 ref_map->peer_ref = get_local_ref(refspec->dst);
2169 if (ref_map->peer_ref && refspec->force)
2170 ref_map->peer_ref->force = 1;
2174 for (rmp = &ref_map; *rmp; ) {
2175 if ((*rmp)->peer_ref) {
2176 if (!starts_with((*rmp)->peer_ref->name, "refs/") ||
2177 check_refname_format((*rmp)->peer_ref->name, 0)) {
2178 struct ref *ignore = *rmp;
2179 error(_("* Ignoring funny ref '%s' locally"),
2180 (*rmp)->peer_ref->name);
2181 *rmp = (*rmp)->next;
2182 free(ignore->peer_ref);
2183 free(ignore);
2184 continue;
2187 rmp = &((*rmp)->next);
2190 if (ref_map)
2191 tail_link_ref(ref_map, tail);
2193 return 0;
2196 int resolve_remote_symref(struct ref *ref, struct ref *list)
2198 if (!ref->symref)
2199 return 0;
2200 for (; list; list = list->next)
2201 if (!strcmp(ref->symref, list->name)) {
2202 oidcpy(&ref->old_oid, &list->old_oid);
2203 return 0;
2205 return 1;
2209 * Compute the commit ahead/behind values for the pair branch_name, base.
2211 * If abf is AHEAD_BEHIND_FULL, compute the full ahead/behind and return the
2212 * counts in *num_ours and *num_theirs. If abf is AHEAD_BEHIND_QUICK, skip
2213 * the (potentially expensive) a/b computation (*num_ours and *num_theirs are
2214 * set to zero).
2216 * Returns -1 if num_ours and num_theirs could not be filled in (e.g., ref
2217 * does not exist). Returns 0 if the commits are identical. Returns 1 if
2218 * commits are different.
2221 static int stat_branch_pair(const char *branch_name, const char *base,
2222 int *num_ours, int *num_theirs,
2223 enum ahead_behind_flags abf)
2225 struct object_id oid;
2226 struct commit *ours, *theirs;
2227 struct rev_info revs;
2228 struct setup_revision_opt opt = {
2229 .free_removed_argv_elements = 1,
2231 struct strvec argv = STRVEC_INIT;
2233 /* Cannot stat if what we used to build on no longer exists */
2234 if (refs_read_ref(get_main_ref_store(the_repository), base, &oid))
2235 return -1;
2236 theirs = lookup_commit_reference(the_repository, &oid);
2237 if (!theirs)
2238 return -1;
2240 if (refs_read_ref(get_main_ref_store(the_repository), branch_name, &oid))
2241 return -1;
2242 ours = lookup_commit_reference(the_repository, &oid);
2243 if (!ours)
2244 return -1;
2246 *num_theirs = *num_ours = 0;
2248 /* are we the same? */
2249 if (theirs == ours)
2250 return 0;
2251 if (abf == AHEAD_BEHIND_QUICK)
2252 return 1;
2253 if (abf != AHEAD_BEHIND_FULL)
2254 BUG("stat_branch_pair: invalid abf '%d'", abf);
2256 /* Run "rev-list --left-right ours...theirs" internally... */
2257 strvec_push(&argv, ""); /* ignored */
2258 strvec_push(&argv, "--left-right");
2259 strvec_pushf(&argv, "%s...%s",
2260 oid_to_hex(&ours->object.oid),
2261 oid_to_hex(&theirs->object.oid));
2262 strvec_push(&argv, "--");
2264 repo_init_revisions(the_repository, &revs, NULL);
2265 setup_revisions(argv.nr, argv.v, &revs, &opt);
2266 if (prepare_revision_walk(&revs))
2267 die(_("revision walk setup failed"));
2269 /* ... and count the commits on each side. */
2270 while (1) {
2271 struct commit *c = get_revision(&revs);
2272 if (!c)
2273 break;
2274 if (c->object.flags & SYMMETRIC_LEFT)
2275 (*num_ours)++;
2276 else
2277 (*num_theirs)++;
2280 /* clear object flags smudged by the above traversal */
2281 clear_commit_marks(ours, ALL_REV_FLAGS);
2282 clear_commit_marks(theirs, ALL_REV_FLAGS);
2284 strvec_clear(&argv);
2285 release_revisions(&revs);
2286 return 1;
2290 * Lookup the tracking branch for the given branch and if present, optionally
2291 * compute the commit ahead/behind values for the pair.
2293 * If for_push is true, the tracking branch refers to the push branch,
2294 * otherwise it refers to the upstream branch.
2296 * The name of the tracking branch (or NULL if it is not defined) is
2297 * returned via *tracking_name, if it is not itself NULL.
2299 * If abf is AHEAD_BEHIND_FULL, compute the full ahead/behind and return the
2300 * counts in *num_ours and *num_theirs. If abf is AHEAD_BEHIND_QUICK, skip
2301 * the (potentially expensive) a/b computation (*num_ours and *num_theirs are
2302 * set to zero).
2304 * Returns -1 if num_ours and num_theirs could not be filled in (e.g., no
2305 * upstream defined, or ref does not exist). Returns 0 if the commits are
2306 * identical. Returns 1 if commits are different.
2308 int stat_tracking_info(struct branch *branch, int *num_ours, int *num_theirs,
2309 const char **tracking_name, int for_push,
2310 enum ahead_behind_flags abf)
2312 const char *base;
2314 /* Cannot stat unless we are marked to build on top of somebody else. */
2315 base = for_push ? branch_get_push(branch, NULL) :
2316 branch_get_upstream(branch, NULL);
2317 if (tracking_name)
2318 *tracking_name = base;
2319 if (!base)
2320 return -1;
2322 return stat_branch_pair(branch->refname, base, num_ours, num_theirs, abf);
2326 * Return true when there is anything to report, otherwise false.
2328 int format_tracking_info(struct branch *branch, struct strbuf *sb,
2329 enum ahead_behind_flags abf,
2330 int show_divergence_advice)
2332 int ours, theirs, sti;
2333 const char *full_base;
2334 char *base;
2335 int upstream_is_gone = 0;
2337 sti = stat_tracking_info(branch, &ours, &theirs, &full_base, 0, abf);
2338 if (sti < 0) {
2339 if (!full_base)
2340 return 0;
2341 upstream_is_gone = 1;
2344 base = refs_shorten_unambiguous_ref(get_main_ref_store(the_repository),
2345 full_base, 0);
2346 if (upstream_is_gone) {
2347 strbuf_addf(sb,
2348 _("Your branch is based on '%s', but the upstream is gone.\n"),
2349 base);
2350 if (advice_enabled(ADVICE_STATUS_HINTS))
2351 strbuf_addstr(sb,
2352 _(" (use \"git branch --unset-upstream\" to fixup)\n"));
2353 } else if (!sti) {
2354 strbuf_addf(sb,
2355 _("Your branch is up to date with '%s'.\n"),
2356 base);
2357 } else if (abf == AHEAD_BEHIND_QUICK) {
2358 strbuf_addf(sb,
2359 _("Your branch and '%s' refer to different commits.\n"),
2360 base);
2361 if (advice_enabled(ADVICE_STATUS_HINTS))
2362 strbuf_addf(sb, _(" (use \"%s\" for details)\n"),
2363 "git status --ahead-behind");
2364 } else if (!theirs) {
2365 strbuf_addf(sb,
2366 Q_("Your branch is ahead of '%s' by %d commit.\n",
2367 "Your branch is ahead of '%s' by %d commits.\n",
2368 ours),
2369 base, ours);
2370 if (advice_enabled(ADVICE_STATUS_HINTS))
2371 strbuf_addstr(sb,
2372 _(" (use \"git push\" to publish your local commits)\n"));
2373 } else if (!ours) {
2374 strbuf_addf(sb,
2375 Q_("Your branch is behind '%s' by %d commit, "
2376 "and can be fast-forwarded.\n",
2377 "Your branch is behind '%s' by %d commits, "
2378 "and can be fast-forwarded.\n",
2379 theirs),
2380 base, theirs);
2381 if (advice_enabled(ADVICE_STATUS_HINTS))
2382 strbuf_addstr(sb,
2383 _(" (use \"git pull\" to update your local branch)\n"));
2384 } else {
2385 strbuf_addf(sb,
2386 Q_("Your branch and '%s' have diverged,\n"
2387 "and have %d and %d different commit each, "
2388 "respectively.\n",
2389 "Your branch and '%s' have diverged,\n"
2390 "and have %d and %d different commits each, "
2391 "respectively.\n",
2392 ours + theirs),
2393 base, ours, theirs);
2394 if (show_divergence_advice &&
2395 advice_enabled(ADVICE_STATUS_HINTS))
2396 strbuf_addstr(sb,
2397 _(" (use \"git pull\" if you want to integrate the remote branch with yours)\n"));
2399 free(base);
2400 return 1;
2403 static int one_local_ref(const char *refname, const char *referent UNUSED, const struct object_id *oid,
2404 int flag UNUSED,
2405 void *cb_data)
2407 struct ref ***local_tail = cb_data;
2408 struct ref *ref;
2410 /* we already know it starts with refs/ to get here */
2411 if (check_refname_format(refname + 5, 0))
2412 return 0;
2414 ref = alloc_ref(refname);
2415 oidcpy(&ref->new_oid, oid);
2416 **local_tail = ref;
2417 *local_tail = &ref->next;
2418 return 0;
2421 struct ref *get_local_heads(void)
2423 struct ref *local_refs = NULL, **local_tail = &local_refs;
2425 refs_for_each_ref(get_main_ref_store(the_repository), one_local_ref,
2426 &local_tail);
2427 return local_refs;
2430 struct ref *guess_remote_head(const struct ref *head,
2431 const struct ref *refs,
2432 int all)
2434 const struct ref *r;
2435 struct ref *list = NULL;
2436 struct ref **tail = &list;
2438 if (!head)
2439 return NULL;
2442 * Some transports support directly peeking at
2443 * where HEAD points; if that is the case, then
2444 * we don't have to guess.
2446 if (head->symref)
2447 return copy_ref(find_ref_by_name(refs, head->symref));
2449 /* If a remote branch exists with the default branch name, let's use it. */
2450 if (!all) {
2451 char *default_branch = repo_default_branch_name(the_repository, 0);
2452 char *ref = xstrfmt("refs/heads/%s", default_branch);
2454 r = find_ref_by_name(refs, ref);
2455 free(ref);
2456 free(default_branch);
2458 if (r && oideq(&r->old_oid, &head->old_oid))
2459 return copy_ref(r);
2461 /* Fall back to the hard-coded historical default */
2462 r = find_ref_by_name(refs, "refs/heads/master");
2463 if (r && oideq(&r->old_oid, &head->old_oid))
2464 return copy_ref(r);
2467 /* Look for another ref that points there */
2468 for (r = refs; r; r = r->next) {
2469 if (r != head &&
2470 starts_with(r->name, "refs/heads/") &&
2471 oideq(&r->old_oid, &head->old_oid)) {
2472 *tail = copy_ref(r);
2473 tail = &((*tail)->next);
2474 if (!all)
2475 break;
2479 return list;
2482 struct stale_heads_info {
2483 struct string_list *ref_names;
2484 struct ref **stale_refs_tail;
2485 struct refspec *rs;
2488 static int get_stale_heads_cb(const char *refname, const char *referent UNUSED, const struct object_id *oid,
2489 int flags, void *cb_data)
2491 struct stale_heads_info *info = cb_data;
2492 struct string_list matches = STRING_LIST_INIT_DUP;
2493 struct refspec_item query;
2494 int i, stale = 1;
2495 memset(&query, 0, sizeof(struct refspec_item));
2496 query.dst = (char *)refname;
2498 query_refspecs_multiple(info->rs, &query, &matches);
2499 if (matches.nr == 0)
2500 goto clean_exit; /* No matches */
2503 * If we did find a suitable refspec and it's not a symref and
2504 * it's not in the list of refs that currently exist in that
2505 * remote, we consider it to be stale. In order to deal with
2506 * overlapping refspecs, we need to go over all of the
2507 * matching refs.
2509 if (flags & REF_ISSYMREF)
2510 goto clean_exit;
2512 for (i = 0; stale && i < matches.nr; i++)
2513 if (string_list_has_string(info->ref_names, matches.items[i].string))
2514 stale = 0;
2516 if (stale) {
2517 struct ref *ref = make_linked_ref(refname, &info->stale_refs_tail);
2518 oidcpy(&ref->new_oid, oid);
2521 clean_exit:
2522 string_list_clear(&matches, 0);
2523 return 0;
2526 struct ref *get_stale_heads(struct refspec *rs, struct ref *fetch_map)
2528 struct ref *ref, *stale_refs = NULL;
2529 struct string_list ref_names = STRING_LIST_INIT_NODUP;
2530 struct stale_heads_info info;
2532 info.ref_names = &ref_names;
2533 info.stale_refs_tail = &stale_refs;
2534 info.rs = rs;
2535 for (ref = fetch_map; ref; ref = ref->next)
2536 string_list_append(&ref_names, ref->name);
2537 string_list_sort(&ref_names);
2538 refs_for_each_ref(get_main_ref_store(the_repository),
2539 get_stale_heads_cb, &info);
2540 string_list_clear(&ref_names, 0);
2541 return stale_refs;
2545 * Compare-and-swap
2547 void clear_cas_option(struct push_cas_option *cas)
2549 int i;
2551 for (i = 0; i < cas->nr; i++)
2552 free(cas->entry[i].refname);
2553 free(cas->entry);
2554 memset(cas, 0, sizeof(*cas));
2557 static struct push_cas *add_cas_entry(struct push_cas_option *cas,
2558 const char *refname,
2559 size_t refnamelen)
2561 struct push_cas *entry;
2562 ALLOC_GROW(cas->entry, cas->nr + 1, cas->alloc);
2563 entry = &cas->entry[cas->nr++];
2564 memset(entry, 0, sizeof(*entry));
2565 entry->refname = xmemdupz(refname, refnamelen);
2566 return entry;
2569 static int parse_push_cas_option(struct push_cas_option *cas, const char *arg, int unset)
2571 const char *colon;
2572 struct push_cas *entry;
2574 if (unset) {
2575 /* "--no-<option>" */
2576 clear_cas_option(cas);
2577 return 0;
2580 if (!arg) {
2581 /* just "--<option>" */
2582 cas->use_tracking_for_rest = 1;
2583 return 0;
2586 /* "--<option>=refname" or "--<option>=refname:value" */
2587 colon = strchrnul(arg, ':');
2588 entry = add_cas_entry(cas, arg, colon - arg);
2589 if (!*colon)
2590 entry->use_tracking = 1;
2591 else if (!colon[1])
2592 oidclr(&entry->expect, the_repository->hash_algo);
2593 else if (repo_get_oid(the_repository, colon + 1, &entry->expect))
2594 return error(_("cannot parse expected object name '%s'"),
2595 colon + 1);
2596 return 0;
2599 int parseopt_push_cas_option(const struct option *opt, const char *arg, int unset)
2601 return parse_push_cas_option(opt->value, arg, unset);
2604 int is_empty_cas(const struct push_cas_option *cas)
2606 return !cas->use_tracking_for_rest && !cas->nr;
2610 * Look at remote.fetch refspec and see if we have a remote
2611 * tracking branch for the refname there. Fill the name of
2612 * the remote-tracking branch in *dst_refname, and the name
2613 * of the commit object at its tip in oid[].
2614 * If we cannot do so, return negative to signal an error.
2616 static int remote_tracking(struct remote *remote, const char *refname,
2617 struct object_id *oid, char **dst_refname)
2619 char *dst;
2621 dst = apply_refspecs(&remote->fetch, refname);
2622 if (!dst)
2623 return -1; /* no tracking ref for refname at remote */
2624 if (refs_read_ref(get_main_ref_store(the_repository), dst, oid)) {
2625 free(dst);
2626 return -1; /* we know what the tracking ref is but we cannot read it */
2629 *dst_refname = dst;
2630 return 0;
2634 * The struct "reflog_commit_array" and related helper functions
2635 * are used for collecting commits into an array during reflog
2636 * traversals in "check_and_collect_until()".
2638 struct reflog_commit_array {
2639 struct commit **item;
2640 size_t nr, alloc;
2643 #define REFLOG_COMMIT_ARRAY_INIT { 0 }
2645 /* Append a commit to the array. */
2646 static void append_commit(struct reflog_commit_array *arr,
2647 struct commit *commit)
2649 ALLOC_GROW(arr->item, arr->nr + 1, arr->alloc);
2650 arr->item[arr->nr++] = commit;
2653 /* Free and reset the array. */
2654 static void free_commit_array(struct reflog_commit_array *arr)
2656 FREE_AND_NULL(arr->item);
2657 arr->nr = arr->alloc = 0;
2660 struct check_and_collect_until_cb_data {
2661 struct commit *remote_commit;
2662 struct reflog_commit_array *local_commits;
2663 timestamp_t remote_reflog_timestamp;
2666 /* Get the timestamp of the latest entry. */
2667 static int peek_reflog(struct object_id *o_oid UNUSED,
2668 struct object_id *n_oid UNUSED,
2669 const char *ident UNUSED,
2670 timestamp_t timestamp, int tz UNUSED,
2671 const char *message UNUSED, void *cb_data)
2673 timestamp_t *ts = cb_data;
2674 *ts = timestamp;
2675 return 1;
2678 static int check_and_collect_until(struct object_id *o_oid UNUSED,
2679 struct object_id *n_oid,
2680 const char *ident UNUSED,
2681 timestamp_t timestamp, int tz UNUSED,
2682 const char *message UNUSED, void *cb_data)
2684 struct commit *commit;
2685 struct check_and_collect_until_cb_data *cb = cb_data;
2687 /* An entry was found. */
2688 if (oideq(n_oid, &cb->remote_commit->object.oid))
2689 return 1;
2691 if ((commit = lookup_commit_reference(the_repository, n_oid)))
2692 append_commit(cb->local_commits, commit);
2695 * If the reflog entry timestamp is older than the remote ref's
2696 * latest reflog entry, there is no need to check or collect
2697 * entries older than this one.
2699 if (timestamp < cb->remote_reflog_timestamp)
2700 return -1;
2702 return 0;
2705 #define MERGE_BASES_BATCH_SIZE 8
2708 * Iterate through the reflog of the local ref to check if there is an entry
2709 * for the given remote-tracking ref; runs until the timestamp of an entry is
2710 * older than latest timestamp of remote-tracking ref's reflog. Any commits
2711 * are that seen along the way are collected into an array to check if the
2712 * remote-tracking ref is reachable from any of them.
2714 static int is_reachable_in_reflog(const char *local, const struct ref *remote)
2716 timestamp_t date;
2717 struct commit *commit;
2718 struct commit **chunk;
2719 struct check_and_collect_until_cb_data cb;
2720 struct reflog_commit_array arr = REFLOG_COMMIT_ARRAY_INIT;
2721 size_t size = 0;
2722 int ret = 0;
2724 commit = lookup_commit_reference(the_repository, &remote->old_oid);
2725 if (!commit)
2726 goto cleanup_return;
2729 * Get the timestamp from the latest entry
2730 * of the remote-tracking ref's reflog.
2732 refs_for_each_reflog_ent_reverse(get_main_ref_store(the_repository),
2733 remote->tracking_ref, peek_reflog,
2734 &date);
2736 cb.remote_commit = commit;
2737 cb.local_commits = &arr;
2738 cb.remote_reflog_timestamp = date;
2739 ret = refs_for_each_reflog_ent_reverse(get_main_ref_store(the_repository),
2740 local, check_and_collect_until,
2741 &cb);
2743 /* We found an entry in the reflog. */
2744 if (ret > 0)
2745 goto cleanup_return;
2748 * Check if the remote commit is reachable from any
2749 * of the commits in the collected array, in batches.
2751 for (chunk = arr.item; chunk < arr.item + arr.nr; chunk += size) {
2752 size = arr.item + arr.nr - chunk;
2753 if (MERGE_BASES_BATCH_SIZE < size)
2754 size = MERGE_BASES_BATCH_SIZE;
2756 if ((ret = repo_in_merge_bases_many(the_repository, commit, size, chunk, 0)))
2757 break;
2760 cleanup_return:
2761 free_commit_array(&arr);
2762 return ret;
2766 * Check for reachability of a remote-tracking
2767 * ref in the reflog entries of its local ref.
2769 static void check_if_includes_upstream(struct ref *remote)
2771 struct ref *local = get_local_ref(remote->name);
2772 if (!local)
2773 return;
2775 if (is_reachable_in_reflog(local->name, remote) <= 0)
2776 remote->unreachable = 1;
2777 free_one_ref(local);
2780 static void apply_cas(struct push_cas_option *cas,
2781 struct remote *remote,
2782 struct ref *ref)
2784 int i;
2786 /* Find an explicit --<option>=<name>[:<value>] entry */
2787 for (i = 0; i < cas->nr; i++) {
2788 struct push_cas *entry = &cas->entry[i];
2789 if (!refname_match(entry->refname, ref->name))
2790 continue;
2791 ref->expect_old_sha1 = 1;
2792 if (!entry->use_tracking)
2793 oidcpy(&ref->old_oid_expect, &entry->expect);
2794 else if (remote_tracking(remote, ref->name,
2795 &ref->old_oid_expect,
2796 &ref->tracking_ref))
2797 oidclr(&ref->old_oid_expect, the_repository->hash_algo);
2798 else
2799 ref->check_reachable = cas->use_force_if_includes;
2800 return;
2803 /* Are we using "--<option>" to cover all? */
2804 if (!cas->use_tracking_for_rest)
2805 return;
2807 ref->expect_old_sha1 = 1;
2808 if (remote_tracking(remote, ref->name,
2809 &ref->old_oid_expect,
2810 &ref->tracking_ref))
2811 oidclr(&ref->old_oid_expect, the_repository->hash_algo);
2812 else
2813 ref->check_reachable = cas->use_force_if_includes;
2816 void apply_push_cas(struct push_cas_option *cas,
2817 struct remote *remote,
2818 struct ref *remote_refs)
2820 struct ref *ref;
2821 for (ref = remote_refs; ref; ref = ref->next) {
2822 apply_cas(cas, remote, ref);
2825 * If "compare-and-swap" is in "use_tracking[_for_rest]"
2826 * mode, and if "--force-if-includes" was specified, run
2827 * the check.
2829 if (ref->check_reachable)
2830 check_if_includes_upstream(ref);
2834 struct remote_state *remote_state_new(void)
2836 struct remote_state *r = xmalloc(sizeof(*r));
2838 memset(r, 0, sizeof(*r));
2840 hashmap_init(&r->remotes_hash, remotes_hash_cmp, NULL, 0);
2841 hashmap_init(&r->branches_hash, branches_hash_cmp, NULL, 0);
2842 return r;
2845 void remote_state_clear(struct remote_state *remote_state)
2847 struct hashmap_iter iter;
2848 struct branch *b;
2849 int i;
2851 for (i = 0; i < remote_state->remotes_nr; i++)
2852 remote_clear(remote_state->remotes[i]);
2853 FREE_AND_NULL(remote_state->remotes);
2854 FREE_AND_NULL(remote_state->pushremote_name);
2855 remote_state->remotes_alloc = 0;
2856 remote_state->remotes_nr = 0;
2858 rewrites_release(&remote_state->rewrites);
2859 rewrites_release(&remote_state->rewrites_push);
2861 hashmap_clear_and_free(&remote_state->remotes_hash, struct remote, ent);
2862 hashmap_for_each_entry(&remote_state->branches_hash, &iter, b, ent) {
2863 branch_release(b);
2864 free(b);
2866 hashmap_clear(&remote_state->branches_hash);
2870 * Returns 1 if it was the last chop before ':'.
2872 static int chop_last_dir(char **remoteurl, int is_relative)
2874 char *rfind = find_last_dir_sep(*remoteurl);
2875 if (rfind) {
2876 *rfind = '\0';
2877 return 0;
2880 rfind = strrchr(*remoteurl, ':');
2881 if (rfind) {
2882 *rfind = '\0';
2883 return 1;
2886 if (is_relative || !strcmp(".", *remoteurl))
2887 die(_("cannot strip one component off url '%s'"),
2888 *remoteurl);
2890 free(*remoteurl);
2891 *remoteurl = xstrdup(".");
2892 return 0;
2895 char *relative_url(const char *remote_url, const char *url,
2896 const char *up_path)
2898 int is_relative = 0;
2899 int colonsep = 0;
2900 char *out;
2901 char *remoteurl;
2902 struct strbuf sb = STRBUF_INIT;
2903 size_t len;
2905 if (!url_is_local_not_ssh(url) || is_absolute_path(url))
2906 return xstrdup(url);
2908 len = strlen(remote_url);
2909 if (!len)
2910 BUG("invalid empty remote_url");
2912 remoteurl = xstrdup(remote_url);
2913 if (is_dir_sep(remoteurl[len-1]))
2914 remoteurl[len-1] = '\0';
2916 if (!url_is_local_not_ssh(remoteurl) || is_absolute_path(remoteurl))
2917 is_relative = 0;
2918 else {
2919 is_relative = 1;
2921 * Prepend a './' to ensure all relative
2922 * remoteurls start with './' or '../'
2924 if (!starts_with_dot_slash_native(remoteurl) &&
2925 !starts_with_dot_dot_slash_native(remoteurl)) {
2926 strbuf_reset(&sb);
2927 strbuf_addf(&sb, "./%s", remoteurl);
2928 free(remoteurl);
2929 remoteurl = strbuf_detach(&sb, NULL);
2933 * When the url starts with '../', remove that and the
2934 * last directory in remoteurl.
2936 while (*url) {
2937 if (starts_with_dot_dot_slash_native(url)) {
2938 url += 3;
2939 colonsep |= chop_last_dir(&remoteurl, is_relative);
2940 } else if (starts_with_dot_slash_native(url))
2941 url += 2;
2942 else
2943 break;
2945 strbuf_reset(&sb);
2946 strbuf_addf(&sb, "%s%s%s", remoteurl, colonsep ? ":" : "/", url);
2947 if (ends_with(url, "/"))
2948 strbuf_setlen(&sb, sb.len - 1);
2949 free(remoteurl);
2951 if (starts_with_dot_slash_native(sb.buf))
2952 out = xstrdup(sb.buf + 2);
2953 else
2954 out = xstrdup(sb.buf);
2956 if (!up_path || !is_relative) {
2957 strbuf_release(&sb);
2958 return out;
2961 strbuf_reset(&sb);
2962 strbuf_addf(&sb, "%s%s", up_path, out);
2963 free(out);
2964 return strbuf_detach(&sb, NULL);