The eighth batch
[alt-git.git] / remote.c
blob7d5b8f750d8b76182dc75a1aa0ca722a60cae535
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 struct rewrite *make_rewrite(struct rewrites *r,
247 const char *base, size_t len)
249 struct rewrite *ret;
250 int i;
252 for (i = 0; i < r->rewrite_nr; i++) {
253 if (len == r->rewrite[i]->baselen &&
254 !strncmp(base, r->rewrite[i]->base, len))
255 return r->rewrite[i];
258 ALLOC_GROW(r->rewrite, r->rewrite_nr + 1, r->rewrite_alloc);
259 CALLOC_ARRAY(ret, 1);
260 r->rewrite[r->rewrite_nr++] = ret;
261 ret->base = xstrndup(base, len);
262 ret->baselen = len;
263 return ret;
266 static void add_instead_of(struct rewrite *rewrite, const char *instead_of)
268 ALLOC_GROW(rewrite->instead_of, rewrite->instead_of_nr + 1, rewrite->instead_of_alloc);
269 rewrite->instead_of[rewrite->instead_of_nr].s = instead_of;
270 rewrite->instead_of[rewrite->instead_of_nr].len = strlen(instead_of);
271 rewrite->instead_of_nr++;
274 static const char *skip_spaces(const char *s)
276 while (isspace(*s))
277 s++;
278 return s;
281 static void read_remotes_file(struct remote_state *remote_state,
282 struct remote *remote)
284 struct strbuf buf = STRBUF_INIT;
285 FILE *f = fopen_or_warn(git_path("remotes/%s", remote->name), "r");
287 if (!f)
288 return;
289 remote->configured_in_repo = 1;
290 remote->origin = REMOTE_REMOTES;
291 while (strbuf_getline(&buf, f) != EOF) {
292 const char *v;
294 strbuf_rtrim(&buf);
296 if (skip_prefix(buf.buf, "URL:", &v))
297 add_url_alias(remote_state, remote,
298 skip_spaces(v));
299 else if (skip_prefix(buf.buf, "Push:", &v))
300 refspec_append(&remote->push, skip_spaces(v));
301 else if (skip_prefix(buf.buf, "Pull:", &v))
302 refspec_append(&remote->fetch, skip_spaces(v));
304 strbuf_release(&buf);
305 fclose(f);
308 static void read_branches_file(struct remote_state *remote_state,
309 struct remote *remote)
311 char *frag, *to_free = NULL;
312 struct strbuf buf = STRBUF_INIT;
313 FILE *f = fopen_or_warn(git_path("branches/%s", remote->name), "r");
315 if (!f)
316 return;
318 strbuf_getline_lf(&buf, f);
319 fclose(f);
320 strbuf_trim(&buf);
321 if (!buf.len) {
322 strbuf_release(&buf);
323 return;
326 remote->configured_in_repo = 1;
327 remote->origin = REMOTE_BRANCHES;
330 * The branches file would have URL and optionally
331 * #branch specified. The default (or specified) branch is
332 * fetched and stored in the local branch matching the
333 * remote name.
335 frag = strchr(buf.buf, '#');
336 if (frag)
337 *(frag++) = '\0';
338 else
339 frag = to_free = repo_default_branch_name(the_repository, 0);
341 add_url_alias(remote_state, remote, buf.buf);
342 refspec_appendf(&remote->fetch, "refs/heads/%s:refs/heads/%s",
343 frag, remote->name);
346 * Cogito compatible push: push current HEAD to remote #branch
347 * (master if missing)
349 refspec_appendf(&remote->push, "HEAD:refs/heads/%s", frag);
350 remote->fetch_tags = 1; /* always auto-follow */
352 strbuf_release(&buf);
353 free(to_free);
356 static int handle_config(const char *key, const char *value,
357 const struct config_context *ctx, void *cb)
359 const char *name;
360 size_t namelen;
361 const char *subkey;
362 struct remote *remote;
363 struct branch *branch;
364 struct remote_state *remote_state = cb;
365 const struct key_value_info *kvi = ctx->kvi;
367 if (parse_config_key(key, "branch", &name, &namelen, &subkey) >= 0) {
368 /* There is no subsection. */
369 if (!name)
370 return 0;
371 /* There is a subsection, but it is empty. */
372 if (!namelen)
373 return -1;
374 branch = make_branch(remote_state, name, namelen);
375 if (!strcmp(subkey, "remote")) {
376 return git_config_string(&branch->remote_name, key, value);
377 } else if (!strcmp(subkey, "pushremote")) {
378 return git_config_string(&branch->pushremote_name, key, value);
379 } else if (!strcmp(subkey, "merge")) {
380 if (!value)
381 return config_error_nonbool(key);
382 add_merge(branch, xstrdup(value));
384 return 0;
386 if (parse_config_key(key, "url", &name, &namelen, &subkey) >= 0) {
387 struct rewrite *rewrite;
388 if (!name)
389 return 0;
390 if (!strcmp(subkey, "insteadof")) {
391 if (!value)
392 return config_error_nonbool(key);
393 rewrite = make_rewrite(&remote_state->rewrites, name,
394 namelen);
395 add_instead_of(rewrite, xstrdup(value));
396 } else if (!strcmp(subkey, "pushinsteadof")) {
397 if (!value)
398 return config_error_nonbool(key);
399 rewrite = make_rewrite(&remote_state->rewrites_push,
400 name, namelen);
401 add_instead_of(rewrite, xstrdup(value));
405 if (parse_config_key(key, "remote", &name, &namelen, &subkey) < 0)
406 return 0;
408 /* Handle remote.* variables */
409 if (!name && !strcmp(subkey, "pushdefault"))
410 return git_config_string(&remote_state->pushremote_name, key,
411 value);
413 if (!name)
414 return 0;
415 /* Handle remote.<name>.* variables */
416 if (*name == '/') {
417 warning(_("config remote shorthand cannot begin with '/': %s"),
418 name);
419 return 0;
421 remote = make_remote(remote_state, name, namelen);
422 remote->origin = REMOTE_CONFIG;
423 if (kvi->scope == CONFIG_SCOPE_LOCAL ||
424 kvi->scope == CONFIG_SCOPE_WORKTREE)
425 remote->configured_in_repo = 1;
426 if (!strcmp(subkey, "mirror"))
427 remote->mirror = git_config_bool(key, value);
428 else if (!strcmp(subkey, "skipdefaultupdate"))
429 remote->skip_default_update = git_config_bool(key, value);
430 else if (!strcmp(subkey, "skipfetchall"))
431 remote->skip_default_update = git_config_bool(key, value);
432 else if (!strcmp(subkey, "prune"))
433 remote->prune = git_config_bool(key, value);
434 else if (!strcmp(subkey, "prunetags"))
435 remote->prune_tags = git_config_bool(key, value);
436 else if (!strcmp(subkey, "url")) {
437 if (!value)
438 return config_error_nonbool(key);
439 add_url(remote, value);
440 } else if (!strcmp(subkey, "pushurl")) {
441 if (!value)
442 return config_error_nonbool(key);
443 add_pushurl(remote, value);
444 } else if (!strcmp(subkey, "push")) {
445 char *v;
446 if (git_config_string(&v, key, value))
447 return -1;
448 refspec_append(&remote->push, v);
449 free(v);
450 } else if (!strcmp(subkey, "fetch")) {
451 char *v;
452 if (git_config_string(&v, key, value))
453 return -1;
454 refspec_append(&remote->fetch, v);
455 free(v);
456 } else if (!strcmp(subkey, "receivepack")) {
457 char *v;
458 if (git_config_string(&v, key, value))
459 return -1;
460 if (!remote->receivepack)
461 remote->receivepack = v;
462 else
463 error(_("more than one receivepack given, using the first"));
464 } else if (!strcmp(subkey, "uploadpack")) {
465 char *v;
466 if (git_config_string(&v, key, value))
467 return -1;
468 if (!remote->uploadpack)
469 remote->uploadpack = v;
470 else
471 error(_("more than one uploadpack given, using the first"));
472 } else if (!strcmp(subkey, "tagopt")) {
473 if (!strcmp(value, "--no-tags"))
474 remote->fetch_tags = -1;
475 else if (!strcmp(value, "--tags"))
476 remote->fetch_tags = 2;
477 } else if (!strcmp(subkey, "proxy")) {
478 return git_config_string(&remote->http_proxy,
479 key, value);
480 } else if (!strcmp(subkey, "proxyauthmethod")) {
481 return git_config_string(&remote->http_proxy_authmethod,
482 key, value);
483 } else if (!strcmp(subkey, "vcs")) {
484 return git_config_string(&remote->foreign_vcs, key, value);
486 return 0;
489 static void alias_all_urls(struct remote_state *remote_state)
491 int i, j;
492 for (i = 0; i < remote_state->remotes_nr; i++) {
493 int add_pushurl_aliases;
494 if (!remote_state->remotes[i])
495 continue;
496 for (j = 0; j < remote_state->remotes[i]->pushurl.nr; j++) {
497 char *alias = alias_url(remote_state->remotes[i]->pushurl.v[j],
498 &remote_state->rewrites);
499 if (alias)
500 strvec_replace(&remote_state->remotes[i]->pushurl,
501 j, alias);
502 free(alias);
504 add_pushurl_aliases = remote_state->remotes[i]->pushurl.nr == 0;
505 for (j = 0; j < remote_state->remotes[i]->url.nr; j++) {
506 char *alias;
507 if (add_pushurl_aliases)
508 add_pushurl_alias(
509 remote_state, remote_state->remotes[i],
510 remote_state->remotes[i]->url.v[j]);
511 alias = alias_url(remote_state->remotes[i]->url.v[j],
512 &remote_state->rewrites);
513 if (alias)
514 strvec_replace(&remote_state->remotes[i]->url,
515 j, alias);
516 free(alias);
521 static void read_config(struct repository *repo, int early)
523 int flag;
525 if (repo->remote_state->initialized)
526 return;
527 repo->remote_state->initialized = 1;
529 repo->remote_state->current_branch = NULL;
530 if (startup_info->have_repository && !early) {
531 const char *head_ref = refs_resolve_ref_unsafe(
532 get_main_ref_store(repo), "HEAD", 0, NULL, &flag);
533 if (head_ref && (flag & REF_ISSYMREF) &&
534 skip_prefix(head_ref, "refs/heads/", &head_ref)) {
535 repo->remote_state->current_branch = make_branch(
536 repo->remote_state, head_ref, strlen(head_ref));
539 repo_config(repo, handle_config, repo->remote_state);
540 alias_all_urls(repo->remote_state);
543 static int valid_remote_nick(const char *name)
545 if (!name[0] || is_dot_or_dotdot(name))
546 return 0;
548 /* remote nicknames cannot contain slashes */
549 while (*name)
550 if (is_dir_sep(*name++))
551 return 0;
552 return 1;
555 static const char *remotes_remote_for_branch(struct remote_state *remote_state,
556 struct branch *branch,
557 int *explicit)
559 if (branch && branch->remote_name) {
560 if (explicit)
561 *explicit = 1;
562 return branch->remote_name;
564 if (explicit)
565 *explicit = 0;
566 if (remote_state->remotes_nr == 1)
567 return remote_state->remotes[0]->name;
568 return "origin";
571 const char *remote_for_branch(struct branch *branch, int *explicit)
573 read_config(the_repository, 0);
574 die_on_missing_branch(the_repository, branch);
576 return remotes_remote_for_branch(the_repository->remote_state, branch,
577 explicit);
580 static const char *
581 remotes_pushremote_for_branch(struct remote_state *remote_state,
582 struct branch *branch, int *explicit)
584 if (branch && branch->pushremote_name) {
585 if (explicit)
586 *explicit = 1;
587 return branch->pushremote_name;
589 if (remote_state->pushremote_name) {
590 if (explicit)
591 *explicit = 1;
592 return remote_state->pushremote_name;
594 return remotes_remote_for_branch(remote_state, branch, explicit);
597 const char *pushremote_for_branch(struct branch *branch, int *explicit)
599 read_config(the_repository, 0);
600 die_on_missing_branch(the_repository, branch);
602 return remotes_pushremote_for_branch(the_repository->remote_state,
603 branch, explicit);
606 static struct remote *remotes_remote_get(struct remote_state *remote_state,
607 const char *name);
609 const char *remote_ref_for_branch(struct branch *branch, int for_push)
611 read_config(the_repository, 0);
612 die_on_missing_branch(the_repository, branch);
614 if (branch) {
615 if (!for_push) {
616 if (branch->merge_nr) {
617 return branch->merge_name[0];
619 } else {
620 const char *dst,
621 *remote_name = remotes_pushremote_for_branch(
622 the_repository->remote_state, branch,
623 NULL);
624 struct remote *remote = remotes_remote_get(
625 the_repository->remote_state, remote_name);
627 if (remote && remote->push.nr &&
628 (dst = apply_refspecs(&remote->push,
629 branch->refname))) {
630 return dst;
634 return NULL;
637 static void validate_remote_url(struct remote *remote)
639 int i;
640 const char *value;
641 struct strbuf redacted = STRBUF_INIT;
642 int warn_not_die;
644 if (git_config_get_string_tmp("transfer.credentialsinurl", &value))
645 return;
647 if (!strcmp("warn", value))
648 warn_not_die = 1;
649 else if (!strcmp("die", value))
650 warn_not_die = 0;
651 else if (!strcmp("allow", value))
652 return;
653 else
654 die(_("unrecognized value transfer.credentialsInUrl: '%s'"), value);
656 for (i = 0; i < remote->url.nr; i++) {
657 struct url_info url_info = { 0 };
659 if (!url_normalize(remote->url.v[i], &url_info) ||
660 !url_info.passwd_off)
661 goto loop_cleanup;
663 strbuf_reset(&redacted);
664 strbuf_add(&redacted, url_info.url, url_info.passwd_off);
665 strbuf_addstr(&redacted, "<redacted>");
666 strbuf_addstr(&redacted,
667 url_info.url + url_info.passwd_off + url_info.passwd_len);
669 if (warn_not_die)
670 warning(_("URL '%s' uses plaintext credentials"), redacted.buf);
671 else
672 die(_("URL '%s' uses plaintext credentials"), redacted.buf);
674 loop_cleanup:
675 free(url_info.url);
678 strbuf_release(&redacted);
681 static struct remote *
682 remotes_remote_get_1(struct remote_state *remote_state, const char *name,
683 const char *(*get_default)(struct remote_state *,
684 struct branch *, int *))
686 struct remote *ret;
687 int name_given = 0;
689 if (name)
690 name_given = 1;
691 else
692 name = get_default(remote_state, remote_state->current_branch,
693 &name_given);
695 ret = make_remote(remote_state, name, 0);
696 if (valid_remote_nick(name) && have_git_dir()) {
697 if (!valid_remote(ret))
698 read_remotes_file(remote_state, ret);
699 if (!valid_remote(ret))
700 read_branches_file(remote_state, ret);
702 if (name_given && !valid_remote(ret))
703 add_url_alias(remote_state, ret, name);
704 if (!valid_remote(ret))
705 return NULL;
707 validate_remote_url(ret);
709 return ret;
712 static inline struct remote *
713 remotes_remote_get(struct remote_state *remote_state, const char *name)
715 return remotes_remote_get_1(remote_state, name,
716 remotes_remote_for_branch);
719 struct remote *remote_get(const char *name)
721 read_config(the_repository, 0);
722 return remotes_remote_get(the_repository->remote_state, name);
725 struct remote *remote_get_early(const char *name)
727 read_config(the_repository, 1);
728 return remotes_remote_get(the_repository->remote_state, name);
731 static inline struct remote *
732 remotes_pushremote_get(struct remote_state *remote_state, const char *name)
734 return remotes_remote_get_1(remote_state, name,
735 remotes_pushremote_for_branch);
738 struct remote *pushremote_get(const char *name)
740 read_config(the_repository, 0);
741 return remotes_pushremote_get(the_repository->remote_state, name);
744 int remote_is_configured(struct remote *remote, int in_repo)
746 if (!remote)
747 return 0;
748 if (in_repo)
749 return remote->configured_in_repo;
750 return !!remote->origin;
753 int for_each_remote(each_remote_fn fn, void *priv)
755 int i, result = 0;
756 read_config(the_repository, 0);
757 for (i = 0; i < the_repository->remote_state->remotes_nr && !result;
758 i++) {
759 struct remote *remote =
760 the_repository->remote_state->remotes[i];
761 if (!remote)
762 continue;
763 result = fn(remote, priv);
765 return result;
768 static void handle_duplicate(struct ref *ref1, struct ref *ref2)
770 if (strcmp(ref1->name, ref2->name)) {
771 if (ref1->fetch_head_status != FETCH_HEAD_IGNORE &&
772 ref2->fetch_head_status != FETCH_HEAD_IGNORE) {
773 die(_("Cannot fetch both %s and %s to %s"),
774 ref1->name, ref2->name, ref2->peer_ref->name);
775 } else if (ref1->fetch_head_status != FETCH_HEAD_IGNORE &&
776 ref2->fetch_head_status == FETCH_HEAD_IGNORE) {
777 warning(_("%s usually tracks %s, not %s"),
778 ref2->peer_ref->name, ref2->name, ref1->name);
779 } else if (ref1->fetch_head_status == FETCH_HEAD_IGNORE &&
780 ref2->fetch_head_status == FETCH_HEAD_IGNORE) {
781 die(_("%s tracks both %s and %s"),
782 ref2->peer_ref->name, ref1->name, ref2->name);
783 } else {
785 * This last possibility doesn't occur because
786 * FETCH_HEAD_IGNORE entries always appear at
787 * the end of the list.
789 BUG("Internal error");
792 free(ref2->peer_ref);
793 free(ref2);
796 struct ref *ref_remove_duplicates(struct ref *ref_map)
798 struct string_list refs = STRING_LIST_INIT_NODUP;
799 struct ref *retval = NULL;
800 struct ref **p = &retval;
802 while (ref_map) {
803 struct ref *ref = ref_map;
805 ref_map = ref_map->next;
806 ref->next = NULL;
808 if (!ref->peer_ref) {
809 *p = ref;
810 p = &ref->next;
811 } else {
812 struct string_list_item *item =
813 string_list_insert(&refs, ref->peer_ref->name);
815 if (item->util) {
816 /* Entry already existed */
817 handle_duplicate((struct ref *)item->util, ref);
818 } else {
819 *p = ref;
820 p = &ref->next;
821 item->util = ref;
826 string_list_clear(&refs, 0);
827 return retval;
830 int remote_has_url(struct remote *remote, const char *url)
832 int i;
833 for (i = 0; i < remote->url.nr; i++) {
834 if (!strcmp(remote->url.v[i], url))
835 return 1;
837 return 0;
840 struct strvec *push_url_of_remote(struct remote *remote)
842 return remote->pushurl.nr ? &remote->pushurl : &remote->url;
845 static int match_name_with_pattern(const char *key, const char *name,
846 const char *value, char **result)
848 const char *kstar = strchr(key, '*');
849 size_t klen;
850 size_t ksuffixlen;
851 size_t namelen;
852 int ret;
853 if (!kstar)
854 die(_("key '%s' of pattern had no '*'"), key);
855 klen = kstar - key;
856 ksuffixlen = strlen(kstar + 1);
857 namelen = strlen(name);
858 ret = !strncmp(name, key, klen) && namelen >= klen + ksuffixlen &&
859 !memcmp(name + namelen - ksuffixlen, kstar + 1, ksuffixlen);
860 if (ret && value) {
861 struct strbuf sb = STRBUF_INIT;
862 const char *vstar = strchr(value, '*');
863 if (!vstar)
864 die(_("value '%s' of pattern has no '*'"), value);
865 strbuf_add(&sb, value, vstar - value);
866 strbuf_add(&sb, name + klen, namelen - klen - ksuffixlen);
867 strbuf_addstr(&sb, vstar + 1);
868 *result = strbuf_detach(&sb, NULL);
870 return ret;
873 static int refspec_match(const struct refspec_item *refspec,
874 const char *name)
876 if (refspec->pattern)
877 return match_name_with_pattern(refspec->src, name, NULL, NULL);
879 return !strcmp(refspec->src, name);
882 int omit_name_by_refspec(const char *name, struct refspec *rs)
884 int i;
886 for (i = 0; i < rs->nr; i++) {
887 if (rs->items[i].negative && refspec_match(&rs->items[i], name))
888 return 1;
890 return 0;
893 struct ref *apply_negative_refspecs(struct ref *ref_map, struct refspec *rs)
895 struct ref **tail;
897 for (tail = &ref_map; *tail; ) {
898 struct ref *ref = *tail;
900 if (omit_name_by_refspec(ref->name, rs)) {
901 *tail = ref->next;
902 free(ref->peer_ref);
903 free(ref);
904 } else
905 tail = &ref->next;
908 return ref_map;
911 static int query_matches_negative_refspec(struct refspec *rs, struct refspec_item *query)
913 int i, matched_negative = 0;
914 int find_src = !query->src;
915 struct string_list reversed = STRING_LIST_INIT_DUP;
916 const char *needle = find_src ? query->dst : query->src;
919 * Check whether the queried ref matches any negative refpsec. If so,
920 * then we should ultimately treat this as not matching the query at
921 * all.
923 * Note that negative refspecs always match the source, but the query
924 * item uses the destination. To handle this, we apply pattern
925 * refspecs in reverse to figure out if the query source matches any
926 * of the negative refspecs.
928 * The first loop finds and expands all positive refspecs
929 * matched by the queried ref.
931 * The second loop checks if any of the results of the first loop
932 * match any negative refspec.
934 for (i = 0; i < rs->nr; i++) {
935 struct refspec_item *refspec = &rs->items[i];
936 char *expn_name;
938 if (refspec->negative)
939 continue;
941 /* Note the reversal of src and dst */
942 if (refspec->pattern) {
943 const char *key = refspec->dst ? refspec->dst : refspec->src;
944 const char *value = refspec->src;
946 if (match_name_with_pattern(key, needle, value, &expn_name))
947 string_list_append_nodup(&reversed, expn_name);
948 } else if (refspec->matching) {
949 /* For the special matching refspec, any query should match */
950 string_list_append(&reversed, needle);
951 } else if (!refspec->src) {
952 BUG("refspec->src should not be null here");
953 } else if (!strcmp(needle, refspec->src)) {
954 string_list_append(&reversed, refspec->src);
958 for (i = 0; !matched_negative && i < reversed.nr; i++) {
959 if (omit_name_by_refspec(reversed.items[i].string, rs))
960 matched_negative = 1;
963 string_list_clear(&reversed, 0);
965 return matched_negative;
968 static void query_refspecs_multiple(struct refspec *rs,
969 struct refspec_item *query,
970 struct string_list *results)
972 int i;
973 int find_src = !query->src;
975 if (find_src && !query->dst)
976 BUG("query_refspecs_multiple: need either src or dst");
978 if (query_matches_negative_refspec(rs, query))
979 return;
981 for (i = 0; i < rs->nr; i++) {
982 struct refspec_item *refspec = &rs->items[i];
983 const char *key = find_src ? refspec->dst : refspec->src;
984 const char *value = find_src ? refspec->src : refspec->dst;
985 const char *needle = find_src ? query->dst : query->src;
986 char **result = find_src ? &query->src : &query->dst;
988 if (!refspec->dst || refspec->negative)
989 continue;
990 if (refspec->pattern) {
991 if (match_name_with_pattern(key, needle, value, result))
992 string_list_append_nodup(results, *result);
993 } else if (!strcmp(needle, key)) {
994 string_list_append(results, value);
999 int query_refspecs(struct refspec *rs, struct refspec_item *query)
1001 int i;
1002 int find_src = !query->src;
1003 const char *needle = find_src ? query->dst : query->src;
1004 char **result = find_src ? &query->src : &query->dst;
1006 if (find_src && !query->dst)
1007 BUG("query_refspecs: need either src or dst");
1009 if (query_matches_negative_refspec(rs, query))
1010 return -1;
1012 for (i = 0; i < rs->nr; i++) {
1013 struct refspec_item *refspec = &rs->items[i];
1014 const char *key = find_src ? refspec->dst : refspec->src;
1015 const char *value = find_src ? refspec->src : refspec->dst;
1017 if (!refspec->dst || refspec->negative)
1018 continue;
1019 if (refspec->pattern) {
1020 if (match_name_with_pattern(key, needle, value, result)) {
1021 query->force = refspec->force;
1022 return 0;
1024 } else if (!strcmp(needle, key)) {
1025 *result = xstrdup(value);
1026 query->force = refspec->force;
1027 return 0;
1030 return -1;
1033 char *apply_refspecs(struct refspec *rs, const char *name)
1035 struct refspec_item query;
1037 memset(&query, 0, sizeof(struct refspec_item));
1038 query.src = (char *)name;
1040 if (query_refspecs(rs, &query))
1041 return NULL;
1043 return query.dst;
1046 int remote_find_tracking(struct remote *remote, struct refspec_item *refspec)
1048 return query_refspecs(&remote->fetch, refspec);
1051 static struct ref *alloc_ref_with_prefix(const char *prefix, size_t prefixlen,
1052 const char *name)
1054 size_t len = strlen(name);
1055 struct ref *ref = xcalloc(1, st_add4(sizeof(*ref), prefixlen, len, 1));
1056 memcpy(ref->name, prefix, prefixlen);
1057 memcpy(ref->name + prefixlen, name, len);
1058 return ref;
1061 struct ref *alloc_ref(const char *name)
1063 return alloc_ref_with_prefix("", 0, name);
1066 struct ref *copy_ref(const struct ref *ref)
1068 struct ref *cpy;
1069 size_t len;
1070 if (!ref)
1071 return NULL;
1072 len = st_add3(sizeof(struct ref), strlen(ref->name), 1);
1073 cpy = xmalloc(len);
1074 memcpy(cpy, ref, len);
1075 cpy->next = NULL;
1076 cpy->symref = xstrdup_or_null(ref->symref);
1077 cpy->remote_status = xstrdup_or_null(ref->remote_status);
1078 cpy->peer_ref = copy_ref(ref->peer_ref);
1079 return cpy;
1082 struct ref *copy_ref_list(const struct ref *ref)
1084 struct ref *ret = NULL;
1085 struct ref **tail = &ret;
1086 while (ref) {
1087 *tail = copy_ref(ref);
1088 ref = ref->next;
1089 tail = &((*tail)->next);
1091 return ret;
1094 void free_one_ref(struct ref *ref)
1096 if (!ref)
1097 return;
1098 free_one_ref(ref->peer_ref);
1099 free(ref->remote_status);
1100 free(ref->symref);
1101 free(ref);
1104 void free_refs(struct ref *ref)
1106 struct ref *next;
1107 while (ref) {
1108 next = ref->next;
1109 free_one_ref(ref);
1110 ref = next;
1114 int count_refspec_match(const char *pattern,
1115 struct ref *refs,
1116 struct ref **matched_ref)
1118 int patlen = strlen(pattern);
1119 struct ref *matched_weak = NULL;
1120 struct ref *matched = NULL;
1121 int weak_match = 0;
1122 int match = 0;
1124 for (weak_match = match = 0; refs; refs = refs->next) {
1125 char *name = refs->name;
1126 int namelen = strlen(name);
1128 if (!refname_match(pattern, name))
1129 continue;
1131 /* A match is "weak" if it is with refs outside
1132 * heads or tags, and did not specify the pattern
1133 * in full (e.g. "refs/remotes/origin/master") or at
1134 * least from the toplevel (e.g. "remotes/origin/master");
1135 * otherwise "git push $URL master" would result in
1136 * ambiguity between remotes/origin/master and heads/master
1137 * at the remote site.
1139 if (namelen != patlen &&
1140 patlen != namelen - 5 &&
1141 !starts_with(name, "refs/heads/") &&
1142 !starts_with(name, "refs/tags/")) {
1143 /* We want to catch the case where only weak
1144 * matches are found and there are multiple
1145 * matches, and where more than one strong
1146 * matches are found, as ambiguous. One
1147 * strong match with zero or more weak matches
1148 * are acceptable as a unique match.
1150 matched_weak = refs;
1151 weak_match++;
1153 else {
1154 matched = refs;
1155 match++;
1158 if (!matched) {
1159 if (matched_ref)
1160 *matched_ref = matched_weak;
1161 return weak_match;
1163 else {
1164 if (matched_ref)
1165 *matched_ref = matched;
1166 return match;
1170 static void tail_link_ref(struct ref *ref, struct ref ***tail)
1172 **tail = ref;
1173 while (ref->next)
1174 ref = ref->next;
1175 *tail = &ref->next;
1178 static struct ref *alloc_delete_ref(void)
1180 struct ref *ref = alloc_ref("(delete)");
1181 oidclr(&ref->new_oid, the_repository->hash_algo);
1182 return ref;
1185 static int try_explicit_object_name(const char *name,
1186 struct ref **match)
1188 struct object_id oid;
1190 if (!*name) {
1191 if (match)
1192 *match = alloc_delete_ref();
1193 return 0;
1196 if (repo_get_oid(the_repository, name, &oid))
1197 return -1;
1199 if (match) {
1200 *match = alloc_ref(name);
1201 oidcpy(&(*match)->new_oid, &oid);
1203 return 0;
1206 static struct ref *make_linked_ref(const char *name, struct ref ***tail)
1208 struct ref *ret = alloc_ref(name);
1209 tail_link_ref(ret, tail);
1210 return ret;
1213 static char *guess_ref(const char *name, struct ref *peer)
1215 struct strbuf buf = STRBUF_INIT;
1217 const char *r = refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
1218 peer->name,
1219 RESOLVE_REF_READING,
1220 NULL, NULL);
1221 if (!r)
1222 return NULL;
1224 if (starts_with(r, "refs/heads/")) {
1225 strbuf_addstr(&buf, "refs/heads/");
1226 } else if (starts_with(r, "refs/tags/")) {
1227 strbuf_addstr(&buf, "refs/tags/");
1228 } else {
1229 return NULL;
1232 strbuf_addstr(&buf, name);
1233 return strbuf_detach(&buf, NULL);
1236 static int match_explicit_lhs(struct ref *src,
1237 struct refspec_item *rs,
1238 struct ref **match,
1239 int *allocated_match)
1241 switch (count_refspec_match(rs->src, src, match)) {
1242 case 1:
1243 if (allocated_match)
1244 *allocated_match = 0;
1245 return 0;
1246 case 0:
1247 /* The source could be in the get_sha1() format
1248 * not a reference name. :refs/other is a
1249 * way to delete 'other' ref at the remote end.
1251 if (try_explicit_object_name(rs->src, match) < 0)
1252 return error(_("src refspec %s does not match any"), rs->src);
1253 if (allocated_match)
1254 *allocated_match = 1;
1255 return 0;
1256 default:
1257 return error(_("src refspec %s matches more than one"), rs->src);
1261 static void show_push_unqualified_ref_name_error(const char *dst_value,
1262 const char *matched_src_name)
1264 struct object_id oid;
1265 enum object_type type;
1268 * TRANSLATORS: "matches '%s'%" is the <dst> part of "git push
1269 * <remote> <src>:<dst>" push, and "being pushed ('%s')" is
1270 * the <src>.
1272 error(_("The destination you provided is not a full refname (i.e.,\n"
1273 "starting with \"refs/\"). We tried to guess what you meant by:\n"
1274 "\n"
1275 "- Looking for a ref that matches '%s' on the remote side.\n"
1276 "- Checking if the <src> being pushed ('%s')\n"
1277 " is a ref in \"refs/{heads,tags}/\". If so we add a corresponding\n"
1278 " refs/{heads,tags}/ prefix on the remote side.\n"
1279 "\n"
1280 "Neither worked, so we gave up. You must fully qualify the ref."),
1281 dst_value, matched_src_name);
1283 if (!advice_enabled(ADVICE_PUSH_UNQUALIFIED_REF_NAME))
1284 return;
1286 if (repo_get_oid(the_repository, matched_src_name, &oid))
1287 BUG("'%s' is not a valid object, "
1288 "match_explicit_lhs() should catch this!",
1289 matched_src_name);
1290 type = oid_object_info(the_repository, &oid, NULL);
1291 if (type == OBJ_COMMIT) {
1292 advise(_("The <src> part of the refspec is a commit object.\n"
1293 "Did you mean to create a new branch by pushing to\n"
1294 "'%s:refs/heads/%s'?"),
1295 matched_src_name, dst_value);
1296 } else if (type == OBJ_TAG) {
1297 advise(_("The <src> part of the refspec is a tag object.\n"
1298 "Did you mean to create a new tag by pushing to\n"
1299 "'%s:refs/tags/%s'?"),
1300 matched_src_name, dst_value);
1301 } else if (type == OBJ_TREE) {
1302 advise(_("The <src> part of the refspec is a tree object.\n"
1303 "Did you mean to tag a new tree by pushing to\n"
1304 "'%s:refs/tags/%s'?"),
1305 matched_src_name, dst_value);
1306 } else if (type == OBJ_BLOB) {
1307 advise(_("The <src> part of the refspec is a blob object.\n"
1308 "Did you mean to tag a new blob by pushing to\n"
1309 "'%s:refs/tags/%s'?"),
1310 matched_src_name, dst_value);
1311 } else {
1312 BUG("'%s' should be commit/tag/tree/blob, is '%d'",
1313 matched_src_name, type);
1317 static int match_explicit(struct ref *src, struct ref *dst,
1318 struct ref ***dst_tail,
1319 struct refspec_item *rs)
1321 struct ref *matched_src, *matched_dst;
1322 int allocated_src;
1324 const char *dst_value = rs->dst;
1325 char *dst_guess;
1327 if (rs->pattern || rs->matching || rs->negative)
1328 return 0;
1330 matched_src = matched_dst = NULL;
1331 if (match_explicit_lhs(src, rs, &matched_src, &allocated_src) < 0)
1332 return -1;
1334 if (!dst_value) {
1335 int flag;
1337 dst_value = refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
1338 matched_src->name,
1339 RESOLVE_REF_READING,
1340 NULL, &flag);
1341 if (!dst_value ||
1342 ((flag & REF_ISSYMREF) &&
1343 !starts_with(dst_value, "refs/heads/")))
1344 die(_("%s cannot be resolved to branch"),
1345 matched_src->name);
1348 switch (count_refspec_match(dst_value, dst, &matched_dst)) {
1349 case 1:
1350 break;
1351 case 0:
1352 if (starts_with(dst_value, "refs/")) {
1353 matched_dst = make_linked_ref(dst_value, dst_tail);
1354 } else if (is_null_oid(&matched_src->new_oid)) {
1355 error(_("unable to delete '%s': remote ref does not exist"),
1356 dst_value);
1357 } else if ((dst_guess = guess_ref(dst_value, matched_src))) {
1358 matched_dst = make_linked_ref(dst_guess, dst_tail);
1359 free(dst_guess);
1360 } else {
1361 show_push_unqualified_ref_name_error(dst_value,
1362 matched_src->name);
1364 break;
1365 default:
1366 matched_dst = NULL;
1367 error(_("dst refspec %s matches more than one"),
1368 dst_value);
1369 break;
1371 if (!matched_dst)
1372 return -1;
1373 if (matched_dst->peer_ref)
1374 return error(_("dst ref %s receives from more than one src"),
1375 matched_dst->name);
1376 else {
1377 matched_dst->peer_ref = allocated_src ?
1378 matched_src :
1379 copy_ref(matched_src);
1380 matched_dst->force = rs->force;
1382 return 0;
1385 static int match_explicit_refs(struct ref *src, struct ref *dst,
1386 struct ref ***dst_tail, struct refspec *rs)
1388 int i, errs;
1389 for (i = errs = 0; i < rs->nr; i++)
1390 errs += match_explicit(src, dst, dst_tail, &rs->items[i]);
1391 return errs;
1394 static char *get_ref_match(const struct refspec *rs, const struct ref *ref,
1395 int send_mirror, int direction,
1396 const struct refspec_item **ret_pat)
1398 const struct refspec_item *pat;
1399 char *name;
1400 int i;
1401 int matching_refs = -1;
1402 for (i = 0; i < rs->nr; i++) {
1403 const struct refspec_item *item = &rs->items[i];
1405 if (item->negative)
1406 continue;
1408 if (item->matching &&
1409 (matching_refs == -1 || item->force)) {
1410 matching_refs = i;
1411 continue;
1414 if (item->pattern) {
1415 const char *dst_side = item->dst ? item->dst : item->src;
1416 int match;
1417 if (direction == FROM_SRC)
1418 match = match_name_with_pattern(item->src, ref->name, dst_side, &name);
1419 else
1420 match = match_name_with_pattern(dst_side, ref->name, item->src, &name);
1421 if (match) {
1422 matching_refs = i;
1423 break;
1427 if (matching_refs == -1)
1428 return NULL;
1430 pat = &rs->items[matching_refs];
1431 if (pat->matching) {
1433 * "matching refs"; traditionally we pushed everything
1434 * including refs outside refs/heads/ hierarchy, but
1435 * that does not make much sense these days.
1437 if (!send_mirror && !starts_with(ref->name, "refs/heads/"))
1438 return NULL;
1439 name = xstrdup(ref->name);
1441 if (ret_pat)
1442 *ret_pat = pat;
1443 return name;
1446 static struct ref **tail_ref(struct ref **head)
1448 struct ref **tail = head;
1449 while (*tail)
1450 tail = &((*tail)->next);
1451 return tail;
1454 struct tips {
1455 struct commit **tip;
1456 int nr, alloc;
1459 static void add_to_tips(struct tips *tips, const struct object_id *oid)
1461 struct commit *commit;
1463 if (is_null_oid(oid))
1464 return;
1465 commit = lookup_commit_reference_gently(the_repository, oid, 1);
1466 if (!commit || (commit->object.flags & TMP_MARK))
1467 return;
1468 commit->object.flags |= TMP_MARK;
1469 ALLOC_GROW(tips->tip, tips->nr + 1, tips->alloc);
1470 tips->tip[tips->nr++] = commit;
1473 static void add_missing_tags(struct ref *src, struct ref **dst, struct ref ***dst_tail)
1475 struct string_list dst_tag = STRING_LIST_INIT_NODUP;
1476 struct string_list src_tag = STRING_LIST_INIT_NODUP;
1477 struct string_list_item *item;
1478 struct ref *ref;
1479 struct tips sent_tips;
1482 * Collect everything we know they would have at the end of
1483 * this push, and collect all tags they have.
1485 memset(&sent_tips, 0, sizeof(sent_tips));
1486 for (ref = *dst; ref; ref = ref->next) {
1487 if (ref->peer_ref &&
1488 !is_null_oid(&ref->peer_ref->new_oid))
1489 add_to_tips(&sent_tips, &ref->peer_ref->new_oid);
1490 else
1491 add_to_tips(&sent_tips, &ref->old_oid);
1492 if (starts_with(ref->name, "refs/tags/"))
1493 string_list_append(&dst_tag, ref->name);
1495 clear_commit_marks_many(sent_tips.nr, sent_tips.tip, TMP_MARK);
1497 string_list_sort(&dst_tag);
1499 /* Collect tags they do not have. */
1500 for (ref = src; ref; ref = ref->next) {
1501 if (!starts_with(ref->name, "refs/tags/"))
1502 continue; /* not a tag */
1503 if (string_list_has_string(&dst_tag, ref->name))
1504 continue; /* they already have it */
1505 if (oid_object_info(the_repository, &ref->new_oid, NULL) != OBJ_TAG)
1506 continue; /* be conservative */
1507 item = string_list_append(&src_tag, ref->name);
1508 item->util = ref;
1510 string_list_clear(&dst_tag, 0);
1513 * At this point, src_tag lists tags that are missing from
1514 * dst, and sent_tips lists the tips we are pushing or those
1515 * that we know they already have. An element in the src_tag
1516 * that is an ancestor of any of the sent_tips needs to be
1517 * sent to the other side.
1519 if (sent_tips.nr) {
1520 const int reachable_flag = 1;
1521 struct commit_list *found_commits;
1522 struct commit **src_commits;
1523 int nr_src_commits = 0, alloc_src_commits = 16;
1524 ALLOC_ARRAY(src_commits, alloc_src_commits);
1526 for_each_string_list_item(item, &src_tag) {
1527 struct ref *ref = item->util;
1528 struct commit *commit;
1530 if (is_null_oid(&ref->new_oid))
1531 continue;
1532 commit = lookup_commit_reference_gently(the_repository,
1533 &ref->new_oid,
1535 if (!commit)
1536 /* not pushing a commit, which is not an error */
1537 continue;
1539 ALLOC_GROW(src_commits, nr_src_commits + 1, alloc_src_commits);
1540 src_commits[nr_src_commits++] = commit;
1543 found_commits = get_reachable_subset(sent_tips.tip, sent_tips.nr,
1544 src_commits, nr_src_commits,
1545 reachable_flag);
1547 for_each_string_list_item(item, &src_tag) {
1548 struct ref *dst_ref;
1549 struct ref *ref = item->util;
1550 struct commit *commit;
1552 if (is_null_oid(&ref->new_oid))
1553 continue;
1554 commit = lookup_commit_reference_gently(the_repository,
1555 &ref->new_oid,
1557 if (!commit)
1558 /* not pushing a commit, which is not an error */
1559 continue;
1562 * Is this tag, which they do not have, reachable from
1563 * any of the commits we are sending?
1565 if (!(commit->object.flags & reachable_flag))
1566 continue;
1568 /* Add it in */
1569 dst_ref = make_linked_ref(ref->name, dst_tail);
1570 oidcpy(&dst_ref->new_oid, &ref->new_oid);
1571 dst_ref->peer_ref = copy_ref(ref);
1574 clear_commit_marks_many(nr_src_commits, src_commits, reachable_flag);
1575 free(src_commits);
1576 free_commit_list(found_commits);
1579 string_list_clear(&src_tag, 0);
1580 free(sent_tips.tip);
1583 struct ref *find_ref_by_name(const struct ref *list, const char *name)
1585 for ( ; list; list = list->next)
1586 if (!strcmp(list->name, name))
1587 return (struct ref *)list;
1588 return NULL;
1591 static void prepare_ref_index(struct string_list *ref_index, struct ref *ref)
1593 for ( ; ref; ref = ref->next)
1594 string_list_append_nodup(ref_index, ref->name)->util = ref;
1596 string_list_sort(ref_index);
1600 * Given only the set of local refs, sanity-check the set of push
1601 * refspecs. We can't catch all errors that match_push_refs would,
1602 * but we can catch some errors early before even talking to the
1603 * remote side.
1605 int check_push_refs(struct ref *src, struct refspec *rs)
1607 int ret = 0;
1608 int i;
1610 for (i = 0; i < rs->nr; i++) {
1611 struct refspec_item *item = &rs->items[i];
1613 if (item->pattern || item->matching || item->negative)
1614 continue;
1616 ret |= match_explicit_lhs(src, item, NULL, NULL);
1619 return ret;
1623 * Given the set of refs the local repository has, the set of refs the
1624 * remote repository has, and the refspec used for push, determine
1625 * what remote refs we will update and with what value by setting
1626 * peer_ref (which object is being pushed) and force (if the push is
1627 * forced) in elements of "dst". The function may add new elements to
1628 * dst (e.g. pushing to a new branch, done in match_explicit_refs).
1630 int match_push_refs(struct ref *src, struct ref **dst,
1631 struct refspec *rs, int flags)
1633 int send_all = flags & MATCH_REFS_ALL;
1634 int send_mirror = flags & MATCH_REFS_MIRROR;
1635 int send_prune = flags & MATCH_REFS_PRUNE;
1636 int errs;
1637 struct ref *ref, **dst_tail = tail_ref(dst);
1638 struct string_list dst_ref_index = STRING_LIST_INIT_NODUP;
1640 /* If no refspec is provided, use the default ":" */
1641 if (!rs->nr)
1642 refspec_append(rs, ":");
1644 errs = match_explicit_refs(src, *dst, &dst_tail, rs);
1646 /* pick the remainder */
1647 for (ref = src; ref; ref = ref->next) {
1648 struct string_list_item *dst_item;
1649 struct ref *dst_peer;
1650 const struct refspec_item *pat = NULL;
1651 char *dst_name;
1653 dst_name = get_ref_match(rs, ref, send_mirror, FROM_SRC, &pat);
1654 if (!dst_name)
1655 continue;
1657 if (!dst_ref_index.nr)
1658 prepare_ref_index(&dst_ref_index, *dst);
1660 dst_item = string_list_lookup(&dst_ref_index, dst_name);
1661 dst_peer = dst_item ? dst_item->util : NULL;
1662 if (dst_peer) {
1663 if (dst_peer->peer_ref)
1664 /* We're already sending something to this ref. */
1665 goto free_name;
1666 } else {
1667 if (pat->matching && !(send_all || send_mirror))
1669 * Remote doesn't have it, and we have no
1670 * explicit pattern, and we don't have
1671 * --all or --mirror.
1673 goto free_name;
1675 /* Create a new one and link it */
1676 dst_peer = make_linked_ref(dst_name, &dst_tail);
1677 oidcpy(&dst_peer->new_oid, &ref->new_oid);
1678 string_list_insert(&dst_ref_index,
1679 dst_peer->name)->util = dst_peer;
1681 dst_peer->peer_ref = copy_ref(ref);
1682 dst_peer->force = pat->force;
1683 free_name:
1684 free(dst_name);
1687 string_list_clear(&dst_ref_index, 0);
1689 if (flags & MATCH_REFS_FOLLOW_TAGS)
1690 add_missing_tags(src, dst, &dst_tail);
1692 if (send_prune) {
1693 struct string_list src_ref_index = STRING_LIST_INIT_NODUP;
1694 /* check for missing refs on the remote */
1695 for (ref = *dst; ref; ref = ref->next) {
1696 char *src_name;
1698 if (ref->peer_ref)
1699 /* We're already sending something to this ref. */
1700 continue;
1702 src_name = get_ref_match(rs, ref, send_mirror, FROM_DST, NULL);
1703 if (src_name) {
1704 if (!src_ref_index.nr)
1705 prepare_ref_index(&src_ref_index, src);
1706 if (!string_list_has_string(&src_ref_index,
1707 src_name))
1708 ref->peer_ref = alloc_delete_ref();
1709 free(src_name);
1712 string_list_clear(&src_ref_index, 0);
1715 *dst = apply_negative_refspecs(*dst, rs);
1717 if (errs)
1718 return -1;
1719 return 0;
1722 void set_ref_status_for_push(struct ref *remote_refs, int send_mirror,
1723 int force_update)
1725 struct ref *ref;
1727 for (ref = remote_refs; ref; ref = ref->next) {
1728 int force_ref_update = ref->force || force_update;
1729 int reject_reason = 0;
1731 if (ref->peer_ref)
1732 oidcpy(&ref->new_oid, &ref->peer_ref->new_oid);
1733 else if (!send_mirror)
1734 continue;
1736 ref->deletion = is_null_oid(&ref->new_oid);
1737 if (!ref->deletion &&
1738 oideq(&ref->old_oid, &ref->new_oid)) {
1739 ref->status = REF_STATUS_UPTODATE;
1740 continue;
1744 * If the remote ref has moved and is now different
1745 * from what we expect, reject any push.
1747 * It also is an error if the user told us to check
1748 * with the remote-tracking branch to find the value
1749 * to expect, but we did not have such a tracking
1750 * branch.
1752 * If the tip of the remote-tracking ref is unreachable
1753 * from any reflog entry of its local ref indicating a
1754 * possible update since checkout; reject the push.
1756 if (ref->expect_old_sha1) {
1757 if (!oideq(&ref->old_oid, &ref->old_oid_expect))
1758 reject_reason = REF_STATUS_REJECT_STALE;
1759 else if (ref->check_reachable && ref->unreachable)
1760 reject_reason =
1761 REF_STATUS_REJECT_REMOTE_UPDATED;
1762 else
1764 * If the ref isn't stale, and is reachable
1765 * from one of the reflog entries of
1766 * the local branch, force the update.
1768 force_ref_update = 1;
1772 * If the update isn't already rejected then check
1773 * the usual "must fast-forward" rules.
1775 * Decide whether an individual refspec A:B can be
1776 * pushed. The push will succeed if any of the
1777 * following are true:
1779 * (1) the remote reference B does not exist
1781 * (2) the remote reference B is being removed (i.e.,
1782 * pushing :B where no source is specified)
1784 * (3) the destination is not under refs/tags/, and
1785 * if the old and new value is a commit, the new
1786 * is a descendant of the old.
1788 * (4) it is forced using the +A:B notation, or by
1789 * passing the --force argument
1792 if (!reject_reason && !ref->deletion && !is_null_oid(&ref->old_oid)) {
1793 if (starts_with(ref->name, "refs/tags/"))
1794 reject_reason = REF_STATUS_REJECT_ALREADY_EXISTS;
1795 else if (!repo_has_object_file_with_flags(the_repository, &ref->old_oid, OBJECT_INFO_SKIP_FETCH_OBJECT))
1796 reject_reason = REF_STATUS_REJECT_FETCH_FIRST;
1797 else if (!lookup_commit_reference_gently(the_repository, &ref->old_oid, 1) ||
1798 !lookup_commit_reference_gently(the_repository, &ref->new_oid, 1))
1799 reject_reason = REF_STATUS_REJECT_NEEDS_FORCE;
1800 else if (!ref_newer(&ref->new_oid, &ref->old_oid))
1801 reject_reason = REF_STATUS_REJECT_NONFASTFORWARD;
1805 * "--force" will defeat any rejection implemented
1806 * by the rules above.
1808 if (!force_ref_update)
1809 ref->status = reject_reason;
1810 else if (reject_reason)
1811 ref->forced_update = 1;
1815 static void set_merge(struct remote_state *remote_state, struct branch *ret)
1817 struct remote *remote;
1818 char *ref;
1819 struct object_id oid;
1820 int i;
1822 if (!ret)
1823 return; /* no branch */
1824 if (ret->merge)
1825 return; /* already run */
1826 if (!ret->remote_name || !ret->merge_nr) {
1828 * no merge config; let's make sure we don't confuse callers
1829 * with a non-zero merge_nr but a NULL merge
1831 ret->merge_nr = 0;
1832 return;
1835 remote = remotes_remote_get(remote_state, ret->remote_name);
1837 CALLOC_ARRAY(ret->merge, ret->merge_nr);
1838 for (i = 0; i < ret->merge_nr; i++) {
1839 ret->merge[i] = xcalloc(1, sizeof(**ret->merge));
1840 ret->merge[i]->src = xstrdup(ret->merge_name[i]);
1841 if (!remote_find_tracking(remote, ret->merge[i]) ||
1842 strcmp(ret->remote_name, "."))
1843 continue;
1844 if (repo_dwim_ref(the_repository, ret->merge_name[i],
1845 strlen(ret->merge_name[i]), &oid, &ref,
1846 0) == 1)
1847 ret->merge[i]->dst = ref;
1848 else
1849 ret->merge[i]->dst = xstrdup(ret->merge_name[i]);
1853 struct branch *branch_get(const char *name)
1855 struct branch *ret;
1857 read_config(the_repository, 0);
1858 if (!name || !*name || !strcmp(name, "HEAD"))
1859 ret = the_repository->remote_state->current_branch;
1860 else
1861 ret = make_branch(the_repository->remote_state, name,
1862 strlen(name));
1863 set_merge(the_repository->remote_state, ret);
1864 return ret;
1867 int branch_has_merge_config(struct branch *branch)
1869 return branch && !!branch->merge;
1872 int branch_merge_matches(struct branch *branch,
1873 int i,
1874 const char *refname)
1876 if (!branch || i < 0 || i >= branch->merge_nr)
1877 return 0;
1878 return refname_match(branch->merge[i]->src, refname);
1881 __attribute__((format (printf,2,3)))
1882 static const char *error_buf(struct strbuf *err, const char *fmt, ...)
1884 if (err) {
1885 va_list ap;
1886 va_start(ap, fmt);
1887 strbuf_vaddf(err, fmt, ap);
1888 va_end(ap);
1890 return NULL;
1893 const char *branch_get_upstream(struct branch *branch, struct strbuf *err)
1895 if (!branch)
1896 return error_buf(err, _("HEAD does not point to a branch"));
1898 if (!branch->merge || !branch->merge[0]) {
1900 * no merge config; is it because the user didn't define any,
1901 * or because it is not a real branch, and get_branch
1902 * auto-vivified it?
1904 if (!refs_ref_exists(get_main_ref_store(the_repository), branch->refname))
1905 return error_buf(err, _("no such branch: '%s'"),
1906 branch->name);
1907 return error_buf(err,
1908 _("no upstream configured for branch '%s'"),
1909 branch->name);
1912 if (!branch->merge[0]->dst)
1913 return error_buf(err,
1914 _("upstream branch '%s' not stored as a remote-tracking branch"),
1915 branch->merge[0]->src);
1917 return branch->merge[0]->dst;
1920 static const char *tracking_for_push_dest(struct remote *remote,
1921 const char *refname,
1922 struct strbuf *err)
1924 char *ret;
1926 ret = apply_refspecs(&remote->fetch, refname);
1927 if (!ret)
1928 return error_buf(err,
1929 _("push destination '%s' on remote '%s' has no local tracking branch"),
1930 refname, remote->name);
1931 return ret;
1934 static const char *branch_get_push_1(struct remote_state *remote_state,
1935 struct branch *branch, struct strbuf *err)
1937 struct remote *remote;
1939 remote = remotes_remote_get(
1940 remote_state,
1941 remotes_pushremote_for_branch(remote_state, branch, NULL));
1942 if (!remote)
1943 return error_buf(err,
1944 _("branch '%s' has no remote for pushing"),
1945 branch->name);
1947 if (remote->push.nr) {
1948 char *dst;
1949 const char *ret;
1951 dst = apply_refspecs(&remote->push, branch->refname);
1952 if (!dst)
1953 return error_buf(err,
1954 _("push refspecs for '%s' do not include '%s'"),
1955 remote->name, branch->name);
1957 ret = tracking_for_push_dest(remote, dst, err);
1958 free(dst);
1959 return ret;
1962 if (remote->mirror)
1963 return tracking_for_push_dest(remote, branch->refname, err);
1965 switch (push_default) {
1966 case PUSH_DEFAULT_NOTHING:
1967 return error_buf(err, _("push has no destination (push.default is 'nothing')"));
1969 case PUSH_DEFAULT_MATCHING:
1970 case PUSH_DEFAULT_CURRENT:
1971 return tracking_for_push_dest(remote, branch->refname, err);
1973 case PUSH_DEFAULT_UPSTREAM:
1974 return branch_get_upstream(branch, err);
1976 case PUSH_DEFAULT_UNSPECIFIED:
1977 case PUSH_DEFAULT_SIMPLE:
1979 const char *up, *cur;
1981 up = branch_get_upstream(branch, err);
1982 if (!up)
1983 return NULL;
1984 cur = tracking_for_push_dest(remote, branch->refname, err);
1985 if (!cur)
1986 return NULL;
1987 if (strcmp(cur, up))
1988 return error_buf(err,
1989 _("cannot resolve 'simple' push to a single destination"));
1990 return cur;
1994 BUG("unhandled push situation");
1997 const char *branch_get_push(struct branch *branch, struct strbuf *err)
1999 read_config(the_repository, 0);
2000 die_on_missing_branch(the_repository, branch);
2002 if (!branch)
2003 return error_buf(err, _("HEAD does not point to a branch"));
2005 if (!branch->push_tracking_ref)
2006 branch->push_tracking_ref = branch_get_push_1(
2007 the_repository->remote_state, branch, err);
2008 return branch->push_tracking_ref;
2011 static int ignore_symref_update(const char *refname, struct strbuf *scratch)
2013 return !refs_read_symbolic_ref(get_main_ref_store(the_repository), refname, scratch);
2017 * Create and return a list of (struct ref) consisting of copies of
2018 * each remote_ref that matches refspec. refspec must be a pattern.
2019 * Fill in the copies' peer_ref to describe the local tracking refs to
2020 * which they map. Omit any references that would map to an existing
2021 * local symbolic ref.
2023 static struct ref *get_expanded_map(const struct ref *remote_refs,
2024 const struct refspec_item *refspec)
2026 struct strbuf scratch = STRBUF_INIT;
2027 const struct ref *ref;
2028 struct ref *ret = NULL;
2029 struct ref **tail = &ret;
2031 for (ref = remote_refs; ref; ref = ref->next) {
2032 char *expn_name = NULL;
2034 strbuf_reset(&scratch);
2036 if (strchr(ref->name, '^'))
2037 continue; /* a dereference item */
2038 if (match_name_with_pattern(refspec->src, ref->name,
2039 refspec->dst, &expn_name) &&
2040 !ignore_symref_update(expn_name, &scratch)) {
2041 struct ref *cpy = copy_ref(ref);
2043 cpy->peer_ref = alloc_ref(expn_name);
2044 if (refspec->force)
2045 cpy->peer_ref->force = 1;
2046 *tail = cpy;
2047 tail = &cpy->next;
2049 free(expn_name);
2052 strbuf_release(&scratch);
2053 return ret;
2056 static const struct ref *find_ref_by_name_abbrev(const struct ref *refs, const char *name)
2058 const struct ref *ref;
2059 const struct ref *best_match = NULL;
2060 int best_score = 0;
2062 for (ref = refs; ref; ref = ref->next) {
2063 int score = refname_match(name, ref->name);
2065 if (best_score < score) {
2066 best_match = ref;
2067 best_score = score;
2070 return best_match;
2073 struct ref *get_remote_ref(const struct ref *remote_refs, const char *name)
2075 const struct ref *ref = find_ref_by_name_abbrev(remote_refs, name);
2077 if (!ref)
2078 return NULL;
2080 return copy_ref(ref);
2083 static struct ref *get_local_ref(const char *name)
2085 if (!name || name[0] == '\0')
2086 return NULL;
2088 if (starts_with(name, "refs/"))
2089 return alloc_ref(name);
2091 if (starts_with(name, "heads/") ||
2092 starts_with(name, "tags/") ||
2093 starts_with(name, "remotes/"))
2094 return alloc_ref_with_prefix("refs/", 5, name);
2096 return alloc_ref_with_prefix("refs/heads/", 11, name);
2099 int get_fetch_map(const struct ref *remote_refs,
2100 const struct refspec_item *refspec,
2101 struct ref ***tail,
2102 int missing_ok)
2104 struct ref *ref_map, **rmp;
2106 if (refspec->negative)
2107 return 0;
2109 if (refspec->pattern) {
2110 ref_map = get_expanded_map(remote_refs, refspec);
2111 } else {
2112 const char *name = refspec->src[0] ? refspec->src : "HEAD";
2114 if (refspec->exact_sha1) {
2115 ref_map = alloc_ref(name);
2116 get_oid_hex(name, &ref_map->old_oid);
2117 ref_map->exact_oid = 1;
2118 } else {
2119 ref_map = get_remote_ref(remote_refs, name);
2121 if (!missing_ok && !ref_map)
2122 die(_("couldn't find remote ref %s"), name);
2123 if (ref_map) {
2124 ref_map->peer_ref = get_local_ref(refspec->dst);
2125 if (ref_map->peer_ref && refspec->force)
2126 ref_map->peer_ref->force = 1;
2130 for (rmp = &ref_map; *rmp; ) {
2131 if ((*rmp)->peer_ref) {
2132 if (!starts_with((*rmp)->peer_ref->name, "refs/") ||
2133 check_refname_format((*rmp)->peer_ref->name, 0)) {
2134 struct ref *ignore = *rmp;
2135 error(_("* Ignoring funny ref '%s' locally"),
2136 (*rmp)->peer_ref->name);
2137 *rmp = (*rmp)->next;
2138 free(ignore->peer_ref);
2139 free(ignore);
2140 continue;
2143 rmp = &((*rmp)->next);
2146 if (ref_map)
2147 tail_link_ref(ref_map, tail);
2149 return 0;
2152 int resolve_remote_symref(struct ref *ref, struct ref *list)
2154 if (!ref->symref)
2155 return 0;
2156 for (; list; list = list->next)
2157 if (!strcmp(ref->symref, list->name)) {
2158 oidcpy(&ref->old_oid, &list->old_oid);
2159 return 0;
2161 return 1;
2165 * Compute the commit ahead/behind values for the pair branch_name, base.
2167 * If abf is AHEAD_BEHIND_FULL, compute the full ahead/behind and return the
2168 * counts in *num_ours and *num_theirs. If abf is AHEAD_BEHIND_QUICK, skip
2169 * the (potentially expensive) a/b computation (*num_ours and *num_theirs are
2170 * set to zero).
2172 * Returns -1 if num_ours and num_theirs could not be filled in (e.g., ref
2173 * does not exist). Returns 0 if the commits are identical. Returns 1 if
2174 * commits are different.
2177 static int stat_branch_pair(const char *branch_name, const char *base,
2178 int *num_ours, int *num_theirs,
2179 enum ahead_behind_flags abf)
2181 struct object_id oid;
2182 struct commit *ours, *theirs;
2183 struct rev_info revs;
2184 struct setup_revision_opt opt = {
2185 .free_removed_argv_elements = 1,
2187 struct strvec argv = STRVEC_INIT;
2189 /* Cannot stat if what we used to build on no longer exists */
2190 if (refs_read_ref(get_main_ref_store(the_repository), base, &oid))
2191 return -1;
2192 theirs = lookup_commit_reference(the_repository, &oid);
2193 if (!theirs)
2194 return -1;
2196 if (refs_read_ref(get_main_ref_store(the_repository), branch_name, &oid))
2197 return -1;
2198 ours = lookup_commit_reference(the_repository, &oid);
2199 if (!ours)
2200 return -1;
2202 *num_theirs = *num_ours = 0;
2204 /* are we the same? */
2205 if (theirs == ours)
2206 return 0;
2207 if (abf == AHEAD_BEHIND_QUICK)
2208 return 1;
2209 if (abf != AHEAD_BEHIND_FULL)
2210 BUG("stat_branch_pair: invalid abf '%d'", abf);
2212 /* Run "rev-list --left-right ours...theirs" internally... */
2213 strvec_push(&argv, ""); /* ignored */
2214 strvec_push(&argv, "--left-right");
2215 strvec_pushf(&argv, "%s...%s",
2216 oid_to_hex(&ours->object.oid),
2217 oid_to_hex(&theirs->object.oid));
2218 strvec_push(&argv, "--");
2220 repo_init_revisions(the_repository, &revs, NULL);
2221 setup_revisions(argv.nr, argv.v, &revs, &opt);
2222 if (prepare_revision_walk(&revs))
2223 die(_("revision walk setup failed"));
2225 /* ... and count the commits on each side. */
2226 while (1) {
2227 struct commit *c = get_revision(&revs);
2228 if (!c)
2229 break;
2230 if (c->object.flags & SYMMETRIC_LEFT)
2231 (*num_ours)++;
2232 else
2233 (*num_theirs)++;
2236 /* clear object flags smudged by the above traversal */
2237 clear_commit_marks(ours, ALL_REV_FLAGS);
2238 clear_commit_marks(theirs, ALL_REV_FLAGS);
2240 strvec_clear(&argv);
2241 release_revisions(&revs);
2242 return 1;
2246 * Lookup the tracking branch for the given branch and if present, optionally
2247 * compute the commit ahead/behind values for the pair.
2249 * If for_push is true, the tracking branch refers to the push branch,
2250 * otherwise it refers to the upstream branch.
2252 * The name of the tracking branch (or NULL if it is not defined) is
2253 * returned via *tracking_name, if it is not itself NULL.
2255 * If abf is AHEAD_BEHIND_FULL, compute the full ahead/behind and return the
2256 * counts in *num_ours and *num_theirs. If abf is AHEAD_BEHIND_QUICK, skip
2257 * the (potentially expensive) a/b computation (*num_ours and *num_theirs are
2258 * set to zero).
2260 * Returns -1 if num_ours and num_theirs could not be filled in (e.g., no
2261 * upstream defined, or ref does not exist). Returns 0 if the commits are
2262 * identical. Returns 1 if commits are different.
2264 int stat_tracking_info(struct branch *branch, int *num_ours, int *num_theirs,
2265 const char **tracking_name, int for_push,
2266 enum ahead_behind_flags abf)
2268 const char *base;
2270 /* Cannot stat unless we are marked to build on top of somebody else. */
2271 base = for_push ? branch_get_push(branch, NULL) :
2272 branch_get_upstream(branch, NULL);
2273 if (tracking_name)
2274 *tracking_name = base;
2275 if (!base)
2276 return -1;
2278 return stat_branch_pair(branch->refname, base, num_ours, num_theirs, abf);
2282 * Return true when there is anything to report, otherwise false.
2284 int format_tracking_info(struct branch *branch, struct strbuf *sb,
2285 enum ahead_behind_flags abf,
2286 int show_divergence_advice)
2288 int ours, theirs, sti;
2289 const char *full_base;
2290 char *base;
2291 int upstream_is_gone = 0;
2293 sti = stat_tracking_info(branch, &ours, &theirs, &full_base, 0, abf);
2294 if (sti < 0) {
2295 if (!full_base)
2296 return 0;
2297 upstream_is_gone = 1;
2300 base = refs_shorten_unambiguous_ref(get_main_ref_store(the_repository),
2301 full_base, 0);
2302 if (upstream_is_gone) {
2303 strbuf_addf(sb,
2304 _("Your branch is based on '%s', but the upstream is gone.\n"),
2305 base);
2306 if (advice_enabled(ADVICE_STATUS_HINTS))
2307 strbuf_addstr(sb,
2308 _(" (use \"git branch --unset-upstream\" to fixup)\n"));
2309 } else if (!sti) {
2310 strbuf_addf(sb,
2311 _("Your branch is up to date with '%s'.\n"),
2312 base);
2313 } else if (abf == AHEAD_BEHIND_QUICK) {
2314 strbuf_addf(sb,
2315 _("Your branch and '%s' refer to different commits.\n"),
2316 base);
2317 if (advice_enabled(ADVICE_STATUS_HINTS))
2318 strbuf_addf(sb, _(" (use \"%s\" for details)\n"),
2319 "git status --ahead-behind");
2320 } else if (!theirs) {
2321 strbuf_addf(sb,
2322 Q_("Your branch is ahead of '%s' by %d commit.\n",
2323 "Your branch is ahead of '%s' by %d commits.\n",
2324 ours),
2325 base, ours);
2326 if (advice_enabled(ADVICE_STATUS_HINTS))
2327 strbuf_addstr(sb,
2328 _(" (use \"git push\" to publish your local commits)\n"));
2329 } else if (!ours) {
2330 strbuf_addf(sb,
2331 Q_("Your branch is behind '%s' by %d commit, "
2332 "and can be fast-forwarded.\n",
2333 "Your branch is behind '%s' by %d commits, "
2334 "and can be fast-forwarded.\n",
2335 theirs),
2336 base, theirs);
2337 if (advice_enabled(ADVICE_STATUS_HINTS))
2338 strbuf_addstr(sb,
2339 _(" (use \"git pull\" to update your local branch)\n"));
2340 } else {
2341 strbuf_addf(sb,
2342 Q_("Your branch and '%s' have diverged,\n"
2343 "and have %d and %d different commit each, "
2344 "respectively.\n",
2345 "Your branch and '%s' have diverged,\n"
2346 "and have %d and %d different commits each, "
2347 "respectively.\n",
2348 ours + theirs),
2349 base, ours, theirs);
2350 if (show_divergence_advice &&
2351 advice_enabled(ADVICE_STATUS_HINTS))
2352 strbuf_addstr(sb,
2353 _(" (use \"git pull\" if you want to integrate the remote branch with yours)\n"));
2355 free(base);
2356 return 1;
2359 static int one_local_ref(const char *refname, const char *referent UNUSED, const struct object_id *oid,
2360 int flag UNUSED,
2361 void *cb_data)
2363 struct ref ***local_tail = cb_data;
2364 struct ref *ref;
2366 /* we already know it starts with refs/ to get here */
2367 if (check_refname_format(refname + 5, 0))
2368 return 0;
2370 ref = alloc_ref(refname);
2371 oidcpy(&ref->new_oid, oid);
2372 **local_tail = ref;
2373 *local_tail = &ref->next;
2374 return 0;
2377 struct ref *get_local_heads(void)
2379 struct ref *local_refs = NULL, **local_tail = &local_refs;
2381 refs_for_each_ref(get_main_ref_store(the_repository), one_local_ref,
2382 &local_tail);
2383 return local_refs;
2386 struct ref *guess_remote_head(const struct ref *head,
2387 const struct ref *refs,
2388 int all)
2390 const struct ref *r;
2391 struct ref *list = NULL;
2392 struct ref **tail = &list;
2394 if (!head)
2395 return NULL;
2398 * Some transports support directly peeking at
2399 * where HEAD points; if that is the case, then
2400 * we don't have to guess.
2402 if (head->symref)
2403 return copy_ref(find_ref_by_name(refs, head->symref));
2405 /* If a remote branch exists with the default branch name, let's use it. */
2406 if (!all) {
2407 char *default_branch = repo_default_branch_name(the_repository, 0);
2408 char *ref = xstrfmt("refs/heads/%s", default_branch);
2410 r = find_ref_by_name(refs, ref);
2411 free(ref);
2412 free(default_branch);
2414 if (r && oideq(&r->old_oid, &head->old_oid))
2415 return copy_ref(r);
2417 /* Fall back to the hard-coded historical default */
2418 r = find_ref_by_name(refs, "refs/heads/master");
2419 if (r && oideq(&r->old_oid, &head->old_oid))
2420 return copy_ref(r);
2423 /* Look for another ref that points there */
2424 for (r = refs; r; r = r->next) {
2425 if (r != head &&
2426 starts_with(r->name, "refs/heads/") &&
2427 oideq(&r->old_oid, &head->old_oid)) {
2428 *tail = copy_ref(r);
2429 tail = &((*tail)->next);
2430 if (!all)
2431 break;
2435 return list;
2438 struct stale_heads_info {
2439 struct string_list *ref_names;
2440 struct ref **stale_refs_tail;
2441 struct refspec *rs;
2444 static int get_stale_heads_cb(const char *refname, const char *referent UNUSED, const struct object_id *oid,
2445 int flags, void *cb_data)
2447 struct stale_heads_info *info = cb_data;
2448 struct string_list matches = STRING_LIST_INIT_DUP;
2449 struct refspec_item query;
2450 int i, stale = 1;
2451 memset(&query, 0, sizeof(struct refspec_item));
2452 query.dst = (char *)refname;
2454 query_refspecs_multiple(info->rs, &query, &matches);
2455 if (matches.nr == 0)
2456 goto clean_exit; /* No matches */
2459 * If we did find a suitable refspec and it's not a symref and
2460 * it's not in the list of refs that currently exist in that
2461 * remote, we consider it to be stale. In order to deal with
2462 * overlapping refspecs, we need to go over all of the
2463 * matching refs.
2465 if (flags & REF_ISSYMREF)
2466 goto clean_exit;
2468 for (i = 0; stale && i < matches.nr; i++)
2469 if (string_list_has_string(info->ref_names, matches.items[i].string))
2470 stale = 0;
2472 if (stale) {
2473 struct ref *ref = make_linked_ref(refname, &info->stale_refs_tail);
2474 oidcpy(&ref->new_oid, oid);
2477 clean_exit:
2478 string_list_clear(&matches, 0);
2479 return 0;
2482 struct ref *get_stale_heads(struct refspec *rs, struct ref *fetch_map)
2484 struct ref *ref, *stale_refs = NULL;
2485 struct string_list ref_names = STRING_LIST_INIT_NODUP;
2486 struct stale_heads_info info;
2488 info.ref_names = &ref_names;
2489 info.stale_refs_tail = &stale_refs;
2490 info.rs = rs;
2491 for (ref = fetch_map; ref; ref = ref->next)
2492 string_list_append(&ref_names, ref->name);
2493 string_list_sort(&ref_names);
2494 refs_for_each_ref(get_main_ref_store(the_repository),
2495 get_stale_heads_cb, &info);
2496 string_list_clear(&ref_names, 0);
2497 return stale_refs;
2501 * Compare-and-swap
2503 static void clear_cas_option(struct push_cas_option *cas)
2505 int i;
2507 for (i = 0; i < cas->nr; i++)
2508 free(cas->entry[i].refname);
2509 free(cas->entry);
2510 memset(cas, 0, sizeof(*cas));
2513 static struct push_cas *add_cas_entry(struct push_cas_option *cas,
2514 const char *refname,
2515 size_t refnamelen)
2517 struct push_cas *entry;
2518 ALLOC_GROW(cas->entry, cas->nr + 1, cas->alloc);
2519 entry = &cas->entry[cas->nr++];
2520 memset(entry, 0, sizeof(*entry));
2521 entry->refname = xmemdupz(refname, refnamelen);
2522 return entry;
2525 static int parse_push_cas_option(struct push_cas_option *cas, const char *arg, int unset)
2527 const char *colon;
2528 struct push_cas *entry;
2530 if (unset) {
2531 /* "--no-<option>" */
2532 clear_cas_option(cas);
2533 return 0;
2536 if (!arg) {
2537 /* just "--<option>" */
2538 cas->use_tracking_for_rest = 1;
2539 return 0;
2542 /* "--<option>=refname" or "--<option>=refname:value" */
2543 colon = strchrnul(arg, ':');
2544 entry = add_cas_entry(cas, arg, colon - arg);
2545 if (!*colon)
2546 entry->use_tracking = 1;
2547 else if (!colon[1])
2548 oidclr(&entry->expect, the_repository->hash_algo);
2549 else if (repo_get_oid(the_repository, colon + 1, &entry->expect))
2550 return error(_("cannot parse expected object name '%s'"),
2551 colon + 1);
2552 return 0;
2555 int parseopt_push_cas_option(const struct option *opt, const char *arg, int unset)
2557 return parse_push_cas_option(opt->value, arg, unset);
2560 int is_empty_cas(const struct push_cas_option *cas)
2562 return !cas->use_tracking_for_rest && !cas->nr;
2566 * Look at remote.fetch refspec and see if we have a remote
2567 * tracking branch for the refname there. Fill the name of
2568 * the remote-tracking branch in *dst_refname, and the name
2569 * of the commit object at its tip in oid[].
2570 * If we cannot do so, return negative to signal an error.
2572 static int remote_tracking(struct remote *remote, const char *refname,
2573 struct object_id *oid, char **dst_refname)
2575 char *dst;
2577 dst = apply_refspecs(&remote->fetch, refname);
2578 if (!dst)
2579 return -1; /* no tracking ref for refname at remote */
2580 if (refs_read_ref(get_main_ref_store(the_repository), dst, oid))
2581 return -1; /* we know what the tracking ref is but we cannot read it */
2583 *dst_refname = dst;
2584 return 0;
2588 * The struct "reflog_commit_array" and related helper functions
2589 * are used for collecting commits into an array during reflog
2590 * traversals in "check_and_collect_until()".
2592 struct reflog_commit_array {
2593 struct commit **item;
2594 size_t nr, alloc;
2597 #define REFLOG_COMMIT_ARRAY_INIT { 0 }
2599 /* Append a commit to the array. */
2600 static void append_commit(struct reflog_commit_array *arr,
2601 struct commit *commit)
2603 ALLOC_GROW(arr->item, arr->nr + 1, arr->alloc);
2604 arr->item[arr->nr++] = commit;
2607 /* Free and reset the array. */
2608 static void free_commit_array(struct reflog_commit_array *arr)
2610 FREE_AND_NULL(arr->item);
2611 arr->nr = arr->alloc = 0;
2614 struct check_and_collect_until_cb_data {
2615 struct commit *remote_commit;
2616 struct reflog_commit_array *local_commits;
2617 timestamp_t remote_reflog_timestamp;
2620 /* Get the timestamp of the latest entry. */
2621 static int peek_reflog(struct object_id *o_oid UNUSED,
2622 struct object_id *n_oid UNUSED,
2623 const char *ident UNUSED,
2624 timestamp_t timestamp, int tz UNUSED,
2625 const char *message UNUSED, void *cb_data)
2627 timestamp_t *ts = cb_data;
2628 *ts = timestamp;
2629 return 1;
2632 static int check_and_collect_until(struct object_id *o_oid UNUSED,
2633 struct object_id *n_oid,
2634 const char *ident UNUSED,
2635 timestamp_t timestamp, int tz UNUSED,
2636 const char *message UNUSED, void *cb_data)
2638 struct commit *commit;
2639 struct check_and_collect_until_cb_data *cb = cb_data;
2641 /* An entry was found. */
2642 if (oideq(n_oid, &cb->remote_commit->object.oid))
2643 return 1;
2645 if ((commit = lookup_commit_reference(the_repository, n_oid)))
2646 append_commit(cb->local_commits, commit);
2649 * If the reflog entry timestamp is older than the remote ref's
2650 * latest reflog entry, there is no need to check or collect
2651 * entries older than this one.
2653 if (timestamp < cb->remote_reflog_timestamp)
2654 return -1;
2656 return 0;
2659 #define MERGE_BASES_BATCH_SIZE 8
2662 * Iterate through the reflog of the local ref to check if there is an entry
2663 * for the given remote-tracking ref; runs until the timestamp of an entry is
2664 * older than latest timestamp of remote-tracking ref's reflog. Any commits
2665 * are that seen along the way are collected into an array to check if the
2666 * remote-tracking ref is reachable from any of them.
2668 static int is_reachable_in_reflog(const char *local, const struct ref *remote)
2670 timestamp_t date;
2671 struct commit *commit;
2672 struct commit **chunk;
2673 struct check_and_collect_until_cb_data cb;
2674 struct reflog_commit_array arr = REFLOG_COMMIT_ARRAY_INIT;
2675 size_t size = 0;
2676 int ret = 0;
2678 commit = lookup_commit_reference(the_repository, &remote->old_oid);
2679 if (!commit)
2680 goto cleanup_return;
2683 * Get the timestamp from the latest entry
2684 * of the remote-tracking ref's reflog.
2686 refs_for_each_reflog_ent_reverse(get_main_ref_store(the_repository),
2687 remote->tracking_ref, peek_reflog,
2688 &date);
2690 cb.remote_commit = commit;
2691 cb.local_commits = &arr;
2692 cb.remote_reflog_timestamp = date;
2693 ret = refs_for_each_reflog_ent_reverse(get_main_ref_store(the_repository),
2694 local, check_and_collect_until,
2695 &cb);
2697 /* We found an entry in the reflog. */
2698 if (ret > 0)
2699 goto cleanup_return;
2702 * Check if the remote commit is reachable from any
2703 * of the commits in the collected array, in batches.
2705 for (chunk = arr.item; chunk < arr.item + arr.nr; chunk += size) {
2706 size = arr.item + arr.nr - chunk;
2707 if (MERGE_BASES_BATCH_SIZE < size)
2708 size = MERGE_BASES_BATCH_SIZE;
2710 if ((ret = repo_in_merge_bases_many(the_repository, commit, size, chunk, 0)))
2711 break;
2714 cleanup_return:
2715 free_commit_array(&arr);
2716 return ret;
2720 * Check for reachability of a remote-tracking
2721 * ref in the reflog entries of its local ref.
2723 static void check_if_includes_upstream(struct ref *remote)
2725 struct ref *local = get_local_ref(remote->name);
2726 if (!local)
2727 return;
2729 if (is_reachable_in_reflog(local->name, remote) <= 0)
2730 remote->unreachable = 1;
2733 static void apply_cas(struct push_cas_option *cas,
2734 struct remote *remote,
2735 struct ref *ref)
2737 int i;
2739 /* Find an explicit --<option>=<name>[:<value>] entry */
2740 for (i = 0; i < cas->nr; i++) {
2741 struct push_cas *entry = &cas->entry[i];
2742 if (!refname_match(entry->refname, ref->name))
2743 continue;
2744 ref->expect_old_sha1 = 1;
2745 if (!entry->use_tracking)
2746 oidcpy(&ref->old_oid_expect, &entry->expect);
2747 else if (remote_tracking(remote, ref->name,
2748 &ref->old_oid_expect,
2749 &ref->tracking_ref))
2750 oidclr(&ref->old_oid_expect, the_repository->hash_algo);
2751 else
2752 ref->check_reachable = cas->use_force_if_includes;
2753 return;
2756 /* Are we using "--<option>" to cover all? */
2757 if (!cas->use_tracking_for_rest)
2758 return;
2760 ref->expect_old_sha1 = 1;
2761 if (remote_tracking(remote, ref->name,
2762 &ref->old_oid_expect,
2763 &ref->tracking_ref))
2764 oidclr(&ref->old_oid_expect, the_repository->hash_algo);
2765 else
2766 ref->check_reachable = cas->use_force_if_includes;
2769 void apply_push_cas(struct push_cas_option *cas,
2770 struct remote *remote,
2771 struct ref *remote_refs)
2773 struct ref *ref;
2774 for (ref = remote_refs; ref; ref = ref->next) {
2775 apply_cas(cas, remote, ref);
2778 * If "compare-and-swap" is in "use_tracking[_for_rest]"
2779 * mode, and if "--force-if-includes" was specified, run
2780 * the check.
2782 if (ref->check_reachable)
2783 check_if_includes_upstream(ref);
2787 struct remote_state *remote_state_new(void)
2789 struct remote_state *r = xmalloc(sizeof(*r));
2791 memset(r, 0, sizeof(*r));
2793 hashmap_init(&r->remotes_hash, remotes_hash_cmp, NULL, 0);
2794 hashmap_init(&r->branches_hash, branches_hash_cmp, NULL, 0);
2795 return r;
2798 void remote_state_clear(struct remote_state *remote_state)
2800 int i;
2802 for (i = 0; i < remote_state->remotes_nr; i++)
2803 remote_clear(remote_state->remotes[i]);
2804 FREE_AND_NULL(remote_state->remotes);
2805 remote_state->remotes_alloc = 0;
2806 remote_state->remotes_nr = 0;
2808 hashmap_clear_and_free(&remote_state->remotes_hash, struct remote, ent);
2809 hashmap_clear_and_free(&remote_state->branches_hash, struct remote, ent);
2813 * Returns 1 if it was the last chop before ':'.
2815 static int chop_last_dir(char **remoteurl, int is_relative)
2817 char *rfind = find_last_dir_sep(*remoteurl);
2818 if (rfind) {
2819 *rfind = '\0';
2820 return 0;
2823 rfind = strrchr(*remoteurl, ':');
2824 if (rfind) {
2825 *rfind = '\0';
2826 return 1;
2829 if (is_relative || !strcmp(".", *remoteurl))
2830 die(_("cannot strip one component off url '%s'"),
2831 *remoteurl);
2833 free(*remoteurl);
2834 *remoteurl = xstrdup(".");
2835 return 0;
2838 char *relative_url(const char *remote_url, const char *url,
2839 const char *up_path)
2841 int is_relative = 0;
2842 int colonsep = 0;
2843 char *out;
2844 char *remoteurl;
2845 struct strbuf sb = STRBUF_INIT;
2846 size_t len;
2848 if (!url_is_local_not_ssh(url) || is_absolute_path(url))
2849 return xstrdup(url);
2851 len = strlen(remote_url);
2852 if (!len)
2853 BUG("invalid empty remote_url");
2855 remoteurl = xstrdup(remote_url);
2856 if (is_dir_sep(remoteurl[len-1]))
2857 remoteurl[len-1] = '\0';
2859 if (!url_is_local_not_ssh(remoteurl) || is_absolute_path(remoteurl))
2860 is_relative = 0;
2861 else {
2862 is_relative = 1;
2864 * Prepend a './' to ensure all relative
2865 * remoteurls start with './' or '../'
2867 if (!starts_with_dot_slash_native(remoteurl) &&
2868 !starts_with_dot_dot_slash_native(remoteurl)) {
2869 strbuf_reset(&sb);
2870 strbuf_addf(&sb, "./%s", remoteurl);
2871 free(remoteurl);
2872 remoteurl = strbuf_detach(&sb, NULL);
2876 * When the url starts with '../', remove that and the
2877 * last directory in remoteurl.
2879 while (*url) {
2880 if (starts_with_dot_dot_slash_native(url)) {
2881 url += 3;
2882 colonsep |= chop_last_dir(&remoteurl, is_relative);
2883 } else if (starts_with_dot_slash_native(url))
2884 url += 2;
2885 else
2886 break;
2888 strbuf_reset(&sb);
2889 strbuf_addf(&sb, "%s%s%s", remoteurl, colonsep ? ":" : "/", url);
2890 if (ends_with(url, "/"))
2891 strbuf_setlen(&sb, sb.len - 1);
2892 free(remoteurl);
2894 if (starts_with_dot_slash_native(sb.buf))
2895 out = xstrdup(sb.buf + 2);
2896 else
2897 out = xstrdup(sb.buf);
2899 if (!up_path || !is_relative) {
2900 strbuf_release(&sb);
2901 return out;
2904 strbuf_reset(&sb);
2905 strbuf_addf(&sb, "%s%s", up_path, out);
2906 free(out);
2907 return strbuf_detach(&sb, NULL);