Merge branch 'ds/bundle-uri'
[alt-git.git] / remote.c
blobe98148ac227310247aa6de0fd1f251b4b028f381
1 #include "cache.h"
2 #include "config.h"
3 #include "remote.h"
4 #include "refs.h"
5 #include "refspec.h"
6 #include "object-store.h"
7 #include "commit.h"
8 #include "diff.h"
9 #include "revision.h"
10 #include "dir.h"
11 #include "tag.h"
12 #include "string-list.h"
13 #include "mergesort.h"
14 #include "strvec.h"
15 #include "commit-reach.h"
16 #include "advice.h"
17 #include "connect.h"
19 enum map_direction { FROM_SRC, FROM_DST };
21 struct counted_string {
22 size_t len;
23 const char *s;
26 static int valid_remote(const struct remote *remote)
28 return (!!remote->url) || (!!remote->foreign_vcs);
31 static const char *alias_url(const char *url, struct rewrites *r)
33 int i, j;
34 struct counted_string *longest;
35 int longest_i;
37 longest = NULL;
38 longest_i = -1;
39 for (i = 0; i < r->rewrite_nr; i++) {
40 if (!r->rewrite[i])
41 continue;
42 for (j = 0; j < r->rewrite[i]->instead_of_nr; j++) {
43 if (starts_with(url, r->rewrite[i]->instead_of[j].s) &&
44 (!longest ||
45 longest->len < r->rewrite[i]->instead_of[j].len)) {
46 longest = &(r->rewrite[i]->instead_of[j]);
47 longest_i = i;
51 if (!longest)
52 return url;
54 return xstrfmt("%s%s", r->rewrite[longest_i]->base, url + longest->len);
57 static void add_url(struct remote *remote, const char *url)
59 ALLOC_GROW(remote->url, remote->url_nr + 1, remote->url_alloc);
60 remote->url[remote->url_nr++] = url;
63 static void add_pushurl(struct remote *remote, const char *pushurl)
65 ALLOC_GROW(remote->pushurl, remote->pushurl_nr + 1, remote->pushurl_alloc);
66 remote->pushurl[remote->pushurl_nr++] = pushurl;
69 static void add_pushurl_alias(struct remote_state *remote_state,
70 struct remote *remote, const char *url)
72 const char *pushurl = alias_url(url, &remote_state->rewrites_push);
73 if (pushurl != url)
74 add_pushurl(remote, pushurl);
77 static void add_url_alias(struct remote_state *remote_state,
78 struct remote *remote, const char *url)
80 add_url(remote, alias_url(url, &remote_state->rewrites));
81 add_pushurl_alias(remote_state, remote, url);
84 struct remotes_hash_key {
85 const char *str;
86 int len;
89 static int remotes_hash_cmp(const void *unused_cmp_data,
90 const struct hashmap_entry *eptr,
91 const struct hashmap_entry *entry_or_key,
92 const void *keydata)
94 const struct remote *a, *b;
95 const struct remotes_hash_key *key = keydata;
97 a = container_of(eptr, const struct remote, ent);
98 b = container_of(entry_or_key, const struct remote, ent);
100 if (key)
101 return strncmp(a->name, key->str, key->len) || a->name[key->len];
102 else
103 return strcmp(a->name, b->name);
106 static struct remote *make_remote(struct remote_state *remote_state,
107 const char *name, int len)
109 struct remote *ret;
110 struct remotes_hash_key lookup;
111 struct hashmap_entry lookup_entry, *e;
113 if (!len)
114 len = strlen(name);
116 lookup.str = name;
117 lookup.len = len;
118 hashmap_entry_init(&lookup_entry, memhash(name, len));
120 e = hashmap_get(&remote_state->remotes_hash, &lookup_entry, &lookup);
121 if (e)
122 return container_of(e, struct remote, ent);
124 CALLOC_ARRAY(ret, 1);
125 ret->prune = -1; /* unspecified */
126 ret->prune_tags = -1; /* unspecified */
127 ret->name = xstrndup(name, len);
128 refspec_init(&ret->push, REFSPEC_PUSH);
129 refspec_init(&ret->fetch, REFSPEC_FETCH);
131 ALLOC_GROW(remote_state->remotes, remote_state->remotes_nr + 1,
132 remote_state->remotes_alloc);
133 remote_state->remotes[remote_state->remotes_nr++] = ret;
135 hashmap_entry_init(&ret->ent, lookup_entry.hash);
136 if (hashmap_put_entry(&remote_state->remotes_hash, ret, ent))
137 BUG("hashmap_put overwrote entry after hashmap_get returned NULL");
138 return ret;
141 static void remote_clear(struct remote *remote)
143 int i;
145 free((char *)remote->name);
146 free((char *)remote->foreign_vcs);
148 for (i = 0; i < remote->url_nr; i++) {
149 free((char *)remote->url[i]);
151 FREE_AND_NULL(remote->pushurl);
153 for (i = 0; i < remote->pushurl_nr; i++) {
154 free((char *)remote->pushurl[i]);
156 FREE_AND_NULL(remote->pushurl);
157 free((char *)remote->receivepack);
158 free((char *)remote->uploadpack);
159 FREE_AND_NULL(remote->http_proxy);
160 FREE_AND_NULL(remote->http_proxy_authmethod);
163 static void add_merge(struct branch *branch, const char *name)
165 ALLOC_GROW(branch->merge_name, branch->merge_nr + 1,
166 branch->merge_alloc);
167 branch->merge_name[branch->merge_nr++] = name;
170 struct branches_hash_key {
171 const char *str;
172 int len;
175 static int branches_hash_cmp(const void *unused_cmp_data,
176 const struct hashmap_entry *eptr,
177 const struct hashmap_entry *entry_or_key,
178 const void *keydata)
180 const struct branch *a, *b;
181 const struct branches_hash_key *key = keydata;
183 a = container_of(eptr, const struct branch, ent);
184 b = container_of(entry_or_key, const struct branch, ent);
186 if (key)
187 return strncmp(a->name, key->str, key->len) ||
188 a->name[key->len];
189 else
190 return strcmp(a->name, b->name);
193 static struct branch *find_branch(struct remote_state *remote_state,
194 const char *name, size_t len)
196 struct branches_hash_key lookup;
197 struct hashmap_entry lookup_entry, *e;
199 if (!len)
200 len = strlen(name);
202 lookup.str = name;
203 lookup.len = len;
204 hashmap_entry_init(&lookup_entry, memhash(name, len));
206 e = hashmap_get(&remote_state->branches_hash, &lookup_entry, &lookup);
207 if (e)
208 return container_of(e, struct branch, ent);
210 return NULL;
213 static void die_on_missing_branch(struct repository *repo,
214 struct branch *branch)
216 /* branch == NULL is always valid because it represents detached HEAD. */
217 if (branch &&
218 branch != find_branch(repo->remote_state, branch->name, 0))
219 die("branch %s was not found in the repository", branch->name);
222 static struct branch *make_branch(struct remote_state *remote_state,
223 const char *name, size_t len)
225 struct branch *ret;
227 ret = find_branch(remote_state, name, len);
228 if (ret)
229 return ret;
231 CALLOC_ARRAY(ret, 1);
232 ret->name = xstrndup(name, len);
233 ret->refname = xstrfmt("refs/heads/%s", ret->name);
235 hashmap_entry_init(&ret->ent, memhash(name, len));
236 if (hashmap_put_entry(&remote_state->branches_hash, ret, ent))
237 BUG("hashmap_put overwrote entry after hashmap_get returned NULL");
238 return ret;
241 static struct rewrite *make_rewrite(struct rewrites *r,
242 const char *base, size_t len)
244 struct rewrite *ret;
245 int i;
247 for (i = 0; i < r->rewrite_nr; i++) {
248 if (len == r->rewrite[i]->baselen &&
249 !strncmp(base, r->rewrite[i]->base, len))
250 return r->rewrite[i];
253 ALLOC_GROW(r->rewrite, r->rewrite_nr + 1, r->rewrite_alloc);
254 CALLOC_ARRAY(ret, 1);
255 r->rewrite[r->rewrite_nr++] = ret;
256 ret->base = xstrndup(base, len);
257 ret->baselen = len;
258 return ret;
261 static void add_instead_of(struct rewrite *rewrite, const char *instead_of)
263 ALLOC_GROW(rewrite->instead_of, rewrite->instead_of_nr + 1, rewrite->instead_of_alloc);
264 rewrite->instead_of[rewrite->instead_of_nr].s = instead_of;
265 rewrite->instead_of[rewrite->instead_of_nr].len = strlen(instead_of);
266 rewrite->instead_of_nr++;
269 static const char *skip_spaces(const char *s)
271 while (isspace(*s))
272 s++;
273 return s;
276 static void read_remotes_file(struct remote_state *remote_state,
277 struct remote *remote)
279 struct strbuf buf = STRBUF_INIT;
280 FILE *f = fopen_or_warn(git_path("remotes/%s", remote->name), "r");
282 if (!f)
283 return;
284 remote->configured_in_repo = 1;
285 remote->origin = REMOTE_REMOTES;
286 while (strbuf_getline(&buf, f) != EOF) {
287 const char *v;
289 strbuf_rtrim(&buf);
291 if (skip_prefix(buf.buf, "URL:", &v))
292 add_url_alias(remote_state, remote,
293 xstrdup(skip_spaces(v)));
294 else if (skip_prefix(buf.buf, "Push:", &v))
295 refspec_append(&remote->push, skip_spaces(v));
296 else if (skip_prefix(buf.buf, "Pull:", &v))
297 refspec_append(&remote->fetch, skip_spaces(v));
299 strbuf_release(&buf);
300 fclose(f);
303 static void read_branches_file(struct remote_state *remote_state,
304 struct remote *remote)
306 char *frag;
307 struct strbuf buf = STRBUF_INIT;
308 FILE *f = fopen_or_warn(git_path("branches/%s", remote->name), "r");
310 if (!f)
311 return;
313 strbuf_getline_lf(&buf, f);
314 fclose(f);
315 strbuf_trim(&buf);
316 if (!buf.len) {
317 strbuf_release(&buf);
318 return;
321 remote->configured_in_repo = 1;
322 remote->origin = REMOTE_BRANCHES;
325 * The branches file would have URL and optionally
326 * #branch specified. The default (or specified) branch is
327 * fetched and stored in the local branch matching the
328 * remote name.
330 frag = strchr(buf.buf, '#');
331 if (frag)
332 *(frag++) = '\0';
333 else
334 frag = (char *)git_default_branch_name(0);
336 add_url_alias(remote_state, remote, strbuf_detach(&buf, NULL));
337 refspec_appendf(&remote->fetch, "refs/heads/%s:refs/heads/%s",
338 frag, remote->name);
341 * Cogito compatible push: push current HEAD to remote #branch
342 * (master if missing)
344 refspec_appendf(&remote->push, "HEAD:refs/heads/%s", frag);
345 remote->fetch_tags = 1; /* always auto-follow */
348 static int handle_config(const char *key, const char *value, void *cb)
350 const char *name;
351 size_t namelen;
352 const char *subkey;
353 struct remote *remote;
354 struct branch *branch;
355 struct remote_state *remote_state = cb;
357 if (parse_config_key(key, "branch", &name, &namelen, &subkey) >= 0) {
358 if (!name)
359 return 0;
360 branch = make_branch(remote_state, name, namelen);
361 if (!strcmp(subkey, "remote")) {
362 return git_config_string(&branch->remote_name, key, value);
363 } else if (!strcmp(subkey, "pushremote")) {
364 return git_config_string(&branch->pushremote_name, key, value);
365 } else if (!strcmp(subkey, "merge")) {
366 if (!value)
367 return config_error_nonbool(key);
368 add_merge(branch, xstrdup(value));
370 return 0;
372 if (parse_config_key(key, "url", &name, &namelen, &subkey) >= 0) {
373 struct rewrite *rewrite;
374 if (!name)
375 return 0;
376 if (!strcmp(subkey, "insteadof")) {
377 if (!value)
378 return config_error_nonbool(key);
379 rewrite = make_rewrite(&remote_state->rewrites, name,
380 namelen);
381 add_instead_of(rewrite, xstrdup(value));
382 } else if (!strcmp(subkey, "pushinsteadof")) {
383 if (!value)
384 return config_error_nonbool(key);
385 rewrite = make_rewrite(&remote_state->rewrites_push,
386 name, namelen);
387 add_instead_of(rewrite, xstrdup(value));
391 if (parse_config_key(key, "remote", &name, &namelen, &subkey) < 0)
392 return 0;
394 /* Handle remote.* variables */
395 if (!name && !strcmp(subkey, "pushdefault"))
396 return git_config_string(&remote_state->pushremote_name, key,
397 value);
399 if (!name)
400 return 0;
401 /* Handle remote.<name>.* variables */
402 if (*name == '/') {
403 warning(_("config remote shorthand cannot begin with '/': %s"),
404 name);
405 return 0;
407 remote = make_remote(remote_state, name, namelen);
408 remote->origin = REMOTE_CONFIG;
409 if (current_config_scope() == CONFIG_SCOPE_LOCAL ||
410 current_config_scope() == CONFIG_SCOPE_WORKTREE)
411 remote->configured_in_repo = 1;
412 if (!strcmp(subkey, "mirror"))
413 remote->mirror = git_config_bool(key, value);
414 else if (!strcmp(subkey, "skipdefaultupdate"))
415 remote->skip_default_update = git_config_bool(key, value);
416 else if (!strcmp(subkey, "skipfetchall"))
417 remote->skip_default_update = git_config_bool(key, value);
418 else if (!strcmp(subkey, "prune"))
419 remote->prune = git_config_bool(key, value);
420 else if (!strcmp(subkey, "prunetags"))
421 remote->prune_tags = git_config_bool(key, value);
422 else if (!strcmp(subkey, "url")) {
423 const char *v;
424 if (git_config_string(&v, key, value))
425 return -1;
426 add_url(remote, v);
427 } else if (!strcmp(subkey, "pushurl")) {
428 const char *v;
429 if (git_config_string(&v, key, value))
430 return -1;
431 add_pushurl(remote, v);
432 } else if (!strcmp(subkey, "push")) {
433 const char *v;
434 if (git_config_string(&v, key, value))
435 return -1;
436 refspec_append(&remote->push, v);
437 free((char *)v);
438 } else if (!strcmp(subkey, "fetch")) {
439 const char *v;
440 if (git_config_string(&v, key, value))
441 return -1;
442 refspec_append(&remote->fetch, v);
443 free((char *)v);
444 } else if (!strcmp(subkey, "receivepack")) {
445 const char *v;
446 if (git_config_string(&v, key, value))
447 return -1;
448 if (!remote->receivepack)
449 remote->receivepack = v;
450 else
451 error(_("more than one receivepack given, using the first"));
452 } else if (!strcmp(subkey, "uploadpack")) {
453 const char *v;
454 if (git_config_string(&v, key, value))
455 return -1;
456 if (!remote->uploadpack)
457 remote->uploadpack = v;
458 else
459 error(_("more than one uploadpack given, using the first"));
460 } else if (!strcmp(subkey, "tagopt")) {
461 if (!strcmp(value, "--no-tags"))
462 remote->fetch_tags = -1;
463 else if (!strcmp(value, "--tags"))
464 remote->fetch_tags = 2;
465 } else if (!strcmp(subkey, "proxy")) {
466 return git_config_string((const char **)&remote->http_proxy,
467 key, value);
468 } else if (!strcmp(subkey, "proxyauthmethod")) {
469 return git_config_string((const char **)&remote->http_proxy_authmethod,
470 key, value);
471 } else if (!strcmp(subkey, "vcs")) {
472 return git_config_string(&remote->foreign_vcs, key, value);
474 return 0;
477 static void alias_all_urls(struct remote_state *remote_state)
479 int i, j;
480 for (i = 0; i < remote_state->remotes_nr; i++) {
481 int add_pushurl_aliases;
482 if (!remote_state->remotes[i])
483 continue;
484 for (j = 0; j < remote_state->remotes[i]->pushurl_nr; j++) {
485 remote_state->remotes[i]->pushurl[j] =
486 alias_url(remote_state->remotes[i]->pushurl[j],
487 &remote_state->rewrites);
489 add_pushurl_aliases = remote_state->remotes[i]->pushurl_nr == 0;
490 for (j = 0; j < remote_state->remotes[i]->url_nr; j++) {
491 if (add_pushurl_aliases)
492 add_pushurl_alias(
493 remote_state, remote_state->remotes[i],
494 remote_state->remotes[i]->url[j]);
495 remote_state->remotes[i]->url[j] =
496 alias_url(remote_state->remotes[i]->url[j],
497 &remote_state->rewrites);
502 static void read_config(struct repository *repo)
504 int flag;
506 if (repo->remote_state->initialized)
507 return;
508 repo->remote_state->initialized = 1;
510 repo->remote_state->current_branch = NULL;
511 if (startup_info->have_repository) {
512 const char *head_ref = refs_resolve_ref_unsafe(
513 get_main_ref_store(repo), "HEAD", 0, NULL, &flag);
514 if (head_ref && (flag & REF_ISSYMREF) &&
515 skip_prefix(head_ref, "refs/heads/", &head_ref)) {
516 repo->remote_state->current_branch = make_branch(
517 repo->remote_state, head_ref, strlen(head_ref));
520 repo_config(repo, handle_config, repo->remote_state);
521 alias_all_urls(repo->remote_state);
524 static int valid_remote_nick(const char *name)
526 if (!name[0] || is_dot_or_dotdot(name))
527 return 0;
529 /* remote nicknames cannot contain slashes */
530 while (*name)
531 if (is_dir_sep(*name++))
532 return 0;
533 return 1;
536 static const char *remotes_remote_for_branch(struct remote_state *remote_state,
537 struct branch *branch,
538 int *explicit)
540 if (branch && branch->remote_name) {
541 if (explicit)
542 *explicit = 1;
543 return branch->remote_name;
545 if (explicit)
546 *explicit = 0;
547 if (remote_state->remotes_nr == 1)
548 return remote_state->remotes[0]->name;
549 return "origin";
552 const char *remote_for_branch(struct branch *branch, int *explicit)
554 read_config(the_repository);
555 die_on_missing_branch(the_repository, branch);
557 return remotes_remote_for_branch(the_repository->remote_state, branch,
558 explicit);
561 static const char *
562 remotes_pushremote_for_branch(struct remote_state *remote_state,
563 struct branch *branch, int *explicit)
565 if (branch && branch->pushremote_name) {
566 if (explicit)
567 *explicit = 1;
568 return branch->pushremote_name;
570 if (remote_state->pushremote_name) {
571 if (explicit)
572 *explicit = 1;
573 return remote_state->pushremote_name;
575 return remotes_remote_for_branch(remote_state, branch, explicit);
578 const char *pushremote_for_branch(struct branch *branch, int *explicit)
580 read_config(the_repository);
581 die_on_missing_branch(the_repository, branch);
583 return remotes_pushremote_for_branch(the_repository->remote_state,
584 branch, explicit);
587 static struct remote *remotes_remote_get(struct remote_state *remote_state,
588 const char *name);
590 const char *remote_ref_for_branch(struct branch *branch, int for_push)
592 read_config(the_repository);
593 die_on_missing_branch(the_repository, branch);
595 if (branch) {
596 if (!for_push) {
597 if (branch->merge_nr) {
598 return branch->merge_name[0];
600 } else {
601 const char *dst,
602 *remote_name = remotes_pushremote_for_branch(
603 the_repository->remote_state, branch,
604 NULL);
605 struct remote *remote = remotes_remote_get(
606 the_repository->remote_state, remote_name);
608 if (remote && remote->push.nr &&
609 (dst = apply_refspecs(&remote->push,
610 branch->refname))) {
611 return dst;
615 return NULL;
618 static struct remote *
619 remotes_remote_get_1(struct remote_state *remote_state, const char *name,
620 const char *(*get_default)(struct remote_state *,
621 struct branch *, int *))
623 struct remote *ret;
624 int name_given = 0;
626 if (name)
627 name_given = 1;
628 else
629 name = get_default(remote_state, remote_state->current_branch,
630 &name_given);
632 ret = make_remote(remote_state, name, 0);
633 if (valid_remote_nick(name) && have_git_dir()) {
634 if (!valid_remote(ret))
635 read_remotes_file(remote_state, ret);
636 if (!valid_remote(ret))
637 read_branches_file(remote_state, ret);
639 if (name_given && !valid_remote(ret))
640 add_url_alias(remote_state, ret, name);
641 if (!valid_remote(ret))
642 return NULL;
643 return ret;
646 static inline struct remote *
647 remotes_remote_get(struct remote_state *remote_state, const char *name)
649 return remotes_remote_get_1(remote_state, name,
650 remotes_remote_for_branch);
653 struct remote *remote_get(const char *name)
655 read_config(the_repository);
656 return remotes_remote_get(the_repository->remote_state, name);
659 static inline struct remote *
660 remotes_pushremote_get(struct remote_state *remote_state, const char *name)
662 return remotes_remote_get_1(remote_state, name,
663 remotes_pushremote_for_branch);
666 struct remote *pushremote_get(const char *name)
668 read_config(the_repository);
669 return remotes_pushremote_get(the_repository->remote_state, name);
672 int remote_is_configured(struct remote *remote, int in_repo)
674 if (!remote)
675 return 0;
676 if (in_repo)
677 return remote->configured_in_repo;
678 return !!remote->origin;
681 int for_each_remote(each_remote_fn fn, void *priv)
683 int i, result = 0;
684 read_config(the_repository);
685 for (i = 0; i < the_repository->remote_state->remotes_nr && !result;
686 i++) {
687 struct remote *remote =
688 the_repository->remote_state->remotes[i];
689 if (!remote)
690 continue;
691 result = fn(remote, priv);
693 return result;
696 static void handle_duplicate(struct ref *ref1, struct ref *ref2)
698 if (strcmp(ref1->name, ref2->name)) {
699 if (ref1->fetch_head_status != FETCH_HEAD_IGNORE &&
700 ref2->fetch_head_status != FETCH_HEAD_IGNORE) {
701 die(_("Cannot fetch both %s and %s to %s"),
702 ref1->name, ref2->name, ref2->peer_ref->name);
703 } else if (ref1->fetch_head_status != FETCH_HEAD_IGNORE &&
704 ref2->fetch_head_status == FETCH_HEAD_IGNORE) {
705 warning(_("%s usually tracks %s, not %s"),
706 ref2->peer_ref->name, ref2->name, ref1->name);
707 } else if (ref1->fetch_head_status == FETCH_HEAD_IGNORE &&
708 ref2->fetch_head_status == FETCH_HEAD_IGNORE) {
709 die(_("%s tracks both %s and %s"),
710 ref2->peer_ref->name, ref1->name, ref2->name);
711 } else {
713 * This last possibility doesn't occur because
714 * FETCH_HEAD_IGNORE entries always appear at
715 * the end of the list.
717 BUG("Internal error");
720 free(ref2->peer_ref);
721 free(ref2);
724 struct ref *ref_remove_duplicates(struct ref *ref_map)
726 struct string_list refs = STRING_LIST_INIT_NODUP;
727 struct ref *retval = NULL;
728 struct ref **p = &retval;
730 while (ref_map) {
731 struct ref *ref = ref_map;
733 ref_map = ref_map->next;
734 ref->next = NULL;
736 if (!ref->peer_ref) {
737 *p = ref;
738 p = &ref->next;
739 } else {
740 struct string_list_item *item =
741 string_list_insert(&refs, ref->peer_ref->name);
743 if (item->util) {
744 /* Entry already existed */
745 handle_duplicate((struct ref *)item->util, ref);
746 } else {
747 *p = ref;
748 p = &ref->next;
749 item->util = ref;
754 string_list_clear(&refs, 0);
755 return retval;
758 int remote_has_url(struct remote *remote, const char *url)
760 int i;
761 for (i = 0; i < remote->url_nr; i++) {
762 if (!strcmp(remote->url[i], url))
763 return 1;
765 return 0;
768 static int match_name_with_pattern(const char *key, const char *name,
769 const char *value, char **result)
771 const char *kstar = strchr(key, '*');
772 size_t klen;
773 size_t ksuffixlen;
774 size_t namelen;
775 int ret;
776 if (!kstar)
777 die(_("key '%s' of pattern had no '*'"), key);
778 klen = kstar - key;
779 ksuffixlen = strlen(kstar + 1);
780 namelen = strlen(name);
781 ret = !strncmp(name, key, klen) && namelen >= klen + ksuffixlen &&
782 !memcmp(name + namelen - ksuffixlen, kstar + 1, ksuffixlen);
783 if (ret && value) {
784 struct strbuf sb = STRBUF_INIT;
785 const char *vstar = strchr(value, '*');
786 if (!vstar)
787 die(_("value '%s' of pattern has no '*'"), value);
788 strbuf_add(&sb, value, vstar - value);
789 strbuf_add(&sb, name + klen, namelen - klen - ksuffixlen);
790 strbuf_addstr(&sb, vstar + 1);
791 *result = strbuf_detach(&sb, NULL);
793 return ret;
796 static int refspec_match(const struct refspec_item *refspec,
797 const char *name)
799 if (refspec->pattern)
800 return match_name_with_pattern(refspec->src, name, NULL, NULL);
802 return !strcmp(refspec->src, name);
805 static int omit_name_by_refspec(const char *name, struct refspec *rs)
807 int i;
809 for (i = 0; i < rs->nr; i++) {
810 if (rs->items[i].negative && refspec_match(&rs->items[i], name))
811 return 1;
813 return 0;
816 struct ref *apply_negative_refspecs(struct ref *ref_map, struct refspec *rs)
818 struct ref **tail;
820 for (tail = &ref_map; *tail; ) {
821 struct ref *ref = *tail;
823 if (omit_name_by_refspec(ref->name, rs)) {
824 *tail = ref->next;
825 free(ref->peer_ref);
826 free(ref);
827 } else
828 tail = &ref->next;
831 return ref_map;
834 static int query_matches_negative_refspec(struct refspec *rs, struct refspec_item *query)
836 int i, matched_negative = 0;
837 int find_src = !query->src;
838 struct string_list reversed = STRING_LIST_INIT_NODUP;
839 const char *needle = find_src ? query->dst : query->src;
842 * Check whether the queried ref matches any negative refpsec. If so,
843 * then we should ultimately treat this as not matching the query at
844 * all.
846 * Note that negative refspecs always match the source, but the query
847 * item uses the destination. To handle this, we apply pattern
848 * refspecs in reverse to figure out if the query source matches any
849 * of the negative refspecs.
851 * The first loop finds and expands all positive refspecs
852 * matched by the queried ref.
854 * The second loop checks if any of the results of the first loop
855 * match any negative refspec.
857 for (i = 0; i < rs->nr; i++) {
858 struct refspec_item *refspec = &rs->items[i];
859 char *expn_name;
861 if (refspec->negative)
862 continue;
864 /* Note the reversal of src and dst */
865 if (refspec->pattern) {
866 const char *key = refspec->dst ? refspec->dst : refspec->src;
867 const char *value = refspec->src;
869 if (match_name_with_pattern(key, needle, value, &expn_name))
870 string_list_append_nodup(&reversed, expn_name);
871 } else if (refspec->matching) {
872 /* For the special matching refspec, any query should match */
873 string_list_append(&reversed, needle);
874 } else if (!refspec->src) {
875 BUG("refspec->src should not be null here");
876 } else if (!strcmp(needle, refspec->src)) {
877 string_list_append(&reversed, refspec->src);
881 for (i = 0; !matched_negative && i < reversed.nr; i++) {
882 if (omit_name_by_refspec(reversed.items[i].string, rs))
883 matched_negative = 1;
886 string_list_clear(&reversed, 0);
888 return matched_negative;
891 static void query_refspecs_multiple(struct refspec *rs,
892 struct refspec_item *query,
893 struct string_list *results)
895 int i;
896 int find_src = !query->src;
898 if (find_src && !query->dst)
899 BUG("query_refspecs_multiple: need either src or dst");
901 if (query_matches_negative_refspec(rs, query))
902 return;
904 for (i = 0; i < rs->nr; i++) {
905 struct refspec_item *refspec = &rs->items[i];
906 const char *key = find_src ? refspec->dst : refspec->src;
907 const char *value = find_src ? refspec->src : refspec->dst;
908 const char *needle = find_src ? query->dst : query->src;
909 char **result = find_src ? &query->src : &query->dst;
911 if (!refspec->dst || refspec->negative)
912 continue;
913 if (refspec->pattern) {
914 if (match_name_with_pattern(key, needle, value, result))
915 string_list_append_nodup(results, *result);
916 } else if (!strcmp(needle, key)) {
917 string_list_append(results, value);
922 int query_refspecs(struct refspec *rs, struct refspec_item *query)
924 int i;
925 int find_src = !query->src;
926 const char *needle = find_src ? query->dst : query->src;
927 char **result = find_src ? &query->src : &query->dst;
929 if (find_src && !query->dst)
930 BUG("query_refspecs: need either src or dst");
932 if (query_matches_negative_refspec(rs, query))
933 return -1;
935 for (i = 0; i < rs->nr; i++) {
936 struct refspec_item *refspec = &rs->items[i];
937 const char *key = find_src ? refspec->dst : refspec->src;
938 const char *value = find_src ? refspec->src : refspec->dst;
940 if (!refspec->dst || refspec->negative)
941 continue;
942 if (refspec->pattern) {
943 if (match_name_with_pattern(key, needle, value, result)) {
944 query->force = refspec->force;
945 return 0;
947 } else if (!strcmp(needle, key)) {
948 *result = xstrdup(value);
949 query->force = refspec->force;
950 return 0;
953 return -1;
956 char *apply_refspecs(struct refspec *rs, const char *name)
958 struct refspec_item query;
960 memset(&query, 0, sizeof(struct refspec_item));
961 query.src = (char *)name;
963 if (query_refspecs(rs, &query))
964 return NULL;
966 return query.dst;
969 int remote_find_tracking(struct remote *remote, struct refspec_item *refspec)
971 return query_refspecs(&remote->fetch, refspec);
974 static struct ref *alloc_ref_with_prefix(const char *prefix, size_t prefixlen,
975 const char *name)
977 size_t len = strlen(name);
978 struct ref *ref = xcalloc(1, st_add4(sizeof(*ref), prefixlen, len, 1));
979 memcpy(ref->name, prefix, prefixlen);
980 memcpy(ref->name + prefixlen, name, len);
981 return ref;
984 struct ref *alloc_ref(const char *name)
986 return alloc_ref_with_prefix("", 0, name);
989 struct ref *copy_ref(const struct ref *ref)
991 struct ref *cpy;
992 size_t len;
993 if (!ref)
994 return NULL;
995 len = st_add3(sizeof(struct ref), strlen(ref->name), 1);
996 cpy = xmalloc(len);
997 memcpy(cpy, ref, len);
998 cpy->next = NULL;
999 cpy->symref = xstrdup_or_null(ref->symref);
1000 cpy->remote_status = xstrdup_or_null(ref->remote_status);
1001 cpy->peer_ref = copy_ref(ref->peer_ref);
1002 return cpy;
1005 struct ref *copy_ref_list(const struct ref *ref)
1007 struct ref *ret = NULL;
1008 struct ref **tail = &ret;
1009 while (ref) {
1010 *tail = copy_ref(ref);
1011 ref = ref->next;
1012 tail = &((*tail)->next);
1014 return ret;
1017 void free_one_ref(struct ref *ref)
1019 if (!ref)
1020 return;
1021 free_one_ref(ref->peer_ref);
1022 free(ref->remote_status);
1023 free(ref->symref);
1024 free(ref);
1027 void free_refs(struct ref *ref)
1029 struct ref *next;
1030 while (ref) {
1031 next = ref->next;
1032 free_one_ref(ref);
1033 ref = next;
1037 int ref_compare_name(const void *va, const void *vb)
1039 const struct ref *a = va, *b = vb;
1040 return strcmp(a->name, b->name);
1043 static void *ref_list_get_next(const void *a)
1045 return ((const struct ref *)a)->next;
1048 static void ref_list_set_next(void *a, void *next)
1050 ((struct ref *)a)->next = next;
1053 void sort_ref_list(struct ref **l, int (*cmp)(const void *, const void *))
1055 *l = llist_mergesort(*l, ref_list_get_next, ref_list_set_next, cmp);
1058 int count_refspec_match(const char *pattern,
1059 struct ref *refs,
1060 struct ref **matched_ref)
1062 int patlen = strlen(pattern);
1063 struct ref *matched_weak = NULL;
1064 struct ref *matched = NULL;
1065 int weak_match = 0;
1066 int match = 0;
1068 for (weak_match = match = 0; refs; refs = refs->next) {
1069 char *name = refs->name;
1070 int namelen = strlen(name);
1072 if (!refname_match(pattern, name))
1073 continue;
1075 /* A match is "weak" if it is with refs outside
1076 * heads or tags, and did not specify the pattern
1077 * in full (e.g. "refs/remotes/origin/master") or at
1078 * least from the toplevel (e.g. "remotes/origin/master");
1079 * otherwise "git push $URL master" would result in
1080 * ambiguity between remotes/origin/master and heads/master
1081 * at the remote site.
1083 if (namelen != patlen &&
1084 patlen != namelen - 5 &&
1085 !starts_with(name, "refs/heads/") &&
1086 !starts_with(name, "refs/tags/")) {
1087 /* We want to catch the case where only weak
1088 * matches are found and there are multiple
1089 * matches, and where more than one strong
1090 * matches are found, as ambiguous. One
1091 * strong match with zero or more weak matches
1092 * are acceptable as a unique match.
1094 matched_weak = refs;
1095 weak_match++;
1097 else {
1098 matched = refs;
1099 match++;
1102 if (!matched) {
1103 if (matched_ref)
1104 *matched_ref = matched_weak;
1105 return weak_match;
1107 else {
1108 if (matched_ref)
1109 *matched_ref = matched;
1110 return match;
1114 static void tail_link_ref(struct ref *ref, struct ref ***tail)
1116 **tail = ref;
1117 while (ref->next)
1118 ref = ref->next;
1119 *tail = &ref->next;
1122 static struct ref *alloc_delete_ref(void)
1124 struct ref *ref = alloc_ref("(delete)");
1125 oidclr(&ref->new_oid);
1126 return ref;
1129 static int try_explicit_object_name(const char *name,
1130 struct ref **match)
1132 struct object_id oid;
1134 if (!*name) {
1135 if (match)
1136 *match = alloc_delete_ref();
1137 return 0;
1140 if (get_oid(name, &oid))
1141 return -1;
1143 if (match) {
1144 *match = alloc_ref(name);
1145 oidcpy(&(*match)->new_oid, &oid);
1147 return 0;
1150 static struct ref *make_linked_ref(const char *name, struct ref ***tail)
1152 struct ref *ret = alloc_ref(name);
1153 tail_link_ref(ret, tail);
1154 return ret;
1157 static char *guess_ref(const char *name, struct ref *peer)
1159 struct strbuf buf = STRBUF_INIT;
1161 const char *r = resolve_ref_unsafe(peer->name, RESOLVE_REF_READING,
1162 NULL, NULL);
1163 if (!r)
1164 return NULL;
1166 if (starts_with(r, "refs/heads/")) {
1167 strbuf_addstr(&buf, "refs/heads/");
1168 } else if (starts_with(r, "refs/tags/")) {
1169 strbuf_addstr(&buf, "refs/tags/");
1170 } else {
1171 return NULL;
1174 strbuf_addstr(&buf, name);
1175 return strbuf_detach(&buf, NULL);
1178 static int match_explicit_lhs(struct ref *src,
1179 struct refspec_item *rs,
1180 struct ref **match,
1181 int *allocated_match)
1183 switch (count_refspec_match(rs->src, src, match)) {
1184 case 1:
1185 if (allocated_match)
1186 *allocated_match = 0;
1187 return 0;
1188 case 0:
1189 /* The source could be in the get_sha1() format
1190 * not a reference name. :refs/other is a
1191 * way to delete 'other' ref at the remote end.
1193 if (try_explicit_object_name(rs->src, match) < 0)
1194 return error(_("src refspec %s does not match any"), rs->src);
1195 if (allocated_match)
1196 *allocated_match = 1;
1197 return 0;
1198 default:
1199 return error(_("src refspec %s matches more than one"), rs->src);
1203 static void show_push_unqualified_ref_name_error(const char *dst_value,
1204 const char *matched_src_name)
1206 struct object_id oid;
1207 enum object_type type;
1210 * TRANSLATORS: "matches '%s'%" is the <dst> part of "git push
1211 * <remote> <src>:<dst>" push, and "being pushed ('%s')" is
1212 * the <src>.
1214 error(_("The destination you provided is not a full refname (i.e.,\n"
1215 "starting with \"refs/\"). We tried to guess what you meant by:\n"
1216 "\n"
1217 "- Looking for a ref that matches '%s' on the remote side.\n"
1218 "- Checking if the <src> being pushed ('%s')\n"
1219 " is a ref in \"refs/{heads,tags}/\". If so we add a corresponding\n"
1220 " refs/{heads,tags}/ prefix on the remote side.\n"
1221 "\n"
1222 "Neither worked, so we gave up. You must fully qualify the ref."),
1223 dst_value, matched_src_name);
1225 if (!advice_enabled(ADVICE_PUSH_UNQUALIFIED_REF_NAME))
1226 return;
1228 if (get_oid(matched_src_name, &oid))
1229 BUG("'%s' is not a valid object, "
1230 "match_explicit_lhs() should catch this!",
1231 matched_src_name);
1232 type = oid_object_info(the_repository, &oid, NULL);
1233 if (type == OBJ_COMMIT) {
1234 advise(_("The <src> part of the refspec is a commit object.\n"
1235 "Did you mean to create a new branch by pushing to\n"
1236 "'%s:refs/heads/%s'?"),
1237 matched_src_name, dst_value);
1238 } else if (type == OBJ_TAG) {
1239 advise(_("The <src> part of the refspec is a tag object.\n"
1240 "Did you mean to create a new tag by pushing to\n"
1241 "'%s:refs/tags/%s'?"),
1242 matched_src_name, dst_value);
1243 } else if (type == OBJ_TREE) {
1244 advise(_("The <src> part of the refspec is a tree object.\n"
1245 "Did you mean to tag a new tree by pushing to\n"
1246 "'%s:refs/tags/%s'?"),
1247 matched_src_name, dst_value);
1248 } else if (type == OBJ_BLOB) {
1249 advise(_("The <src> part of the refspec is a blob object.\n"
1250 "Did you mean to tag a new blob by pushing to\n"
1251 "'%s:refs/tags/%s'?"),
1252 matched_src_name, dst_value);
1253 } else {
1254 BUG("'%s' should be commit/tag/tree/blob, is '%d'",
1255 matched_src_name, type);
1259 static int match_explicit(struct ref *src, struct ref *dst,
1260 struct ref ***dst_tail,
1261 struct refspec_item *rs)
1263 struct ref *matched_src, *matched_dst;
1264 int allocated_src;
1266 const char *dst_value = rs->dst;
1267 char *dst_guess;
1269 if (rs->pattern || rs->matching || rs->negative)
1270 return 0;
1272 matched_src = matched_dst = NULL;
1273 if (match_explicit_lhs(src, rs, &matched_src, &allocated_src) < 0)
1274 return -1;
1276 if (!dst_value) {
1277 int flag;
1279 dst_value = resolve_ref_unsafe(matched_src->name,
1280 RESOLVE_REF_READING,
1281 NULL, &flag);
1282 if (!dst_value ||
1283 ((flag & REF_ISSYMREF) &&
1284 !starts_with(dst_value, "refs/heads/")))
1285 die(_("%s cannot be resolved to branch"),
1286 matched_src->name);
1289 switch (count_refspec_match(dst_value, dst, &matched_dst)) {
1290 case 1:
1291 break;
1292 case 0:
1293 if (starts_with(dst_value, "refs/")) {
1294 matched_dst = make_linked_ref(dst_value, dst_tail);
1295 } else if (is_null_oid(&matched_src->new_oid)) {
1296 error(_("unable to delete '%s': remote ref does not exist"),
1297 dst_value);
1298 } else if ((dst_guess = guess_ref(dst_value, matched_src))) {
1299 matched_dst = make_linked_ref(dst_guess, dst_tail);
1300 free(dst_guess);
1301 } else {
1302 show_push_unqualified_ref_name_error(dst_value,
1303 matched_src->name);
1305 break;
1306 default:
1307 matched_dst = NULL;
1308 error(_("dst refspec %s matches more than one"),
1309 dst_value);
1310 break;
1312 if (!matched_dst)
1313 return -1;
1314 if (matched_dst->peer_ref)
1315 return error(_("dst ref %s receives from more than one src"),
1316 matched_dst->name);
1317 else {
1318 matched_dst->peer_ref = allocated_src ?
1319 matched_src :
1320 copy_ref(matched_src);
1321 matched_dst->force = rs->force;
1323 return 0;
1326 static int match_explicit_refs(struct ref *src, struct ref *dst,
1327 struct ref ***dst_tail, struct refspec *rs)
1329 int i, errs;
1330 for (i = errs = 0; i < rs->nr; i++)
1331 errs += match_explicit(src, dst, dst_tail, &rs->items[i]);
1332 return errs;
1335 static char *get_ref_match(const struct refspec *rs, const struct ref *ref,
1336 int send_mirror, int direction,
1337 const struct refspec_item **ret_pat)
1339 const struct refspec_item *pat;
1340 char *name;
1341 int i;
1342 int matching_refs = -1;
1343 for (i = 0; i < rs->nr; i++) {
1344 const struct refspec_item *item = &rs->items[i];
1346 if (item->negative)
1347 continue;
1349 if (item->matching &&
1350 (matching_refs == -1 || item->force)) {
1351 matching_refs = i;
1352 continue;
1355 if (item->pattern) {
1356 const char *dst_side = item->dst ? item->dst : item->src;
1357 int match;
1358 if (direction == FROM_SRC)
1359 match = match_name_with_pattern(item->src, ref->name, dst_side, &name);
1360 else
1361 match = match_name_with_pattern(dst_side, ref->name, item->src, &name);
1362 if (match) {
1363 matching_refs = i;
1364 break;
1368 if (matching_refs == -1)
1369 return NULL;
1371 pat = &rs->items[matching_refs];
1372 if (pat->matching) {
1374 * "matching refs"; traditionally we pushed everything
1375 * including refs outside refs/heads/ hierarchy, but
1376 * that does not make much sense these days.
1378 if (!send_mirror && !starts_with(ref->name, "refs/heads/"))
1379 return NULL;
1380 name = xstrdup(ref->name);
1382 if (ret_pat)
1383 *ret_pat = pat;
1384 return name;
1387 static struct ref **tail_ref(struct ref **head)
1389 struct ref **tail = head;
1390 while (*tail)
1391 tail = &((*tail)->next);
1392 return tail;
1395 struct tips {
1396 struct commit **tip;
1397 int nr, alloc;
1400 static void add_to_tips(struct tips *tips, const struct object_id *oid)
1402 struct commit *commit;
1404 if (is_null_oid(oid))
1405 return;
1406 commit = lookup_commit_reference_gently(the_repository, oid, 1);
1407 if (!commit || (commit->object.flags & TMP_MARK))
1408 return;
1409 commit->object.flags |= TMP_MARK;
1410 ALLOC_GROW(tips->tip, tips->nr + 1, tips->alloc);
1411 tips->tip[tips->nr++] = commit;
1414 static void add_missing_tags(struct ref *src, struct ref **dst, struct ref ***dst_tail)
1416 struct string_list dst_tag = STRING_LIST_INIT_NODUP;
1417 struct string_list src_tag = STRING_LIST_INIT_NODUP;
1418 struct string_list_item *item;
1419 struct ref *ref;
1420 struct tips sent_tips;
1423 * Collect everything we know they would have at the end of
1424 * this push, and collect all tags they have.
1426 memset(&sent_tips, 0, sizeof(sent_tips));
1427 for (ref = *dst; ref; ref = ref->next) {
1428 if (ref->peer_ref &&
1429 !is_null_oid(&ref->peer_ref->new_oid))
1430 add_to_tips(&sent_tips, &ref->peer_ref->new_oid);
1431 else
1432 add_to_tips(&sent_tips, &ref->old_oid);
1433 if (starts_with(ref->name, "refs/tags/"))
1434 string_list_append(&dst_tag, ref->name);
1436 clear_commit_marks_many(sent_tips.nr, sent_tips.tip, TMP_MARK);
1438 string_list_sort(&dst_tag);
1440 /* Collect tags they do not have. */
1441 for (ref = src; ref; ref = ref->next) {
1442 if (!starts_with(ref->name, "refs/tags/"))
1443 continue; /* not a tag */
1444 if (string_list_has_string(&dst_tag, ref->name))
1445 continue; /* they already have it */
1446 if (oid_object_info(the_repository, &ref->new_oid, NULL) != OBJ_TAG)
1447 continue; /* be conservative */
1448 item = string_list_append(&src_tag, ref->name);
1449 item->util = ref;
1451 string_list_clear(&dst_tag, 0);
1454 * At this point, src_tag lists tags that are missing from
1455 * dst, and sent_tips lists the tips we are pushing or those
1456 * that we know they already have. An element in the src_tag
1457 * that is an ancestor of any of the sent_tips needs to be
1458 * sent to the other side.
1460 if (sent_tips.nr) {
1461 const int reachable_flag = 1;
1462 struct commit_list *found_commits;
1463 struct commit **src_commits;
1464 int nr_src_commits = 0, alloc_src_commits = 16;
1465 ALLOC_ARRAY(src_commits, alloc_src_commits);
1467 for_each_string_list_item(item, &src_tag) {
1468 struct ref *ref = item->util;
1469 struct commit *commit;
1471 if (is_null_oid(&ref->new_oid))
1472 continue;
1473 commit = lookup_commit_reference_gently(the_repository,
1474 &ref->new_oid,
1476 if (!commit)
1477 /* not pushing a commit, which is not an error */
1478 continue;
1480 ALLOC_GROW(src_commits, nr_src_commits + 1, alloc_src_commits);
1481 src_commits[nr_src_commits++] = commit;
1484 found_commits = get_reachable_subset(sent_tips.tip, sent_tips.nr,
1485 src_commits, nr_src_commits,
1486 reachable_flag);
1488 for_each_string_list_item(item, &src_tag) {
1489 struct ref *dst_ref;
1490 struct ref *ref = item->util;
1491 struct commit *commit;
1493 if (is_null_oid(&ref->new_oid))
1494 continue;
1495 commit = lookup_commit_reference_gently(the_repository,
1496 &ref->new_oid,
1498 if (!commit)
1499 /* not pushing a commit, which is not an error */
1500 continue;
1503 * Is this tag, which they do not have, reachable from
1504 * any of the commits we are sending?
1506 if (!(commit->object.flags & reachable_flag))
1507 continue;
1509 /* Add it in */
1510 dst_ref = make_linked_ref(ref->name, dst_tail);
1511 oidcpy(&dst_ref->new_oid, &ref->new_oid);
1512 dst_ref->peer_ref = copy_ref(ref);
1515 clear_commit_marks_many(nr_src_commits, src_commits, reachable_flag);
1516 free(src_commits);
1517 free_commit_list(found_commits);
1520 string_list_clear(&src_tag, 0);
1521 free(sent_tips.tip);
1524 struct ref *find_ref_by_name(const struct ref *list, const char *name)
1526 for ( ; list; list = list->next)
1527 if (!strcmp(list->name, name))
1528 return (struct ref *)list;
1529 return NULL;
1532 static void prepare_ref_index(struct string_list *ref_index, struct ref *ref)
1534 for ( ; ref; ref = ref->next)
1535 string_list_append_nodup(ref_index, ref->name)->util = ref;
1537 string_list_sort(ref_index);
1541 * Given only the set of local refs, sanity-check the set of push
1542 * refspecs. We can't catch all errors that match_push_refs would,
1543 * but we can catch some errors early before even talking to the
1544 * remote side.
1546 int check_push_refs(struct ref *src, struct refspec *rs)
1548 int ret = 0;
1549 int i;
1551 for (i = 0; i < rs->nr; i++) {
1552 struct refspec_item *item = &rs->items[i];
1554 if (item->pattern || item->matching || item->negative)
1555 continue;
1557 ret |= match_explicit_lhs(src, item, NULL, NULL);
1560 return ret;
1564 * Given the set of refs the local repository has, the set of refs the
1565 * remote repository has, and the refspec used for push, determine
1566 * what remote refs we will update and with what value by setting
1567 * peer_ref (which object is being pushed) and force (if the push is
1568 * forced) in elements of "dst". The function may add new elements to
1569 * dst (e.g. pushing to a new branch, done in match_explicit_refs).
1571 int match_push_refs(struct ref *src, struct ref **dst,
1572 struct refspec *rs, int flags)
1574 int send_all = flags & MATCH_REFS_ALL;
1575 int send_mirror = flags & MATCH_REFS_MIRROR;
1576 int send_prune = flags & MATCH_REFS_PRUNE;
1577 int errs;
1578 struct ref *ref, **dst_tail = tail_ref(dst);
1579 struct string_list dst_ref_index = STRING_LIST_INIT_NODUP;
1581 /* If no refspec is provided, use the default ":" */
1582 if (!rs->nr)
1583 refspec_append(rs, ":");
1585 errs = match_explicit_refs(src, *dst, &dst_tail, rs);
1587 /* pick the remainder */
1588 for (ref = src; ref; ref = ref->next) {
1589 struct string_list_item *dst_item;
1590 struct ref *dst_peer;
1591 const struct refspec_item *pat = NULL;
1592 char *dst_name;
1594 dst_name = get_ref_match(rs, ref, send_mirror, FROM_SRC, &pat);
1595 if (!dst_name)
1596 continue;
1598 if (!dst_ref_index.nr)
1599 prepare_ref_index(&dst_ref_index, *dst);
1601 dst_item = string_list_lookup(&dst_ref_index, dst_name);
1602 dst_peer = dst_item ? dst_item->util : NULL;
1603 if (dst_peer) {
1604 if (dst_peer->peer_ref)
1605 /* We're already sending something to this ref. */
1606 goto free_name;
1607 } else {
1608 if (pat->matching && !(send_all || send_mirror))
1610 * Remote doesn't have it, and we have no
1611 * explicit pattern, and we don't have
1612 * --all or --mirror.
1614 goto free_name;
1616 /* Create a new one and link it */
1617 dst_peer = make_linked_ref(dst_name, &dst_tail);
1618 oidcpy(&dst_peer->new_oid, &ref->new_oid);
1619 string_list_insert(&dst_ref_index,
1620 dst_peer->name)->util = dst_peer;
1622 dst_peer->peer_ref = copy_ref(ref);
1623 dst_peer->force = pat->force;
1624 free_name:
1625 free(dst_name);
1628 string_list_clear(&dst_ref_index, 0);
1630 if (flags & MATCH_REFS_FOLLOW_TAGS)
1631 add_missing_tags(src, dst, &dst_tail);
1633 if (send_prune) {
1634 struct string_list src_ref_index = STRING_LIST_INIT_NODUP;
1635 /* check for missing refs on the remote */
1636 for (ref = *dst; ref; ref = ref->next) {
1637 char *src_name;
1639 if (ref->peer_ref)
1640 /* We're already sending something to this ref. */
1641 continue;
1643 src_name = get_ref_match(rs, ref, send_mirror, FROM_DST, NULL);
1644 if (src_name) {
1645 if (!src_ref_index.nr)
1646 prepare_ref_index(&src_ref_index, src);
1647 if (!string_list_has_string(&src_ref_index,
1648 src_name))
1649 ref->peer_ref = alloc_delete_ref();
1650 free(src_name);
1653 string_list_clear(&src_ref_index, 0);
1656 *dst = apply_negative_refspecs(*dst, rs);
1658 if (errs)
1659 return -1;
1660 return 0;
1663 void set_ref_status_for_push(struct ref *remote_refs, int send_mirror,
1664 int force_update)
1666 struct ref *ref;
1668 for (ref = remote_refs; ref; ref = ref->next) {
1669 int force_ref_update = ref->force || force_update;
1670 int reject_reason = 0;
1672 if (ref->peer_ref)
1673 oidcpy(&ref->new_oid, &ref->peer_ref->new_oid);
1674 else if (!send_mirror)
1675 continue;
1677 ref->deletion = is_null_oid(&ref->new_oid);
1678 if (!ref->deletion &&
1679 oideq(&ref->old_oid, &ref->new_oid)) {
1680 ref->status = REF_STATUS_UPTODATE;
1681 continue;
1685 * If the remote ref has moved and is now different
1686 * from what we expect, reject any push.
1688 * It also is an error if the user told us to check
1689 * with the remote-tracking branch to find the value
1690 * to expect, but we did not have such a tracking
1691 * branch.
1693 * If the tip of the remote-tracking ref is unreachable
1694 * from any reflog entry of its local ref indicating a
1695 * possible update since checkout; reject the push.
1697 if (ref->expect_old_sha1) {
1698 if (!oideq(&ref->old_oid, &ref->old_oid_expect))
1699 reject_reason = REF_STATUS_REJECT_STALE;
1700 else if (ref->check_reachable && ref->unreachable)
1701 reject_reason =
1702 REF_STATUS_REJECT_REMOTE_UPDATED;
1703 else
1705 * If the ref isn't stale, and is reachable
1706 * from one of the reflog entries of
1707 * the local branch, force the update.
1709 force_ref_update = 1;
1713 * If the update isn't already rejected then check
1714 * the usual "must fast-forward" rules.
1716 * Decide whether an individual refspec A:B can be
1717 * pushed. The push will succeed if any of the
1718 * following are true:
1720 * (1) the remote reference B does not exist
1722 * (2) the remote reference B is being removed (i.e.,
1723 * pushing :B where no source is specified)
1725 * (3) the destination is not under refs/tags/, and
1726 * if the old and new value is a commit, the new
1727 * is a descendant of the old.
1729 * (4) it is forced using the +A:B notation, or by
1730 * passing the --force argument
1733 if (!reject_reason && !ref->deletion && !is_null_oid(&ref->old_oid)) {
1734 if (starts_with(ref->name, "refs/tags/"))
1735 reject_reason = REF_STATUS_REJECT_ALREADY_EXISTS;
1736 else if (!has_object_file(&ref->old_oid))
1737 reject_reason = REF_STATUS_REJECT_FETCH_FIRST;
1738 else if (!lookup_commit_reference_gently(the_repository, &ref->old_oid, 1) ||
1739 !lookup_commit_reference_gently(the_repository, &ref->new_oid, 1))
1740 reject_reason = REF_STATUS_REJECT_NEEDS_FORCE;
1741 else if (!ref_newer(&ref->new_oid, &ref->old_oid))
1742 reject_reason = REF_STATUS_REJECT_NONFASTFORWARD;
1746 * "--force" will defeat any rejection implemented
1747 * by the rules above.
1749 if (!force_ref_update)
1750 ref->status = reject_reason;
1751 else if (reject_reason)
1752 ref->forced_update = 1;
1756 static void set_merge(struct remote_state *remote_state, struct branch *ret)
1758 struct remote *remote;
1759 char *ref;
1760 struct object_id oid;
1761 int i;
1763 if (!ret)
1764 return; /* no branch */
1765 if (ret->merge)
1766 return; /* already run */
1767 if (!ret->remote_name || !ret->merge_nr) {
1769 * no merge config; let's make sure we don't confuse callers
1770 * with a non-zero merge_nr but a NULL merge
1772 ret->merge_nr = 0;
1773 return;
1776 remote = remotes_remote_get(remote_state, ret->remote_name);
1778 CALLOC_ARRAY(ret->merge, ret->merge_nr);
1779 for (i = 0; i < ret->merge_nr; i++) {
1780 ret->merge[i] = xcalloc(1, sizeof(**ret->merge));
1781 ret->merge[i]->src = xstrdup(ret->merge_name[i]);
1782 if (!remote_find_tracking(remote, ret->merge[i]) ||
1783 strcmp(ret->remote_name, "."))
1784 continue;
1785 if (dwim_ref(ret->merge_name[i], strlen(ret->merge_name[i]),
1786 &oid, &ref, 0) == 1)
1787 ret->merge[i]->dst = ref;
1788 else
1789 ret->merge[i]->dst = xstrdup(ret->merge_name[i]);
1793 struct branch *branch_get(const char *name)
1795 struct branch *ret;
1797 read_config(the_repository);
1798 if (!name || !*name || !strcmp(name, "HEAD"))
1799 ret = the_repository->remote_state->current_branch;
1800 else
1801 ret = make_branch(the_repository->remote_state, name,
1802 strlen(name));
1803 set_merge(the_repository->remote_state, ret);
1804 return ret;
1807 int branch_has_merge_config(struct branch *branch)
1809 return branch && !!branch->merge;
1812 int branch_merge_matches(struct branch *branch,
1813 int i,
1814 const char *refname)
1816 if (!branch || i < 0 || i >= branch->merge_nr)
1817 return 0;
1818 return refname_match(branch->merge[i]->src, refname);
1821 __attribute__((format (printf,2,3)))
1822 static const char *error_buf(struct strbuf *err, const char *fmt, ...)
1824 if (err) {
1825 va_list ap;
1826 va_start(ap, fmt);
1827 strbuf_vaddf(err, fmt, ap);
1828 va_end(ap);
1830 return NULL;
1833 const char *branch_get_upstream(struct branch *branch, struct strbuf *err)
1835 if (!branch)
1836 return error_buf(err, _("HEAD does not point to a branch"));
1838 if (!branch->merge || !branch->merge[0]) {
1840 * no merge config; is it because the user didn't define any,
1841 * or because it is not a real branch, and get_branch
1842 * auto-vivified it?
1844 if (!ref_exists(branch->refname))
1845 return error_buf(err, _("no such branch: '%s'"),
1846 branch->name);
1847 return error_buf(err,
1848 _("no upstream configured for branch '%s'"),
1849 branch->name);
1852 if (!branch->merge[0]->dst)
1853 return error_buf(err,
1854 _("upstream branch '%s' not stored as a remote-tracking branch"),
1855 branch->merge[0]->src);
1857 return branch->merge[0]->dst;
1860 static const char *tracking_for_push_dest(struct remote *remote,
1861 const char *refname,
1862 struct strbuf *err)
1864 char *ret;
1866 ret = apply_refspecs(&remote->fetch, refname);
1867 if (!ret)
1868 return error_buf(err,
1869 _("push destination '%s' on remote '%s' has no local tracking branch"),
1870 refname, remote->name);
1871 return ret;
1874 static const char *branch_get_push_1(struct remote_state *remote_state,
1875 struct branch *branch, struct strbuf *err)
1877 struct remote *remote;
1879 remote = remotes_remote_get(
1880 remote_state,
1881 remotes_pushremote_for_branch(remote_state, branch, NULL));
1882 if (!remote)
1883 return error_buf(err,
1884 _("branch '%s' has no remote for pushing"),
1885 branch->name);
1887 if (remote->push.nr) {
1888 char *dst;
1889 const char *ret;
1891 dst = apply_refspecs(&remote->push, branch->refname);
1892 if (!dst)
1893 return error_buf(err,
1894 _("push refspecs for '%s' do not include '%s'"),
1895 remote->name, branch->name);
1897 ret = tracking_for_push_dest(remote, dst, err);
1898 free(dst);
1899 return ret;
1902 if (remote->mirror)
1903 return tracking_for_push_dest(remote, branch->refname, err);
1905 switch (push_default) {
1906 case PUSH_DEFAULT_NOTHING:
1907 return error_buf(err, _("push has no destination (push.default is 'nothing')"));
1909 case PUSH_DEFAULT_MATCHING:
1910 case PUSH_DEFAULT_CURRENT:
1911 return tracking_for_push_dest(remote, branch->refname, err);
1913 case PUSH_DEFAULT_UPSTREAM:
1914 return branch_get_upstream(branch, err);
1916 case PUSH_DEFAULT_UNSPECIFIED:
1917 case PUSH_DEFAULT_SIMPLE:
1919 const char *up, *cur;
1921 up = branch_get_upstream(branch, err);
1922 if (!up)
1923 return NULL;
1924 cur = tracking_for_push_dest(remote, branch->refname, err);
1925 if (!cur)
1926 return NULL;
1927 if (strcmp(cur, up))
1928 return error_buf(err,
1929 _("cannot resolve 'simple' push to a single destination"));
1930 return cur;
1934 BUG("unhandled push situation");
1937 const char *branch_get_push(struct branch *branch, struct strbuf *err)
1939 read_config(the_repository);
1940 die_on_missing_branch(the_repository, branch);
1942 if (!branch)
1943 return error_buf(err, _("HEAD does not point to a branch"));
1945 if (!branch->push_tracking_ref)
1946 branch->push_tracking_ref = branch_get_push_1(
1947 the_repository->remote_state, branch, err);
1948 return branch->push_tracking_ref;
1951 static int ignore_symref_update(const char *refname, struct strbuf *scratch)
1953 return !refs_read_symbolic_ref(get_main_ref_store(the_repository), refname, scratch);
1957 * Create and return a list of (struct ref) consisting of copies of
1958 * each remote_ref that matches refspec. refspec must be a pattern.
1959 * Fill in the copies' peer_ref to describe the local tracking refs to
1960 * which they map. Omit any references that would map to an existing
1961 * local symbolic ref.
1963 static struct ref *get_expanded_map(const struct ref *remote_refs,
1964 const struct refspec_item *refspec)
1966 struct strbuf scratch = STRBUF_INIT;
1967 const struct ref *ref;
1968 struct ref *ret = NULL;
1969 struct ref **tail = &ret;
1971 for (ref = remote_refs; ref; ref = ref->next) {
1972 char *expn_name = NULL;
1974 strbuf_reset(&scratch);
1976 if (strchr(ref->name, '^'))
1977 continue; /* a dereference item */
1978 if (match_name_with_pattern(refspec->src, ref->name,
1979 refspec->dst, &expn_name) &&
1980 !ignore_symref_update(expn_name, &scratch)) {
1981 struct ref *cpy = copy_ref(ref);
1983 cpy->peer_ref = alloc_ref(expn_name);
1984 if (refspec->force)
1985 cpy->peer_ref->force = 1;
1986 *tail = cpy;
1987 tail = &cpy->next;
1989 free(expn_name);
1992 strbuf_release(&scratch);
1993 return ret;
1996 static const struct ref *find_ref_by_name_abbrev(const struct ref *refs, const char *name)
1998 const struct ref *ref;
1999 const struct ref *best_match = NULL;
2000 int best_score = 0;
2002 for (ref = refs; ref; ref = ref->next) {
2003 int score = refname_match(name, ref->name);
2005 if (best_score < score) {
2006 best_match = ref;
2007 best_score = score;
2010 return best_match;
2013 struct ref *get_remote_ref(const struct ref *remote_refs, const char *name)
2015 const struct ref *ref = find_ref_by_name_abbrev(remote_refs, name);
2017 if (!ref)
2018 return NULL;
2020 return copy_ref(ref);
2023 static struct ref *get_local_ref(const char *name)
2025 if (!name || name[0] == '\0')
2026 return NULL;
2028 if (starts_with(name, "refs/"))
2029 return alloc_ref(name);
2031 if (starts_with(name, "heads/") ||
2032 starts_with(name, "tags/") ||
2033 starts_with(name, "remotes/"))
2034 return alloc_ref_with_prefix("refs/", 5, name);
2036 return alloc_ref_with_prefix("refs/heads/", 11, name);
2039 int get_fetch_map(const struct ref *remote_refs,
2040 const struct refspec_item *refspec,
2041 struct ref ***tail,
2042 int missing_ok)
2044 struct ref *ref_map, **rmp;
2046 if (refspec->negative)
2047 return 0;
2049 if (refspec->pattern) {
2050 ref_map = get_expanded_map(remote_refs, refspec);
2051 } else {
2052 const char *name = refspec->src[0] ? refspec->src : "HEAD";
2054 if (refspec->exact_sha1) {
2055 ref_map = alloc_ref(name);
2056 get_oid_hex(name, &ref_map->old_oid);
2057 ref_map->exact_oid = 1;
2058 } else {
2059 ref_map = get_remote_ref(remote_refs, name);
2061 if (!missing_ok && !ref_map)
2062 die(_("couldn't find remote ref %s"), name);
2063 if (ref_map) {
2064 ref_map->peer_ref = get_local_ref(refspec->dst);
2065 if (ref_map->peer_ref && refspec->force)
2066 ref_map->peer_ref->force = 1;
2070 for (rmp = &ref_map; *rmp; ) {
2071 if ((*rmp)->peer_ref) {
2072 if (!starts_with((*rmp)->peer_ref->name, "refs/") ||
2073 check_refname_format((*rmp)->peer_ref->name, 0)) {
2074 struct ref *ignore = *rmp;
2075 error(_("* Ignoring funny ref '%s' locally"),
2076 (*rmp)->peer_ref->name);
2077 *rmp = (*rmp)->next;
2078 free(ignore->peer_ref);
2079 free(ignore);
2080 continue;
2083 rmp = &((*rmp)->next);
2086 if (ref_map)
2087 tail_link_ref(ref_map, tail);
2089 return 0;
2092 int resolve_remote_symref(struct ref *ref, struct ref *list)
2094 if (!ref->symref)
2095 return 0;
2096 for (; list; list = list->next)
2097 if (!strcmp(ref->symref, list->name)) {
2098 oidcpy(&ref->old_oid, &list->old_oid);
2099 return 0;
2101 return 1;
2105 * Compute the commit ahead/behind values for the pair branch_name, base.
2107 * If abf is AHEAD_BEHIND_FULL, compute the full ahead/behind and return the
2108 * counts in *num_ours and *num_theirs. If abf is AHEAD_BEHIND_QUICK, skip
2109 * the (potentially expensive) a/b computation (*num_ours and *num_theirs are
2110 * set to zero).
2112 * Returns -1 if num_ours and num_theirs could not be filled in (e.g., ref
2113 * does not exist). Returns 0 if the commits are identical. Returns 1 if
2114 * commits are different.
2117 static int stat_branch_pair(const char *branch_name, const char *base,
2118 int *num_ours, int *num_theirs,
2119 enum ahead_behind_flags abf)
2121 struct object_id oid;
2122 struct commit *ours, *theirs;
2123 struct rev_info revs;
2124 struct strvec argv = STRVEC_INIT;
2126 /* Cannot stat if what we used to build on no longer exists */
2127 if (read_ref(base, &oid))
2128 return -1;
2129 theirs = lookup_commit_reference(the_repository, &oid);
2130 if (!theirs)
2131 return -1;
2133 if (read_ref(branch_name, &oid))
2134 return -1;
2135 ours = lookup_commit_reference(the_repository, &oid);
2136 if (!ours)
2137 return -1;
2139 *num_theirs = *num_ours = 0;
2141 /* are we the same? */
2142 if (theirs == ours)
2143 return 0;
2144 if (abf == AHEAD_BEHIND_QUICK)
2145 return 1;
2146 if (abf != AHEAD_BEHIND_FULL)
2147 BUG("stat_branch_pair: invalid abf '%d'", abf);
2149 /* Run "rev-list --left-right ours...theirs" internally... */
2150 strvec_push(&argv, ""); /* ignored */
2151 strvec_push(&argv, "--left-right");
2152 strvec_pushf(&argv, "%s...%s",
2153 oid_to_hex(&ours->object.oid),
2154 oid_to_hex(&theirs->object.oid));
2155 strvec_push(&argv, "--");
2157 repo_init_revisions(the_repository, &revs, NULL);
2158 setup_revisions(argv.nr, argv.v, &revs, NULL);
2159 if (prepare_revision_walk(&revs))
2160 die(_("revision walk setup failed"));
2162 /* ... and count the commits on each side. */
2163 while (1) {
2164 struct commit *c = get_revision(&revs);
2165 if (!c)
2166 break;
2167 if (c->object.flags & SYMMETRIC_LEFT)
2168 (*num_ours)++;
2169 else
2170 (*num_theirs)++;
2173 /* clear object flags smudged by the above traversal */
2174 clear_commit_marks(ours, ALL_REV_FLAGS);
2175 clear_commit_marks(theirs, ALL_REV_FLAGS);
2177 strvec_clear(&argv);
2178 return 1;
2182 * Lookup the tracking branch for the given branch and if present, optionally
2183 * compute the commit ahead/behind values for the pair.
2185 * If for_push is true, the tracking branch refers to the push branch,
2186 * otherwise it refers to the upstream branch.
2188 * The name of the tracking branch (or NULL if it is not defined) is
2189 * returned via *tracking_name, if it is not itself NULL.
2191 * If abf is AHEAD_BEHIND_FULL, compute the full ahead/behind and return the
2192 * counts in *num_ours and *num_theirs. If abf is AHEAD_BEHIND_QUICK, skip
2193 * the (potentially expensive) a/b computation (*num_ours and *num_theirs are
2194 * set to zero).
2196 * Returns -1 if num_ours and num_theirs could not be filled in (e.g., no
2197 * upstream defined, or ref does not exist). Returns 0 if the commits are
2198 * identical. Returns 1 if commits are different.
2200 int stat_tracking_info(struct branch *branch, int *num_ours, int *num_theirs,
2201 const char **tracking_name, int for_push,
2202 enum ahead_behind_flags abf)
2204 const char *base;
2206 /* Cannot stat unless we are marked to build on top of somebody else. */
2207 base = for_push ? branch_get_push(branch, NULL) :
2208 branch_get_upstream(branch, NULL);
2209 if (tracking_name)
2210 *tracking_name = base;
2211 if (!base)
2212 return -1;
2214 return stat_branch_pair(branch->refname, base, num_ours, num_theirs, abf);
2218 * Return true when there is anything to report, otherwise false.
2220 int format_tracking_info(struct branch *branch, struct strbuf *sb,
2221 enum ahead_behind_flags abf)
2223 int ours, theirs, sti;
2224 const char *full_base;
2225 char *base;
2226 int upstream_is_gone = 0;
2228 sti = stat_tracking_info(branch, &ours, &theirs, &full_base, 0, abf);
2229 if (sti < 0) {
2230 if (!full_base)
2231 return 0;
2232 upstream_is_gone = 1;
2235 base = shorten_unambiguous_ref(full_base, 0);
2236 if (upstream_is_gone) {
2237 strbuf_addf(sb,
2238 _("Your branch is based on '%s', but the upstream is gone.\n"),
2239 base);
2240 if (advice_enabled(ADVICE_STATUS_HINTS))
2241 strbuf_addstr(sb,
2242 _(" (use \"git branch --unset-upstream\" to fixup)\n"));
2243 } else if (!sti) {
2244 strbuf_addf(sb,
2245 _("Your branch is up to date with '%s'.\n"),
2246 base);
2247 } else if (abf == AHEAD_BEHIND_QUICK) {
2248 strbuf_addf(sb,
2249 _("Your branch and '%s' refer to different commits.\n"),
2250 base);
2251 if (advice_enabled(ADVICE_STATUS_HINTS))
2252 strbuf_addf(sb, _(" (use \"%s\" for details)\n"),
2253 "git status --ahead-behind");
2254 } else if (!theirs) {
2255 strbuf_addf(sb,
2256 Q_("Your branch is ahead of '%s' by %d commit.\n",
2257 "Your branch is ahead of '%s' by %d commits.\n",
2258 ours),
2259 base, ours);
2260 if (advice_enabled(ADVICE_STATUS_HINTS))
2261 strbuf_addstr(sb,
2262 _(" (use \"git push\" to publish your local commits)\n"));
2263 } else if (!ours) {
2264 strbuf_addf(sb,
2265 Q_("Your branch is behind '%s' by %d commit, "
2266 "and can be fast-forwarded.\n",
2267 "Your branch is behind '%s' by %d commits, "
2268 "and can be fast-forwarded.\n",
2269 theirs),
2270 base, theirs);
2271 if (advice_enabled(ADVICE_STATUS_HINTS))
2272 strbuf_addstr(sb,
2273 _(" (use \"git pull\" to update your local branch)\n"));
2274 } else {
2275 strbuf_addf(sb,
2276 Q_("Your branch and '%s' have diverged,\n"
2277 "and have %d and %d different commit each, "
2278 "respectively.\n",
2279 "Your branch and '%s' have diverged,\n"
2280 "and have %d and %d different commits each, "
2281 "respectively.\n",
2282 ours + theirs),
2283 base, ours, theirs);
2284 if (advice_enabled(ADVICE_STATUS_HINTS))
2285 strbuf_addstr(sb,
2286 _(" (use \"git pull\" to merge the remote branch into yours)\n"));
2288 free(base);
2289 return 1;
2292 static int one_local_ref(const char *refname, const struct object_id *oid,
2293 int flag, void *cb_data)
2295 struct ref ***local_tail = cb_data;
2296 struct ref *ref;
2298 /* we already know it starts with refs/ to get here */
2299 if (check_refname_format(refname + 5, 0))
2300 return 0;
2302 ref = alloc_ref(refname);
2303 oidcpy(&ref->new_oid, oid);
2304 **local_tail = ref;
2305 *local_tail = &ref->next;
2306 return 0;
2309 struct ref *get_local_heads(void)
2311 struct ref *local_refs = NULL, **local_tail = &local_refs;
2313 for_each_ref(one_local_ref, &local_tail);
2314 return local_refs;
2317 struct ref *guess_remote_head(const struct ref *head,
2318 const struct ref *refs,
2319 int all)
2321 const struct ref *r;
2322 struct ref *list = NULL;
2323 struct ref **tail = &list;
2325 if (!head)
2326 return NULL;
2329 * Some transports support directly peeking at
2330 * where HEAD points; if that is the case, then
2331 * we don't have to guess.
2333 if (head->symref)
2334 return copy_ref(find_ref_by_name(refs, head->symref));
2336 /* If a remote branch exists with the default branch name, let's use it. */
2337 if (!all) {
2338 char *ref = xstrfmt("refs/heads/%s",
2339 git_default_branch_name(0));
2341 r = find_ref_by_name(refs, ref);
2342 free(ref);
2343 if (r && oideq(&r->old_oid, &head->old_oid))
2344 return copy_ref(r);
2346 /* Fall back to the hard-coded historical default */
2347 r = find_ref_by_name(refs, "refs/heads/master");
2348 if (r && oideq(&r->old_oid, &head->old_oid))
2349 return copy_ref(r);
2352 /* Look for another ref that points there */
2353 for (r = refs; r; r = r->next) {
2354 if (r != head &&
2355 starts_with(r->name, "refs/heads/") &&
2356 oideq(&r->old_oid, &head->old_oid)) {
2357 *tail = copy_ref(r);
2358 tail = &((*tail)->next);
2359 if (!all)
2360 break;
2364 return list;
2367 struct stale_heads_info {
2368 struct string_list *ref_names;
2369 struct ref **stale_refs_tail;
2370 struct refspec *rs;
2373 static int get_stale_heads_cb(const char *refname, const struct object_id *oid,
2374 int flags, void *cb_data)
2376 struct stale_heads_info *info = cb_data;
2377 struct string_list matches = STRING_LIST_INIT_DUP;
2378 struct refspec_item query;
2379 int i, stale = 1;
2380 memset(&query, 0, sizeof(struct refspec_item));
2381 query.dst = (char *)refname;
2383 query_refspecs_multiple(info->rs, &query, &matches);
2384 if (matches.nr == 0)
2385 goto clean_exit; /* No matches */
2388 * If we did find a suitable refspec and it's not a symref and
2389 * it's not in the list of refs that currently exist in that
2390 * remote, we consider it to be stale. In order to deal with
2391 * overlapping refspecs, we need to go over all of the
2392 * matching refs.
2394 if (flags & REF_ISSYMREF)
2395 goto clean_exit;
2397 for (i = 0; stale && i < matches.nr; i++)
2398 if (string_list_has_string(info->ref_names, matches.items[i].string))
2399 stale = 0;
2401 if (stale) {
2402 struct ref *ref = make_linked_ref(refname, &info->stale_refs_tail);
2403 oidcpy(&ref->new_oid, oid);
2406 clean_exit:
2407 string_list_clear(&matches, 0);
2408 return 0;
2411 struct ref *get_stale_heads(struct refspec *rs, struct ref *fetch_map)
2413 struct ref *ref, *stale_refs = NULL;
2414 struct string_list ref_names = STRING_LIST_INIT_NODUP;
2415 struct stale_heads_info info;
2417 info.ref_names = &ref_names;
2418 info.stale_refs_tail = &stale_refs;
2419 info.rs = rs;
2420 for (ref = fetch_map; ref; ref = ref->next)
2421 string_list_append(&ref_names, ref->name);
2422 string_list_sort(&ref_names);
2423 for_each_ref(get_stale_heads_cb, &info);
2424 string_list_clear(&ref_names, 0);
2425 return stale_refs;
2429 * Compare-and-swap
2431 static void clear_cas_option(struct push_cas_option *cas)
2433 int i;
2435 for (i = 0; i < cas->nr; i++)
2436 free(cas->entry[i].refname);
2437 free(cas->entry);
2438 memset(cas, 0, sizeof(*cas));
2441 static struct push_cas *add_cas_entry(struct push_cas_option *cas,
2442 const char *refname,
2443 size_t refnamelen)
2445 struct push_cas *entry;
2446 ALLOC_GROW(cas->entry, cas->nr + 1, cas->alloc);
2447 entry = &cas->entry[cas->nr++];
2448 memset(entry, 0, sizeof(*entry));
2449 entry->refname = xmemdupz(refname, refnamelen);
2450 return entry;
2453 static int parse_push_cas_option(struct push_cas_option *cas, const char *arg, int unset)
2455 const char *colon;
2456 struct push_cas *entry;
2458 if (unset) {
2459 /* "--no-<option>" */
2460 clear_cas_option(cas);
2461 return 0;
2464 if (!arg) {
2465 /* just "--<option>" */
2466 cas->use_tracking_for_rest = 1;
2467 return 0;
2470 /* "--<option>=refname" or "--<option>=refname:value" */
2471 colon = strchrnul(arg, ':');
2472 entry = add_cas_entry(cas, arg, colon - arg);
2473 if (!*colon)
2474 entry->use_tracking = 1;
2475 else if (!colon[1])
2476 oidclr(&entry->expect);
2477 else if (get_oid(colon + 1, &entry->expect))
2478 return error(_("cannot parse expected object name '%s'"),
2479 colon + 1);
2480 return 0;
2483 int parseopt_push_cas_option(const struct option *opt, const char *arg, int unset)
2485 return parse_push_cas_option(opt->value, arg, unset);
2488 int is_empty_cas(const struct push_cas_option *cas)
2490 return !cas->use_tracking_for_rest && !cas->nr;
2494 * Look at remote.fetch refspec and see if we have a remote
2495 * tracking branch for the refname there. Fill the name of
2496 * the remote-tracking branch in *dst_refname, and the name
2497 * of the commit object at its tip in oid[].
2498 * If we cannot do so, return negative to signal an error.
2500 static int remote_tracking(struct remote *remote, const char *refname,
2501 struct object_id *oid, char **dst_refname)
2503 char *dst;
2505 dst = apply_refspecs(&remote->fetch, refname);
2506 if (!dst)
2507 return -1; /* no tracking ref for refname at remote */
2508 if (read_ref(dst, oid))
2509 return -1; /* we know what the tracking ref is but we cannot read it */
2511 *dst_refname = dst;
2512 return 0;
2516 * The struct "reflog_commit_array" and related helper functions
2517 * are used for collecting commits into an array during reflog
2518 * traversals in "check_and_collect_until()".
2520 struct reflog_commit_array {
2521 struct commit **item;
2522 size_t nr, alloc;
2525 #define REFLOG_COMMIT_ARRAY_INIT { 0 }
2527 /* Append a commit to the array. */
2528 static void append_commit(struct reflog_commit_array *arr,
2529 struct commit *commit)
2531 ALLOC_GROW(arr->item, arr->nr + 1, arr->alloc);
2532 arr->item[arr->nr++] = commit;
2535 /* Free and reset the array. */
2536 static void free_commit_array(struct reflog_commit_array *arr)
2538 FREE_AND_NULL(arr->item);
2539 arr->nr = arr->alloc = 0;
2542 struct check_and_collect_until_cb_data {
2543 struct commit *remote_commit;
2544 struct reflog_commit_array *local_commits;
2545 timestamp_t remote_reflog_timestamp;
2548 /* Get the timestamp of the latest entry. */
2549 static int peek_reflog(struct object_id *o_oid, struct object_id *n_oid,
2550 const char *ident, timestamp_t timestamp,
2551 int tz, const char *message, void *cb_data)
2553 timestamp_t *ts = cb_data;
2554 *ts = timestamp;
2555 return 1;
2558 static int check_and_collect_until(struct object_id *o_oid,
2559 struct object_id *n_oid,
2560 const char *ident, timestamp_t timestamp,
2561 int tz, const char *message, void *cb_data)
2563 struct commit *commit;
2564 struct check_and_collect_until_cb_data *cb = cb_data;
2566 /* An entry was found. */
2567 if (oideq(n_oid, &cb->remote_commit->object.oid))
2568 return 1;
2570 if ((commit = lookup_commit_reference(the_repository, n_oid)))
2571 append_commit(cb->local_commits, commit);
2574 * If the reflog entry timestamp is older than the remote ref's
2575 * latest reflog entry, there is no need to check or collect
2576 * entries older than this one.
2578 if (timestamp < cb->remote_reflog_timestamp)
2579 return -1;
2581 return 0;
2584 #define MERGE_BASES_BATCH_SIZE 8
2587 * Iterate through the reflog of the local ref to check if there is an entry
2588 * for the given remote-tracking ref; runs until the timestamp of an entry is
2589 * older than latest timestamp of remote-tracking ref's reflog. Any commits
2590 * are that seen along the way are collected into an array to check if the
2591 * remote-tracking ref is reachable from any of them.
2593 static int is_reachable_in_reflog(const char *local, const struct ref *remote)
2595 timestamp_t date;
2596 struct commit *commit;
2597 struct commit **chunk;
2598 struct check_and_collect_until_cb_data cb;
2599 struct reflog_commit_array arr = REFLOG_COMMIT_ARRAY_INIT;
2600 size_t size = 0;
2601 int ret = 0;
2603 commit = lookup_commit_reference(the_repository, &remote->old_oid);
2604 if (!commit)
2605 goto cleanup_return;
2608 * Get the timestamp from the latest entry
2609 * of the remote-tracking ref's reflog.
2611 for_each_reflog_ent_reverse(remote->tracking_ref, peek_reflog, &date);
2613 cb.remote_commit = commit;
2614 cb.local_commits = &arr;
2615 cb.remote_reflog_timestamp = date;
2616 ret = for_each_reflog_ent_reverse(local, check_and_collect_until, &cb);
2618 /* We found an entry in the reflog. */
2619 if (ret > 0)
2620 goto cleanup_return;
2623 * Check if the remote commit is reachable from any
2624 * of the commits in the collected array, in batches.
2626 for (chunk = arr.item; chunk < arr.item + arr.nr; chunk += size) {
2627 size = arr.item + arr.nr - chunk;
2628 if (MERGE_BASES_BATCH_SIZE < size)
2629 size = MERGE_BASES_BATCH_SIZE;
2631 if ((ret = in_merge_bases_many(commit, size, chunk)))
2632 break;
2635 cleanup_return:
2636 free_commit_array(&arr);
2637 return ret;
2641 * Check for reachability of a remote-tracking
2642 * ref in the reflog entries of its local ref.
2644 static void check_if_includes_upstream(struct ref *remote)
2646 struct ref *local = get_local_ref(remote->name);
2647 if (!local)
2648 return;
2650 if (is_reachable_in_reflog(local->name, remote) <= 0)
2651 remote->unreachable = 1;
2654 static void apply_cas(struct push_cas_option *cas,
2655 struct remote *remote,
2656 struct ref *ref)
2658 int i;
2660 /* Find an explicit --<option>=<name>[:<value>] entry */
2661 for (i = 0; i < cas->nr; i++) {
2662 struct push_cas *entry = &cas->entry[i];
2663 if (!refname_match(entry->refname, ref->name))
2664 continue;
2665 ref->expect_old_sha1 = 1;
2666 if (!entry->use_tracking)
2667 oidcpy(&ref->old_oid_expect, &entry->expect);
2668 else if (remote_tracking(remote, ref->name,
2669 &ref->old_oid_expect,
2670 &ref->tracking_ref))
2671 oidclr(&ref->old_oid_expect);
2672 else
2673 ref->check_reachable = cas->use_force_if_includes;
2674 return;
2677 /* Are we using "--<option>" to cover all? */
2678 if (!cas->use_tracking_for_rest)
2679 return;
2681 ref->expect_old_sha1 = 1;
2682 if (remote_tracking(remote, ref->name,
2683 &ref->old_oid_expect,
2684 &ref->tracking_ref))
2685 oidclr(&ref->old_oid_expect);
2686 else
2687 ref->check_reachable = cas->use_force_if_includes;
2690 void apply_push_cas(struct push_cas_option *cas,
2691 struct remote *remote,
2692 struct ref *remote_refs)
2694 struct ref *ref;
2695 for (ref = remote_refs; ref; ref = ref->next) {
2696 apply_cas(cas, remote, ref);
2699 * If "compare-and-swap" is in "use_tracking[_for_rest]"
2700 * mode, and if "--force-if-includes" was specified, run
2701 * the check.
2703 if (ref->check_reachable)
2704 check_if_includes_upstream(ref);
2708 struct remote_state *remote_state_new(void)
2710 struct remote_state *r = xmalloc(sizeof(*r));
2712 memset(r, 0, sizeof(*r));
2714 hashmap_init(&r->remotes_hash, remotes_hash_cmp, NULL, 0);
2715 hashmap_init(&r->branches_hash, branches_hash_cmp, NULL, 0);
2716 return r;
2719 void remote_state_clear(struct remote_state *remote_state)
2721 int i;
2723 for (i = 0; i < remote_state->remotes_nr; i++) {
2724 remote_clear(remote_state->remotes[i]);
2726 FREE_AND_NULL(remote_state->remotes);
2727 remote_state->remotes_alloc = 0;
2728 remote_state->remotes_nr = 0;
2730 hashmap_clear_and_free(&remote_state->remotes_hash, struct remote, ent);
2731 hashmap_clear_and_free(&remote_state->branches_hash, struct remote, ent);
2735 * Returns 1 if it was the last chop before ':'.
2737 static int chop_last_dir(char **remoteurl, int is_relative)
2739 char *rfind = find_last_dir_sep(*remoteurl);
2740 if (rfind) {
2741 *rfind = '\0';
2742 return 0;
2745 rfind = strrchr(*remoteurl, ':');
2746 if (rfind) {
2747 *rfind = '\0';
2748 return 1;
2751 if (is_relative || !strcmp(".", *remoteurl))
2752 die(_("cannot strip one component off url '%s'"),
2753 *remoteurl);
2755 free(*remoteurl);
2756 *remoteurl = xstrdup(".");
2757 return 0;
2760 char *relative_url(const char *remote_url, const char *url,
2761 const char *up_path)
2763 int is_relative = 0;
2764 int colonsep = 0;
2765 char *out;
2766 char *remoteurl;
2767 struct strbuf sb = STRBUF_INIT;
2768 size_t len;
2770 if (!url_is_local_not_ssh(url) || is_absolute_path(url))
2771 return xstrdup(url);
2773 len = strlen(remote_url);
2774 if (!len)
2775 BUG("invalid empty remote_url");
2777 remoteurl = xstrdup(remote_url);
2778 if (is_dir_sep(remoteurl[len-1]))
2779 remoteurl[len-1] = '\0';
2781 if (!url_is_local_not_ssh(remoteurl) || is_absolute_path(remoteurl))
2782 is_relative = 0;
2783 else {
2784 is_relative = 1;
2786 * Prepend a './' to ensure all relative
2787 * remoteurls start with './' or '../'
2789 if (!starts_with_dot_slash_native(remoteurl) &&
2790 !starts_with_dot_dot_slash_native(remoteurl)) {
2791 strbuf_reset(&sb);
2792 strbuf_addf(&sb, "./%s", remoteurl);
2793 free(remoteurl);
2794 remoteurl = strbuf_detach(&sb, NULL);
2798 * When the url starts with '../', remove that and the
2799 * last directory in remoteurl.
2801 while (url) {
2802 if (starts_with_dot_dot_slash_native(url)) {
2803 url += 3;
2804 colonsep |= chop_last_dir(&remoteurl, is_relative);
2805 } else if (starts_with_dot_slash_native(url))
2806 url += 2;
2807 else
2808 break;
2810 strbuf_reset(&sb);
2811 strbuf_addf(&sb, "%s%s%s", remoteurl, colonsep ? ":" : "/", url);
2812 if (ends_with(url, "/"))
2813 strbuf_setlen(&sb, sb.len - 1);
2814 free(remoteurl);
2816 if (starts_with_dot_slash_native(sb.buf))
2817 out = xstrdup(sb.buf + 2);
2818 else
2819 out = xstrdup(sb.buf);
2821 if (!up_path || !is_relative) {
2822 strbuf_release(&sb);
2823 return out;
2826 strbuf_reset(&sb);
2827 strbuf_addf(&sb, "%s%s", up_path, out);
2828 free(out);
2829 return strbuf_detach(&sb, NULL);