Merge branch 'rs/userdiff-multibyte-regex'
[alt-git.git] / remote.c
blob3a831cb5304937122125c26d9e700be16362af4b
1 #include "cache.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-store.h"
13 #include "commit.h"
14 #include "diff.h"
15 #include "revision.h"
16 #include "dir.h"
17 #include "tag.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, void *cb)
353 const char *name;
354 size_t namelen;
355 const char *subkey;
356 struct remote *remote;
357 struct branch *branch;
358 struct remote_state *remote_state = cb;
360 if (parse_config_key(key, "branch", &name, &namelen, &subkey) >= 0) {
361 /* There is no subsection. */
362 if (!name)
363 return 0;
364 /* There is a subsection, but it is empty. */
365 if (!namelen)
366 return -1;
367 branch = make_branch(remote_state, name, namelen);
368 if (!strcmp(subkey, "remote")) {
369 return git_config_string(&branch->remote_name, key, value);
370 } else if (!strcmp(subkey, "pushremote")) {
371 return git_config_string(&branch->pushremote_name, key, value);
372 } else if (!strcmp(subkey, "merge")) {
373 if (!value)
374 return config_error_nonbool(key);
375 add_merge(branch, xstrdup(value));
377 return 0;
379 if (parse_config_key(key, "url", &name, &namelen, &subkey) >= 0) {
380 struct rewrite *rewrite;
381 if (!name)
382 return 0;
383 if (!strcmp(subkey, "insteadof")) {
384 if (!value)
385 return config_error_nonbool(key);
386 rewrite = make_rewrite(&remote_state->rewrites, name,
387 namelen);
388 add_instead_of(rewrite, xstrdup(value));
389 } else if (!strcmp(subkey, "pushinsteadof")) {
390 if (!value)
391 return config_error_nonbool(key);
392 rewrite = make_rewrite(&remote_state->rewrites_push,
393 name, namelen);
394 add_instead_of(rewrite, xstrdup(value));
398 if (parse_config_key(key, "remote", &name, &namelen, &subkey) < 0)
399 return 0;
401 /* Handle remote.* variables */
402 if (!name && !strcmp(subkey, "pushdefault"))
403 return git_config_string(&remote_state->pushremote_name, key,
404 value);
406 if (!name)
407 return 0;
408 /* Handle remote.<name>.* variables */
409 if (*name == '/') {
410 warning(_("config remote shorthand cannot begin with '/': %s"),
411 name);
412 return 0;
414 remote = make_remote(remote_state, name, namelen);
415 remote->origin = REMOTE_CONFIG;
416 if (current_config_scope() == CONFIG_SCOPE_LOCAL ||
417 current_config_scope() == CONFIG_SCOPE_WORKTREE)
418 remote->configured_in_repo = 1;
419 if (!strcmp(subkey, "mirror"))
420 remote->mirror = git_config_bool(key, value);
421 else if (!strcmp(subkey, "skipdefaultupdate"))
422 remote->skip_default_update = git_config_bool(key, value);
423 else if (!strcmp(subkey, "skipfetchall"))
424 remote->skip_default_update = git_config_bool(key, value);
425 else if (!strcmp(subkey, "prune"))
426 remote->prune = git_config_bool(key, value);
427 else if (!strcmp(subkey, "prunetags"))
428 remote->prune_tags = git_config_bool(key, value);
429 else if (!strcmp(subkey, "url")) {
430 const char *v;
431 if (git_config_string(&v, key, value))
432 return -1;
433 add_url(remote, v);
434 } else if (!strcmp(subkey, "pushurl")) {
435 const char *v;
436 if (git_config_string(&v, key, value))
437 return -1;
438 add_pushurl(remote, v);
439 } else if (!strcmp(subkey, "push")) {
440 const char *v;
441 if (git_config_string(&v, key, value))
442 return -1;
443 refspec_append(&remote->push, v);
444 free((char *)v);
445 } else if (!strcmp(subkey, "fetch")) {
446 const char *v;
447 if (git_config_string(&v, key, value))
448 return -1;
449 refspec_append(&remote->fetch, v);
450 free((char *)v);
451 } else if (!strcmp(subkey, "receivepack")) {
452 const char *v;
453 if (git_config_string(&v, key, value))
454 return -1;
455 if (!remote->receivepack)
456 remote->receivepack = v;
457 else
458 error(_("more than one receivepack given, using the first"));
459 } else if (!strcmp(subkey, "uploadpack")) {
460 const char *v;
461 if (git_config_string(&v, key, value))
462 return -1;
463 if (!remote->uploadpack)
464 remote->uploadpack = v;
465 else
466 error(_("more than one uploadpack given, using the first"));
467 } else if (!strcmp(subkey, "tagopt")) {
468 if (!strcmp(value, "--no-tags"))
469 remote->fetch_tags = -1;
470 else if (!strcmp(value, "--tags"))
471 remote->fetch_tags = 2;
472 } else if (!strcmp(subkey, "proxy")) {
473 return git_config_string((const char **)&remote->http_proxy,
474 key, value);
475 } else if (!strcmp(subkey, "proxyauthmethod")) {
476 return git_config_string((const char **)&remote->http_proxy_authmethod,
477 key, value);
478 } else if (!strcmp(subkey, "vcs")) {
479 return git_config_string(&remote->foreign_vcs, key, value);
481 return 0;
484 static void alias_all_urls(struct remote_state *remote_state)
486 int i, j;
487 for (i = 0; i < remote_state->remotes_nr; i++) {
488 int add_pushurl_aliases;
489 if (!remote_state->remotes[i])
490 continue;
491 for (j = 0; j < remote_state->remotes[i]->pushurl_nr; j++) {
492 remote_state->remotes[i]->pushurl[j] =
493 alias_url(remote_state->remotes[i]->pushurl[j],
494 &remote_state->rewrites);
496 add_pushurl_aliases = remote_state->remotes[i]->pushurl_nr == 0;
497 for (j = 0; j < remote_state->remotes[i]->url_nr; j++) {
498 if (add_pushurl_aliases)
499 add_pushurl_alias(
500 remote_state, remote_state->remotes[i],
501 remote_state->remotes[i]->url[j]);
502 remote_state->remotes[i]->url[j] =
503 alias_url(remote_state->remotes[i]->url[j],
504 &remote_state->rewrites);
509 static void read_config(struct repository *repo)
511 int flag;
513 if (repo->remote_state->initialized)
514 return;
515 repo->remote_state->initialized = 1;
517 repo->remote_state->current_branch = NULL;
518 if (startup_info->have_repository) {
519 const char *head_ref = refs_resolve_ref_unsafe(
520 get_main_ref_store(repo), "HEAD", 0, NULL, &flag);
521 if (head_ref && (flag & REF_ISSYMREF) &&
522 skip_prefix(head_ref, "refs/heads/", &head_ref)) {
523 repo->remote_state->current_branch = make_branch(
524 repo->remote_state, head_ref, strlen(head_ref));
527 repo_config(repo, handle_config, repo->remote_state);
528 alias_all_urls(repo->remote_state);
531 static int valid_remote_nick(const char *name)
533 if (!name[0] || is_dot_or_dotdot(name))
534 return 0;
536 /* remote nicknames cannot contain slashes */
537 while (*name)
538 if (is_dir_sep(*name++))
539 return 0;
540 return 1;
543 static const char *remotes_remote_for_branch(struct remote_state *remote_state,
544 struct branch *branch,
545 int *explicit)
547 if (branch && branch->remote_name) {
548 if (explicit)
549 *explicit = 1;
550 return branch->remote_name;
552 if (explicit)
553 *explicit = 0;
554 if (remote_state->remotes_nr == 1)
555 return remote_state->remotes[0]->name;
556 return "origin";
559 const char *remote_for_branch(struct branch *branch, int *explicit)
561 read_config(the_repository);
562 die_on_missing_branch(the_repository, branch);
564 return remotes_remote_for_branch(the_repository->remote_state, branch,
565 explicit);
568 static const char *
569 remotes_pushremote_for_branch(struct remote_state *remote_state,
570 struct branch *branch, int *explicit)
572 if (branch && branch->pushremote_name) {
573 if (explicit)
574 *explicit = 1;
575 return branch->pushremote_name;
577 if (remote_state->pushremote_name) {
578 if (explicit)
579 *explicit = 1;
580 return remote_state->pushremote_name;
582 return remotes_remote_for_branch(remote_state, branch, explicit);
585 const char *pushremote_for_branch(struct branch *branch, int *explicit)
587 read_config(the_repository);
588 die_on_missing_branch(the_repository, branch);
590 return remotes_pushremote_for_branch(the_repository->remote_state,
591 branch, explicit);
594 static struct remote *remotes_remote_get(struct remote_state *remote_state,
595 const char *name);
597 const char *remote_ref_for_branch(struct branch *branch, int for_push)
599 read_config(the_repository);
600 die_on_missing_branch(the_repository, branch);
602 if (branch) {
603 if (!for_push) {
604 if (branch->merge_nr) {
605 return branch->merge_name[0];
607 } else {
608 const char *dst,
609 *remote_name = remotes_pushremote_for_branch(
610 the_repository->remote_state, branch,
611 NULL);
612 struct remote *remote = remotes_remote_get(
613 the_repository->remote_state, remote_name);
615 if (remote && remote->push.nr &&
616 (dst = apply_refspecs(&remote->push,
617 branch->refname))) {
618 return dst;
622 return NULL;
625 static void validate_remote_url(struct remote *remote)
627 int i;
628 const char *value;
629 struct strbuf redacted = STRBUF_INIT;
630 int warn_not_die;
632 if (git_config_get_string_tmp("transfer.credentialsinurl", &value))
633 return;
635 if (!strcmp("warn", value))
636 warn_not_die = 1;
637 else if (!strcmp("die", value))
638 warn_not_die = 0;
639 else if (!strcmp("allow", value))
640 return;
641 else
642 die(_("unrecognized value transfer.credentialsInUrl: '%s'"), value);
644 for (i = 0; i < remote->url_nr; i++) {
645 struct url_info url_info = { 0 };
647 if (!url_normalize(remote->url[i], &url_info) ||
648 !url_info.passwd_off)
649 goto loop_cleanup;
651 strbuf_reset(&redacted);
652 strbuf_add(&redacted, url_info.url, url_info.passwd_off);
653 strbuf_addstr(&redacted, "<redacted>");
654 strbuf_addstr(&redacted,
655 url_info.url + url_info.passwd_off + url_info.passwd_len);
657 if (warn_not_die)
658 warning(_("URL '%s' uses plaintext credentials"), redacted.buf);
659 else
660 die(_("URL '%s' uses plaintext credentials"), redacted.buf);
662 loop_cleanup:
663 free(url_info.url);
666 strbuf_release(&redacted);
669 static struct remote *
670 remotes_remote_get_1(struct remote_state *remote_state, const char *name,
671 const char *(*get_default)(struct remote_state *,
672 struct branch *, int *))
674 struct remote *ret;
675 int name_given = 0;
677 if (name)
678 name_given = 1;
679 else
680 name = get_default(remote_state, remote_state->current_branch,
681 &name_given);
683 ret = make_remote(remote_state, name, 0);
684 if (valid_remote_nick(name) && have_git_dir()) {
685 if (!valid_remote(ret))
686 read_remotes_file(remote_state, ret);
687 if (!valid_remote(ret))
688 read_branches_file(remote_state, ret);
690 if (name_given && !valid_remote(ret))
691 add_url_alias(remote_state, ret, name);
692 if (!valid_remote(ret))
693 return NULL;
695 validate_remote_url(ret);
697 return ret;
700 static inline struct remote *
701 remotes_remote_get(struct remote_state *remote_state, const char *name)
703 return remotes_remote_get_1(remote_state, name,
704 remotes_remote_for_branch);
707 struct remote *remote_get(const char *name)
709 read_config(the_repository);
710 return remotes_remote_get(the_repository->remote_state, name);
713 static inline struct remote *
714 remotes_pushremote_get(struct remote_state *remote_state, const char *name)
716 return remotes_remote_get_1(remote_state, name,
717 remotes_pushremote_for_branch);
720 struct remote *pushremote_get(const char *name)
722 read_config(the_repository);
723 return remotes_pushremote_get(the_repository->remote_state, name);
726 int remote_is_configured(struct remote *remote, int in_repo)
728 if (!remote)
729 return 0;
730 if (in_repo)
731 return remote->configured_in_repo;
732 return !!remote->origin;
735 int for_each_remote(each_remote_fn fn, void *priv)
737 int i, result = 0;
738 read_config(the_repository);
739 for (i = 0; i < the_repository->remote_state->remotes_nr && !result;
740 i++) {
741 struct remote *remote =
742 the_repository->remote_state->remotes[i];
743 if (!remote)
744 continue;
745 result = fn(remote, priv);
747 return result;
750 static void handle_duplicate(struct ref *ref1, struct ref *ref2)
752 if (strcmp(ref1->name, ref2->name)) {
753 if (ref1->fetch_head_status != FETCH_HEAD_IGNORE &&
754 ref2->fetch_head_status != FETCH_HEAD_IGNORE) {
755 die(_("Cannot fetch both %s and %s to %s"),
756 ref1->name, ref2->name, ref2->peer_ref->name);
757 } else if (ref1->fetch_head_status != FETCH_HEAD_IGNORE &&
758 ref2->fetch_head_status == FETCH_HEAD_IGNORE) {
759 warning(_("%s usually tracks %s, not %s"),
760 ref2->peer_ref->name, ref2->name, ref1->name);
761 } else if (ref1->fetch_head_status == FETCH_HEAD_IGNORE &&
762 ref2->fetch_head_status == FETCH_HEAD_IGNORE) {
763 die(_("%s tracks both %s and %s"),
764 ref2->peer_ref->name, ref1->name, ref2->name);
765 } else {
767 * This last possibility doesn't occur because
768 * FETCH_HEAD_IGNORE entries always appear at
769 * the end of the list.
771 BUG("Internal error");
774 free(ref2->peer_ref);
775 free(ref2);
778 struct ref *ref_remove_duplicates(struct ref *ref_map)
780 struct string_list refs = STRING_LIST_INIT_NODUP;
781 struct ref *retval = NULL;
782 struct ref **p = &retval;
784 while (ref_map) {
785 struct ref *ref = ref_map;
787 ref_map = ref_map->next;
788 ref->next = NULL;
790 if (!ref->peer_ref) {
791 *p = ref;
792 p = &ref->next;
793 } else {
794 struct string_list_item *item =
795 string_list_insert(&refs, ref->peer_ref->name);
797 if (item->util) {
798 /* Entry already existed */
799 handle_duplicate((struct ref *)item->util, ref);
800 } else {
801 *p = ref;
802 p = &ref->next;
803 item->util = ref;
808 string_list_clear(&refs, 0);
809 return retval;
812 int remote_has_url(struct remote *remote, const char *url)
814 int i;
815 for (i = 0; i < remote->url_nr; i++) {
816 if (!strcmp(remote->url[i], url))
817 return 1;
819 return 0;
822 static int match_name_with_pattern(const char *key, const char *name,
823 const char *value, char **result)
825 const char *kstar = strchr(key, '*');
826 size_t klen;
827 size_t ksuffixlen;
828 size_t namelen;
829 int ret;
830 if (!kstar)
831 die(_("key '%s' of pattern had no '*'"), key);
832 klen = kstar - key;
833 ksuffixlen = strlen(kstar + 1);
834 namelen = strlen(name);
835 ret = !strncmp(name, key, klen) && namelen >= klen + ksuffixlen &&
836 !memcmp(name + namelen - ksuffixlen, kstar + 1, ksuffixlen);
837 if (ret && value) {
838 struct strbuf sb = STRBUF_INIT;
839 const char *vstar = strchr(value, '*');
840 if (!vstar)
841 die(_("value '%s' of pattern has no '*'"), value);
842 strbuf_add(&sb, value, vstar - value);
843 strbuf_add(&sb, name + klen, namelen - klen - ksuffixlen);
844 strbuf_addstr(&sb, vstar + 1);
845 *result = strbuf_detach(&sb, NULL);
847 return ret;
850 static int refspec_match(const struct refspec_item *refspec,
851 const char *name)
853 if (refspec->pattern)
854 return match_name_with_pattern(refspec->src, name, NULL, NULL);
856 return !strcmp(refspec->src, name);
859 int omit_name_by_refspec(const char *name, struct refspec *rs)
861 int i;
863 for (i = 0; i < rs->nr; i++) {
864 if (rs->items[i].negative && refspec_match(&rs->items[i], name))
865 return 1;
867 return 0;
870 struct ref *apply_negative_refspecs(struct ref *ref_map, struct refspec *rs)
872 struct ref **tail;
874 for (tail = &ref_map; *tail; ) {
875 struct ref *ref = *tail;
877 if (omit_name_by_refspec(ref->name, rs)) {
878 *tail = ref->next;
879 free(ref->peer_ref);
880 free(ref);
881 } else
882 tail = &ref->next;
885 return ref_map;
888 static int query_matches_negative_refspec(struct refspec *rs, struct refspec_item *query)
890 int i, matched_negative = 0;
891 int find_src = !query->src;
892 struct string_list reversed = STRING_LIST_INIT_NODUP;
893 const char *needle = find_src ? query->dst : query->src;
896 * Check whether the queried ref matches any negative refpsec. If so,
897 * then we should ultimately treat this as not matching the query at
898 * all.
900 * Note that negative refspecs always match the source, but the query
901 * item uses the destination. To handle this, we apply pattern
902 * refspecs in reverse to figure out if the query source matches any
903 * of the negative refspecs.
905 * The first loop finds and expands all positive refspecs
906 * matched by the queried ref.
908 * The second loop checks if any of the results of the first loop
909 * match any negative refspec.
911 for (i = 0; i < rs->nr; i++) {
912 struct refspec_item *refspec = &rs->items[i];
913 char *expn_name;
915 if (refspec->negative)
916 continue;
918 /* Note the reversal of src and dst */
919 if (refspec->pattern) {
920 const char *key = refspec->dst ? refspec->dst : refspec->src;
921 const char *value = refspec->src;
923 if (match_name_with_pattern(key, needle, value, &expn_name))
924 string_list_append_nodup(&reversed, expn_name);
925 } else if (refspec->matching) {
926 /* For the special matching refspec, any query should match */
927 string_list_append(&reversed, needle);
928 } else if (!refspec->src) {
929 BUG("refspec->src should not be null here");
930 } else if (!strcmp(needle, refspec->src)) {
931 string_list_append(&reversed, refspec->src);
935 for (i = 0; !matched_negative && i < reversed.nr; i++) {
936 if (omit_name_by_refspec(reversed.items[i].string, rs))
937 matched_negative = 1;
940 string_list_clear(&reversed, 0);
942 return matched_negative;
945 static void query_refspecs_multiple(struct refspec *rs,
946 struct refspec_item *query,
947 struct string_list *results)
949 int i;
950 int find_src = !query->src;
952 if (find_src && !query->dst)
953 BUG("query_refspecs_multiple: need either src or dst");
955 if (query_matches_negative_refspec(rs, query))
956 return;
958 for (i = 0; i < rs->nr; i++) {
959 struct refspec_item *refspec = &rs->items[i];
960 const char *key = find_src ? refspec->dst : refspec->src;
961 const char *value = find_src ? refspec->src : refspec->dst;
962 const char *needle = find_src ? query->dst : query->src;
963 char **result = find_src ? &query->src : &query->dst;
965 if (!refspec->dst || refspec->negative)
966 continue;
967 if (refspec->pattern) {
968 if (match_name_with_pattern(key, needle, value, result))
969 string_list_append_nodup(results, *result);
970 } else if (!strcmp(needle, key)) {
971 string_list_append(results, value);
976 int query_refspecs(struct refspec *rs, struct refspec_item *query)
978 int i;
979 int find_src = !query->src;
980 const char *needle = find_src ? query->dst : query->src;
981 char **result = find_src ? &query->src : &query->dst;
983 if (find_src && !query->dst)
984 BUG("query_refspecs: need either src or dst");
986 if (query_matches_negative_refspec(rs, query))
987 return -1;
989 for (i = 0; i < rs->nr; i++) {
990 struct refspec_item *refspec = &rs->items[i];
991 const char *key = find_src ? refspec->dst : refspec->src;
992 const char *value = find_src ? refspec->src : refspec->dst;
994 if (!refspec->dst || refspec->negative)
995 continue;
996 if (refspec->pattern) {
997 if (match_name_with_pattern(key, needle, value, result)) {
998 query->force = refspec->force;
999 return 0;
1001 } else if (!strcmp(needle, key)) {
1002 *result = xstrdup(value);
1003 query->force = refspec->force;
1004 return 0;
1007 return -1;
1010 char *apply_refspecs(struct refspec *rs, const char *name)
1012 struct refspec_item query;
1014 memset(&query, 0, sizeof(struct refspec_item));
1015 query.src = (char *)name;
1017 if (query_refspecs(rs, &query))
1018 return NULL;
1020 return query.dst;
1023 int remote_find_tracking(struct remote *remote, struct refspec_item *refspec)
1025 return query_refspecs(&remote->fetch, refspec);
1028 static struct ref *alloc_ref_with_prefix(const char *prefix, size_t prefixlen,
1029 const char *name)
1031 size_t len = strlen(name);
1032 struct ref *ref = xcalloc(1, st_add4(sizeof(*ref), prefixlen, len, 1));
1033 memcpy(ref->name, prefix, prefixlen);
1034 memcpy(ref->name + prefixlen, name, len);
1035 return ref;
1038 struct ref *alloc_ref(const char *name)
1040 return alloc_ref_with_prefix("", 0, name);
1043 struct ref *copy_ref(const struct ref *ref)
1045 struct ref *cpy;
1046 size_t len;
1047 if (!ref)
1048 return NULL;
1049 len = st_add3(sizeof(struct ref), strlen(ref->name), 1);
1050 cpy = xmalloc(len);
1051 memcpy(cpy, ref, len);
1052 cpy->next = NULL;
1053 cpy->symref = xstrdup_or_null(ref->symref);
1054 cpy->remote_status = xstrdup_or_null(ref->remote_status);
1055 cpy->peer_ref = copy_ref(ref->peer_ref);
1056 return cpy;
1059 struct ref *copy_ref_list(const struct ref *ref)
1061 struct ref *ret = NULL;
1062 struct ref **tail = &ret;
1063 while (ref) {
1064 *tail = copy_ref(ref);
1065 ref = ref->next;
1066 tail = &((*tail)->next);
1068 return ret;
1071 void free_one_ref(struct ref *ref)
1073 if (!ref)
1074 return;
1075 free_one_ref(ref->peer_ref);
1076 free(ref->remote_status);
1077 free(ref->symref);
1078 free(ref);
1081 void free_refs(struct ref *ref)
1083 struct ref *next;
1084 while (ref) {
1085 next = ref->next;
1086 free_one_ref(ref);
1087 ref = next;
1091 int count_refspec_match(const char *pattern,
1092 struct ref *refs,
1093 struct ref **matched_ref)
1095 int patlen = strlen(pattern);
1096 struct ref *matched_weak = NULL;
1097 struct ref *matched = NULL;
1098 int weak_match = 0;
1099 int match = 0;
1101 for (weak_match = match = 0; refs; refs = refs->next) {
1102 char *name = refs->name;
1103 int namelen = strlen(name);
1105 if (!refname_match(pattern, name))
1106 continue;
1108 /* A match is "weak" if it is with refs outside
1109 * heads or tags, and did not specify the pattern
1110 * in full (e.g. "refs/remotes/origin/master") or at
1111 * least from the toplevel (e.g. "remotes/origin/master");
1112 * otherwise "git push $URL master" would result in
1113 * ambiguity between remotes/origin/master and heads/master
1114 * at the remote site.
1116 if (namelen != patlen &&
1117 patlen != namelen - 5 &&
1118 !starts_with(name, "refs/heads/") &&
1119 !starts_with(name, "refs/tags/")) {
1120 /* We want to catch the case where only weak
1121 * matches are found and there are multiple
1122 * matches, and where more than one strong
1123 * matches are found, as ambiguous. One
1124 * strong match with zero or more weak matches
1125 * are acceptable as a unique match.
1127 matched_weak = refs;
1128 weak_match++;
1130 else {
1131 matched = refs;
1132 match++;
1135 if (!matched) {
1136 if (matched_ref)
1137 *matched_ref = matched_weak;
1138 return weak_match;
1140 else {
1141 if (matched_ref)
1142 *matched_ref = matched;
1143 return match;
1147 static void tail_link_ref(struct ref *ref, struct ref ***tail)
1149 **tail = ref;
1150 while (ref->next)
1151 ref = ref->next;
1152 *tail = &ref->next;
1155 static struct ref *alloc_delete_ref(void)
1157 struct ref *ref = alloc_ref("(delete)");
1158 oidclr(&ref->new_oid);
1159 return ref;
1162 static int try_explicit_object_name(const char *name,
1163 struct ref **match)
1165 struct object_id oid;
1167 if (!*name) {
1168 if (match)
1169 *match = alloc_delete_ref();
1170 return 0;
1173 if (repo_get_oid(the_repository, name, &oid))
1174 return -1;
1176 if (match) {
1177 *match = alloc_ref(name);
1178 oidcpy(&(*match)->new_oid, &oid);
1180 return 0;
1183 static struct ref *make_linked_ref(const char *name, struct ref ***tail)
1185 struct ref *ret = alloc_ref(name);
1186 tail_link_ref(ret, tail);
1187 return ret;
1190 static char *guess_ref(const char *name, struct ref *peer)
1192 struct strbuf buf = STRBUF_INIT;
1194 const char *r = resolve_ref_unsafe(peer->name, RESOLVE_REF_READING,
1195 NULL, NULL);
1196 if (!r)
1197 return NULL;
1199 if (starts_with(r, "refs/heads/")) {
1200 strbuf_addstr(&buf, "refs/heads/");
1201 } else if (starts_with(r, "refs/tags/")) {
1202 strbuf_addstr(&buf, "refs/tags/");
1203 } else {
1204 return NULL;
1207 strbuf_addstr(&buf, name);
1208 return strbuf_detach(&buf, NULL);
1211 static int match_explicit_lhs(struct ref *src,
1212 struct refspec_item *rs,
1213 struct ref **match,
1214 int *allocated_match)
1216 switch (count_refspec_match(rs->src, src, match)) {
1217 case 1:
1218 if (allocated_match)
1219 *allocated_match = 0;
1220 return 0;
1221 case 0:
1222 /* The source could be in the get_sha1() format
1223 * not a reference name. :refs/other is a
1224 * way to delete 'other' ref at the remote end.
1226 if (try_explicit_object_name(rs->src, match) < 0)
1227 return error(_("src refspec %s does not match any"), rs->src);
1228 if (allocated_match)
1229 *allocated_match = 1;
1230 return 0;
1231 default:
1232 return error(_("src refspec %s matches more than one"), rs->src);
1236 static void show_push_unqualified_ref_name_error(const char *dst_value,
1237 const char *matched_src_name)
1239 struct object_id oid;
1240 enum object_type type;
1243 * TRANSLATORS: "matches '%s'%" is the <dst> part of "git push
1244 * <remote> <src>:<dst>" push, and "being pushed ('%s')" is
1245 * the <src>.
1247 error(_("The destination you provided is not a full refname (i.e.,\n"
1248 "starting with \"refs/\"). We tried to guess what you meant by:\n"
1249 "\n"
1250 "- Looking for a ref that matches '%s' on the remote side.\n"
1251 "- Checking if the <src> being pushed ('%s')\n"
1252 " is a ref in \"refs/{heads,tags}/\". If so we add a corresponding\n"
1253 " refs/{heads,tags}/ prefix on the remote side.\n"
1254 "\n"
1255 "Neither worked, so we gave up. You must fully qualify the ref."),
1256 dst_value, matched_src_name);
1258 if (!advice_enabled(ADVICE_PUSH_UNQUALIFIED_REF_NAME))
1259 return;
1261 if (repo_get_oid(the_repository, matched_src_name, &oid))
1262 BUG("'%s' is not a valid object, "
1263 "match_explicit_lhs() should catch this!",
1264 matched_src_name);
1265 type = oid_object_info(the_repository, &oid, NULL);
1266 if (type == OBJ_COMMIT) {
1267 advise(_("The <src> part of the refspec is a commit object.\n"
1268 "Did you mean to create a new branch by pushing to\n"
1269 "'%s:refs/heads/%s'?"),
1270 matched_src_name, dst_value);
1271 } else if (type == OBJ_TAG) {
1272 advise(_("The <src> part of the refspec is a tag object.\n"
1273 "Did you mean to create a new tag by pushing to\n"
1274 "'%s:refs/tags/%s'?"),
1275 matched_src_name, dst_value);
1276 } else if (type == OBJ_TREE) {
1277 advise(_("The <src> part of the refspec is a tree object.\n"
1278 "Did you mean to tag a new tree by pushing to\n"
1279 "'%s:refs/tags/%s'?"),
1280 matched_src_name, dst_value);
1281 } else if (type == OBJ_BLOB) {
1282 advise(_("The <src> part of the refspec is a blob object.\n"
1283 "Did you mean to tag a new blob by pushing to\n"
1284 "'%s:refs/tags/%s'?"),
1285 matched_src_name, dst_value);
1286 } else {
1287 BUG("'%s' should be commit/tag/tree/blob, is '%d'",
1288 matched_src_name, type);
1292 static int match_explicit(struct ref *src, struct ref *dst,
1293 struct ref ***dst_tail,
1294 struct refspec_item *rs)
1296 struct ref *matched_src, *matched_dst;
1297 int allocated_src;
1299 const char *dst_value = rs->dst;
1300 char *dst_guess;
1302 if (rs->pattern || rs->matching || rs->negative)
1303 return 0;
1305 matched_src = matched_dst = NULL;
1306 if (match_explicit_lhs(src, rs, &matched_src, &allocated_src) < 0)
1307 return -1;
1309 if (!dst_value) {
1310 int flag;
1312 dst_value = resolve_ref_unsafe(matched_src->name,
1313 RESOLVE_REF_READING,
1314 NULL, &flag);
1315 if (!dst_value ||
1316 ((flag & REF_ISSYMREF) &&
1317 !starts_with(dst_value, "refs/heads/")))
1318 die(_("%s cannot be resolved to branch"),
1319 matched_src->name);
1322 switch (count_refspec_match(dst_value, dst, &matched_dst)) {
1323 case 1:
1324 break;
1325 case 0:
1326 if (starts_with(dst_value, "refs/")) {
1327 matched_dst = make_linked_ref(dst_value, dst_tail);
1328 } else if (is_null_oid(&matched_src->new_oid)) {
1329 error(_("unable to delete '%s': remote ref does not exist"),
1330 dst_value);
1331 } else if ((dst_guess = guess_ref(dst_value, matched_src))) {
1332 matched_dst = make_linked_ref(dst_guess, dst_tail);
1333 free(dst_guess);
1334 } else {
1335 show_push_unqualified_ref_name_error(dst_value,
1336 matched_src->name);
1338 break;
1339 default:
1340 matched_dst = NULL;
1341 error(_("dst refspec %s matches more than one"),
1342 dst_value);
1343 break;
1345 if (!matched_dst)
1346 return -1;
1347 if (matched_dst->peer_ref)
1348 return error(_("dst ref %s receives from more than one src"),
1349 matched_dst->name);
1350 else {
1351 matched_dst->peer_ref = allocated_src ?
1352 matched_src :
1353 copy_ref(matched_src);
1354 matched_dst->force = rs->force;
1356 return 0;
1359 static int match_explicit_refs(struct ref *src, struct ref *dst,
1360 struct ref ***dst_tail, struct refspec *rs)
1362 int i, errs;
1363 for (i = errs = 0; i < rs->nr; i++)
1364 errs += match_explicit(src, dst, dst_tail, &rs->items[i]);
1365 return errs;
1368 static char *get_ref_match(const struct refspec *rs, const struct ref *ref,
1369 int send_mirror, int direction,
1370 const struct refspec_item **ret_pat)
1372 const struct refspec_item *pat;
1373 char *name;
1374 int i;
1375 int matching_refs = -1;
1376 for (i = 0; i < rs->nr; i++) {
1377 const struct refspec_item *item = &rs->items[i];
1379 if (item->negative)
1380 continue;
1382 if (item->matching &&
1383 (matching_refs == -1 || item->force)) {
1384 matching_refs = i;
1385 continue;
1388 if (item->pattern) {
1389 const char *dst_side = item->dst ? item->dst : item->src;
1390 int match;
1391 if (direction == FROM_SRC)
1392 match = match_name_with_pattern(item->src, ref->name, dst_side, &name);
1393 else
1394 match = match_name_with_pattern(dst_side, ref->name, item->src, &name);
1395 if (match) {
1396 matching_refs = i;
1397 break;
1401 if (matching_refs == -1)
1402 return NULL;
1404 pat = &rs->items[matching_refs];
1405 if (pat->matching) {
1407 * "matching refs"; traditionally we pushed everything
1408 * including refs outside refs/heads/ hierarchy, but
1409 * that does not make much sense these days.
1411 if (!send_mirror && !starts_with(ref->name, "refs/heads/"))
1412 return NULL;
1413 name = xstrdup(ref->name);
1415 if (ret_pat)
1416 *ret_pat = pat;
1417 return name;
1420 static struct ref **tail_ref(struct ref **head)
1422 struct ref **tail = head;
1423 while (*tail)
1424 tail = &((*tail)->next);
1425 return tail;
1428 struct tips {
1429 struct commit **tip;
1430 int nr, alloc;
1433 static void add_to_tips(struct tips *tips, const struct object_id *oid)
1435 struct commit *commit;
1437 if (is_null_oid(oid))
1438 return;
1439 commit = lookup_commit_reference_gently(the_repository, oid, 1);
1440 if (!commit || (commit->object.flags & TMP_MARK))
1441 return;
1442 commit->object.flags |= TMP_MARK;
1443 ALLOC_GROW(tips->tip, tips->nr + 1, tips->alloc);
1444 tips->tip[tips->nr++] = commit;
1447 static void add_missing_tags(struct ref *src, struct ref **dst, struct ref ***dst_tail)
1449 struct string_list dst_tag = STRING_LIST_INIT_NODUP;
1450 struct string_list src_tag = STRING_LIST_INIT_NODUP;
1451 struct string_list_item *item;
1452 struct ref *ref;
1453 struct tips sent_tips;
1456 * Collect everything we know they would have at the end of
1457 * this push, and collect all tags they have.
1459 memset(&sent_tips, 0, sizeof(sent_tips));
1460 for (ref = *dst; ref; ref = ref->next) {
1461 if (ref->peer_ref &&
1462 !is_null_oid(&ref->peer_ref->new_oid))
1463 add_to_tips(&sent_tips, &ref->peer_ref->new_oid);
1464 else
1465 add_to_tips(&sent_tips, &ref->old_oid);
1466 if (starts_with(ref->name, "refs/tags/"))
1467 string_list_append(&dst_tag, ref->name);
1469 clear_commit_marks_many(sent_tips.nr, sent_tips.tip, TMP_MARK);
1471 string_list_sort(&dst_tag);
1473 /* Collect tags they do not have. */
1474 for (ref = src; ref; ref = ref->next) {
1475 if (!starts_with(ref->name, "refs/tags/"))
1476 continue; /* not a tag */
1477 if (string_list_has_string(&dst_tag, ref->name))
1478 continue; /* they already have it */
1479 if (oid_object_info(the_repository, &ref->new_oid, NULL) != OBJ_TAG)
1480 continue; /* be conservative */
1481 item = string_list_append(&src_tag, ref->name);
1482 item->util = ref;
1484 string_list_clear(&dst_tag, 0);
1487 * At this point, src_tag lists tags that are missing from
1488 * dst, and sent_tips lists the tips we are pushing or those
1489 * that we know they already have. An element in the src_tag
1490 * that is an ancestor of any of the sent_tips needs to be
1491 * sent to the other side.
1493 if (sent_tips.nr) {
1494 const int reachable_flag = 1;
1495 struct commit_list *found_commits;
1496 struct commit **src_commits;
1497 int nr_src_commits = 0, alloc_src_commits = 16;
1498 ALLOC_ARRAY(src_commits, alloc_src_commits);
1500 for_each_string_list_item(item, &src_tag) {
1501 struct ref *ref = item->util;
1502 struct commit *commit;
1504 if (is_null_oid(&ref->new_oid))
1505 continue;
1506 commit = lookup_commit_reference_gently(the_repository,
1507 &ref->new_oid,
1509 if (!commit)
1510 /* not pushing a commit, which is not an error */
1511 continue;
1513 ALLOC_GROW(src_commits, nr_src_commits + 1, alloc_src_commits);
1514 src_commits[nr_src_commits++] = commit;
1517 found_commits = get_reachable_subset(sent_tips.tip, sent_tips.nr,
1518 src_commits, nr_src_commits,
1519 reachable_flag);
1521 for_each_string_list_item(item, &src_tag) {
1522 struct ref *dst_ref;
1523 struct ref *ref = item->util;
1524 struct commit *commit;
1526 if (is_null_oid(&ref->new_oid))
1527 continue;
1528 commit = lookup_commit_reference_gently(the_repository,
1529 &ref->new_oid,
1531 if (!commit)
1532 /* not pushing a commit, which is not an error */
1533 continue;
1536 * Is this tag, which they do not have, reachable from
1537 * any of the commits we are sending?
1539 if (!(commit->object.flags & reachable_flag))
1540 continue;
1542 /* Add it in */
1543 dst_ref = make_linked_ref(ref->name, dst_tail);
1544 oidcpy(&dst_ref->new_oid, &ref->new_oid);
1545 dst_ref->peer_ref = copy_ref(ref);
1548 clear_commit_marks_many(nr_src_commits, src_commits, reachable_flag);
1549 free(src_commits);
1550 free_commit_list(found_commits);
1553 string_list_clear(&src_tag, 0);
1554 free(sent_tips.tip);
1557 struct ref *find_ref_by_name(const struct ref *list, const char *name)
1559 for ( ; list; list = list->next)
1560 if (!strcmp(list->name, name))
1561 return (struct ref *)list;
1562 return NULL;
1565 static void prepare_ref_index(struct string_list *ref_index, struct ref *ref)
1567 for ( ; ref; ref = ref->next)
1568 string_list_append_nodup(ref_index, ref->name)->util = ref;
1570 string_list_sort(ref_index);
1574 * Given only the set of local refs, sanity-check the set of push
1575 * refspecs. We can't catch all errors that match_push_refs would,
1576 * but we can catch some errors early before even talking to the
1577 * remote side.
1579 int check_push_refs(struct ref *src, struct refspec *rs)
1581 int ret = 0;
1582 int i;
1584 for (i = 0; i < rs->nr; i++) {
1585 struct refspec_item *item = &rs->items[i];
1587 if (item->pattern || item->matching || item->negative)
1588 continue;
1590 ret |= match_explicit_lhs(src, item, NULL, NULL);
1593 return ret;
1597 * Given the set of refs the local repository has, the set of refs the
1598 * remote repository has, and the refspec used for push, determine
1599 * what remote refs we will update and with what value by setting
1600 * peer_ref (which object is being pushed) and force (if the push is
1601 * forced) in elements of "dst". The function may add new elements to
1602 * dst (e.g. pushing to a new branch, done in match_explicit_refs).
1604 int match_push_refs(struct ref *src, struct ref **dst,
1605 struct refspec *rs, int flags)
1607 int send_all = flags & MATCH_REFS_ALL;
1608 int send_mirror = flags & MATCH_REFS_MIRROR;
1609 int send_prune = flags & MATCH_REFS_PRUNE;
1610 int errs;
1611 struct ref *ref, **dst_tail = tail_ref(dst);
1612 struct string_list dst_ref_index = STRING_LIST_INIT_NODUP;
1614 /* If no refspec is provided, use the default ":" */
1615 if (!rs->nr)
1616 refspec_append(rs, ":");
1618 errs = match_explicit_refs(src, *dst, &dst_tail, rs);
1620 /* pick the remainder */
1621 for (ref = src; ref; ref = ref->next) {
1622 struct string_list_item *dst_item;
1623 struct ref *dst_peer;
1624 const struct refspec_item *pat = NULL;
1625 char *dst_name;
1627 dst_name = get_ref_match(rs, ref, send_mirror, FROM_SRC, &pat);
1628 if (!dst_name)
1629 continue;
1631 if (!dst_ref_index.nr)
1632 prepare_ref_index(&dst_ref_index, *dst);
1634 dst_item = string_list_lookup(&dst_ref_index, dst_name);
1635 dst_peer = dst_item ? dst_item->util : NULL;
1636 if (dst_peer) {
1637 if (dst_peer->peer_ref)
1638 /* We're already sending something to this ref. */
1639 goto free_name;
1640 } else {
1641 if (pat->matching && !(send_all || send_mirror))
1643 * Remote doesn't have it, and we have no
1644 * explicit pattern, and we don't have
1645 * --all or --mirror.
1647 goto free_name;
1649 /* Create a new one and link it */
1650 dst_peer = make_linked_ref(dst_name, &dst_tail);
1651 oidcpy(&dst_peer->new_oid, &ref->new_oid);
1652 string_list_insert(&dst_ref_index,
1653 dst_peer->name)->util = dst_peer;
1655 dst_peer->peer_ref = copy_ref(ref);
1656 dst_peer->force = pat->force;
1657 free_name:
1658 free(dst_name);
1661 string_list_clear(&dst_ref_index, 0);
1663 if (flags & MATCH_REFS_FOLLOW_TAGS)
1664 add_missing_tags(src, dst, &dst_tail);
1666 if (send_prune) {
1667 struct string_list src_ref_index = STRING_LIST_INIT_NODUP;
1668 /* check for missing refs on the remote */
1669 for (ref = *dst; ref; ref = ref->next) {
1670 char *src_name;
1672 if (ref->peer_ref)
1673 /* We're already sending something to this ref. */
1674 continue;
1676 src_name = get_ref_match(rs, ref, send_mirror, FROM_DST, NULL);
1677 if (src_name) {
1678 if (!src_ref_index.nr)
1679 prepare_ref_index(&src_ref_index, src);
1680 if (!string_list_has_string(&src_ref_index,
1681 src_name))
1682 ref->peer_ref = alloc_delete_ref();
1683 free(src_name);
1686 string_list_clear(&src_ref_index, 0);
1689 *dst = apply_negative_refspecs(*dst, rs);
1691 if (errs)
1692 return -1;
1693 return 0;
1696 void set_ref_status_for_push(struct ref *remote_refs, int send_mirror,
1697 int force_update)
1699 struct ref *ref;
1701 for (ref = remote_refs; ref; ref = ref->next) {
1702 int force_ref_update = ref->force || force_update;
1703 int reject_reason = 0;
1705 if (ref->peer_ref)
1706 oidcpy(&ref->new_oid, &ref->peer_ref->new_oid);
1707 else if (!send_mirror)
1708 continue;
1710 ref->deletion = is_null_oid(&ref->new_oid);
1711 if (!ref->deletion &&
1712 oideq(&ref->old_oid, &ref->new_oid)) {
1713 ref->status = REF_STATUS_UPTODATE;
1714 continue;
1718 * If the remote ref has moved and is now different
1719 * from what we expect, reject any push.
1721 * It also is an error if the user told us to check
1722 * with the remote-tracking branch to find the value
1723 * to expect, but we did not have such a tracking
1724 * branch.
1726 * If the tip of the remote-tracking ref is unreachable
1727 * from any reflog entry of its local ref indicating a
1728 * possible update since checkout; reject the push.
1730 if (ref->expect_old_sha1) {
1731 if (!oideq(&ref->old_oid, &ref->old_oid_expect))
1732 reject_reason = REF_STATUS_REJECT_STALE;
1733 else if (ref->check_reachable && ref->unreachable)
1734 reject_reason =
1735 REF_STATUS_REJECT_REMOTE_UPDATED;
1736 else
1738 * If the ref isn't stale, and is reachable
1739 * from one of the reflog entries of
1740 * the local branch, force the update.
1742 force_ref_update = 1;
1746 * If the update isn't already rejected then check
1747 * the usual "must fast-forward" rules.
1749 * Decide whether an individual refspec A:B can be
1750 * pushed. The push will succeed if any of the
1751 * following are true:
1753 * (1) the remote reference B does not exist
1755 * (2) the remote reference B is being removed (i.e.,
1756 * pushing :B where no source is specified)
1758 * (3) the destination is not under refs/tags/, and
1759 * if the old and new value is a commit, the new
1760 * is a descendant of the old.
1762 * (4) it is forced using the +A:B notation, or by
1763 * passing the --force argument
1766 if (!reject_reason && !ref->deletion && !is_null_oid(&ref->old_oid)) {
1767 if (starts_with(ref->name, "refs/tags/"))
1768 reject_reason = REF_STATUS_REJECT_ALREADY_EXISTS;
1769 else if (!repo_has_object_file(the_repository, &ref->old_oid))
1770 reject_reason = REF_STATUS_REJECT_FETCH_FIRST;
1771 else if (!lookup_commit_reference_gently(the_repository, &ref->old_oid, 1) ||
1772 !lookup_commit_reference_gently(the_repository, &ref->new_oid, 1))
1773 reject_reason = REF_STATUS_REJECT_NEEDS_FORCE;
1774 else if (!ref_newer(&ref->new_oid, &ref->old_oid))
1775 reject_reason = REF_STATUS_REJECT_NONFASTFORWARD;
1779 * "--force" will defeat any rejection implemented
1780 * by the rules above.
1782 if (!force_ref_update)
1783 ref->status = reject_reason;
1784 else if (reject_reason)
1785 ref->forced_update = 1;
1789 static void set_merge(struct remote_state *remote_state, struct branch *ret)
1791 struct remote *remote;
1792 char *ref;
1793 struct object_id oid;
1794 int i;
1796 if (!ret)
1797 return; /* no branch */
1798 if (ret->merge)
1799 return; /* already run */
1800 if (!ret->remote_name || !ret->merge_nr) {
1802 * no merge config; let's make sure we don't confuse callers
1803 * with a non-zero merge_nr but a NULL merge
1805 ret->merge_nr = 0;
1806 return;
1809 remote = remotes_remote_get(remote_state, ret->remote_name);
1811 CALLOC_ARRAY(ret->merge, ret->merge_nr);
1812 for (i = 0; i < ret->merge_nr; i++) {
1813 ret->merge[i] = xcalloc(1, sizeof(**ret->merge));
1814 ret->merge[i]->src = xstrdup(ret->merge_name[i]);
1815 if (!remote_find_tracking(remote, ret->merge[i]) ||
1816 strcmp(ret->remote_name, "."))
1817 continue;
1818 if (repo_dwim_ref(the_repository, ret->merge_name[i],
1819 strlen(ret->merge_name[i]), &oid, &ref,
1820 0) == 1)
1821 ret->merge[i]->dst = ref;
1822 else
1823 ret->merge[i]->dst = xstrdup(ret->merge_name[i]);
1827 struct branch *branch_get(const char *name)
1829 struct branch *ret;
1831 read_config(the_repository);
1832 if (!name || !*name || !strcmp(name, "HEAD"))
1833 ret = the_repository->remote_state->current_branch;
1834 else
1835 ret = make_branch(the_repository->remote_state, name,
1836 strlen(name));
1837 set_merge(the_repository->remote_state, ret);
1838 return ret;
1841 int branch_has_merge_config(struct branch *branch)
1843 return branch && !!branch->merge;
1846 int branch_merge_matches(struct branch *branch,
1847 int i,
1848 const char *refname)
1850 if (!branch || i < 0 || i >= branch->merge_nr)
1851 return 0;
1852 return refname_match(branch->merge[i]->src, refname);
1855 __attribute__((format (printf,2,3)))
1856 static const char *error_buf(struct strbuf *err, const char *fmt, ...)
1858 if (err) {
1859 va_list ap;
1860 va_start(ap, fmt);
1861 strbuf_vaddf(err, fmt, ap);
1862 va_end(ap);
1864 return NULL;
1867 const char *branch_get_upstream(struct branch *branch, struct strbuf *err)
1869 if (!branch)
1870 return error_buf(err, _("HEAD does not point to a branch"));
1872 if (!branch->merge || !branch->merge[0]) {
1874 * no merge config; is it because the user didn't define any,
1875 * or because it is not a real branch, and get_branch
1876 * auto-vivified it?
1878 if (!ref_exists(branch->refname))
1879 return error_buf(err, _("no such branch: '%s'"),
1880 branch->name);
1881 return error_buf(err,
1882 _("no upstream configured for branch '%s'"),
1883 branch->name);
1886 if (!branch->merge[0]->dst)
1887 return error_buf(err,
1888 _("upstream branch '%s' not stored as a remote-tracking branch"),
1889 branch->merge[0]->src);
1891 return branch->merge[0]->dst;
1894 static const char *tracking_for_push_dest(struct remote *remote,
1895 const char *refname,
1896 struct strbuf *err)
1898 char *ret;
1900 ret = apply_refspecs(&remote->fetch, refname);
1901 if (!ret)
1902 return error_buf(err,
1903 _("push destination '%s' on remote '%s' has no local tracking branch"),
1904 refname, remote->name);
1905 return ret;
1908 static const char *branch_get_push_1(struct remote_state *remote_state,
1909 struct branch *branch, struct strbuf *err)
1911 struct remote *remote;
1913 remote = remotes_remote_get(
1914 remote_state,
1915 remotes_pushremote_for_branch(remote_state, branch, NULL));
1916 if (!remote)
1917 return error_buf(err,
1918 _("branch '%s' has no remote for pushing"),
1919 branch->name);
1921 if (remote->push.nr) {
1922 char *dst;
1923 const char *ret;
1925 dst = apply_refspecs(&remote->push, branch->refname);
1926 if (!dst)
1927 return error_buf(err,
1928 _("push refspecs for '%s' do not include '%s'"),
1929 remote->name, branch->name);
1931 ret = tracking_for_push_dest(remote, dst, err);
1932 free(dst);
1933 return ret;
1936 if (remote->mirror)
1937 return tracking_for_push_dest(remote, branch->refname, err);
1939 switch (push_default) {
1940 case PUSH_DEFAULT_NOTHING:
1941 return error_buf(err, _("push has no destination (push.default is 'nothing')"));
1943 case PUSH_DEFAULT_MATCHING:
1944 case PUSH_DEFAULT_CURRENT:
1945 return tracking_for_push_dest(remote, branch->refname, err);
1947 case PUSH_DEFAULT_UPSTREAM:
1948 return branch_get_upstream(branch, err);
1950 case PUSH_DEFAULT_UNSPECIFIED:
1951 case PUSH_DEFAULT_SIMPLE:
1953 const char *up, *cur;
1955 up = branch_get_upstream(branch, err);
1956 if (!up)
1957 return NULL;
1958 cur = tracking_for_push_dest(remote, branch->refname, err);
1959 if (!cur)
1960 return NULL;
1961 if (strcmp(cur, up))
1962 return error_buf(err,
1963 _("cannot resolve 'simple' push to a single destination"));
1964 return cur;
1968 BUG("unhandled push situation");
1971 const char *branch_get_push(struct branch *branch, struct strbuf *err)
1973 read_config(the_repository);
1974 die_on_missing_branch(the_repository, branch);
1976 if (!branch)
1977 return error_buf(err, _("HEAD does not point to a branch"));
1979 if (!branch->push_tracking_ref)
1980 branch->push_tracking_ref = branch_get_push_1(
1981 the_repository->remote_state, branch, err);
1982 return branch->push_tracking_ref;
1985 static int ignore_symref_update(const char *refname, struct strbuf *scratch)
1987 return !refs_read_symbolic_ref(get_main_ref_store(the_repository), refname, scratch);
1991 * Create and return a list of (struct ref) consisting of copies of
1992 * each remote_ref that matches refspec. refspec must be a pattern.
1993 * Fill in the copies' peer_ref to describe the local tracking refs to
1994 * which they map. Omit any references that would map to an existing
1995 * local symbolic ref.
1997 static struct ref *get_expanded_map(const struct ref *remote_refs,
1998 const struct refspec_item *refspec)
2000 struct strbuf scratch = STRBUF_INIT;
2001 const struct ref *ref;
2002 struct ref *ret = NULL;
2003 struct ref **tail = &ret;
2005 for (ref = remote_refs; ref; ref = ref->next) {
2006 char *expn_name = NULL;
2008 strbuf_reset(&scratch);
2010 if (strchr(ref->name, '^'))
2011 continue; /* a dereference item */
2012 if (match_name_with_pattern(refspec->src, ref->name,
2013 refspec->dst, &expn_name) &&
2014 !ignore_symref_update(expn_name, &scratch)) {
2015 struct ref *cpy = copy_ref(ref);
2017 cpy->peer_ref = alloc_ref(expn_name);
2018 if (refspec->force)
2019 cpy->peer_ref->force = 1;
2020 *tail = cpy;
2021 tail = &cpy->next;
2023 free(expn_name);
2026 strbuf_release(&scratch);
2027 return ret;
2030 static const struct ref *find_ref_by_name_abbrev(const struct ref *refs, const char *name)
2032 const struct ref *ref;
2033 const struct ref *best_match = NULL;
2034 int best_score = 0;
2036 for (ref = refs; ref; ref = ref->next) {
2037 int score = refname_match(name, ref->name);
2039 if (best_score < score) {
2040 best_match = ref;
2041 best_score = score;
2044 return best_match;
2047 struct ref *get_remote_ref(const struct ref *remote_refs, const char *name)
2049 const struct ref *ref = find_ref_by_name_abbrev(remote_refs, name);
2051 if (!ref)
2052 return NULL;
2054 return copy_ref(ref);
2057 static struct ref *get_local_ref(const char *name)
2059 if (!name || name[0] == '\0')
2060 return NULL;
2062 if (starts_with(name, "refs/"))
2063 return alloc_ref(name);
2065 if (starts_with(name, "heads/") ||
2066 starts_with(name, "tags/") ||
2067 starts_with(name, "remotes/"))
2068 return alloc_ref_with_prefix("refs/", 5, name);
2070 return alloc_ref_with_prefix("refs/heads/", 11, name);
2073 int get_fetch_map(const struct ref *remote_refs,
2074 const struct refspec_item *refspec,
2075 struct ref ***tail,
2076 int missing_ok)
2078 struct ref *ref_map, **rmp;
2080 if (refspec->negative)
2081 return 0;
2083 if (refspec->pattern) {
2084 ref_map = get_expanded_map(remote_refs, refspec);
2085 } else {
2086 const char *name = refspec->src[0] ? refspec->src : "HEAD";
2088 if (refspec->exact_sha1) {
2089 ref_map = alloc_ref(name);
2090 get_oid_hex(name, &ref_map->old_oid);
2091 ref_map->exact_oid = 1;
2092 } else {
2093 ref_map = get_remote_ref(remote_refs, name);
2095 if (!missing_ok && !ref_map)
2096 die(_("couldn't find remote ref %s"), name);
2097 if (ref_map) {
2098 ref_map->peer_ref = get_local_ref(refspec->dst);
2099 if (ref_map->peer_ref && refspec->force)
2100 ref_map->peer_ref->force = 1;
2104 for (rmp = &ref_map; *rmp; ) {
2105 if ((*rmp)->peer_ref) {
2106 if (!starts_with((*rmp)->peer_ref->name, "refs/") ||
2107 check_refname_format((*rmp)->peer_ref->name, 0)) {
2108 struct ref *ignore = *rmp;
2109 error(_("* Ignoring funny ref '%s' locally"),
2110 (*rmp)->peer_ref->name);
2111 *rmp = (*rmp)->next;
2112 free(ignore->peer_ref);
2113 free(ignore);
2114 continue;
2117 rmp = &((*rmp)->next);
2120 if (ref_map)
2121 tail_link_ref(ref_map, tail);
2123 return 0;
2126 int resolve_remote_symref(struct ref *ref, struct ref *list)
2128 if (!ref->symref)
2129 return 0;
2130 for (; list; list = list->next)
2131 if (!strcmp(ref->symref, list->name)) {
2132 oidcpy(&ref->old_oid, &list->old_oid);
2133 return 0;
2135 return 1;
2139 * Compute the commit ahead/behind values for the pair branch_name, base.
2141 * If abf is AHEAD_BEHIND_FULL, compute the full ahead/behind and return the
2142 * counts in *num_ours and *num_theirs. If abf is AHEAD_BEHIND_QUICK, skip
2143 * the (potentially expensive) a/b computation (*num_ours and *num_theirs are
2144 * set to zero).
2146 * Returns -1 if num_ours and num_theirs could not be filled in (e.g., ref
2147 * does not exist). Returns 0 if the commits are identical. Returns 1 if
2148 * commits are different.
2151 static int stat_branch_pair(const char *branch_name, const char *base,
2152 int *num_ours, int *num_theirs,
2153 enum ahead_behind_flags abf)
2155 struct object_id oid;
2156 struct commit *ours, *theirs;
2157 struct rev_info revs;
2158 struct setup_revision_opt opt = {
2159 .free_removed_argv_elements = 1,
2161 struct strvec argv = STRVEC_INIT;
2163 /* Cannot stat if what we used to build on no longer exists */
2164 if (read_ref(base, &oid))
2165 return -1;
2166 theirs = lookup_commit_reference(the_repository, &oid);
2167 if (!theirs)
2168 return -1;
2170 if (read_ref(branch_name, &oid))
2171 return -1;
2172 ours = lookup_commit_reference(the_repository, &oid);
2173 if (!ours)
2174 return -1;
2176 *num_theirs = *num_ours = 0;
2178 /* are we the same? */
2179 if (theirs == ours)
2180 return 0;
2181 if (abf == AHEAD_BEHIND_QUICK)
2182 return 1;
2183 if (abf != AHEAD_BEHIND_FULL)
2184 BUG("stat_branch_pair: invalid abf '%d'", abf);
2186 /* Run "rev-list --left-right ours...theirs" internally... */
2187 strvec_push(&argv, ""); /* ignored */
2188 strvec_push(&argv, "--left-right");
2189 strvec_pushf(&argv, "%s...%s",
2190 oid_to_hex(&ours->object.oid),
2191 oid_to_hex(&theirs->object.oid));
2192 strvec_push(&argv, "--");
2194 repo_init_revisions(the_repository, &revs, NULL);
2195 setup_revisions(argv.nr, argv.v, &revs, &opt);
2196 if (prepare_revision_walk(&revs))
2197 die(_("revision walk setup failed"));
2199 /* ... and count the commits on each side. */
2200 while (1) {
2201 struct commit *c = get_revision(&revs);
2202 if (!c)
2203 break;
2204 if (c->object.flags & SYMMETRIC_LEFT)
2205 (*num_ours)++;
2206 else
2207 (*num_theirs)++;
2210 /* clear object flags smudged by the above traversal */
2211 clear_commit_marks(ours, ALL_REV_FLAGS);
2212 clear_commit_marks(theirs, ALL_REV_FLAGS);
2214 strvec_clear(&argv);
2215 release_revisions(&revs);
2216 return 1;
2220 * Lookup the tracking branch for the given branch and if present, optionally
2221 * compute the commit ahead/behind values for the pair.
2223 * If for_push is true, the tracking branch refers to the push branch,
2224 * otherwise it refers to the upstream branch.
2226 * The name of the tracking branch (or NULL if it is not defined) is
2227 * returned via *tracking_name, if it is not itself NULL.
2229 * If abf is AHEAD_BEHIND_FULL, compute the full ahead/behind and return the
2230 * counts in *num_ours and *num_theirs. If abf is AHEAD_BEHIND_QUICK, skip
2231 * the (potentially expensive) a/b computation (*num_ours and *num_theirs are
2232 * set to zero).
2234 * Returns -1 if num_ours and num_theirs could not be filled in (e.g., no
2235 * upstream defined, or ref does not exist). Returns 0 if the commits are
2236 * identical. Returns 1 if commits are different.
2238 int stat_tracking_info(struct branch *branch, int *num_ours, int *num_theirs,
2239 const char **tracking_name, int for_push,
2240 enum ahead_behind_flags abf)
2242 const char *base;
2244 /* Cannot stat unless we are marked to build on top of somebody else. */
2245 base = for_push ? branch_get_push(branch, NULL) :
2246 branch_get_upstream(branch, NULL);
2247 if (tracking_name)
2248 *tracking_name = base;
2249 if (!base)
2250 return -1;
2252 return stat_branch_pair(branch->refname, base, num_ours, num_theirs, abf);
2256 * Return true when there is anything to report, otherwise false.
2258 int format_tracking_info(struct branch *branch, struct strbuf *sb,
2259 enum ahead_behind_flags abf)
2261 int ours, theirs, sti;
2262 const char *full_base;
2263 char *base;
2264 int upstream_is_gone = 0;
2266 sti = stat_tracking_info(branch, &ours, &theirs, &full_base, 0, abf);
2267 if (sti < 0) {
2268 if (!full_base)
2269 return 0;
2270 upstream_is_gone = 1;
2273 base = shorten_unambiguous_ref(full_base, 0);
2274 if (upstream_is_gone) {
2275 strbuf_addf(sb,
2276 _("Your branch is based on '%s', but the upstream is gone.\n"),
2277 base);
2278 if (advice_enabled(ADVICE_STATUS_HINTS))
2279 strbuf_addstr(sb,
2280 _(" (use \"git branch --unset-upstream\" to fixup)\n"));
2281 } else if (!sti) {
2282 strbuf_addf(sb,
2283 _("Your branch is up to date with '%s'.\n"),
2284 base);
2285 } else if (abf == AHEAD_BEHIND_QUICK) {
2286 strbuf_addf(sb,
2287 _("Your branch and '%s' refer to different commits.\n"),
2288 base);
2289 if (advice_enabled(ADVICE_STATUS_HINTS))
2290 strbuf_addf(sb, _(" (use \"%s\" for details)\n"),
2291 "git status --ahead-behind");
2292 } else if (!theirs) {
2293 strbuf_addf(sb,
2294 Q_("Your branch is ahead of '%s' by %d commit.\n",
2295 "Your branch is ahead of '%s' by %d commits.\n",
2296 ours),
2297 base, ours);
2298 if (advice_enabled(ADVICE_STATUS_HINTS))
2299 strbuf_addstr(sb,
2300 _(" (use \"git push\" to publish your local commits)\n"));
2301 } else if (!ours) {
2302 strbuf_addf(sb,
2303 Q_("Your branch is behind '%s' by %d commit, "
2304 "and can be fast-forwarded.\n",
2305 "Your branch is behind '%s' by %d commits, "
2306 "and can be fast-forwarded.\n",
2307 theirs),
2308 base, theirs);
2309 if (advice_enabled(ADVICE_STATUS_HINTS))
2310 strbuf_addstr(sb,
2311 _(" (use \"git pull\" to update your local branch)\n"));
2312 } else {
2313 strbuf_addf(sb,
2314 Q_("Your branch and '%s' have diverged,\n"
2315 "and have %d and %d different commit each, "
2316 "respectively.\n",
2317 "Your branch and '%s' have diverged,\n"
2318 "and have %d and %d different commits each, "
2319 "respectively.\n",
2320 ours + theirs),
2321 base, ours, theirs);
2322 if (advice_enabled(ADVICE_STATUS_HINTS))
2323 strbuf_addstr(sb,
2324 _(" (use \"git pull\" to merge the remote branch into yours)\n"));
2326 free(base);
2327 return 1;
2330 static int one_local_ref(const char *refname, const struct object_id *oid,
2331 int flag UNUSED,
2332 void *cb_data)
2334 struct ref ***local_tail = cb_data;
2335 struct ref *ref;
2337 /* we already know it starts with refs/ to get here */
2338 if (check_refname_format(refname + 5, 0))
2339 return 0;
2341 ref = alloc_ref(refname);
2342 oidcpy(&ref->new_oid, oid);
2343 **local_tail = ref;
2344 *local_tail = &ref->next;
2345 return 0;
2348 struct ref *get_local_heads(void)
2350 struct ref *local_refs = NULL, **local_tail = &local_refs;
2352 for_each_ref(one_local_ref, &local_tail);
2353 return local_refs;
2356 struct ref *guess_remote_head(const struct ref *head,
2357 const struct ref *refs,
2358 int all)
2360 const struct ref *r;
2361 struct ref *list = NULL;
2362 struct ref **tail = &list;
2364 if (!head)
2365 return NULL;
2368 * Some transports support directly peeking at
2369 * where HEAD points; if that is the case, then
2370 * we don't have to guess.
2372 if (head->symref)
2373 return copy_ref(find_ref_by_name(refs, head->symref));
2375 /* If a remote branch exists with the default branch name, let's use it. */
2376 if (!all) {
2377 char *ref = xstrfmt("refs/heads/%s",
2378 git_default_branch_name(0));
2380 r = find_ref_by_name(refs, ref);
2381 free(ref);
2382 if (r && oideq(&r->old_oid, &head->old_oid))
2383 return copy_ref(r);
2385 /* Fall back to the hard-coded historical default */
2386 r = find_ref_by_name(refs, "refs/heads/master");
2387 if (r && oideq(&r->old_oid, &head->old_oid))
2388 return copy_ref(r);
2391 /* Look for another ref that points there */
2392 for (r = refs; r; r = r->next) {
2393 if (r != head &&
2394 starts_with(r->name, "refs/heads/") &&
2395 oideq(&r->old_oid, &head->old_oid)) {
2396 *tail = copy_ref(r);
2397 tail = &((*tail)->next);
2398 if (!all)
2399 break;
2403 return list;
2406 struct stale_heads_info {
2407 struct string_list *ref_names;
2408 struct ref **stale_refs_tail;
2409 struct refspec *rs;
2412 static int get_stale_heads_cb(const char *refname, const struct object_id *oid,
2413 int flags, void *cb_data)
2415 struct stale_heads_info *info = cb_data;
2416 struct string_list matches = STRING_LIST_INIT_DUP;
2417 struct refspec_item query;
2418 int i, stale = 1;
2419 memset(&query, 0, sizeof(struct refspec_item));
2420 query.dst = (char *)refname;
2422 query_refspecs_multiple(info->rs, &query, &matches);
2423 if (matches.nr == 0)
2424 goto clean_exit; /* No matches */
2427 * If we did find a suitable refspec and it's not a symref and
2428 * it's not in the list of refs that currently exist in that
2429 * remote, we consider it to be stale. In order to deal with
2430 * overlapping refspecs, we need to go over all of the
2431 * matching refs.
2433 if (flags & REF_ISSYMREF)
2434 goto clean_exit;
2436 for (i = 0; stale && i < matches.nr; i++)
2437 if (string_list_has_string(info->ref_names, matches.items[i].string))
2438 stale = 0;
2440 if (stale) {
2441 struct ref *ref = make_linked_ref(refname, &info->stale_refs_tail);
2442 oidcpy(&ref->new_oid, oid);
2445 clean_exit:
2446 string_list_clear(&matches, 0);
2447 return 0;
2450 struct ref *get_stale_heads(struct refspec *rs, struct ref *fetch_map)
2452 struct ref *ref, *stale_refs = NULL;
2453 struct string_list ref_names = STRING_LIST_INIT_NODUP;
2454 struct stale_heads_info info;
2456 info.ref_names = &ref_names;
2457 info.stale_refs_tail = &stale_refs;
2458 info.rs = rs;
2459 for (ref = fetch_map; ref; ref = ref->next)
2460 string_list_append(&ref_names, ref->name);
2461 string_list_sort(&ref_names);
2462 for_each_ref(get_stale_heads_cb, &info);
2463 string_list_clear(&ref_names, 0);
2464 return stale_refs;
2468 * Compare-and-swap
2470 static void clear_cas_option(struct push_cas_option *cas)
2472 int i;
2474 for (i = 0; i < cas->nr; i++)
2475 free(cas->entry[i].refname);
2476 free(cas->entry);
2477 memset(cas, 0, sizeof(*cas));
2480 static struct push_cas *add_cas_entry(struct push_cas_option *cas,
2481 const char *refname,
2482 size_t refnamelen)
2484 struct push_cas *entry;
2485 ALLOC_GROW(cas->entry, cas->nr + 1, cas->alloc);
2486 entry = &cas->entry[cas->nr++];
2487 memset(entry, 0, sizeof(*entry));
2488 entry->refname = xmemdupz(refname, refnamelen);
2489 return entry;
2492 static int parse_push_cas_option(struct push_cas_option *cas, const char *arg, int unset)
2494 const char *colon;
2495 struct push_cas *entry;
2497 if (unset) {
2498 /* "--no-<option>" */
2499 clear_cas_option(cas);
2500 return 0;
2503 if (!arg) {
2504 /* just "--<option>" */
2505 cas->use_tracking_for_rest = 1;
2506 return 0;
2509 /* "--<option>=refname" or "--<option>=refname:value" */
2510 colon = strchrnul(arg, ':');
2511 entry = add_cas_entry(cas, arg, colon - arg);
2512 if (!*colon)
2513 entry->use_tracking = 1;
2514 else if (!colon[1])
2515 oidclr(&entry->expect);
2516 else if (repo_get_oid(the_repository, colon + 1, &entry->expect))
2517 return error(_("cannot parse expected object name '%s'"),
2518 colon + 1);
2519 return 0;
2522 int parseopt_push_cas_option(const struct option *opt, const char *arg, int unset)
2524 return parse_push_cas_option(opt->value, arg, unset);
2527 int is_empty_cas(const struct push_cas_option *cas)
2529 return !cas->use_tracking_for_rest && !cas->nr;
2533 * Look at remote.fetch refspec and see if we have a remote
2534 * tracking branch for the refname there. Fill the name of
2535 * the remote-tracking branch in *dst_refname, and the name
2536 * of the commit object at its tip in oid[].
2537 * If we cannot do so, return negative to signal an error.
2539 static int remote_tracking(struct remote *remote, const char *refname,
2540 struct object_id *oid, char **dst_refname)
2542 char *dst;
2544 dst = apply_refspecs(&remote->fetch, refname);
2545 if (!dst)
2546 return -1; /* no tracking ref for refname at remote */
2547 if (read_ref(dst, oid))
2548 return -1; /* we know what the tracking ref is but we cannot read it */
2550 *dst_refname = dst;
2551 return 0;
2555 * The struct "reflog_commit_array" and related helper functions
2556 * are used for collecting commits into an array during reflog
2557 * traversals in "check_and_collect_until()".
2559 struct reflog_commit_array {
2560 struct commit **item;
2561 size_t nr, alloc;
2564 #define REFLOG_COMMIT_ARRAY_INIT { 0 }
2566 /* Append a commit to the array. */
2567 static void append_commit(struct reflog_commit_array *arr,
2568 struct commit *commit)
2570 ALLOC_GROW(arr->item, arr->nr + 1, arr->alloc);
2571 arr->item[arr->nr++] = commit;
2574 /* Free and reset the array. */
2575 static void free_commit_array(struct reflog_commit_array *arr)
2577 FREE_AND_NULL(arr->item);
2578 arr->nr = arr->alloc = 0;
2581 struct check_and_collect_until_cb_data {
2582 struct commit *remote_commit;
2583 struct reflog_commit_array *local_commits;
2584 timestamp_t remote_reflog_timestamp;
2587 /* Get the timestamp of the latest entry. */
2588 static int peek_reflog(struct object_id *o_oid UNUSED,
2589 struct object_id *n_oid UNUSED,
2590 const char *ident UNUSED,
2591 timestamp_t timestamp, int tz UNUSED,
2592 const char *message UNUSED, void *cb_data)
2594 timestamp_t *ts = cb_data;
2595 *ts = timestamp;
2596 return 1;
2599 static int check_and_collect_until(struct object_id *o_oid UNUSED,
2600 struct object_id *n_oid,
2601 const char *ident UNUSED,
2602 timestamp_t timestamp, int tz UNUSED,
2603 const char *message UNUSED, void *cb_data)
2605 struct commit *commit;
2606 struct check_and_collect_until_cb_data *cb = cb_data;
2608 /* An entry was found. */
2609 if (oideq(n_oid, &cb->remote_commit->object.oid))
2610 return 1;
2612 if ((commit = lookup_commit_reference(the_repository, n_oid)))
2613 append_commit(cb->local_commits, commit);
2616 * If the reflog entry timestamp is older than the remote ref's
2617 * latest reflog entry, there is no need to check or collect
2618 * entries older than this one.
2620 if (timestamp < cb->remote_reflog_timestamp)
2621 return -1;
2623 return 0;
2626 #define MERGE_BASES_BATCH_SIZE 8
2629 * Iterate through the reflog of the local ref to check if there is an entry
2630 * for the given remote-tracking ref; runs until the timestamp of an entry is
2631 * older than latest timestamp of remote-tracking ref's reflog. Any commits
2632 * are that seen along the way are collected into an array to check if the
2633 * remote-tracking ref is reachable from any of them.
2635 static int is_reachable_in_reflog(const char *local, const struct ref *remote)
2637 timestamp_t date;
2638 struct commit *commit;
2639 struct commit **chunk;
2640 struct check_and_collect_until_cb_data cb;
2641 struct reflog_commit_array arr = REFLOG_COMMIT_ARRAY_INIT;
2642 size_t size = 0;
2643 int ret = 0;
2645 commit = lookup_commit_reference(the_repository, &remote->old_oid);
2646 if (!commit)
2647 goto cleanup_return;
2650 * Get the timestamp from the latest entry
2651 * of the remote-tracking ref's reflog.
2653 for_each_reflog_ent_reverse(remote->tracking_ref, peek_reflog, &date);
2655 cb.remote_commit = commit;
2656 cb.local_commits = &arr;
2657 cb.remote_reflog_timestamp = date;
2658 ret = for_each_reflog_ent_reverse(local, check_and_collect_until, &cb);
2660 /* We found an entry in the reflog. */
2661 if (ret > 0)
2662 goto cleanup_return;
2665 * Check if the remote commit is reachable from any
2666 * of the commits in the collected array, in batches.
2668 for (chunk = arr.item; chunk < arr.item + arr.nr; chunk += size) {
2669 size = arr.item + arr.nr - chunk;
2670 if (MERGE_BASES_BATCH_SIZE < size)
2671 size = MERGE_BASES_BATCH_SIZE;
2673 if ((ret = repo_in_merge_bases_many(the_repository, commit, size, chunk)))
2674 break;
2677 cleanup_return:
2678 free_commit_array(&arr);
2679 return ret;
2683 * Check for reachability of a remote-tracking
2684 * ref in the reflog entries of its local ref.
2686 static void check_if_includes_upstream(struct ref *remote)
2688 struct ref *local = get_local_ref(remote->name);
2689 if (!local)
2690 return;
2692 if (is_reachable_in_reflog(local->name, remote) <= 0)
2693 remote->unreachable = 1;
2696 static void apply_cas(struct push_cas_option *cas,
2697 struct remote *remote,
2698 struct ref *ref)
2700 int i;
2702 /* Find an explicit --<option>=<name>[:<value>] entry */
2703 for (i = 0; i < cas->nr; i++) {
2704 struct push_cas *entry = &cas->entry[i];
2705 if (!refname_match(entry->refname, ref->name))
2706 continue;
2707 ref->expect_old_sha1 = 1;
2708 if (!entry->use_tracking)
2709 oidcpy(&ref->old_oid_expect, &entry->expect);
2710 else if (remote_tracking(remote, ref->name,
2711 &ref->old_oid_expect,
2712 &ref->tracking_ref))
2713 oidclr(&ref->old_oid_expect);
2714 else
2715 ref->check_reachable = cas->use_force_if_includes;
2716 return;
2719 /* Are we using "--<option>" to cover all? */
2720 if (!cas->use_tracking_for_rest)
2721 return;
2723 ref->expect_old_sha1 = 1;
2724 if (remote_tracking(remote, ref->name,
2725 &ref->old_oid_expect,
2726 &ref->tracking_ref))
2727 oidclr(&ref->old_oid_expect);
2728 else
2729 ref->check_reachable = cas->use_force_if_includes;
2732 void apply_push_cas(struct push_cas_option *cas,
2733 struct remote *remote,
2734 struct ref *remote_refs)
2736 struct ref *ref;
2737 for (ref = remote_refs; ref; ref = ref->next) {
2738 apply_cas(cas, remote, ref);
2741 * If "compare-and-swap" is in "use_tracking[_for_rest]"
2742 * mode, and if "--force-if-includes" was specified, run
2743 * the check.
2745 if (ref->check_reachable)
2746 check_if_includes_upstream(ref);
2750 struct remote_state *remote_state_new(void)
2752 struct remote_state *r = xmalloc(sizeof(*r));
2754 memset(r, 0, sizeof(*r));
2756 hashmap_init(&r->remotes_hash, remotes_hash_cmp, NULL, 0);
2757 hashmap_init(&r->branches_hash, branches_hash_cmp, NULL, 0);
2758 return r;
2761 void remote_state_clear(struct remote_state *remote_state)
2763 int i;
2765 for (i = 0; i < remote_state->remotes_nr; i++)
2766 remote_clear(remote_state->remotes[i]);
2767 FREE_AND_NULL(remote_state->remotes);
2768 remote_state->remotes_alloc = 0;
2769 remote_state->remotes_nr = 0;
2771 hashmap_clear_and_free(&remote_state->remotes_hash, struct remote, ent);
2772 hashmap_clear_and_free(&remote_state->branches_hash, struct remote, ent);
2776 * Returns 1 if it was the last chop before ':'.
2778 static int chop_last_dir(char **remoteurl, int is_relative)
2780 char *rfind = find_last_dir_sep(*remoteurl);
2781 if (rfind) {
2782 *rfind = '\0';
2783 return 0;
2786 rfind = strrchr(*remoteurl, ':');
2787 if (rfind) {
2788 *rfind = '\0';
2789 return 1;
2792 if (is_relative || !strcmp(".", *remoteurl))
2793 die(_("cannot strip one component off url '%s'"),
2794 *remoteurl);
2796 free(*remoteurl);
2797 *remoteurl = xstrdup(".");
2798 return 0;
2801 char *relative_url(const char *remote_url, const char *url,
2802 const char *up_path)
2804 int is_relative = 0;
2805 int colonsep = 0;
2806 char *out;
2807 char *remoteurl;
2808 struct strbuf sb = STRBUF_INIT;
2809 size_t len;
2811 if (!url_is_local_not_ssh(url) || is_absolute_path(url))
2812 return xstrdup(url);
2814 len = strlen(remote_url);
2815 if (!len)
2816 BUG("invalid empty remote_url");
2818 remoteurl = xstrdup(remote_url);
2819 if (is_dir_sep(remoteurl[len-1]))
2820 remoteurl[len-1] = '\0';
2822 if (!url_is_local_not_ssh(remoteurl) || is_absolute_path(remoteurl))
2823 is_relative = 0;
2824 else {
2825 is_relative = 1;
2827 * Prepend a './' to ensure all relative
2828 * remoteurls start with './' or '../'
2830 if (!starts_with_dot_slash_native(remoteurl) &&
2831 !starts_with_dot_dot_slash_native(remoteurl)) {
2832 strbuf_reset(&sb);
2833 strbuf_addf(&sb, "./%s", remoteurl);
2834 free(remoteurl);
2835 remoteurl = strbuf_detach(&sb, NULL);
2839 * When the url starts with '../', remove that and the
2840 * last directory in remoteurl.
2842 while (*url) {
2843 if (starts_with_dot_dot_slash_native(url)) {
2844 url += 3;
2845 colonsep |= chop_last_dir(&remoteurl, is_relative);
2846 } else if (starts_with_dot_slash_native(url))
2847 url += 2;
2848 else
2849 break;
2851 strbuf_reset(&sb);
2852 strbuf_addf(&sb, "%s%s%s", remoteurl, colonsep ? ":" : "/", url);
2853 if (ends_with(url, "/"))
2854 strbuf_setlen(&sb, sb.len - 1);
2855 free(remoteurl);
2857 if (starts_with_dot_slash_native(sb.buf))
2858 out = xstrdup(sb.buf + 2);
2859 else
2860 out = xstrdup(sb.buf);
2862 if (!up_path || !is_relative) {
2863 strbuf_release(&sb);
2864 return out;
2867 strbuf_reset(&sb);
2868 strbuf_addf(&sb, "%s%s", up_path, out);
2869 free(out);
2870 return strbuf_detach(&sb, NULL);