Merge branch 'rs/fast-import-simplify-mempool-allocation' into maint-2.43
[alt-git.git] / remote.c
blob6bef95316af6573b5a6829ace42b183e25548939
1 #include "git-compat-util.h"
2 #include "abspath.h"
3 #include "config.h"
4 #include "environment.h"
5 #include "gettext.h"
6 #include "hex.h"
7 #include "remote.h"
8 #include "urlmatch.h"
9 #include "refs.h"
10 #include "refspec.h"
11 #include "object-name.h"
12 #include "object-store-ll.h"
13 #include "path.h"
14 #include "commit.h"
15 #include "diff.h"
16 #include "revision.h"
17 #include "dir.h"
18 #include "setup.h"
19 #include "string-list.h"
20 #include "strvec.h"
21 #include "commit-reach.h"
22 #include "advice.h"
23 #include "connect.h"
24 #include "parse-options.h"
26 enum map_direction { FROM_SRC, FROM_DST };
28 struct counted_string {
29 size_t len;
30 const char *s;
33 static int valid_remote(const struct remote *remote)
35 return (!!remote->url) || (!!remote->foreign_vcs);
38 static const char *alias_url(const char *url, struct rewrites *r)
40 int i, j;
41 struct counted_string *longest;
42 int longest_i;
44 longest = NULL;
45 longest_i = -1;
46 for (i = 0; i < r->rewrite_nr; i++) {
47 if (!r->rewrite[i])
48 continue;
49 for (j = 0; j < r->rewrite[i]->instead_of_nr; j++) {
50 if (starts_with(url, r->rewrite[i]->instead_of[j].s) &&
51 (!longest ||
52 longest->len < r->rewrite[i]->instead_of[j].len)) {
53 longest = &(r->rewrite[i]->instead_of[j]);
54 longest_i = i;
58 if (!longest)
59 return url;
61 return xstrfmt("%s%s", r->rewrite[longest_i]->base, url + longest->len);
64 static void add_url(struct remote *remote, const char *url)
66 ALLOC_GROW(remote->url, remote->url_nr + 1, remote->url_alloc);
67 remote->url[remote->url_nr++] = url;
70 static void add_pushurl(struct remote *remote, const char *pushurl)
72 ALLOC_GROW(remote->pushurl, remote->pushurl_nr + 1, remote->pushurl_alloc);
73 remote->pushurl[remote->pushurl_nr++] = pushurl;
76 static void add_pushurl_alias(struct remote_state *remote_state,
77 struct remote *remote, const char *url)
79 const char *pushurl = alias_url(url, &remote_state->rewrites_push);
80 if (pushurl != url)
81 add_pushurl(remote, pushurl);
84 static void add_url_alias(struct remote_state *remote_state,
85 struct remote *remote, const char *url)
87 add_url(remote, alias_url(url, &remote_state->rewrites));
88 add_pushurl_alias(remote_state, remote, url);
91 struct remotes_hash_key {
92 const char *str;
93 int len;
96 static int remotes_hash_cmp(const void *cmp_data UNUSED,
97 const struct hashmap_entry *eptr,
98 const struct hashmap_entry *entry_or_key,
99 const void *keydata)
101 const struct remote *a, *b;
102 const struct remotes_hash_key *key = keydata;
104 a = container_of(eptr, const struct remote, ent);
105 b = container_of(entry_or_key, const struct remote, ent);
107 if (key)
108 return strncmp(a->name, key->str, key->len) || a->name[key->len];
109 else
110 return strcmp(a->name, b->name);
113 static struct remote *make_remote(struct remote_state *remote_state,
114 const char *name, int len)
116 struct remote *ret;
117 struct remotes_hash_key lookup;
118 struct hashmap_entry lookup_entry, *e;
120 if (!len)
121 len = strlen(name);
123 lookup.str = name;
124 lookup.len = len;
125 hashmap_entry_init(&lookup_entry, memhash(name, len));
127 e = hashmap_get(&remote_state->remotes_hash, &lookup_entry, &lookup);
128 if (e)
129 return container_of(e, struct remote, ent);
131 CALLOC_ARRAY(ret, 1);
132 ret->prune = -1; /* unspecified */
133 ret->prune_tags = -1; /* unspecified */
134 ret->name = xstrndup(name, len);
135 refspec_init(&ret->push, REFSPEC_PUSH);
136 refspec_init(&ret->fetch, REFSPEC_FETCH);
138 ALLOC_GROW(remote_state->remotes, remote_state->remotes_nr + 1,
139 remote_state->remotes_alloc);
140 remote_state->remotes[remote_state->remotes_nr++] = ret;
142 hashmap_entry_init(&ret->ent, lookup_entry.hash);
143 if (hashmap_put_entry(&remote_state->remotes_hash, ret, ent))
144 BUG("hashmap_put overwrote entry after hashmap_get returned NULL");
145 return ret;
148 static void remote_clear(struct remote *remote)
150 int i;
152 free((char *)remote->name);
153 free((char *)remote->foreign_vcs);
155 for (i = 0; i < remote->url_nr; i++)
156 free((char *)remote->url[i]);
157 FREE_AND_NULL(remote->url);
159 for (i = 0; i < remote->pushurl_nr; i++)
160 free((char *)remote->pushurl[i]);
161 FREE_AND_NULL(remote->pushurl);
162 free((char *)remote->receivepack);
163 free((char *)remote->uploadpack);
164 FREE_AND_NULL(remote->http_proxy);
165 FREE_AND_NULL(remote->http_proxy_authmethod);
168 static void add_merge(struct branch *branch, const char *name)
170 ALLOC_GROW(branch->merge_name, branch->merge_nr + 1,
171 branch->merge_alloc);
172 branch->merge_name[branch->merge_nr++] = name;
175 struct branches_hash_key {
176 const char *str;
177 int len;
180 static int branches_hash_cmp(const void *cmp_data UNUSED,
181 const struct hashmap_entry *eptr,
182 const struct hashmap_entry *entry_or_key,
183 const void *keydata)
185 const struct branch *a, *b;
186 const struct branches_hash_key *key = keydata;
188 a = container_of(eptr, const struct branch, ent);
189 b = container_of(entry_or_key, const struct branch, ent);
191 if (key)
192 return strncmp(a->name, key->str, key->len) ||
193 a->name[key->len];
194 else
195 return strcmp(a->name, b->name);
198 static struct branch *find_branch(struct remote_state *remote_state,
199 const char *name, size_t len)
201 struct branches_hash_key lookup;
202 struct hashmap_entry lookup_entry, *e;
204 lookup.str = name;
205 lookup.len = len;
206 hashmap_entry_init(&lookup_entry, memhash(name, len));
208 e = hashmap_get(&remote_state->branches_hash, &lookup_entry, &lookup);
209 if (e)
210 return container_of(e, struct branch, ent);
212 return NULL;
215 static void die_on_missing_branch(struct repository *repo,
216 struct branch *branch)
218 /* branch == NULL is always valid because it represents detached HEAD. */
219 if (branch &&
220 branch != find_branch(repo->remote_state, branch->name,
221 strlen(branch->name)))
222 die("branch %s was not found in the repository", branch->name);
225 static struct branch *make_branch(struct remote_state *remote_state,
226 const char *name, size_t len)
228 struct branch *ret;
230 ret = find_branch(remote_state, name, len);
231 if (ret)
232 return ret;
234 CALLOC_ARRAY(ret, 1);
235 ret->name = xstrndup(name, len);
236 ret->refname = xstrfmt("refs/heads/%s", ret->name);
238 hashmap_entry_init(&ret->ent, memhash(name, len));
239 if (hashmap_put_entry(&remote_state->branches_hash, ret, ent))
240 BUG("hashmap_put overwrote entry after hashmap_get returned NULL");
241 return ret;
244 static struct rewrite *make_rewrite(struct rewrites *r,
245 const char *base, size_t len)
247 struct rewrite *ret;
248 int i;
250 for (i = 0; i < r->rewrite_nr; i++) {
251 if (len == r->rewrite[i]->baselen &&
252 !strncmp(base, r->rewrite[i]->base, len))
253 return r->rewrite[i];
256 ALLOC_GROW(r->rewrite, r->rewrite_nr + 1, r->rewrite_alloc);
257 CALLOC_ARRAY(ret, 1);
258 r->rewrite[r->rewrite_nr++] = ret;
259 ret->base = xstrndup(base, len);
260 ret->baselen = len;
261 return ret;
264 static void add_instead_of(struct rewrite *rewrite, const char *instead_of)
266 ALLOC_GROW(rewrite->instead_of, rewrite->instead_of_nr + 1, rewrite->instead_of_alloc);
267 rewrite->instead_of[rewrite->instead_of_nr].s = instead_of;
268 rewrite->instead_of[rewrite->instead_of_nr].len = strlen(instead_of);
269 rewrite->instead_of_nr++;
272 static const char *skip_spaces(const char *s)
274 while (isspace(*s))
275 s++;
276 return s;
279 static void read_remotes_file(struct remote_state *remote_state,
280 struct remote *remote)
282 struct strbuf buf = STRBUF_INIT;
283 FILE *f = fopen_or_warn(git_path("remotes/%s", remote->name), "r");
285 if (!f)
286 return;
287 remote->configured_in_repo = 1;
288 remote->origin = REMOTE_REMOTES;
289 while (strbuf_getline(&buf, f) != EOF) {
290 const char *v;
292 strbuf_rtrim(&buf);
294 if (skip_prefix(buf.buf, "URL:", &v))
295 add_url_alias(remote_state, remote,
296 xstrdup(skip_spaces(v)));
297 else if (skip_prefix(buf.buf, "Push:", &v))
298 refspec_append(&remote->push, skip_spaces(v));
299 else if (skip_prefix(buf.buf, "Pull:", &v))
300 refspec_append(&remote->fetch, skip_spaces(v));
302 strbuf_release(&buf);
303 fclose(f);
306 static void read_branches_file(struct remote_state *remote_state,
307 struct remote *remote)
309 char *frag;
310 struct strbuf buf = STRBUF_INIT;
311 FILE *f = fopen_or_warn(git_path("branches/%s", remote->name), "r");
313 if (!f)
314 return;
316 strbuf_getline_lf(&buf, f);
317 fclose(f);
318 strbuf_trim(&buf);
319 if (!buf.len) {
320 strbuf_release(&buf);
321 return;
324 remote->configured_in_repo = 1;
325 remote->origin = REMOTE_BRANCHES;
328 * The branches file would have URL and optionally
329 * #branch specified. The default (or specified) branch is
330 * fetched and stored in the local branch matching the
331 * remote name.
333 frag = strchr(buf.buf, '#');
334 if (frag)
335 *(frag++) = '\0';
336 else
337 frag = (char *)git_default_branch_name(0);
339 add_url_alias(remote_state, remote, strbuf_detach(&buf, NULL));
340 refspec_appendf(&remote->fetch, "refs/heads/%s:refs/heads/%s",
341 frag, remote->name);
344 * Cogito compatible push: push current HEAD to remote #branch
345 * (master if missing)
347 refspec_appendf(&remote->push, "HEAD:refs/heads/%s", frag);
348 remote->fetch_tags = 1; /* always auto-follow */
351 static int handle_config(const char *key, const char *value,
352 const struct config_context *ctx, void *cb)
354 const char *name;
355 size_t namelen;
356 const char *subkey;
357 struct remote *remote;
358 struct branch *branch;
359 struct remote_state *remote_state = cb;
360 const struct key_value_info *kvi = ctx->kvi;
362 if (parse_config_key(key, "branch", &name, &namelen, &subkey) >= 0) {
363 /* There is no subsection. */
364 if (!name)
365 return 0;
366 /* There is a subsection, but it is empty. */
367 if (!namelen)
368 return -1;
369 branch = make_branch(remote_state, name, namelen);
370 if (!strcmp(subkey, "remote")) {
371 return git_config_string(&branch->remote_name, key, value);
372 } else if (!strcmp(subkey, "pushremote")) {
373 return git_config_string(&branch->pushremote_name, key, value);
374 } else if (!strcmp(subkey, "merge")) {
375 if (!value)
376 return config_error_nonbool(key);
377 add_merge(branch, xstrdup(value));
379 return 0;
381 if (parse_config_key(key, "url", &name, &namelen, &subkey) >= 0) {
382 struct rewrite *rewrite;
383 if (!name)
384 return 0;
385 if (!strcmp(subkey, "insteadof")) {
386 if (!value)
387 return config_error_nonbool(key);
388 rewrite = make_rewrite(&remote_state->rewrites, name,
389 namelen);
390 add_instead_of(rewrite, xstrdup(value));
391 } else if (!strcmp(subkey, "pushinsteadof")) {
392 if (!value)
393 return config_error_nonbool(key);
394 rewrite = make_rewrite(&remote_state->rewrites_push,
395 name, namelen);
396 add_instead_of(rewrite, xstrdup(value));
400 if (parse_config_key(key, "remote", &name, &namelen, &subkey) < 0)
401 return 0;
403 /* Handle remote.* variables */
404 if (!name && !strcmp(subkey, "pushdefault"))
405 return git_config_string(&remote_state->pushremote_name, key,
406 value);
408 if (!name)
409 return 0;
410 /* Handle remote.<name>.* variables */
411 if (*name == '/') {
412 warning(_("config remote shorthand cannot begin with '/': %s"),
413 name);
414 return 0;
416 remote = make_remote(remote_state, name, namelen);
417 remote->origin = REMOTE_CONFIG;
418 if (kvi->scope == CONFIG_SCOPE_LOCAL ||
419 kvi->scope == CONFIG_SCOPE_WORKTREE)
420 remote->configured_in_repo = 1;
421 if (!strcmp(subkey, "mirror"))
422 remote->mirror = git_config_bool(key, value);
423 else if (!strcmp(subkey, "skipdefaultupdate"))
424 remote->skip_default_update = git_config_bool(key, value);
425 else if (!strcmp(subkey, "skipfetchall"))
426 remote->skip_default_update = git_config_bool(key, value);
427 else if (!strcmp(subkey, "prune"))
428 remote->prune = git_config_bool(key, value);
429 else if (!strcmp(subkey, "prunetags"))
430 remote->prune_tags = git_config_bool(key, value);
431 else if (!strcmp(subkey, "url")) {
432 const char *v;
433 if (git_config_string(&v, key, value))
434 return -1;
435 add_url(remote, v);
436 } else if (!strcmp(subkey, "pushurl")) {
437 const char *v;
438 if (git_config_string(&v, key, value))
439 return -1;
440 add_pushurl(remote, v);
441 } else if (!strcmp(subkey, "push")) {
442 const char *v;
443 if (git_config_string(&v, key, value))
444 return -1;
445 refspec_append(&remote->push, v);
446 free((char *)v);
447 } else if (!strcmp(subkey, "fetch")) {
448 const char *v;
449 if (git_config_string(&v, key, value))
450 return -1;
451 refspec_append(&remote->fetch, v);
452 free((char *)v);
453 } else if (!strcmp(subkey, "receivepack")) {
454 const char *v;
455 if (git_config_string(&v, key, value))
456 return -1;
457 if (!remote->receivepack)
458 remote->receivepack = v;
459 else
460 error(_("more than one receivepack given, using the first"));
461 } else if (!strcmp(subkey, "uploadpack")) {
462 const char *v;
463 if (git_config_string(&v, key, value))
464 return -1;
465 if (!remote->uploadpack)
466 remote->uploadpack = v;
467 else
468 error(_("more than one uploadpack given, using the first"));
469 } else if (!strcmp(subkey, "tagopt")) {
470 if (!strcmp(value, "--no-tags"))
471 remote->fetch_tags = -1;
472 else if (!strcmp(value, "--tags"))
473 remote->fetch_tags = 2;
474 } else if (!strcmp(subkey, "proxy")) {
475 return git_config_string((const char **)&remote->http_proxy,
476 key, value);
477 } else if (!strcmp(subkey, "proxyauthmethod")) {
478 return git_config_string((const char **)&remote->http_proxy_authmethod,
479 key, value);
480 } else if (!strcmp(subkey, "vcs")) {
481 return git_config_string(&remote->foreign_vcs, key, value);
483 return 0;
486 static void alias_all_urls(struct remote_state *remote_state)
488 int i, j;
489 for (i = 0; i < remote_state->remotes_nr; i++) {
490 int add_pushurl_aliases;
491 if (!remote_state->remotes[i])
492 continue;
493 for (j = 0; j < remote_state->remotes[i]->pushurl_nr; j++) {
494 remote_state->remotes[i]->pushurl[j] =
495 alias_url(remote_state->remotes[i]->pushurl[j],
496 &remote_state->rewrites);
498 add_pushurl_aliases = remote_state->remotes[i]->pushurl_nr == 0;
499 for (j = 0; j < remote_state->remotes[i]->url_nr; j++) {
500 if (add_pushurl_aliases)
501 add_pushurl_alias(
502 remote_state, remote_state->remotes[i],
503 remote_state->remotes[i]->url[j]);
504 remote_state->remotes[i]->url[j] =
505 alias_url(remote_state->remotes[i]->url[j],
506 &remote_state->rewrites);
511 static void read_config(struct repository *repo)
513 int flag;
515 if (repo->remote_state->initialized)
516 return;
517 repo->remote_state->initialized = 1;
519 repo->remote_state->current_branch = NULL;
520 if (startup_info->have_repository) {
521 const char *head_ref = refs_resolve_ref_unsafe(
522 get_main_ref_store(repo), "HEAD", 0, NULL, &flag);
523 if (head_ref && (flag & REF_ISSYMREF) &&
524 skip_prefix(head_ref, "refs/heads/", &head_ref)) {
525 repo->remote_state->current_branch = make_branch(
526 repo->remote_state, head_ref, strlen(head_ref));
529 repo_config(repo, handle_config, repo->remote_state);
530 alias_all_urls(repo->remote_state);
533 static int valid_remote_nick(const char *name)
535 if (!name[0] || is_dot_or_dotdot(name))
536 return 0;
538 /* remote nicknames cannot contain slashes */
539 while (*name)
540 if (is_dir_sep(*name++))
541 return 0;
542 return 1;
545 static const char *remotes_remote_for_branch(struct remote_state *remote_state,
546 struct branch *branch,
547 int *explicit)
549 if (branch && branch->remote_name) {
550 if (explicit)
551 *explicit = 1;
552 return branch->remote_name;
554 if (explicit)
555 *explicit = 0;
556 if (remote_state->remotes_nr == 1)
557 return remote_state->remotes[0]->name;
558 return "origin";
561 const char *remote_for_branch(struct branch *branch, int *explicit)
563 read_config(the_repository);
564 die_on_missing_branch(the_repository, branch);
566 return remotes_remote_for_branch(the_repository->remote_state, branch,
567 explicit);
570 static const char *
571 remotes_pushremote_for_branch(struct remote_state *remote_state,
572 struct branch *branch, int *explicit)
574 if (branch && branch->pushremote_name) {
575 if (explicit)
576 *explicit = 1;
577 return branch->pushremote_name;
579 if (remote_state->pushremote_name) {
580 if (explicit)
581 *explicit = 1;
582 return remote_state->pushremote_name;
584 return remotes_remote_for_branch(remote_state, branch, explicit);
587 const char *pushremote_for_branch(struct branch *branch, int *explicit)
589 read_config(the_repository);
590 die_on_missing_branch(the_repository, branch);
592 return remotes_pushremote_for_branch(the_repository->remote_state,
593 branch, explicit);
596 static struct remote *remotes_remote_get(struct remote_state *remote_state,
597 const char *name);
599 const char *remote_ref_for_branch(struct branch *branch, int for_push)
601 read_config(the_repository);
602 die_on_missing_branch(the_repository, branch);
604 if (branch) {
605 if (!for_push) {
606 if (branch->merge_nr) {
607 return branch->merge_name[0];
609 } else {
610 const char *dst,
611 *remote_name = remotes_pushremote_for_branch(
612 the_repository->remote_state, branch,
613 NULL);
614 struct remote *remote = remotes_remote_get(
615 the_repository->remote_state, remote_name);
617 if (remote && remote->push.nr &&
618 (dst = apply_refspecs(&remote->push,
619 branch->refname))) {
620 return dst;
624 return NULL;
627 static void validate_remote_url(struct remote *remote)
629 int i;
630 const char *value;
631 struct strbuf redacted = STRBUF_INIT;
632 int warn_not_die;
634 if (git_config_get_string_tmp("transfer.credentialsinurl", &value))
635 return;
637 if (!strcmp("warn", value))
638 warn_not_die = 1;
639 else if (!strcmp("die", value))
640 warn_not_die = 0;
641 else if (!strcmp("allow", value))
642 return;
643 else
644 die(_("unrecognized value transfer.credentialsInUrl: '%s'"), value);
646 for (i = 0; i < remote->url_nr; i++) {
647 struct url_info url_info = { 0 };
649 if (!url_normalize(remote->url[i], &url_info) ||
650 !url_info.passwd_off)
651 goto loop_cleanup;
653 strbuf_reset(&redacted);
654 strbuf_add(&redacted, url_info.url, url_info.passwd_off);
655 strbuf_addstr(&redacted, "<redacted>");
656 strbuf_addstr(&redacted,
657 url_info.url + url_info.passwd_off + url_info.passwd_len);
659 if (warn_not_die)
660 warning(_("URL '%s' uses plaintext credentials"), redacted.buf);
661 else
662 die(_("URL '%s' uses plaintext credentials"), redacted.buf);
664 loop_cleanup:
665 free(url_info.url);
668 strbuf_release(&redacted);
671 static struct remote *
672 remotes_remote_get_1(struct remote_state *remote_state, const char *name,
673 const char *(*get_default)(struct remote_state *,
674 struct branch *, int *))
676 struct remote *ret;
677 int name_given = 0;
679 if (name)
680 name_given = 1;
681 else
682 name = get_default(remote_state, remote_state->current_branch,
683 &name_given);
685 ret = make_remote(remote_state, name, 0);
686 if (valid_remote_nick(name) && have_git_dir()) {
687 if (!valid_remote(ret))
688 read_remotes_file(remote_state, ret);
689 if (!valid_remote(ret))
690 read_branches_file(remote_state, ret);
692 if (name_given && !valid_remote(ret))
693 add_url_alias(remote_state, ret, name);
694 if (!valid_remote(ret))
695 return NULL;
697 validate_remote_url(ret);
699 return ret;
702 static inline struct remote *
703 remotes_remote_get(struct remote_state *remote_state, const char *name)
705 return remotes_remote_get_1(remote_state, name,
706 remotes_remote_for_branch);
709 struct remote *remote_get(const char *name)
711 read_config(the_repository);
712 return remotes_remote_get(the_repository->remote_state, name);
715 static inline struct remote *
716 remotes_pushremote_get(struct remote_state *remote_state, const char *name)
718 return remotes_remote_get_1(remote_state, name,
719 remotes_pushremote_for_branch);
722 struct remote *pushremote_get(const char *name)
724 read_config(the_repository);
725 return remotes_pushremote_get(the_repository->remote_state, name);
728 int remote_is_configured(struct remote *remote, int in_repo)
730 if (!remote)
731 return 0;
732 if (in_repo)
733 return remote->configured_in_repo;
734 return !!remote->origin;
737 int for_each_remote(each_remote_fn fn, void *priv)
739 int i, result = 0;
740 read_config(the_repository);
741 for (i = 0; i < the_repository->remote_state->remotes_nr && !result;
742 i++) {
743 struct remote *remote =
744 the_repository->remote_state->remotes[i];
745 if (!remote)
746 continue;
747 result = fn(remote, priv);
749 return result;
752 static void handle_duplicate(struct ref *ref1, struct ref *ref2)
754 if (strcmp(ref1->name, ref2->name)) {
755 if (ref1->fetch_head_status != FETCH_HEAD_IGNORE &&
756 ref2->fetch_head_status != FETCH_HEAD_IGNORE) {
757 die(_("Cannot fetch both %s and %s to %s"),
758 ref1->name, ref2->name, ref2->peer_ref->name);
759 } else if (ref1->fetch_head_status != FETCH_HEAD_IGNORE &&
760 ref2->fetch_head_status == FETCH_HEAD_IGNORE) {
761 warning(_("%s usually tracks %s, not %s"),
762 ref2->peer_ref->name, ref2->name, ref1->name);
763 } else if (ref1->fetch_head_status == FETCH_HEAD_IGNORE &&
764 ref2->fetch_head_status == FETCH_HEAD_IGNORE) {
765 die(_("%s tracks both %s and %s"),
766 ref2->peer_ref->name, ref1->name, ref2->name);
767 } else {
769 * This last possibility doesn't occur because
770 * FETCH_HEAD_IGNORE entries always appear at
771 * the end of the list.
773 BUG("Internal error");
776 free(ref2->peer_ref);
777 free(ref2);
780 struct ref *ref_remove_duplicates(struct ref *ref_map)
782 struct string_list refs = STRING_LIST_INIT_NODUP;
783 struct ref *retval = NULL;
784 struct ref **p = &retval;
786 while (ref_map) {
787 struct ref *ref = ref_map;
789 ref_map = ref_map->next;
790 ref->next = NULL;
792 if (!ref->peer_ref) {
793 *p = ref;
794 p = &ref->next;
795 } else {
796 struct string_list_item *item =
797 string_list_insert(&refs, ref->peer_ref->name);
799 if (item->util) {
800 /* Entry already existed */
801 handle_duplicate((struct ref *)item->util, ref);
802 } else {
803 *p = ref;
804 p = &ref->next;
805 item->util = ref;
810 string_list_clear(&refs, 0);
811 return retval;
814 int remote_has_url(struct remote *remote, const char *url)
816 int i;
817 for (i = 0; i < remote->url_nr; i++) {
818 if (!strcmp(remote->url[i], url))
819 return 1;
821 return 0;
824 static int match_name_with_pattern(const char *key, const char *name,
825 const char *value, char **result)
827 const char *kstar = strchr(key, '*');
828 size_t klen;
829 size_t ksuffixlen;
830 size_t namelen;
831 int ret;
832 if (!kstar)
833 die(_("key '%s' of pattern had no '*'"), key);
834 klen = kstar - key;
835 ksuffixlen = strlen(kstar + 1);
836 namelen = strlen(name);
837 ret = !strncmp(name, key, klen) && namelen >= klen + ksuffixlen &&
838 !memcmp(name + namelen - ksuffixlen, kstar + 1, ksuffixlen);
839 if (ret && value) {
840 struct strbuf sb = STRBUF_INIT;
841 const char *vstar = strchr(value, '*');
842 if (!vstar)
843 die(_("value '%s' of pattern has no '*'"), value);
844 strbuf_add(&sb, value, vstar - value);
845 strbuf_add(&sb, name + klen, namelen - klen - ksuffixlen);
846 strbuf_addstr(&sb, vstar + 1);
847 *result = strbuf_detach(&sb, NULL);
849 return ret;
852 static int refspec_match(const struct refspec_item *refspec,
853 const char *name)
855 if (refspec->pattern)
856 return match_name_with_pattern(refspec->src, name, NULL, NULL);
858 return !strcmp(refspec->src, name);
861 int omit_name_by_refspec(const char *name, struct refspec *rs)
863 int i;
865 for (i = 0; i < rs->nr; i++) {
866 if (rs->items[i].negative && refspec_match(&rs->items[i], name))
867 return 1;
869 return 0;
872 struct ref *apply_negative_refspecs(struct ref *ref_map, struct refspec *rs)
874 struct ref **tail;
876 for (tail = &ref_map; *tail; ) {
877 struct ref *ref = *tail;
879 if (omit_name_by_refspec(ref->name, rs)) {
880 *tail = ref->next;
881 free(ref->peer_ref);
882 free(ref);
883 } else
884 tail = &ref->next;
887 return ref_map;
890 static int query_matches_negative_refspec(struct refspec *rs, struct refspec_item *query)
892 int i, matched_negative = 0;
893 int find_src = !query->src;
894 struct string_list reversed = STRING_LIST_INIT_DUP;
895 const char *needle = find_src ? query->dst : query->src;
898 * Check whether the queried ref matches any negative refpsec. If so,
899 * then we should ultimately treat this as not matching the query at
900 * all.
902 * Note that negative refspecs always match the source, but the query
903 * item uses the destination. To handle this, we apply pattern
904 * refspecs in reverse to figure out if the query source matches any
905 * of the negative refspecs.
907 * The first loop finds and expands all positive refspecs
908 * matched by the queried ref.
910 * The second loop checks if any of the results of the first loop
911 * match any negative refspec.
913 for (i = 0; i < rs->nr; i++) {
914 struct refspec_item *refspec = &rs->items[i];
915 char *expn_name;
917 if (refspec->negative)
918 continue;
920 /* Note the reversal of src and dst */
921 if (refspec->pattern) {
922 const char *key = refspec->dst ? refspec->dst : refspec->src;
923 const char *value = refspec->src;
925 if (match_name_with_pattern(key, needle, value, &expn_name))
926 string_list_append_nodup(&reversed, expn_name);
927 } else if (refspec->matching) {
928 /* For the special matching refspec, any query should match */
929 string_list_append(&reversed, needle);
930 } else if (!refspec->src) {
931 BUG("refspec->src should not be null here");
932 } else if (!strcmp(needle, refspec->src)) {
933 string_list_append(&reversed, refspec->src);
937 for (i = 0; !matched_negative && i < reversed.nr; i++) {
938 if (omit_name_by_refspec(reversed.items[i].string, rs))
939 matched_negative = 1;
942 string_list_clear(&reversed, 0);
944 return matched_negative;
947 static void query_refspecs_multiple(struct refspec *rs,
948 struct refspec_item *query,
949 struct string_list *results)
951 int i;
952 int find_src = !query->src;
954 if (find_src && !query->dst)
955 BUG("query_refspecs_multiple: need either src or dst");
957 if (query_matches_negative_refspec(rs, query))
958 return;
960 for (i = 0; i < rs->nr; i++) {
961 struct refspec_item *refspec = &rs->items[i];
962 const char *key = find_src ? refspec->dst : refspec->src;
963 const char *value = find_src ? refspec->src : refspec->dst;
964 const char *needle = find_src ? query->dst : query->src;
965 char **result = find_src ? &query->src : &query->dst;
967 if (!refspec->dst || refspec->negative)
968 continue;
969 if (refspec->pattern) {
970 if (match_name_with_pattern(key, needle, value, result))
971 string_list_append_nodup(results, *result);
972 } else if (!strcmp(needle, key)) {
973 string_list_append(results, value);
978 int query_refspecs(struct refspec *rs, struct refspec_item *query)
980 int i;
981 int find_src = !query->src;
982 const char *needle = find_src ? query->dst : query->src;
983 char **result = find_src ? &query->src : &query->dst;
985 if (find_src && !query->dst)
986 BUG("query_refspecs: need either src or dst");
988 if (query_matches_negative_refspec(rs, query))
989 return -1;
991 for (i = 0; i < rs->nr; i++) {
992 struct refspec_item *refspec = &rs->items[i];
993 const char *key = find_src ? refspec->dst : refspec->src;
994 const char *value = find_src ? refspec->src : refspec->dst;
996 if (!refspec->dst || refspec->negative)
997 continue;
998 if (refspec->pattern) {
999 if (match_name_with_pattern(key, needle, value, result)) {
1000 query->force = refspec->force;
1001 return 0;
1003 } else if (!strcmp(needle, key)) {
1004 *result = xstrdup(value);
1005 query->force = refspec->force;
1006 return 0;
1009 return -1;
1012 char *apply_refspecs(struct refspec *rs, const char *name)
1014 struct refspec_item query;
1016 memset(&query, 0, sizeof(struct refspec_item));
1017 query.src = (char *)name;
1019 if (query_refspecs(rs, &query))
1020 return NULL;
1022 return query.dst;
1025 int remote_find_tracking(struct remote *remote, struct refspec_item *refspec)
1027 return query_refspecs(&remote->fetch, refspec);
1030 static struct ref *alloc_ref_with_prefix(const char *prefix, size_t prefixlen,
1031 const char *name)
1033 size_t len = strlen(name);
1034 struct ref *ref = xcalloc(1, st_add4(sizeof(*ref), prefixlen, len, 1));
1035 memcpy(ref->name, prefix, prefixlen);
1036 memcpy(ref->name + prefixlen, name, len);
1037 return ref;
1040 struct ref *alloc_ref(const char *name)
1042 return alloc_ref_with_prefix("", 0, name);
1045 struct ref *copy_ref(const struct ref *ref)
1047 struct ref *cpy;
1048 size_t len;
1049 if (!ref)
1050 return NULL;
1051 len = st_add3(sizeof(struct ref), strlen(ref->name), 1);
1052 cpy = xmalloc(len);
1053 memcpy(cpy, ref, len);
1054 cpy->next = NULL;
1055 cpy->symref = xstrdup_or_null(ref->symref);
1056 cpy->remote_status = xstrdup_or_null(ref->remote_status);
1057 cpy->peer_ref = copy_ref(ref->peer_ref);
1058 return cpy;
1061 struct ref *copy_ref_list(const struct ref *ref)
1063 struct ref *ret = NULL;
1064 struct ref **tail = &ret;
1065 while (ref) {
1066 *tail = copy_ref(ref);
1067 ref = ref->next;
1068 tail = &((*tail)->next);
1070 return ret;
1073 void free_one_ref(struct ref *ref)
1075 if (!ref)
1076 return;
1077 free_one_ref(ref->peer_ref);
1078 free(ref->remote_status);
1079 free(ref->symref);
1080 free(ref);
1083 void free_refs(struct ref *ref)
1085 struct ref *next;
1086 while (ref) {
1087 next = ref->next;
1088 free_one_ref(ref);
1089 ref = next;
1093 int count_refspec_match(const char *pattern,
1094 struct ref *refs,
1095 struct ref **matched_ref)
1097 int patlen = strlen(pattern);
1098 struct ref *matched_weak = NULL;
1099 struct ref *matched = NULL;
1100 int weak_match = 0;
1101 int match = 0;
1103 for (weak_match = match = 0; refs; refs = refs->next) {
1104 char *name = refs->name;
1105 int namelen = strlen(name);
1107 if (!refname_match(pattern, name))
1108 continue;
1110 /* A match is "weak" if it is with refs outside
1111 * heads or tags, and did not specify the pattern
1112 * in full (e.g. "refs/remotes/origin/master") or at
1113 * least from the toplevel (e.g. "remotes/origin/master");
1114 * otherwise "git push $URL master" would result in
1115 * ambiguity between remotes/origin/master and heads/master
1116 * at the remote site.
1118 if (namelen != patlen &&
1119 patlen != namelen - 5 &&
1120 !starts_with(name, "refs/heads/") &&
1121 !starts_with(name, "refs/tags/")) {
1122 /* We want to catch the case where only weak
1123 * matches are found and there are multiple
1124 * matches, and where more than one strong
1125 * matches are found, as ambiguous. One
1126 * strong match with zero or more weak matches
1127 * are acceptable as a unique match.
1129 matched_weak = refs;
1130 weak_match++;
1132 else {
1133 matched = refs;
1134 match++;
1137 if (!matched) {
1138 if (matched_ref)
1139 *matched_ref = matched_weak;
1140 return weak_match;
1142 else {
1143 if (matched_ref)
1144 *matched_ref = matched;
1145 return match;
1149 static void tail_link_ref(struct ref *ref, struct ref ***tail)
1151 **tail = ref;
1152 while (ref->next)
1153 ref = ref->next;
1154 *tail = &ref->next;
1157 static struct ref *alloc_delete_ref(void)
1159 struct ref *ref = alloc_ref("(delete)");
1160 oidclr(&ref->new_oid);
1161 return ref;
1164 static int try_explicit_object_name(const char *name,
1165 struct ref **match)
1167 struct object_id oid;
1169 if (!*name) {
1170 if (match)
1171 *match = alloc_delete_ref();
1172 return 0;
1175 if (repo_get_oid(the_repository, name, &oid))
1176 return -1;
1178 if (match) {
1179 *match = alloc_ref(name);
1180 oidcpy(&(*match)->new_oid, &oid);
1182 return 0;
1185 static struct ref *make_linked_ref(const char *name, struct ref ***tail)
1187 struct ref *ret = alloc_ref(name);
1188 tail_link_ref(ret, tail);
1189 return ret;
1192 static char *guess_ref(const char *name, struct ref *peer)
1194 struct strbuf buf = STRBUF_INIT;
1196 const char *r = resolve_ref_unsafe(peer->name, RESOLVE_REF_READING,
1197 NULL, NULL);
1198 if (!r)
1199 return NULL;
1201 if (starts_with(r, "refs/heads/")) {
1202 strbuf_addstr(&buf, "refs/heads/");
1203 } else if (starts_with(r, "refs/tags/")) {
1204 strbuf_addstr(&buf, "refs/tags/");
1205 } else {
1206 return NULL;
1209 strbuf_addstr(&buf, name);
1210 return strbuf_detach(&buf, NULL);
1213 static int match_explicit_lhs(struct ref *src,
1214 struct refspec_item *rs,
1215 struct ref **match,
1216 int *allocated_match)
1218 switch (count_refspec_match(rs->src, src, match)) {
1219 case 1:
1220 if (allocated_match)
1221 *allocated_match = 0;
1222 return 0;
1223 case 0:
1224 /* The source could be in the get_sha1() format
1225 * not a reference name. :refs/other is a
1226 * way to delete 'other' ref at the remote end.
1228 if (try_explicit_object_name(rs->src, match) < 0)
1229 return error(_("src refspec %s does not match any"), rs->src);
1230 if (allocated_match)
1231 *allocated_match = 1;
1232 return 0;
1233 default:
1234 return error(_("src refspec %s matches more than one"), rs->src);
1238 static void show_push_unqualified_ref_name_error(const char *dst_value,
1239 const char *matched_src_name)
1241 struct object_id oid;
1242 enum object_type type;
1245 * TRANSLATORS: "matches '%s'%" is the <dst> part of "git push
1246 * <remote> <src>:<dst>" push, and "being pushed ('%s')" is
1247 * the <src>.
1249 error(_("The destination you provided is not a full refname (i.e.,\n"
1250 "starting with \"refs/\"). We tried to guess what you meant by:\n"
1251 "\n"
1252 "- Looking for a ref that matches '%s' on the remote side.\n"
1253 "- Checking if the <src> being pushed ('%s')\n"
1254 " is a ref in \"refs/{heads,tags}/\". If so we add a corresponding\n"
1255 " refs/{heads,tags}/ prefix on the remote side.\n"
1256 "\n"
1257 "Neither worked, so we gave up. You must fully qualify the ref."),
1258 dst_value, matched_src_name);
1260 if (!advice_enabled(ADVICE_PUSH_UNQUALIFIED_REF_NAME))
1261 return;
1263 if (repo_get_oid(the_repository, matched_src_name, &oid))
1264 BUG("'%s' is not a valid object, "
1265 "match_explicit_lhs() should catch this!",
1266 matched_src_name);
1267 type = oid_object_info(the_repository, &oid, NULL);
1268 if (type == OBJ_COMMIT) {
1269 advise(_("The <src> part of the refspec is a commit object.\n"
1270 "Did you mean to create a new branch by pushing to\n"
1271 "'%s:refs/heads/%s'?"),
1272 matched_src_name, dst_value);
1273 } else if (type == OBJ_TAG) {
1274 advise(_("The <src> part of the refspec is a tag object.\n"
1275 "Did you mean to create a new tag by pushing to\n"
1276 "'%s:refs/tags/%s'?"),
1277 matched_src_name, dst_value);
1278 } else if (type == OBJ_TREE) {
1279 advise(_("The <src> part of the refspec is a tree object.\n"
1280 "Did you mean to tag a new tree by pushing to\n"
1281 "'%s:refs/tags/%s'?"),
1282 matched_src_name, dst_value);
1283 } else if (type == OBJ_BLOB) {
1284 advise(_("The <src> part of the refspec is a blob object.\n"
1285 "Did you mean to tag a new blob by pushing to\n"
1286 "'%s:refs/tags/%s'?"),
1287 matched_src_name, dst_value);
1288 } else {
1289 BUG("'%s' should be commit/tag/tree/blob, is '%d'",
1290 matched_src_name, type);
1294 static int match_explicit(struct ref *src, struct ref *dst,
1295 struct ref ***dst_tail,
1296 struct refspec_item *rs)
1298 struct ref *matched_src, *matched_dst;
1299 int allocated_src;
1301 const char *dst_value = rs->dst;
1302 char *dst_guess;
1304 if (rs->pattern || rs->matching || rs->negative)
1305 return 0;
1307 matched_src = matched_dst = NULL;
1308 if (match_explicit_lhs(src, rs, &matched_src, &allocated_src) < 0)
1309 return -1;
1311 if (!dst_value) {
1312 int flag;
1314 dst_value = resolve_ref_unsafe(matched_src->name,
1315 RESOLVE_REF_READING,
1316 NULL, &flag);
1317 if (!dst_value ||
1318 ((flag & REF_ISSYMREF) &&
1319 !starts_with(dst_value, "refs/heads/")))
1320 die(_("%s cannot be resolved to branch"),
1321 matched_src->name);
1324 switch (count_refspec_match(dst_value, dst, &matched_dst)) {
1325 case 1:
1326 break;
1327 case 0:
1328 if (starts_with(dst_value, "refs/")) {
1329 matched_dst = make_linked_ref(dst_value, dst_tail);
1330 } else if (is_null_oid(&matched_src->new_oid)) {
1331 error(_("unable to delete '%s': remote ref does not exist"),
1332 dst_value);
1333 } else if ((dst_guess = guess_ref(dst_value, matched_src))) {
1334 matched_dst = make_linked_ref(dst_guess, dst_tail);
1335 free(dst_guess);
1336 } else {
1337 show_push_unqualified_ref_name_error(dst_value,
1338 matched_src->name);
1340 break;
1341 default:
1342 matched_dst = NULL;
1343 error(_("dst refspec %s matches more than one"),
1344 dst_value);
1345 break;
1347 if (!matched_dst)
1348 return -1;
1349 if (matched_dst->peer_ref)
1350 return error(_("dst ref %s receives from more than one src"),
1351 matched_dst->name);
1352 else {
1353 matched_dst->peer_ref = allocated_src ?
1354 matched_src :
1355 copy_ref(matched_src);
1356 matched_dst->force = rs->force;
1358 return 0;
1361 static int match_explicit_refs(struct ref *src, struct ref *dst,
1362 struct ref ***dst_tail, struct refspec *rs)
1364 int i, errs;
1365 for (i = errs = 0; i < rs->nr; i++)
1366 errs += match_explicit(src, dst, dst_tail, &rs->items[i]);
1367 return errs;
1370 static char *get_ref_match(const struct refspec *rs, const struct ref *ref,
1371 int send_mirror, int direction,
1372 const struct refspec_item **ret_pat)
1374 const struct refspec_item *pat;
1375 char *name;
1376 int i;
1377 int matching_refs = -1;
1378 for (i = 0; i < rs->nr; i++) {
1379 const struct refspec_item *item = &rs->items[i];
1381 if (item->negative)
1382 continue;
1384 if (item->matching &&
1385 (matching_refs == -1 || item->force)) {
1386 matching_refs = i;
1387 continue;
1390 if (item->pattern) {
1391 const char *dst_side = item->dst ? item->dst : item->src;
1392 int match;
1393 if (direction == FROM_SRC)
1394 match = match_name_with_pattern(item->src, ref->name, dst_side, &name);
1395 else
1396 match = match_name_with_pattern(dst_side, ref->name, item->src, &name);
1397 if (match) {
1398 matching_refs = i;
1399 break;
1403 if (matching_refs == -1)
1404 return NULL;
1406 pat = &rs->items[matching_refs];
1407 if (pat->matching) {
1409 * "matching refs"; traditionally we pushed everything
1410 * including refs outside refs/heads/ hierarchy, but
1411 * that does not make much sense these days.
1413 if (!send_mirror && !starts_with(ref->name, "refs/heads/"))
1414 return NULL;
1415 name = xstrdup(ref->name);
1417 if (ret_pat)
1418 *ret_pat = pat;
1419 return name;
1422 static struct ref **tail_ref(struct ref **head)
1424 struct ref **tail = head;
1425 while (*tail)
1426 tail = &((*tail)->next);
1427 return tail;
1430 struct tips {
1431 struct commit **tip;
1432 int nr, alloc;
1435 static void add_to_tips(struct tips *tips, const struct object_id *oid)
1437 struct commit *commit;
1439 if (is_null_oid(oid))
1440 return;
1441 commit = lookup_commit_reference_gently(the_repository, oid, 1);
1442 if (!commit || (commit->object.flags & TMP_MARK))
1443 return;
1444 commit->object.flags |= TMP_MARK;
1445 ALLOC_GROW(tips->tip, tips->nr + 1, tips->alloc);
1446 tips->tip[tips->nr++] = commit;
1449 static void add_missing_tags(struct ref *src, struct ref **dst, struct ref ***dst_tail)
1451 struct string_list dst_tag = STRING_LIST_INIT_NODUP;
1452 struct string_list src_tag = STRING_LIST_INIT_NODUP;
1453 struct string_list_item *item;
1454 struct ref *ref;
1455 struct tips sent_tips;
1458 * Collect everything we know they would have at the end of
1459 * this push, and collect all tags they have.
1461 memset(&sent_tips, 0, sizeof(sent_tips));
1462 for (ref = *dst; ref; ref = ref->next) {
1463 if (ref->peer_ref &&
1464 !is_null_oid(&ref->peer_ref->new_oid))
1465 add_to_tips(&sent_tips, &ref->peer_ref->new_oid);
1466 else
1467 add_to_tips(&sent_tips, &ref->old_oid);
1468 if (starts_with(ref->name, "refs/tags/"))
1469 string_list_append(&dst_tag, ref->name);
1471 clear_commit_marks_many(sent_tips.nr, sent_tips.tip, TMP_MARK);
1473 string_list_sort(&dst_tag);
1475 /* Collect tags they do not have. */
1476 for (ref = src; ref; ref = ref->next) {
1477 if (!starts_with(ref->name, "refs/tags/"))
1478 continue; /* not a tag */
1479 if (string_list_has_string(&dst_tag, ref->name))
1480 continue; /* they already have it */
1481 if (oid_object_info(the_repository, &ref->new_oid, NULL) != OBJ_TAG)
1482 continue; /* be conservative */
1483 item = string_list_append(&src_tag, ref->name);
1484 item->util = ref;
1486 string_list_clear(&dst_tag, 0);
1489 * At this point, src_tag lists tags that are missing from
1490 * dst, and sent_tips lists the tips we are pushing or those
1491 * that we know they already have. An element in the src_tag
1492 * that is an ancestor of any of the sent_tips needs to be
1493 * sent to the other side.
1495 if (sent_tips.nr) {
1496 const int reachable_flag = 1;
1497 struct commit_list *found_commits;
1498 struct commit **src_commits;
1499 int nr_src_commits = 0, alloc_src_commits = 16;
1500 ALLOC_ARRAY(src_commits, alloc_src_commits);
1502 for_each_string_list_item(item, &src_tag) {
1503 struct ref *ref = item->util;
1504 struct commit *commit;
1506 if (is_null_oid(&ref->new_oid))
1507 continue;
1508 commit = lookup_commit_reference_gently(the_repository,
1509 &ref->new_oid,
1511 if (!commit)
1512 /* not pushing a commit, which is not an error */
1513 continue;
1515 ALLOC_GROW(src_commits, nr_src_commits + 1, alloc_src_commits);
1516 src_commits[nr_src_commits++] = commit;
1519 found_commits = get_reachable_subset(sent_tips.tip, sent_tips.nr,
1520 src_commits, nr_src_commits,
1521 reachable_flag);
1523 for_each_string_list_item(item, &src_tag) {
1524 struct ref *dst_ref;
1525 struct ref *ref = item->util;
1526 struct commit *commit;
1528 if (is_null_oid(&ref->new_oid))
1529 continue;
1530 commit = lookup_commit_reference_gently(the_repository,
1531 &ref->new_oid,
1533 if (!commit)
1534 /* not pushing a commit, which is not an error */
1535 continue;
1538 * Is this tag, which they do not have, reachable from
1539 * any of the commits we are sending?
1541 if (!(commit->object.flags & reachable_flag))
1542 continue;
1544 /* Add it in */
1545 dst_ref = make_linked_ref(ref->name, dst_tail);
1546 oidcpy(&dst_ref->new_oid, &ref->new_oid);
1547 dst_ref->peer_ref = copy_ref(ref);
1550 clear_commit_marks_many(nr_src_commits, src_commits, reachable_flag);
1551 free(src_commits);
1552 free_commit_list(found_commits);
1555 string_list_clear(&src_tag, 0);
1556 free(sent_tips.tip);
1559 struct ref *find_ref_by_name(const struct ref *list, const char *name)
1561 for ( ; list; list = list->next)
1562 if (!strcmp(list->name, name))
1563 return (struct ref *)list;
1564 return NULL;
1567 static void prepare_ref_index(struct string_list *ref_index, struct ref *ref)
1569 for ( ; ref; ref = ref->next)
1570 string_list_append_nodup(ref_index, ref->name)->util = ref;
1572 string_list_sort(ref_index);
1576 * Given only the set of local refs, sanity-check the set of push
1577 * refspecs. We can't catch all errors that match_push_refs would,
1578 * but we can catch some errors early before even talking to the
1579 * remote side.
1581 int check_push_refs(struct ref *src, struct refspec *rs)
1583 int ret = 0;
1584 int i;
1586 for (i = 0; i < rs->nr; i++) {
1587 struct refspec_item *item = &rs->items[i];
1589 if (item->pattern || item->matching || item->negative)
1590 continue;
1592 ret |= match_explicit_lhs(src, item, NULL, NULL);
1595 return ret;
1599 * Given the set of refs the local repository has, the set of refs the
1600 * remote repository has, and the refspec used for push, determine
1601 * what remote refs we will update and with what value by setting
1602 * peer_ref (which object is being pushed) and force (if the push is
1603 * forced) in elements of "dst". The function may add new elements to
1604 * dst (e.g. pushing to a new branch, done in match_explicit_refs).
1606 int match_push_refs(struct ref *src, struct ref **dst,
1607 struct refspec *rs, int flags)
1609 int send_all = flags & MATCH_REFS_ALL;
1610 int send_mirror = flags & MATCH_REFS_MIRROR;
1611 int send_prune = flags & MATCH_REFS_PRUNE;
1612 int errs;
1613 struct ref *ref, **dst_tail = tail_ref(dst);
1614 struct string_list dst_ref_index = STRING_LIST_INIT_NODUP;
1616 /* If no refspec is provided, use the default ":" */
1617 if (!rs->nr)
1618 refspec_append(rs, ":");
1620 errs = match_explicit_refs(src, *dst, &dst_tail, rs);
1622 /* pick the remainder */
1623 for (ref = src; ref; ref = ref->next) {
1624 struct string_list_item *dst_item;
1625 struct ref *dst_peer;
1626 const struct refspec_item *pat = NULL;
1627 char *dst_name;
1629 dst_name = get_ref_match(rs, ref, send_mirror, FROM_SRC, &pat);
1630 if (!dst_name)
1631 continue;
1633 if (!dst_ref_index.nr)
1634 prepare_ref_index(&dst_ref_index, *dst);
1636 dst_item = string_list_lookup(&dst_ref_index, dst_name);
1637 dst_peer = dst_item ? dst_item->util : NULL;
1638 if (dst_peer) {
1639 if (dst_peer->peer_ref)
1640 /* We're already sending something to this ref. */
1641 goto free_name;
1642 } else {
1643 if (pat->matching && !(send_all || send_mirror))
1645 * Remote doesn't have it, and we have no
1646 * explicit pattern, and we don't have
1647 * --all or --mirror.
1649 goto free_name;
1651 /* Create a new one and link it */
1652 dst_peer = make_linked_ref(dst_name, &dst_tail);
1653 oidcpy(&dst_peer->new_oid, &ref->new_oid);
1654 string_list_insert(&dst_ref_index,
1655 dst_peer->name)->util = dst_peer;
1657 dst_peer->peer_ref = copy_ref(ref);
1658 dst_peer->force = pat->force;
1659 free_name:
1660 free(dst_name);
1663 string_list_clear(&dst_ref_index, 0);
1665 if (flags & MATCH_REFS_FOLLOW_TAGS)
1666 add_missing_tags(src, dst, &dst_tail);
1668 if (send_prune) {
1669 struct string_list src_ref_index = STRING_LIST_INIT_NODUP;
1670 /* check for missing refs on the remote */
1671 for (ref = *dst; ref; ref = ref->next) {
1672 char *src_name;
1674 if (ref->peer_ref)
1675 /* We're already sending something to this ref. */
1676 continue;
1678 src_name = get_ref_match(rs, ref, send_mirror, FROM_DST, NULL);
1679 if (src_name) {
1680 if (!src_ref_index.nr)
1681 prepare_ref_index(&src_ref_index, src);
1682 if (!string_list_has_string(&src_ref_index,
1683 src_name))
1684 ref->peer_ref = alloc_delete_ref();
1685 free(src_name);
1688 string_list_clear(&src_ref_index, 0);
1691 *dst = apply_negative_refspecs(*dst, rs);
1693 if (errs)
1694 return -1;
1695 return 0;
1698 void set_ref_status_for_push(struct ref *remote_refs, int send_mirror,
1699 int force_update)
1701 struct ref *ref;
1703 for (ref = remote_refs; ref; ref = ref->next) {
1704 int force_ref_update = ref->force || force_update;
1705 int reject_reason = 0;
1707 if (ref->peer_ref)
1708 oidcpy(&ref->new_oid, &ref->peer_ref->new_oid);
1709 else if (!send_mirror)
1710 continue;
1712 ref->deletion = is_null_oid(&ref->new_oid);
1713 if (!ref->deletion &&
1714 oideq(&ref->old_oid, &ref->new_oid)) {
1715 ref->status = REF_STATUS_UPTODATE;
1716 continue;
1720 * If the remote ref has moved and is now different
1721 * from what we expect, reject any push.
1723 * It also is an error if the user told us to check
1724 * with the remote-tracking branch to find the value
1725 * to expect, but we did not have such a tracking
1726 * branch.
1728 * If the tip of the remote-tracking ref is unreachable
1729 * from any reflog entry of its local ref indicating a
1730 * possible update since checkout; reject the push.
1732 if (ref->expect_old_sha1) {
1733 if (!oideq(&ref->old_oid, &ref->old_oid_expect))
1734 reject_reason = REF_STATUS_REJECT_STALE;
1735 else if (ref->check_reachable && ref->unreachable)
1736 reject_reason =
1737 REF_STATUS_REJECT_REMOTE_UPDATED;
1738 else
1740 * If the ref isn't stale, and is reachable
1741 * from one of the reflog entries of
1742 * the local branch, force the update.
1744 force_ref_update = 1;
1748 * If the update isn't already rejected then check
1749 * the usual "must fast-forward" rules.
1751 * Decide whether an individual refspec A:B can be
1752 * pushed. The push will succeed if any of the
1753 * following are true:
1755 * (1) the remote reference B does not exist
1757 * (2) the remote reference B is being removed (i.e.,
1758 * pushing :B where no source is specified)
1760 * (3) the destination is not under refs/tags/, and
1761 * if the old and new value is a commit, the new
1762 * is a descendant of the old.
1764 * (4) it is forced using the +A:B notation, or by
1765 * passing the --force argument
1768 if (!reject_reason && !ref->deletion && !is_null_oid(&ref->old_oid)) {
1769 if (starts_with(ref->name, "refs/tags/"))
1770 reject_reason = REF_STATUS_REJECT_ALREADY_EXISTS;
1771 else if (!repo_has_object_file(the_repository, &ref->old_oid))
1772 reject_reason = REF_STATUS_REJECT_FETCH_FIRST;
1773 else if (!lookup_commit_reference_gently(the_repository, &ref->old_oid, 1) ||
1774 !lookup_commit_reference_gently(the_repository, &ref->new_oid, 1))
1775 reject_reason = REF_STATUS_REJECT_NEEDS_FORCE;
1776 else if (!ref_newer(&ref->new_oid, &ref->old_oid))
1777 reject_reason = REF_STATUS_REJECT_NONFASTFORWARD;
1781 * "--force" will defeat any rejection implemented
1782 * by the rules above.
1784 if (!force_ref_update)
1785 ref->status = reject_reason;
1786 else if (reject_reason)
1787 ref->forced_update = 1;
1791 static void set_merge(struct remote_state *remote_state, struct branch *ret)
1793 struct remote *remote;
1794 char *ref;
1795 struct object_id oid;
1796 int i;
1798 if (!ret)
1799 return; /* no branch */
1800 if (ret->merge)
1801 return; /* already run */
1802 if (!ret->remote_name || !ret->merge_nr) {
1804 * no merge config; let's make sure we don't confuse callers
1805 * with a non-zero merge_nr but a NULL merge
1807 ret->merge_nr = 0;
1808 return;
1811 remote = remotes_remote_get(remote_state, ret->remote_name);
1813 CALLOC_ARRAY(ret->merge, ret->merge_nr);
1814 for (i = 0; i < ret->merge_nr; i++) {
1815 ret->merge[i] = xcalloc(1, sizeof(**ret->merge));
1816 ret->merge[i]->src = xstrdup(ret->merge_name[i]);
1817 if (!remote_find_tracking(remote, ret->merge[i]) ||
1818 strcmp(ret->remote_name, "."))
1819 continue;
1820 if (repo_dwim_ref(the_repository, ret->merge_name[i],
1821 strlen(ret->merge_name[i]), &oid, &ref,
1822 0) == 1)
1823 ret->merge[i]->dst = ref;
1824 else
1825 ret->merge[i]->dst = xstrdup(ret->merge_name[i]);
1829 struct branch *branch_get(const char *name)
1831 struct branch *ret;
1833 read_config(the_repository);
1834 if (!name || !*name || !strcmp(name, "HEAD"))
1835 ret = the_repository->remote_state->current_branch;
1836 else
1837 ret = make_branch(the_repository->remote_state, name,
1838 strlen(name));
1839 set_merge(the_repository->remote_state, ret);
1840 return ret;
1843 int branch_has_merge_config(struct branch *branch)
1845 return branch && !!branch->merge;
1848 int branch_merge_matches(struct branch *branch,
1849 int i,
1850 const char *refname)
1852 if (!branch || i < 0 || i >= branch->merge_nr)
1853 return 0;
1854 return refname_match(branch->merge[i]->src, refname);
1857 __attribute__((format (printf,2,3)))
1858 static const char *error_buf(struct strbuf *err, const char *fmt, ...)
1860 if (err) {
1861 va_list ap;
1862 va_start(ap, fmt);
1863 strbuf_vaddf(err, fmt, ap);
1864 va_end(ap);
1866 return NULL;
1869 const char *branch_get_upstream(struct branch *branch, struct strbuf *err)
1871 if (!branch)
1872 return error_buf(err, _("HEAD does not point to a branch"));
1874 if (!branch->merge || !branch->merge[0]) {
1876 * no merge config; is it because the user didn't define any,
1877 * or because it is not a real branch, and get_branch
1878 * auto-vivified it?
1880 if (!ref_exists(branch->refname))
1881 return error_buf(err, _("no such branch: '%s'"),
1882 branch->name);
1883 return error_buf(err,
1884 _("no upstream configured for branch '%s'"),
1885 branch->name);
1888 if (!branch->merge[0]->dst)
1889 return error_buf(err,
1890 _("upstream branch '%s' not stored as a remote-tracking branch"),
1891 branch->merge[0]->src);
1893 return branch->merge[0]->dst;
1896 static const char *tracking_for_push_dest(struct remote *remote,
1897 const char *refname,
1898 struct strbuf *err)
1900 char *ret;
1902 ret = apply_refspecs(&remote->fetch, refname);
1903 if (!ret)
1904 return error_buf(err,
1905 _("push destination '%s' on remote '%s' has no local tracking branch"),
1906 refname, remote->name);
1907 return ret;
1910 static const char *branch_get_push_1(struct remote_state *remote_state,
1911 struct branch *branch, struct strbuf *err)
1913 struct remote *remote;
1915 remote = remotes_remote_get(
1916 remote_state,
1917 remotes_pushremote_for_branch(remote_state, branch, NULL));
1918 if (!remote)
1919 return error_buf(err,
1920 _("branch '%s' has no remote for pushing"),
1921 branch->name);
1923 if (remote->push.nr) {
1924 char *dst;
1925 const char *ret;
1927 dst = apply_refspecs(&remote->push, branch->refname);
1928 if (!dst)
1929 return error_buf(err,
1930 _("push refspecs for '%s' do not include '%s'"),
1931 remote->name, branch->name);
1933 ret = tracking_for_push_dest(remote, dst, err);
1934 free(dst);
1935 return ret;
1938 if (remote->mirror)
1939 return tracking_for_push_dest(remote, branch->refname, err);
1941 switch (push_default) {
1942 case PUSH_DEFAULT_NOTHING:
1943 return error_buf(err, _("push has no destination (push.default is 'nothing')"));
1945 case PUSH_DEFAULT_MATCHING:
1946 case PUSH_DEFAULT_CURRENT:
1947 return tracking_for_push_dest(remote, branch->refname, err);
1949 case PUSH_DEFAULT_UPSTREAM:
1950 return branch_get_upstream(branch, err);
1952 case PUSH_DEFAULT_UNSPECIFIED:
1953 case PUSH_DEFAULT_SIMPLE:
1955 const char *up, *cur;
1957 up = branch_get_upstream(branch, err);
1958 if (!up)
1959 return NULL;
1960 cur = tracking_for_push_dest(remote, branch->refname, err);
1961 if (!cur)
1962 return NULL;
1963 if (strcmp(cur, up))
1964 return error_buf(err,
1965 _("cannot resolve 'simple' push to a single destination"));
1966 return cur;
1970 BUG("unhandled push situation");
1973 const char *branch_get_push(struct branch *branch, struct strbuf *err)
1975 read_config(the_repository);
1976 die_on_missing_branch(the_repository, branch);
1978 if (!branch)
1979 return error_buf(err, _("HEAD does not point to a branch"));
1981 if (!branch->push_tracking_ref)
1982 branch->push_tracking_ref = branch_get_push_1(
1983 the_repository->remote_state, branch, err);
1984 return branch->push_tracking_ref;
1987 static int ignore_symref_update(const char *refname, struct strbuf *scratch)
1989 return !refs_read_symbolic_ref(get_main_ref_store(the_repository), refname, scratch);
1993 * Create and return a list of (struct ref) consisting of copies of
1994 * each remote_ref that matches refspec. refspec must be a pattern.
1995 * Fill in the copies' peer_ref to describe the local tracking refs to
1996 * which they map. Omit any references that would map to an existing
1997 * local symbolic ref.
1999 static struct ref *get_expanded_map(const struct ref *remote_refs,
2000 const struct refspec_item *refspec)
2002 struct strbuf scratch = STRBUF_INIT;
2003 const struct ref *ref;
2004 struct ref *ret = NULL;
2005 struct ref **tail = &ret;
2007 for (ref = remote_refs; ref; ref = ref->next) {
2008 char *expn_name = NULL;
2010 strbuf_reset(&scratch);
2012 if (strchr(ref->name, '^'))
2013 continue; /* a dereference item */
2014 if (match_name_with_pattern(refspec->src, ref->name,
2015 refspec->dst, &expn_name) &&
2016 !ignore_symref_update(expn_name, &scratch)) {
2017 struct ref *cpy = copy_ref(ref);
2019 cpy->peer_ref = alloc_ref(expn_name);
2020 if (refspec->force)
2021 cpy->peer_ref->force = 1;
2022 *tail = cpy;
2023 tail = &cpy->next;
2025 free(expn_name);
2028 strbuf_release(&scratch);
2029 return ret;
2032 static const struct ref *find_ref_by_name_abbrev(const struct ref *refs, const char *name)
2034 const struct ref *ref;
2035 const struct ref *best_match = NULL;
2036 int best_score = 0;
2038 for (ref = refs; ref; ref = ref->next) {
2039 int score = refname_match(name, ref->name);
2041 if (best_score < score) {
2042 best_match = ref;
2043 best_score = score;
2046 return best_match;
2049 struct ref *get_remote_ref(const struct ref *remote_refs, const char *name)
2051 const struct ref *ref = find_ref_by_name_abbrev(remote_refs, name);
2053 if (!ref)
2054 return NULL;
2056 return copy_ref(ref);
2059 static struct ref *get_local_ref(const char *name)
2061 if (!name || name[0] == '\0')
2062 return NULL;
2064 if (starts_with(name, "refs/"))
2065 return alloc_ref(name);
2067 if (starts_with(name, "heads/") ||
2068 starts_with(name, "tags/") ||
2069 starts_with(name, "remotes/"))
2070 return alloc_ref_with_prefix("refs/", 5, name);
2072 return alloc_ref_with_prefix("refs/heads/", 11, name);
2075 int get_fetch_map(const struct ref *remote_refs,
2076 const struct refspec_item *refspec,
2077 struct ref ***tail,
2078 int missing_ok)
2080 struct ref *ref_map, **rmp;
2082 if (refspec->negative)
2083 return 0;
2085 if (refspec->pattern) {
2086 ref_map = get_expanded_map(remote_refs, refspec);
2087 } else {
2088 const char *name = refspec->src[0] ? refspec->src : "HEAD";
2090 if (refspec->exact_sha1) {
2091 ref_map = alloc_ref(name);
2092 get_oid_hex(name, &ref_map->old_oid);
2093 ref_map->exact_oid = 1;
2094 } else {
2095 ref_map = get_remote_ref(remote_refs, name);
2097 if (!missing_ok && !ref_map)
2098 die(_("couldn't find remote ref %s"), name);
2099 if (ref_map) {
2100 ref_map->peer_ref = get_local_ref(refspec->dst);
2101 if (ref_map->peer_ref && refspec->force)
2102 ref_map->peer_ref->force = 1;
2106 for (rmp = &ref_map; *rmp; ) {
2107 if ((*rmp)->peer_ref) {
2108 if (!starts_with((*rmp)->peer_ref->name, "refs/") ||
2109 check_refname_format((*rmp)->peer_ref->name, 0)) {
2110 struct ref *ignore = *rmp;
2111 error(_("* Ignoring funny ref '%s' locally"),
2112 (*rmp)->peer_ref->name);
2113 *rmp = (*rmp)->next;
2114 free(ignore->peer_ref);
2115 free(ignore);
2116 continue;
2119 rmp = &((*rmp)->next);
2122 if (ref_map)
2123 tail_link_ref(ref_map, tail);
2125 return 0;
2128 int resolve_remote_symref(struct ref *ref, struct ref *list)
2130 if (!ref->symref)
2131 return 0;
2132 for (; list; list = list->next)
2133 if (!strcmp(ref->symref, list->name)) {
2134 oidcpy(&ref->old_oid, &list->old_oid);
2135 return 0;
2137 return 1;
2141 * Compute the commit ahead/behind values for the pair branch_name, base.
2143 * If abf is AHEAD_BEHIND_FULL, compute the full ahead/behind and return the
2144 * counts in *num_ours and *num_theirs. If abf is AHEAD_BEHIND_QUICK, skip
2145 * the (potentially expensive) a/b computation (*num_ours and *num_theirs are
2146 * set to zero).
2148 * Returns -1 if num_ours and num_theirs could not be filled in (e.g., ref
2149 * does not exist). Returns 0 if the commits are identical. Returns 1 if
2150 * commits are different.
2153 static int stat_branch_pair(const char *branch_name, const char *base,
2154 int *num_ours, int *num_theirs,
2155 enum ahead_behind_flags abf)
2157 struct object_id oid;
2158 struct commit *ours, *theirs;
2159 struct rev_info revs;
2160 struct setup_revision_opt opt = {
2161 .free_removed_argv_elements = 1,
2163 struct strvec argv = STRVEC_INIT;
2165 /* Cannot stat if what we used to build on no longer exists */
2166 if (read_ref(base, &oid))
2167 return -1;
2168 theirs = lookup_commit_reference(the_repository, &oid);
2169 if (!theirs)
2170 return -1;
2172 if (read_ref(branch_name, &oid))
2173 return -1;
2174 ours = lookup_commit_reference(the_repository, &oid);
2175 if (!ours)
2176 return -1;
2178 *num_theirs = *num_ours = 0;
2180 /* are we the same? */
2181 if (theirs == ours)
2182 return 0;
2183 if (abf == AHEAD_BEHIND_QUICK)
2184 return 1;
2185 if (abf != AHEAD_BEHIND_FULL)
2186 BUG("stat_branch_pair: invalid abf '%d'", abf);
2188 /* Run "rev-list --left-right ours...theirs" internally... */
2189 strvec_push(&argv, ""); /* ignored */
2190 strvec_push(&argv, "--left-right");
2191 strvec_pushf(&argv, "%s...%s",
2192 oid_to_hex(&ours->object.oid),
2193 oid_to_hex(&theirs->object.oid));
2194 strvec_push(&argv, "--");
2196 repo_init_revisions(the_repository, &revs, NULL);
2197 setup_revisions(argv.nr, argv.v, &revs, &opt);
2198 if (prepare_revision_walk(&revs))
2199 die(_("revision walk setup failed"));
2201 /* ... and count the commits on each side. */
2202 while (1) {
2203 struct commit *c = get_revision(&revs);
2204 if (!c)
2205 break;
2206 if (c->object.flags & SYMMETRIC_LEFT)
2207 (*num_ours)++;
2208 else
2209 (*num_theirs)++;
2212 /* clear object flags smudged by the above traversal */
2213 clear_commit_marks(ours, ALL_REV_FLAGS);
2214 clear_commit_marks(theirs, ALL_REV_FLAGS);
2216 strvec_clear(&argv);
2217 release_revisions(&revs);
2218 return 1;
2222 * Lookup the tracking branch for the given branch and if present, optionally
2223 * compute the commit ahead/behind values for the pair.
2225 * If for_push is true, the tracking branch refers to the push branch,
2226 * otherwise it refers to the upstream branch.
2228 * The name of the tracking branch (or NULL if it is not defined) is
2229 * returned via *tracking_name, if it is not itself NULL.
2231 * If abf is AHEAD_BEHIND_FULL, compute the full ahead/behind and return the
2232 * counts in *num_ours and *num_theirs. If abf is AHEAD_BEHIND_QUICK, skip
2233 * the (potentially expensive) a/b computation (*num_ours and *num_theirs are
2234 * set to zero).
2236 * Returns -1 if num_ours and num_theirs could not be filled in (e.g., no
2237 * upstream defined, or ref does not exist). Returns 0 if the commits are
2238 * identical. Returns 1 if commits are different.
2240 int stat_tracking_info(struct branch *branch, int *num_ours, int *num_theirs,
2241 const char **tracking_name, int for_push,
2242 enum ahead_behind_flags abf)
2244 const char *base;
2246 /* Cannot stat unless we are marked to build on top of somebody else. */
2247 base = for_push ? branch_get_push(branch, NULL) :
2248 branch_get_upstream(branch, NULL);
2249 if (tracking_name)
2250 *tracking_name = base;
2251 if (!base)
2252 return -1;
2254 return stat_branch_pair(branch->refname, base, num_ours, num_theirs, abf);
2258 * Return true when there is anything to report, otherwise false.
2260 int format_tracking_info(struct branch *branch, struct strbuf *sb,
2261 enum ahead_behind_flags abf,
2262 int show_divergence_advice)
2264 int ours, theirs, sti;
2265 const char *full_base;
2266 char *base;
2267 int upstream_is_gone = 0;
2269 sti = stat_tracking_info(branch, &ours, &theirs, &full_base, 0, abf);
2270 if (sti < 0) {
2271 if (!full_base)
2272 return 0;
2273 upstream_is_gone = 1;
2276 base = shorten_unambiguous_ref(full_base, 0);
2277 if (upstream_is_gone) {
2278 strbuf_addf(sb,
2279 _("Your branch is based on '%s', but the upstream is gone.\n"),
2280 base);
2281 if (advice_enabled(ADVICE_STATUS_HINTS))
2282 strbuf_addstr(sb,
2283 _(" (use \"git branch --unset-upstream\" to fixup)\n"));
2284 } else if (!sti) {
2285 strbuf_addf(sb,
2286 _("Your branch is up to date with '%s'.\n"),
2287 base);
2288 } else if (abf == AHEAD_BEHIND_QUICK) {
2289 strbuf_addf(sb,
2290 _("Your branch and '%s' refer to different commits.\n"),
2291 base);
2292 if (advice_enabled(ADVICE_STATUS_HINTS))
2293 strbuf_addf(sb, _(" (use \"%s\" for details)\n"),
2294 "git status --ahead-behind");
2295 } else if (!theirs) {
2296 strbuf_addf(sb,
2297 Q_("Your branch is ahead of '%s' by %d commit.\n",
2298 "Your branch is ahead of '%s' by %d commits.\n",
2299 ours),
2300 base, ours);
2301 if (advice_enabled(ADVICE_STATUS_HINTS))
2302 strbuf_addstr(sb,
2303 _(" (use \"git push\" to publish your local commits)\n"));
2304 } else if (!ours) {
2305 strbuf_addf(sb,
2306 Q_("Your branch is behind '%s' by %d commit, "
2307 "and can be fast-forwarded.\n",
2308 "Your branch is behind '%s' by %d commits, "
2309 "and can be fast-forwarded.\n",
2310 theirs),
2311 base, theirs);
2312 if (advice_enabled(ADVICE_STATUS_HINTS))
2313 strbuf_addstr(sb,
2314 _(" (use \"git pull\" to update your local branch)\n"));
2315 } else {
2316 strbuf_addf(sb,
2317 Q_("Your branch and '%s' have diverged,\n"
2318 "and have %d and %d different commit each, "
2319 "respectively.\n",
2320 "Your branch and '%s' have diverged,\n"
2321 "and have %d and %d different commits each, "
2322 "respectively.\n",
2323 ours + theirs),
2324 base, ours, theirs);
2325 if (show_divergence_advice &&
2326 advice_enabled(ADVICE_STATUS_HINTS))
2327 strbuf_addstr(sb,
2328 _(" (use \"git pull\" if you want to integrate the remote branch with yours)\n"));
2330 free(base);
2331 return 1;
2334 static int one_local_ref(const char *refname, const struct object_id *oid,
2335 int flag UNUSED,
2336 void *cb_data)
2338 struct ref ***local_tail = cb_data;
2339 struct ref *ref;
2341 /* we already know it starts with refs/ to get here */
2342 if (check_refname_format(refname + 5, 0))
2343 return 0;
2345 ref = alloc_ref(refname);
2346 oidcpy(&ref->new_oid, oid);
2347 **local_tail = ref;
2348 *local_tail = &ref->next;
2349 return 0;
2352 struct ref *get_local_heads(void)
2354 struct ref *local_refs = NULL, **local_tail = &local_refs;
2356 for_each_ref(one_local_ref, &local_tail);
2357 return local_refs;
2360 struct ref *guess_remote_head(const struct ref *head,
2361 const struct ref *refs,
2362 int all)
2364 const struct ref *r;
2365 struct ref *list = NULL;
2366 struct ref **tail = &list;
2368 if (!head)
2369 return NULL;
2372 * Some transports support directly peeking at
2373 * where HEAD points; if that is the case, then
2374 * we don't have to guess.
2376 if (head->symref)
2377 return copy_ref(find_ref_by_name(refs, head->symref));
2379 /* If a remote branch exists with the default branch name, let's use it. */
2380 if (!all) {
2381 char *ref = xstrfmt("refs/heads/%s",
2382 git_default_branch_name(0));
2384 r = find_ref_by_name(refs, ref);
2385 free(ref);
2386 if (r && oideq(&r->old_oid, &head->old_oid))
2387 return copy_ref(r);
2389 /* Fall back to the hard-coded historical default */
2390 r = find_ref_by_name(refs, "refs/heads/master");
2391 if (r && oideq(&r->old_oid, &head->old_oid))
2392 return copy_ref(r);
2395 /* Look for another ref that points there */
2396 for (r = refs; r; r = r->next) {
2397 if (r != head &&
2398 starts_with(r->name, "refs/heads/") &&
2399 oideq(&r->old_oid, &head->old_oid)) {
2400 *tail = copy_ref(r);
2401 tail = &((*tail)->next);
2402 if (!all)
2403 break;
2407 return list;
2410 struct stale_heads_info {
2411 struct string_list *ref_names;
2412 struct ref **stale_refs_tail;
2413 struct refspec *rs;
2416 static int get_stale_heads_cb(const char *refname, const struct object_id *oid,
2417 int flags, void *cb_data)
2419 struct stale_heads_info *info = cb_data;
2420 struct string_list matches = STRING_LIST_INIT_DUP;
2421 struct refspec_item query;
2422 int i, stale = 1;
2423 memset(&query, 0, sizeof(struct refspec_item));
2424 query.dst = (char *)refname;
2426 query_refspecs_multiple(info->rs, &query, &matches);
2427 if (matches.nr == 0)
2428 goto clean_exit; /* No matches */
2431 * If we did find a suitable refspec and it's not a symref and
2432 * it's not in the list of refs that currently exist in that
2433 * remote, we consider it to be stale. In order to deal with
2434 * overlapping refspecs, we need to go over all of the
2435 * matching refs.
2437 if (flags & REF_ISSYMREF)
2438 goto clean_exit;
2440 for (i = 0; stale && i < matches.nr; i++)
2441 if (string_list_has_string(info->ref_names, matches.items[i].string))
2442 stale = 0;
2444 if (stale) {
2445 struct ref *ref = make_linked_ref(refname, &info->stale_refs_tail);
2446 oidcpy(&ref->new_oid, oid);
2449 clean_exit:
2450 string_list_clear(&matches, 0);
2451 return 0;
2454 struct ref *get_stale_heads(struct refspec *rs, struct ref *fetch_map)
2456 struct ref *ref, *stale_refs = NULL;
2457 struct string_list ref_names = STRING_LIST_INIT_NODUP;
2458 struct stale_heads_info info;
2460 info.ref_names = &ref_names;
2461 info.stale_refs_tail = &stale_refs;
2462 info.rs = rs;
2463 for (ref = fetch_map; ref; ref = ref->next)
2464 string_list_append(&ref_names, ref->name);
2465 string_list_sort(&ref_names);
2466 for_each_ref(get_stale_heads_cb, &info);
2467 string_list_clear(&ref_names, 0);
2468 return stale_refs;
2472 * Compare-and-swap
2474 static void clear_cas_option(struct push_cas_option *cas)
2476 int i;
2478 for (i = 0; i < cas->nr; i++)
2479 free(cas->entry[i].refname);
2480 free(cas->entry);
2481 memset(cas, 0, sizeof(*cas));
2484 static struct push_cas *add_cas_entry(struct push_cas_option *cas,
2485 const char *refname,
2486 size_t refnamelen)
2488 struct push_cas *entry;
2489 ALLOC_GROW(cas->entry, cas->nr + 1, cas->alloc);
2490 entry = &cas->entry[cas->nr++];
2491 memset(entry, 0, sizeof(*entry));
2492 entry->refname = xmemdupz(refname, refnamelen);
2493 return entry;
2496 static int parse_push_cas_option(struct push_cas_option *cas, const char *arg, int unset)
2498 const char *colon;
2499 struct push_cas *entry;
2501 if (unset) {
2502 /* "--no-<option>" */
2503 clear_cas_option(cas);
2504 return 0;
2507 if (!arg) {
2508 /* just "--<option>" */
2509 cas->use_tracking_for_rest = 1;
2510 return 0;
2513 /* "--<option>=refname" or "--<option>=refname:value" */
2514 colon = strchrnul(arg, ':');
2515 entry = add_cas_entry(cas, arg, colon - arg);
2516 if (!*colon)
2517 entry->use_tracking = 1;
2518 else if (!colon[1])
2519 oidclr(&entry->expect);
2520 else if (repo_get_oid(the_repository, colon + 1, &entry->expect))
2521 return error(_("cannot parse expected object name '%s'"),
2522 colon + 1);
2523 return 0;
2526 int parseopt_push_cas_option(const struct option *opt, const char *arg, int unset)
2528 return parse_push_cas_option(opt->value, arg, unset);
2531 int is_empty_cas(const struct push_cas_option *cas)
2533 return !cas->use_tracking_for_rest && !cas->nr;
2537 * Look at remote.fetch refspec and see if we have a remote
2538 * tracking branch for the refname there. Fill the name of
2539 * the remote-tracking branch in *dst_refname, and the name
2540 * of the commit object at its tip in oid[].
2541 * If we cannot do so, return negative to signal an error.
2543 static int remote_tracking(struct remote *remote, const char *refname,
2544 struct object_id *oid, char **dst_refname)
2546 char *dst;
2548 dst = apply_refspecs(&remote->fetch, refname);
2549 if (!dst)
2550 return -1; /* no tracking ref for refname at remote */
2551 if (read_ref(dst, oid))
2552 return -1; /* we know what the tracking ref is but we cannot read it */
2554 *dst_refname = dst;
2555 return 0;
2559 * The struct "reflog_commit_array" and related helper functions
2560 * are used for collecting commits into an array during reflog
2561 * traversals in "check_and_collect_until()".
2563 struct reflog_commit_array {
2564 struct commit **item;
2565 size_t nr, alloc;
2568 #define REFLOG_COMMIT_ARRAY_INIT { 0 }
2570 /* Append a commit to the array. */
2571 static void append_commit(struct reflog_commit_array *arr,
2572 struct commit *commit)
2574 ALLOC_GROW(arr->item, arr->nr + 1, arr->alloc);
2575 arr->item[arr->nr++] = commit;
2578 /* Free and reset the array. */
2579 static void free_commit_array(struct reflog_commit_array *arr)
2581 FREE_AND_NULL(arr->item);
2582 arr->nr = arr->alloc = 0;
2585 struct check_and_collect_until_cb_data {
2586 struct commit *remote_commit;
2587 struct reflog_commit_array *local_commits;
2588 timestamp_t remote_reflog_timestamp;
2591 /* Get the timestamp of the latest entry. */
2592 static int peek_reflog(struct object_id *o_oid UNUSED,
2593 struct object_id *n_oid UNUSED,
2594 const char *ident UNUSED,
2595 timestamp_t timestamp, int tz UNUSED,
2596 const char *message UNUSED, void *cb_data)
2598 timestamp_t *ts = cb_data;
2599 *ts = timestamp;
2600 return 1;
2603 static int check_and_collect_until(struct object_id *o_oid UNUSED,
2604 struct object_id *n_oid,
2605 const char *ident UNUSED,
2606 timestamp_t timestamp, int tz UNUSED,
2607 const char *message UNUSED, void *cb_data)
2609 struct commit *commit;
2610 struct check_and_collect_until_cb_data *cb = cb_data;
2612 /* An entry was found. */
2613 if (oideq(n_oid, &cb->remote_commit->object.oid))
2614 return 1;
2616 if ((commit = lookup_commit_reference(the_repository, n_oid)))
2617 append_commit(cb->local_commits, commit);
2620 * If the reflog entry timestamp is older than the remote ref's
2621 * latest reflog entry, there is no need to check or collect
2622 * entries older than this one.
2624 if (timestamp < cb->remote_reflog_timestamp)
2625 return -1;
2627 return 0;
2630 #define MERGE_BASES_BATCH_SIZE 8
2633 * Iterate through the reflog of the local ref to check if there is an entry
2634 * for the given remote-tracking ref; runs until the timestamp of an entry is
2635 * older than latest timestamp of remote-tracking ref's reflog. Any commits
2636 * are that seen along the way are collected into an array to check if the
2637 * remote-tracking ref is reachable from any of them.
2639 static int is_reachable_in_reflog(const char *local, const struct ref *remote)
2641 timestamp_t date;
2642 struct commit *commit;
2643 struct commit **chunk;
2644 struct check_and_collect_until_cb_data cb;
2645 struct reflog_commit_array arr = REFLOG_COMMIT_ARRAY_INIT;
2646 size_t size = 0;
2647 int ret = 0;
2649 commit = lookup_commit_reference(the_repository, &remote->old_oid);
2650 if (!commit)
2651 goto cleanup_return;
2654 * Get the timestamp from the latest entry
2655 * of the remote-tracking ref's reflog.
2657 for_each_reflog_ent_reverse(remote->tracking_ref, peek_reflog, &date);
2659 cb.remote_commit = commit;
2660 cb.local_commits = &arr;
2661 cb.remote_reflog_timestamp = date;
2662 ret = for_each_reflog_ent_reverse(local, check_and_collect_until, &cb);
2664 /* We found an entry in the reflog. */
2665 if (ret > 0)
2666 goto cleanup_return;
2669 * Check if the remote commit is reachable from any
2670 * of the commits in the collected array, in batches.
2672 for (chunk = arr.item; chunk < arr.item + arr.nr; chunk += size) {
2673 size = arr.item + arr.nr - chunk;
2674 if (MERGE_BASES_BATCH_SIZE < size)
2675 size = MERGE_BASES_BATCH_SIZE;
2677 if ((ret = repo_in_merge_bases_many(the_repository, commit, size, chunk)))
2678 break;
2681 cleanup_return:
2682 free_commit_array(&arr);
2683 return ret;
2687 * Check for reachability of a remote-tracking
2688 * ref in the reflog entries of its local ref.
2690 static void check_if_includes_upstream(struct ref *remote)
2692 struct ref *local = get_local_ref(remote->name);
2693 if (!local)
2694 return;
2696 if (is_reachable_in_reflog(local->name, remote) <= 0)
2697 remote->unreachable = 1;
2700 static void apply_cas(struct push_cas_option *cas,
2701 struct remote *remote,
2702 struct ref *ref)
2704 int i;
2706 /* Find an explicit --<option>=<name>[:<value>] entry */
2707 for (i = 0; i < cas->nr; i++) {
2708 struct push_cas *entry = &cas->entry[i];
2709 if (!refname_match(entry->refname, ref->name))
2710 continue;
2711 ref->expect_old_sha1 = 1;
2712 if (!entry->use_tracking)
2713 oidcpy(&ref->old_oid_expect, &entry->expect);
2714 else if (remote_tracking(remote, ref->name,
2715 &ref->old_oid_expect,
2716 &ref->tracking_ref))
2717 oidclr(&ref->old_oid_expect);
2718 else
2719 ref->check_reachable = cas->use_force_if_includes;
2720 return;
2723 /* Are we using "--<option>" to cover all? */
2724 if (!cas->use_tracking_for_rest)
2725 return;
2727 ref->expect_old_sha1 = 1;
2728 if (remote_tracking(remote, ref->name,
2729 &ref->old_oid_expect,
2730 &ref->tracking_ref))
2731 oidclr(&ref->old_oid_expect);
2732 else
2733 ref->check_reachable = cas->use_force_if_includes;
2736 void apply_push_cas(struct push_cas_option *cas,
2737 struct remote *remote,
2738 struct ref *remote_refs)
2740 struct ref *ref;
2741 for (ref = remote_refs; ref; ref = ref->next) {
2742 apply_cas(cas, remote, ref);
2745 * If "compare-and-swap" is in "use_tracking[_for_rest]"
2746 * mode, and if "--force-if-includes" was specified, run
2747 * the check.
2749 if (ref->check_reachable)
2750 check_if_includes_upstream(ref);
2754 struct remote_state *remote_state_new(void)
2756 struct remote_state *r = xmalloc(sizeof(*r));
2758 memset(r, 0, sizeof(*r));
2760 hashmap_init(&r->remotes_hash, remotes_hash_cmp, NULL, 0);
2761 hashmap_init(&r->branches_hash, branches_hash_cmp, NULL, 0);
2762 return r;
2765 void remote_state_clear(struct remote_state *remote_state)
2767 int i;
2769 for (i = 0; i < remote_state->remotes_nr; i++)
2770 remote_clear(remote_state->remotes[i]);
2771 FREE_AND_NULL(remote_state->remotes);
2772 remote_state->remotes_alloc = 0;
2773 remote_state->remotes_nr = 0;
2775 hashmap_clear_and_free(&remote_state->remotes_hash, struct remote, ent);
2776 hashmap_clear_and_free(&remote_state->branches_hash, struct remote, ent);
2780 * Returns 1 if it was the last chop before ':'.
2782 static int chop_last_dir(char **remoteurl, int is_relative)
2784 char *rfind = find_last_dir_sep(*remoteurl);
2785 if (rfind) {
2786 *rfind = '\0';
2787 return 0;
2790 rfind = strrchr(*remoteurl, ':');
2791 if (rfind) {
2792 *rfind = '\0';
2793 return 1;
2796 if (is_relative || !strcmp(".", *remoteurl))
2797 die(_("cannot strip one component off url '%s'"),
2798 *remoteurl);
2800 free(*remoteurl);
2801 *remoteurl = xstrdup(".");
2802 return 0;
2805 char *relative_url(const char *remote_url, const char *url,
2806 const char *up_path)
2808 int is_relative = 0;
2809 int colonsep = 0;
2810 char *out;
2811 char *remoteurl;
2812 struct strbuf sb = STRBUF_INIT;
2813 size_t len;
2815 if (!url_is_local_not_ssh(url) || is_absolute_path(url))
2816 return xstrdup(url);
2818 len = strlen(remote_url);
2819 if (!len)
2820 BUG("invalid empty remote_url");
2822 remoteurl = xstrdup(remote_url);
2823 if (is_dir_sep(remoteurl[len-1]))
2824 remoteurl[len-1] = '\0';
2826 if (!url_is_local_not_ssh(remoteurl) || is_absolute_path(remoteurl))
2827 is_relative = 0;
2828 else {
2829 is_relative = 1;
2831 * Prepend a './' to ensure all relative
2832 * remoteurls start with './' or '../'
2834 if (!starts_with_dot_slash_native(remoteurl) &&
2835 !starts_with_dot_dot_slash_native(remoteurl)) {
2836 strbuf_reset(&sb);
2837 strbuf_addf(&sb, "./%s", remoteurl);
2838 free(remoteurl);
2839 remoteurl = strbuf_detach(&sb, NULL);
2843 * When the url starts with '../', remove that and the
2844 * last directory in remoteurl.
2846 while (*url) {
2847 if (starts_with_dot_dot_slash_native(url)) {
2848 url += 3;
2849 colonsep |= chop_last_dir(&remoteurl, is_relative);
2850 } else if (starts_with_dot_slash_native(url))
2851 url += 2;
2852 else
2853 break;
2855 strbuf_reset(&sb);
2856 strbuf_addf(&sb, "%s%s%s", remoteurl, colonsep ? ":" : "/", url);
2857 if (ends_with(url, "/"))
2858 strbuf_setlen(&sb, sb.len - 1);
2859 free(remoteurl);
2861 if (starts_with_dot_slash_native(sb.buf))
2862 out = xstrdup(sb.buf + 2);
2863 else
2864 out = xstrdup(sb.buf);
2866 if (!up_path || !is_relative) {
2867 strbuf_release(&sb);
2868 return out;
2871 strbuf_reset(&sb);
2872 strbuf_addf(&sb, "%s%s", up_path, out);
2873 free(out);
2874 return strbuf_detach(&sb, NULL);