repository: remove unnecessary include of path.h
[alt-git.git] / remote.c
blob8550056db433b3b2b55e6405b283c919321b22d6
1 #include "git-compat-util.h"
2 #include "abspath.h"
3 #include "alloc.h"
4 #include "config.h"
5 #include "environment.h"
6 #include "gettext.h"
7 #include "hex.h"
8 #include "remote.h"
9 #include "urlmatch.h"
10 #include "refs.h"
11 #include "refspec.h"
12 #include "object-name.h"
13 #include "object-store.h"
14 #include "path.h"
15 #include "commit.h"
16 #include "diff.h"
17 #include "revision.h"
18 #include "dir.h"
19 #include "tag.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) || (!!remote->foreign_vcs);
40 static const 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 url;
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 ALLOC_GROW(remote->url, remote->url_nr + 1, remote->url_alloc);
69 remote->url[remote->url_nr++] = url;
72 static void add_pushurl(struct remote *remote, const char *pushurl)
74 ALLOC_GROW(remote->pushurl, remote->pushurl_nr + 1, remote->pushurl_alloc);
75 remote->pushurl[remote->pushurl_nr++] = pushurl;
78 static void add_pushurl_alias(struct remote_state *remote_state,
79 struct remote *remote, const char *url)
81 const char *pushurl = alias_url(url, &remote_state->rewrites_push);
82 if (pushurl != url)
83 add_pushurl(remote, pushurl);
86 static void add_url_alias(struct remote_state *remote_state,
87 struct remote *remote, const char *url)
89 add_url(remote, alias_url(url, &remote_state->rewrites));
90 add_pushurl_alias(remote_state, remote, url);
93 struct remotes_hash_key {
94 const char *str;
95 int len;
98 static int remotes_hash_cmp(const void *cmp_data UNUSED,
99 const struct hashmap_entry *eptr,
100 const struct hashmap_entry *entry_or_key,
101 const void *keydata)
103 const struct remote *a, *b;
104 const struct remotes_hash_key *key = keydata;
106 a = container_of(eptr, const struct remote, ent);
107 b = container_of(entry_or_key, const struct remote, ent);
109 if (key)
110 return strncmp(a->name, key->str, key->len) || a->name[key->len];
111 else
112 return strcmp(a->name, b->name);
115 static struct remote *make_remote(struct remote_state *remote_state,
116 const char *name, int len)
118 struct remote *ret;
119 struct remotes_hash_key lookup;
120 struct hashmap_entry lookup_entry, *e;
122 if (!len)
123 len = strlen(name);
125 lookup.str = name;
126 lookup.len = len;
127 hashmap_entry_init(&lookup_entry, memhash(name, len));
129 e = hashmap_get(&remote_state->remotes_hash, &lookup_entry, &lookup);
130 if (e)
131 return container_of(e, struct remote, ent);
133 CALLOC_ARRAY(ret, 1);
134 ret->prune = -1; /* unspecified */
135 ret->prune_tags = -1; /* unspecified */
136 ret->name = xstrndup(name, len);
137 refspec_init(&ret->push, REFSPEC_PUSH);
138 refspec_init(&ret->fetch, REFSPEC_FETCH);
140 ALLOC_GROW(remote_state->remotes, remote_state->remotes_nr + 1,
141 remote_state->remotes_alloc);
142 remote_state->remotes[remote_state->remotes_nr++] = ret;
144 hashmap_entry_init(&ret->ent, lookup_entry.hash);
145 if (hashmap_put_entry(&remote_state->remotes_hash, ret, ent))
146 BUG("hashmap_put overwrote entry after hashmap_get returned NULL");
147 return ret;
150 static void remote_clear(struct remote *remote)
152 int i;
154 free((char *)remote->name);
155 free((char *)remote->foreign_vcs);
157 for (i = 0; i < remote->url_nr; i++)
158 free((char *)remote->url[i]);
159 FREE_AND_NULL(remote->url);
161 for (i = 0; i < remote->pushurl_nr; i++)
162 free((char *)remote->pushurl[i]);
163 FREE_AND_NULL(remote->pushurl);
164 free((char *)remote->receivepack);
165 free((char *)remote->uploadpack);
166 FREE_AND_NULL(remote->http_proxy);
167 FREE_AND_NULL(remote->http_proxy_authmethod);
170 static void add_merge(struct branch *branch, const char *name)
172 ALLOC_GROW(branch->merge_name, branch->merge_nr + 1,
173 branch->merge_alloc);
174 branch->merge_name[branch->merge_nr++] = name;
177 struct branches_hash_key {
178 const char *str;
179 int len;
182 static int branches_hash_cmp(const void *cmp_data UNUSED,
183 const struct hashmap_entry *eptr,
184 const struct hashmap_entry *entry_or_key,
185 const void *keydata)
187 const struct branch *a, *b;
188 const struct branches_hash_key *key = keydata;
190 a = container_of(eptr, const struct branch, ent);
191 b = container_of(entry_or_key, const struct branch, ent);
193 if (key)
194 return strncmp(a->name, key->str, key->len) ||
195 a->name[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 xstrdup(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;
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 = (char *)git_default_branch_name(0);
341 add_url_alias(remote_state, remote, strbuf_detach(&buf, NULL));
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 */
353 static int handle_config(const char *key, const char *value, void *cb)
355 const char *name;
356 size_t namelen;
357 const char *subkey;
358 struct remote *remote;
359 struct branch *branch;
360 struct remote_state *remote_state = cb;
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 (current_config_scope() == CONFIG_SCOPE_LOCAL ||
419 current_config_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_NODUP;
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)
2263 int ours, theirs, sti;
2264 const char *full_base;
2265 char *base;
2266 int upstream_is_gone = 0;
2268 sti = stat_tracking_info(branch, &ours, &theirs, &full_base, 0, abf);
2269 if (sti < 0) {
2270 if (!full_base)
2271 return 0;
2272 upstream_is_gone = 1;
2275 base = shorten_unambiguous_ref(full_base, 0);
2276 if (upstream_is_gone) {
2277 strbuf_addf(sb,
2278 _("Your branch is based on '%s', but the upstream is gone.\n"),
2279 base);
2280 if (advice_enabled(ADVICE_STATUS_HINTS))
2281 strbuf_addstr(sb,
2282 _(" (use \"git branch --unset-upstream\" to fixup)\n"));
2283 } else if (!sti) {
2284 strbuf_addf(sb,
2285 _("Your branch is up to date with '%s'.\n"),
2286 base);
2287 } else if (abf == AHEAD_BEHIND_QUICK) {
2288 strbuf_addf(sb,
2289 _("Your branch and '%s' refer to different commits.\n"),
2290 base);
2291 if (advice_enabled(ADVICE_STATUS_HINTS))
2292 strbuf_addf(sb, _(" (use \"%s\" for details)\n"),
2293 "git status --ahead-behind");
2294 } else if (!theirs) {
2295 strbuf_addf(sb,
2296 Q_("Your branch is ahead of '%s' by %d commit.\n",
2297 "Your branch is ahead of '%s' by %d commits.\n",
2298 ours),
2299 base, ours);
2300 if (advice_enabled(ADVICE_STATUS_HINTS))
2301 strbuf_addstr(sb,
2302 _(" (use \"git push\" to publish your local commits)\n"));
2303 } else if (!ours) {
2304 strbuf_addf(sb,
2305 Q_("Your branch is behind '%s' by %d commit, "
2306 "and can be fast-forwarded.\n",
2307 "Your branch is behind '%s' by %d commits, "
2308 "and can be fast-forwarded.\n",
2309 theirs),
2310 base, theirs);
2311 if (advice_enabled(ADVICE_STATUS_HINTS))
2312 strbuf_addstr(sb,
2313 _(" (use \"git pull\" to update your local branch)\n"));
2314 } else {
2315 strbuf_addf(sb,
2316 Q_("Your branch and '%s' have diverged,\n"
2317 "and have %d and %d different commit each, "
2318 "respectively.\n",
2319 "Your branch and '%s' have diverged,\n"
2320 "and have %d and %d different commits each, "
2321 "respectively.\n",
2322 ours + theirs),
2323 base, ours, theirs);
2324 if (advice_enabled(ADVICE_STATUS_HINTS))
2325 strbuf_addstr(sb,
2326 _(" (use \"git pull\" to merge the remote branch into yours)\n"));
2328 free(base);
2329 return 1;
2332 static int one_local_ref(const char *refname, const struct object_id *oid,
2333 int flag UNUSED,
2334 void *cb_data)
2336 struct ref ***local_tail = cb_data;
2337 struct ref *ref;
2339 /* we already know it starts with refs/ to get here */
2340 if (check_refname_format(refname + 5, 0))
2341 return 0;
2343 ref = alloc_ref(refname);
2344 oidcpy(&ref->new_oid, oid);
2345 **local_tail = ref;
2346 *local_tail = &ref->next;
2347 return 0;
2350 struct ref *get_local_heads(void)
2352 struct ref *local_refs = NULL, **local_tail = &local_refs;
2354 for_each_ref(one_local_ref, &local_tail);
2355 return local_refs;
2358 struct ref *guess_remote_head(const struct ref *head,
2359 const struct ref *refs,
2360 int all)
2362 const struct ref *r;
2363 struct ref *list = NULL;
2364 struct ref **tail = &list;
2366 if (!head)
2367 return NULL;
2370 * Some transports support directly peeking at
2371 * where HEAD points; if that is the case, then
2372 * we don't have to guess.
2374 if (head->symref)
2375 return copy_ref(find_ref_by_name(refs, head->symref));
2377 /* If a remote branch exists with the default branch name, let's use it. */
2378 if (!all) {
2379 char *ref = xstrfmt("refs/heads/%s",
2380 git_default_branch_name(0));
2382 r = find_ref_by_name(refs, ref);
2383 free(ref);
2384 if (r && oideq(&r->old_oid, &head->old_oid))
2385 return copy_ref(r);
2387 /* Fall back to the hard-coded historical default */
2388 r = find_ref_by_name(refs, "refs/heads/master");
2389 if (r && oideq(&r->old_oid, &head->old_oid))
2390 return copy_ref(r);
2393 /* Look for another ref that points there */
2394 for (r = refs; r; r = r->next) {
2395 if (r != head &&
2396 starts_with(r->name, "refs/heads/") &&
2397 oideq(&r->old_oid, &head->old_oid)) {
2398 *tail = copy_ref(r);
2399 tail = &((*tail)->next);
2400 if (!all)
2401 break;
2405 return list;
2408 struct stale_heads_info {
2409 struct string_list *ref_names;
2410 struct ref **stale_refs_tail;
2411 struct refspec *rs;
2414 static int get_stale_heads_cb(const char *refname, const struct object_id *oid,
2415 int flags, void *cb_data)
2417 struct stale_heads_info *info = cb_data;
2418 struct string_list matches = STRING_LIST_INIT_DUP;
2419 struct refspec_item query;
2420 int i, stale = 1;
2421 memset(&query, 0, sizeof(struct refspec_item));
2422 query.dst = (char *)refname;
2424 query_refspecs_multiple(info->rs, &query, &matches);
2425 if (matches.nr == 0)
2426 goto clean_exit; /* No matches */
2429 * If we did find a suitable refspec and it's not a symref and
2430 * it's not in the list of refs that currently exist in that
2431 * remote, we consider it to be stale. In order to deal with
2432 * overlapping refspecs, we need to go over all of the
2433 * matching refs.
2435 if (flags & REF_ISSYMREF)
2436 goto clean_exit;
2438 for (i = 0; stale && i < matches.nr; i++)
2439 if (string_list_has_string(info->ref_names, matches.items[i].string))
2440 stale = 0;
2442 if (stale) {
2443 struct ref *ref = make_linked_ref(refname, &info->stale_refs_tail);
2444 oidcpy(&ref->new_oid, oid);
2447 clean_exit:
2448 string_list_clear(&matches, 0);
2449 return 0;
2452 struct ref *get_stale_heads(struct refspec *rs, struct ref *fetch_map)
2454 struct ref *ref, *stale_refs = NULL;
2455 struct string_list ref_names = STRING_LIST_INIT_NODUP;
2456 struct stale_heads_info info;
2458 info.ref_names = &ref_names;
2459 info.stale_refs_tail = &stale_refs;
2460 info.rs = rs;
2461 for (ref = fetch_map; ref; ref = ref->next)
2462 string_list_append(&ref_names, ref->name);
2463 string_list_sort(&ref_names);
2464 for_each_ref(get_stale_heads_cb, &info);
2465 string_list_clear(&ref_names, 0);
2466 return stale_refs;
2470 * Compare-and-swap
2472 static void clear_cas_option(struct push_cas_option *cas)
2474 int i;
2476 for (i = 0; i < cas->nr; i++)
2477 free(cas->entry[i].refname);
2478 free(cas->entry);
2479 memset(cas, 0, sizeof(*cas));
2482 static struct push_cas *add_cas_entry(struct push_cas_option *cas,
2483 const char *refname,
2484 size_t refnamelen)
2486 struct push_cas *entry;
2487 ALLOC_GROW(cas->entry, cas->nr + 1, cas->alloc);
2488 entry = &cas->entry[cas->nr++];
2489 memset(entry, 0, sizeof(*entry));
2490 entry->refname = xmemdupz(refname, refnamelen);
2491 return entry;
2494 static int parse_push_cas_option(struct push_cas_option *cas, const char *arg, int unset)
2496 const char *colon;
2497 struct push_cas *entry;
2499 if (unset) {
2500 /* "--no-<option>" */
2501 clear_cas_option(cas);
2502 return 0;
2505 if (!arg) {
2506 /* just "--<option>" */
2507 cas->use_tracking_for_rest = 1;
2508 return 0;
2511 /* "--<option>=refname" or "--<option>=refname:value" */
2512 colon = strchrnul(arg, ':');
2513 entry = add_cas_entry(cas, arg, colon - arg);
2514 if (!*colon)
2515 entry->use_tracking = 1;
2516 else if (!colon[1])
2517 oidclr(&entry->expect);
2518 else if (repo_get_oid(the_repository, colon + 1, &entry->expect))
2519 return error(_("cannot parse expected object name '%s'"),
2520 colon + 1);
2521 return 0;
2524 int parseopt_push_cas_option(const struct option *opt, const char *arg, int unset)
2526 return parse_push_cas_option(opt->value, arg, unset);
2529 int is_empty_cas(const struct push_cas_option *cas)
2531 return !cas->use_tracking_for_rest && !cas->nr;
2535 * Look at remote.fetch refspec and see if we have a remote
2536 * tracking branch for the refname there. Fill the name of
2537 * the remote-tracking branch in *dst_refname, and the name
2538 * of the commit object at its tip in oid[].
2539 * If we cannot do so, return negative to signal an error.
2541 static int remote_tracking(struct remote *remote, const char *refname,
2542 struct object_id *oid, char **dst_refname)
2544 char *dst;
2546 dst = apply_refspecs(&remote->fetch, refname);
2547 if (!dst)
2548 return -1; /* no tracking ref for refname at remote */
2549 if (read_ref(dst, oid))
2550 return -1; /* we know what the tracking ref is but we cannot read it */
2552 *dst_refname = dst;
2553 return 0;
2557 * The struct "reflog_commit_array" and related helper functions
2558 * are used for collecting commits into an array during reflog
2559 * traversals in "check_and_collect_until()".
2561 struct reflog_commit_array {
2562 struct commit **item;
2563 size_t nr, alloc;
2566 #define REFLOG_COMMIT_ARRAY_INIT { 0 }
2568 /* Append a commit to the array. */
2569 static void append_commit(struct reflog_commit_array *arr,
2570 struct commit *commit)
2572 ALLOC_GROW(arr->item, arr->nr + 1, arr->alloc);
2573 arr->item[arr->nr++] = commit;
2576 /* Free and reset the array. */
2577 static void free_commit_array(struct reflog_commit_array *arr)
2579 FREE_AND_NULL(arr->item);
2580 arr->nr = arr->alloc = 0;
2583 struct check_and_collect_until_cb_data {
2584 struct commit *remote_commit;
2585 struct reflog_commit_array *local_commits;
2586 timestamp_t remote_reflog_timestamp;
2589 /* Get the timestamp of the latest entry. */
2590 static int peek_reflog(struct object_id *o_oid UNUSED,
2591 struct object_id *n_oid UNUSED,
2592 const char *ident UNUSED,
2593 timestamp_t timestamp, int tz UNUSED,
2594 const char *message UNUSED, void *cb_data)
2596 timestamp_t *ts = cb_data;
2597 *ts = timestamp;
2598 return 1;
2601 static int check_and_collect_until(struct object_id *o_oid UNUSED,
2602 struct object_id *n_oid,
2603 const char *ident UNUSED,
2604 timestamp_t timestamp, int tz UNUSED,
2605 const char *message UNUSED, void *cb_data)
2607 struct commit *commit;
2608 struct check_and_collect_until_cb_data *cb = cb_data;
2610 /* An entry was found. */
2611 if (oideq(n_oid, &cb->remote_commit->object.oid))
2612 return 1;
2614 if ((commit = lookup_commit_reference(the_repository, n_oid)))
2615 append_commit(cb->local_commits, commit);
2618 * If the reflog entry timestamp is older than the remote ref's
2619 * latest reflog entry, there is no need to check or collect
2620 * entries older than this one.
2622 if (timestamp < cb->remote_reflog_timestamp)
2623 return -1;
2625 return 0;
2628 #define MERGE_BASES_BATCH_SIZE 8
2631 * Iterate through the reflog of the local ref to check if there is an entry
2632 * for the given remote-tracking ref; runs until the timestamp of an entry is
2633 * older than latest timestamp of remote-tracking ref's reflog. Any commits
2634 * are that seen along the way are collected into an array to check if the
2635 * remote-tracking ref is reachable from any of them.
2637 static int is_reachable_in_reflog(const char *local, const struct ref *remote)
2639 timestamp_t date;
2640 struct commit *commit;
2641 struct commit **chunk;
2642 struct check_and_collect_until_cb_data cb;
2643 struct reflog_commit_array arr = REFLOG_COMMIT_ARRAY_INIT;
2644 size_t size = 0;
2645 int ret = 0;
2647 commit = lookup_commit_reference(the_repository, &remote->old_oid);
2648 if (!commit)
2649 goto cleanup_return;
2652 * Get the timestamp from the latest entry
2653 * of the remote-tracking ref's reflog.
2655 for_each_reflog_ent_reverse(remote->tracking_ref, peek_reflog, &date);
2657 cb.remote_commit = commit;
2658 cb.local_commits = &arr;
2659 cb.remote_reflog_timestamp = date;
2660 ret = for_each_reflog_ent_reverse(local, check_and_collect_until, &cb);
2662 /* We found an entry in the reflog. */
2663 if (ret > 0)
2664 goto cleanup_return;
2667 * Check if the remote commit is reachable from any
2668 * of the commits in the collected array, in batches.
2670 for (chunk = arr.item; chunk < arr.item + arr.nr; chunk += size) {
2671 size = arr.item + arr.nr - chunk;
2672 if (MERGE_BASES_BATCH_SIZE < size)
2673 size = MERGE_BASES_BATCH_SIZE;
2675 if ((ret = repo_in_merge_bases_many(the_repository, commit, size, chunk)))
2676 break;
2679 cleanup_return:
2680 free_commit_array(&arr);
2681 return ret;
2685 * Check for reachability of a remote-tracking
2686 * ref in the reflog entries of its local ref.
2688 static void check_if_includes_upstream(struct ref *remote)
2690 struct ref *local = get_local_ref(remote->name);
2691 if (!local)
2692 return;
2694 if (is_reachable_in_reflog(local->name, remote) <= 0)
2695 remote->unreachable = 1;
2698 static void apply_cas(struct push_cas_option *cas,
2699 struct remote *remote,
2700 struct ref *ref)
2702 int i;
2704 /* Find an explicit --<option>=<name>[:<value>] entry */
2705 for (i = 0; i < cas->nr; i++) {
2706 struct push_cas *entry = &cas->entry[i];
2707 if (!refname_match(entry->refname, ref->name))
2708 continue;
2709 ref->expect_old_sha1 = 1;
2710 if (!entry->use_tracking)
2711 oidcpy(&ref->old_oid_expect, &entry->expect);
2712 else if (remote_tracking(remote, ref->name,
2713 &ref->old_oid_expect,
2714 &ref->tracking_ref))
2715 oidclr(&ref->old_oid_expect);
2716 else
2717 ref->check_reachable = cas->use_force_if_includes;
2718 return;
2721 /* Are we using "--<option>" to cover all? */
2722 if (!cas->use_tracking_for_rest)
2723 return;
2725 ref->expect_old_sha1 = 1;
2726 if (remote_tracking(remote, ref->name,
2727 &ref->old_oid_expect,
2728 &ref->tracking_ref))
2729 oidclr(&ref->old_oid_expect);
2730 else
2731 ref->check_reachable = cas->use_force_if_includes;
2734 void apply_push_cas(struct push_cas_option *cas,
2735 struct remote *remote,
2736 struct ref *remote_refs)
2738 struct ref *ref;
2739 for (ref = remote_refs; ref; ref = ref->next) {
2740 apply_cas(cas, remote, ref);
2743 * If "compare-and-swap" is in "use_tracking[_for_rest]"
2744 * mode, and if "--force-if-includes" was specified, run
2745 * the check.
2747 if (ref->check_reachable)
2748 check_if_includes_upstream(ref);
2752 struct remote_state *remote_state_new(void)
2754 struct remote_state *r = xmalloc(sizeof(*r));
2756 memset(r, 0, sizeof(*r));
2758 hashmap_init(&r->remotes_hash, remotes_hash_cmp, NULL, 0);
2759 hashmap_init(&r->branches_hash, branches_hash_cmp, NULL, 0);
2760 return r;
2763 void remote_state_clear(struct remote_state *remote_state)
2765 int i;
2767 for (i = 0; i < remote_state->remotes_nr; i++)
2768 remote_clear(remote_state->remotes[i]);
2769 FREE_AND_NULL(remote_state->remotes);
2770 remote_state->remotes_alloc = 0;
2771 remote_state->remotes_nr = 0;
2773 hashmap_clear_and_free(&remote_state->remotes_hash, struct remote, ent);
2774 hashmap_clear_and_free(&remote_state->branches_hash, struct remote, ent);
2778 * Returns 1 if it was the last chop before ':'.
2780 static int chop_last_dir(char **remoteurl, int is_relative)
2782 char *rfind = find_last_dir_sep(*remoteurl);
2783 if (rfind) {
2784 *rfind = '\0';
2785 return 0;
2788 rfind = strrchr(*remoteurl, ':');
2789 if (rfind) {
2790 *rfind = '\0';
2791 return 1;
2794 if (is_relative || !strcmp(".", *remoteurl))
2795 die(_("cannot strip one component off url '%s'"),
2796 *remoteurl);
2798 free(*remoteurl);
2799 *remoteurl = xstrdup(".");
2800 return 0;
2803 char *relative_url(const char *remote_url, const char *url,
2804 const char *up_path)
2806 int is_relative = 0;
2807 int colonsep = 0;
2808 char *out;
2809 char *remoteurl;
2810 struct strbuf sb = STRBUF_INIT;
2811 size_t len;
2813 if (!url_is_local_not_ssh(url) || is_absolute_path(url))
2814 return xstrdup(url);
2816 len = strlen(remote_url);
2817 if (!len)
2818 BUG("invalid empty remote_url");
2820 remoteurl = xstrdup(remote_url);
2821 if (is_dir_sep(remoteurl[len-1]))
2822 remoteurl[len-1] = '\0';
2824 if (!url_is_local_not_ssh(remoteurl) || is_absolute_path(remoteurl))
2825 is_relative = 0;
2826 else {
2827 is_relative = 1;
2829 * Prepend a './' to ensure all relative
2830 * remoteurls start with './' or '../'
2832 if (!starts_with_dot_slash_native(remoteurl) &&
2833 !starts_with_dot_dot_slash_native(remoteurl)) {
2834 strbuf_reset(&sb);
2835 strbuf_addf(&sb, "./%s", remoteurl);
2836 free(remoteurl);
2837 remoteurl = strbuf_detach(&sb, NULL);
2841 * When the url starts with '../', remove that and the
2842 * last directory in remoteurl.
2844 while (*url) {
2845 if (starts_with_dot_dot_slash_native(url)) {
2846 url += 3;
2847 colonsep |= chop_last_dir(&remoteurl, is_relative);
2848 } else if (starts_with_dot_slash_native(url))
2849 url += 2;
2850 else
2851 break;
2853 strbuf_reset(&sb);
2854 strbuf_addf(&sb, "%s%s%s", remoteurl, colonsep ? ":" : "/", url);
2855 if (ends_with(url, "/"))
2856 strbuf_setlen(&sb, sb.len - 1);
2857 free(remoteurl);
2859 if (starts_with_dot_slash_native(sb.buf))
2860 out = xstrdup(sb.buf + 2);
2861 else
2862 out = xstrdup(sb.buf);
2864 if (!up_path || !is_relative) {
2865 strbuf_release(&sb);
2866 return out;
2869 strbuf_reset(&sb);
2870 strbuf_addf(&sb, "%s%s", up_path, out);
2871 free(out);
2872 return strbuf_detach(&sb, NULL);