archive-tar: use OS_CODE 3 (Unix) for internal gzip
[git/debian.git] / remote.c
blob404e1e0a0ddb0722e0787e82fdeacbab4e8c6050
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 lookup.str = name;
200 lookup.len = len;
201 hashmap_entry_init(&lookup_entry, memhash(name, len));
203 e = hashmap_get(&remote_state->branches_hash, &lookup_entry, &lookup);
204 if (e)
205 return container_of(e, struct branch, ent);
207 return NULL;
210 static void die_on_missing_branch(struct repository *repo,
211 struct branch *branch)
213 /* branch == NULL is always valid because it represents detached HEAD. */
214 if (branch &&
215 branch != find_branch(repo->remote_state, branch->name,
216 strlen(branch->name)))
217 die("branch %s was not found in the repository", branch->name);
220 static struct branch *make_branch(struct remote_state *remote_state,
221 const char *name, size_t len)
223 struct branch *ret;
225 ret = find_branch(remote_state, name, len);
226 if (ret)
227 return ret;
229 CALLOC_ARRAY(ret, 1);
230 ret->name = xstrndup(name, len);
231 ret->refname = xstrfmt("refs/heads/%s", ret->name);
233 hashmap_entry_init(&ret->ent, memhash(name, len));
234 if (hashmap_put_entry(&remote_state->branches_hash, ret, ent))
235 BUG("hashmap_put overwrote entry after hashmap_get returned NULL");
236 return ret;
239 static struct rewrite *make_rewrite(struct rewrites *r,
240 const char *base, size_t len)
242 struct rewrite *ret;
243 int i;
245 for (i = 0; i < r->rewrite_nr; i++) {
246 if (len == r->rewrite[i]->baselen &&
247 !strncmp(base, r->rewrite[i]->base, len))
248 return r->rewrite[i];
251 ALLOC_GROW(r->rewrite, r->rewrite_nr + 1, r->rewrite_alloc);
252 CALLOC_ARRAY(ret, 1);
253 r->rewrite[r->rewrite_nr++] = ret;
254 ret->base = xstrndup(base, len);
255 ret->baselen = len;
256 return ret;
259 static void add_instead_of(struct rewrite *rewrite, const char *instead_of)
261 ALLOC_GROW(rewrite->instead_of, rewrite->instead_of_nr + 1, rewrite->instead_of_alloc);
262 rewrite->instead_of[rewrite->instead_of_nr].s = instead_of;
263 rewrite->instead_of[rewrite->instead_of_nr].len = strlen(instead_of);
264 rewrite->instead_of_nr++;
267 static const char *skip_spaces(const char *s)
269 while (isspace(*s))
270 s++;
271 return s;
274 static void read_remotes_file(struct remote_state *remote_state,
275 struct remote *remote)
277 struct strbuf buf = STRBUF_INIT;
278 FILE *f = fopen_or_warn(git_path("remotes/%s", remote->name), "r");
280 if (!f)
281 return;
282 remote->configured_in_repo = 1;
283 remote->origin = REMOTE_REMOTES;
284 while (strbuf_getline(&buf, f) != EOF) {
285 const char *v;
287 strbuf_rtrim(&buf);
289 if (skip_prefix(buf.buf, "URL:", &v))
290 add_url_alias(remote_state, remote,
291 xstrdup(skip_spaces(v)));
292 else if (skip_prefix(buf.buf, "Push:", &v))
293 refspec_append(&remote->push, skip_spaces(v));
294 else if (skip_prefix(buf.buf, "Pull:", &v))
295 refspec_append(&remote->fetch, skip_spaces(v));
297 strbuf_release(&buf);
298 fclose(f);
301 static void read_branches_file(struct remote_state *remote_state,
302 struct remote *remote)
304 char *frag;
305 struct strbuf buf = STRBUF_INIT;
306 FILE *f = fopen_or_warn(git_path("branches/%s", remote->name), "r");
308 if (!f)
309 return;
311 strbuf_getline_lf(&buf, f);
312 fclose(f);
313 strbuf_trim(&buf);
314 if (!buf.len) {
315 strbuf_release(&buf);
316 return;
319 remote->configured_in_repo = 1;
320 remote->origin = REMOTE_BRANCHES;
323 * The branches file would have URL and optionally
324 * #branch specified. The default (or specified) branch is
325 * fetched and stored in the local branch matching the
326 * remote name.
328 frag = strchr(buf.buf, '#');
329 if (frag)
330 *(frag++) = '\0';
331 else
332 frag = (char *)git_default_branch_name(0);
334 add_url_alias(remote_state, remote, strbuf_detach(&buf, NULL));
335 refspec_appendf(&remote->fetch, "refs/heads/%s:refs/heads/%s",
336 frag, remote->name);
339 * Cogito compatible push: push current HEAD to remote #branch
340 * (master if missing)
342 refspec_appendf(&remote->push, "HEAD:refs/heads/%s", frag);
343 remote->fetch_tags = 1; /* always auto-follow */
346 static int handle_config(const char *key, const char *value, void *cb)
348 const char *name;
349 size_t namelen;
350 const char *subkey;
351 struct remote *remote;
352 struct branch *branch;
353 struct remote_state *remote_state = cb;
355 if (parse_config_key(key, "branch", &name, &namelen, &subkey) >= 0) {
356 /* There is no subsection. */
357 if (!name)
358 return 0;
359 /* There is a subsection, but it is empty. */
360 if (!namelen)
361 return -1;
362 branch = make_branch(remote_state, name, namelen);
363 if (!strcmp(subkey, "remote")) {
364 return git_config_string(&branch->remote_name, key, value);
365 } else if (!strcmp(subkey, "pushremote")) {
366 return git_config_string(&branch->pushremote_name, key, value);
367 } else if (!strcmp(subkey, "merge")) {
368 if (!value)
369 return config_error_nonbool(key);
370 add_merge(branch, xstrdup(value));
372 return 0;
374 if (parse_config_key(key, "url", &name, &namelen, &subkey) >= 0) {
375 struct rewrite *rewrite;
376 if (!name)
377 return 0;
378 if (!strcmp(subkey, "insteadof")) {
379 if (!value)
380 return config_error_nonbool(key);
381 rewrite = make_rewrite(&remote_state->rewrites, name,
382 namelen);
383 add_instead_of(rewrite, xstrdup(value));
384 } else if (!strcmp(subkey, "pushinsteadof")) {
385 if (!value)
386 return config_error_nonbool(key);
387 rewrite = make_rewrite(&remote_state->rewrites_push,
388 name, namelen);
389 add_instead_of(rewrite, xstrdup(value));
393 if (parse_config_key(key, "remote", &name, &namelen, &subkey) < 0)
394 return 0;
396 /* Handle remote.* variables */
397 if (!name && !strcmp(subkey, "pushdefault"))
398 return git_config_string(&remote_state->pushremote_name, key,
399 value);
401 if (!name)
402 return 0;
403 /* Handle remote.<name>.* variables */
404 if (*name == '/') {
405 warning(_("config remote shorthand cannot begin with '/': %s"),
406 name);
407 return 0;
409 remote = make_remote(remote_state, name, namelen);
410 remote->origin = REMOTE_CONFIG;
411 if (current_config_scope() == CONFIG_SCOPE_LOCAL ||
412 current_config_scope() == CONFIG_SCOPE_WORKTREE)
413 remote->configured_in_repo = 1;
414 if (!strcmp(subkey, "mirror"))
415 remote->mirror = git_config_bool(key, value);
416 else if (!strcmp(subkey, "skipdefaultupdate"))
417 remote->skip_default_update = git_config_bool(key, value);
418 else if (!strcmp(subkey, "skipfetchall"))
419 remote->skip_default_update = git_config_bool(key, value);
420 else if (!strcmp(subkey, "prune"))
421 remote->prune = git_config_bool(key, value);
422 else if (!strcmp(subkey, "prunetags"))
423 remote->prune_tags = git_config_bool(key, value);
424 else if (!strcmp(subkey, "url")) {
425 const char *v;
426 if (git_config_string(&v, key, value))
427 return -1;
428 add_url(remote, v);
429 } else if (!strcmp(subkey, "pushurl")) {
430 const char *v;
431 if (git_config_string(&v, key, value))
432 return -1;
433 add_pushurl(remote, v);
434 } else if (!strcmp(subkey, "push")) {
435 const char *v;
436 if (git_config_string(&v, key, value))
437 return -1;
438 refspec_append(&remote->push, v);
439 free((char *)v);
440 } else if (!strcmp(subkey, "fetch")) {
441 const char *v;
442 if (git_config_string(&v, key, value))
443 return -1;
444 refspec_append(&remote->fetch, v);
445 free((char *)v);
446 } else if (!strcmp(subkey, "receivepack")) {
447 const char *v;
448 if (git_config_string(&v, key, value))
449 return -1;
450 if (!remote->receivepack)
451 remote->receivepack = v;
452 else
453 error(_("more than one receivepack given, using the first"));
454 } else if (!strcmp(subkey, "uploadpack")) {
455 const char *v;
456 if (git_config_string(&v, key, value))
457 return -1;
458 if (!remote->uploadpack)
459 remote->uploadpack = v;
460 else
461 error(_("more than one uploadpack given, using the first"));
462 } else if (!strcmp(subkey, "tagopt")) {
463 if (!strcmp(value, "--no-tags"))
464 remote->fetch_tags = -1;
465 else if (!strcmp(value, "--tags"))
466 remote->fetch_tags = 2;
467 } else if (!strcmp(subkey, "proxy")) {
468 return git_config_string((const char **)&remote->http_proxy,
469 key, value);
470 } else if (!strcmp(subkey, "proxyauthmethod")) {
471 return git_config_string((const char **)&remote->http_proxy_authmethod,
472 key, value);
473 } else if (!strcmp(subkey, "vcs")) {
474 return git_config_string(&remote->foreign_vcs, key, value);
476 return 0;
479 static void alias_all_urls(struct remote_state *remote_state)
481 int i, j;
482 for (i = 0; i < remote_state->remotes_nr; i++) {
483 int add_pushurl_aliases;
484 if (!remote_state->remotes[i])
485 continue;
486 for (j = 0; j < remote_state->remotes[i]->pushurl_nr; j++) {
487 remote_state->remotes[i]->pushurl[j] =
488 alias_url(remote_state->remotes[i]->pushurl[j],
489 &remote_state->rewrites);
491 add_pushurl_aliases = remote_state->remotes[i]->pushurl_nr == 0;
492 for (j = 0; j < remote_state->remotes[i]->url_nr; j++) {
493 if (add_pushurl_aliases)
494 add_pushurl_alias(
495 remote_state, remote_state->remotes[i],
496 remote_state->remotes[i]->url[j]);
497 remote_state->remotes[i]->url[j] =
498 alias_url(remote_state->remotes[i]->url[j],
499 &remote_state->rewrites);
504 static void read_config(struct repository *repo)
506 int flag;
508 if (repo->remote_state->initialized)
509 return;
510 repo->remote_state->initialized = 1;
512 repo->remote_state->current_branch = NULL;
513 if (startup_info->have_repository) {
514 const char *head_ref = refs_resolve_ref_unsafe(
515 get_main_ref_store(repo), "HEAD", 0, NULL, &flag);
516 if (head_ref && (flag & REF_ISSYMREF) &&
517 skip_prefix(head_ref, "refs/heads/", &head_ref)) {
518 repo->remote_state->current_branch = make_branch(
519 repo->remote_state, head_ref, strlen(head_ref));
522 repo_config(repo, handle_config, repo->remote_state);
523 alias_all_urls(repo->remote_state);
526 static int valid_remote_nick(const char *name)
528 if (!name[0] || is_dot_or_dotdot(name))
529 return 0;
531 /* remote nicknames cannot contain slashes */
532 while (*name)
533 if (is_dir_sep(*name++))
534 return 0;
535 return 1;
538 static const char *remotes_remote_for_branch(struct remote_state *remote_state,
539 struct branch *branch,
540 int *explicit)
542 if (branch && branch->remote_name) {
543 if (explicit)
544 *explicit = 1;
545 return branch->remote_name;
547 if (explicit)
548 *explicit = 0;
549 if (remote_state->remotes_nr == 1)
550 return remote_state->remotes[0]->name;
551 return "origin";
554 const char *remote_for_branch(struct branch *branch, int *explicit)
556 read_config(the_repository);
557 die_on_missing_branch(the_repository, branch);
559 return remotes_remote_for_branch(the_repository->remote_state, branch,
560 explicit);
563 static const char *
564 remotes_pushremote_for_branch(struct remote_state *remote_state,
565 struct branch *branch, int *explicit)
567 if (branch && branch->pushremote_name) {
568 if (explicit)
569 *explicit = 1;
570 return branch->pushremote_name;
572 if (remote_state->pushremote_name) {
573 if (explicit)
574 *explicit = 1;
575 return remote_state->pushremote_name;
577 return remotes_remote_for_branch(remote_state, branch, explicit);
580 const char *pushremote_for_branch(struct branch *branch, int *explicit)
582 read_config(the_repository);
583 die_on_missing_branch(the_repository, branch);
585 return remotes_pushremote_for_branch(the_repository->remote_state,
586 branch, explicit);
589 static struct remote *remotes_remote_get(struct remote_state *remote_state,
590 const char *name);
592 const char *remote_ref_for_branch(struct branch *branch, int for_push)
594 read_config(the_repository);
595 die_on_missing_branch(the_repository, branch);
597 if (branch) {
598 if (!for_push) {
599 if (branch->merge_nr) {
600 return branch->merge_name[0];
602 } else {
603 const char *dst,
604 *remote_name = remotes_pushremote_for_branch(
605 the_repository->remote_state, branch,
606 NULL);
607 struct remote *remote = remotes_remote_get(
608 the_repository->remote_state, remote_name);
610 if (remote && remote->push.nr &&
611 (dst = apply_refspecs(&remote->push,
612 branch->refname))) {
613 return dst;
617 return NULL;
620 static struct remote *
621 remotes_remote_get_1(struct remote_state *remote_state, const char *name,
622 const char *(*get_default)(struct remote_state *,
623 struct branch *, int *))
625 struct remote *ret;
626 int name_given = 0;
628 if (name)
629 name_given = 1;
630 else
631 name = get_default(remote_state, remote_state->current_branch,
632 &name_given);
634 ret = make_remote(remote_state, name, 0);
635 if (valid_remote_nick(name) && have_git_dir()) {
636 if (!valid_remote(ret))
637 read_remotes_file(remote_state, ret);
638 if (!valid_remote(ret))
639 read_branches_file(remote_state, ret);
641 if (name_given && !valid_remote(ret))
642 add_url_alias(remote_state, ret, name);
643 if (!valid_remote(ret))
644 return NULL;
645 return ret;
648 static inline struct remote *
649 remotes_remote_get(struct remote_state *remote_state, const char *name)
651 return remotes_remote_get_1(remote_state, name,
652 remotes_remote_for_branch);
655 struct remote *remote_get(const char *name)
657 read_config(the_repository);
658 return remotes_remote_get(the_repository->remote_state, name);
661 static inline struct remote *
662 remotes_pushremote_get(struct remote_state *remote_state, const char *name)
664 return remotes_remote_get_1(remote_state, name,
665 remotes_pushremote_for_branch);
668 struct remote *pushremote_get(const char *name)
670 read_config(the_repository);
671 return remotes_pushremote_get(the_repository->remote_state, name);
674 int remote_is_configured(struct remote *remote, int in_repo)
676 if (!remote)
677 return 0;
678 if (in_repo)
679 return remote->configured_in_repo;
680 return !!remote->origin;
683 int for_each_remote(each_remote_fn fn, void *priv)
685 int i, result = 0;
686 read_config(the_repository);
687 for (i = 0; i < the_repository->remote_state->remotes_nr && !result;
688 i++) {
689 struct remote *remote =
690 the_repository->remote_state->remotes[i];
691 if (!remote)
692 continue;
693 result = fn(remote, priv);
695 return result;
698 static void handle_duplicate(struct ref *ref1, struct ref *ref2)
700 if (strcmp(ref1->name, ref2->name)) {
701 if (ref1->fetch_head_status != FETCH_HEAD_IGNORE &&
702 ref2->fetch_head_status != FETCH_HEAD_IGNORE) {
703 die(_("Cannot fetch both %s and %s to %s"),
704 ref1->name, ref2->name, ref2->peer_ref->name);
705 } else if (ref1->fetch_head_status != FETCH_HEAD_IGNORE &&
706 ref2->fetch_head_status == FETCH_HEAD_IGNORE) {
707 warning(_("%s usually tracks %s, not %s"),
708 ref2->peer_ref->name, ref2->name, ref1->name);
709 } else if (ref1->fetch_head_status == FETCH_HEAD_IGNORE &&
710 ref2->fetch_head_status == FETCH_HEAD_IGNORE) {
711 die(_("%s tracks both %s and %s"),
712 ref2->peer_ref->name, ref1->name, ref2->name);
713 } else {
715 * This last possibility doesn't occur because
716 * FETCH_HEAD_IGNORE entries always appear at
717 * the end of the list.
719 BUG("Internal error");
722 free(ref2->peer_ref);
723 free(ref2);
726 struct ref *ref_remove_duplicates(struct ref *ref_map)
728 struct string_list refs = STRING_LIST_INIT_NODUP;
729 struct ref *retval = NULL;
730 struct ref **p = &retval;
732 while (ref_map) {
733 struct ref *ref = ref_map;
735 ref_map = ref_map->next;
736 ref->next = NULL;
738 if (!ref->peer_ref) {
739 *p = ref;
740 p = &ref->next;
741 } else {
742 struct string_list_item *item =
743 string_list_insert(&refs, ref->peer_ref->name);
745 if (item->util) {
746 /* Entry already existed */
747 handle_duplicate((struct ref *)item->util, ref);
748 } else {
749 *p = ref;
750 p = &ref->next;
751 item->util = ref;
756 string_list_clear(&refs, 0);
757 return retval;
760 int remote_has_url(struct remote *remote, const char *url)
762 int i;
763 for (i = 0; i < remote->url_nr; i++) {
764 if (!strcmp(remote->url[i], url))
765 return 1;
767 return 0;
770 static int match_name_with_pattern(const char *key, const char *name,
771 const char *value, char **result)
773 const char *kstar = strchr(key, '*');
774 size_t klen;
775 size_t ksuffixlen;
776 size_t namelen;
777 int ret;
778 if (!kstar)
779 die(_("key '%s' of pattern had no '*'"), key);
780 klen = kstar - key;
781 ksuffixlen = strlen(kstar + 1);
782 namelen = strlen(name);
783 ret = !strncmp(name, key, klen) && namelen >= klen + ksuffixlen &&
784 !memcmp(name + namelen - ksuffixlen, kstar + 1, ksuffixlen);
785 if (ret && value) {
786 struct strbuf sb = STRBUF_INIT;
787 const char *vstar = strchr(value, '*');
788 if (!vstar)
789 die(_("value '%s' of pattern has no '*'"), value);
790 strbuf_add(&sb, value, vstar - value);
791 strbuf_add(&sb, name + klen, namelen - klen - ksuffixlen);
792 strbuf_addstr(&sb, vstar + 1);
793 *result = strbuf_detach(&sb, NULL);
795 return ret;
798 static int refspec_match(const struct refspec_item *refspec,
799 const char *name)
801 if (refspec->pattern)
802 return match_name_with_pattern(refspec->src, name, NULL, NULL);
804 return !strcmp(refspec->src, name);
807 static int omit_name_by_refspec(const char *name, struct refspec *rs)
809 int i;
811 for (i = 0; i < rs->nr; i++) {
812 if (rs->items[i].negative && refspec_match(&rs->items[i], name))
813 return 1;
815 return 0;
818 struct ref *apply_negative_refspecs(struct ref *ref_map, struct refspec *rs)
820 struct ref **tail;
822 for (tail = &ref_map; *tail; ) {
823 struct ref *ref = *tail;
825 if (omit_name_by_refspec(ref->name, rs)) {
826 *tail = ref->next;
827 free(ref->peer_ref);
828 free(ref);
829 } else
830 tail = &ref->next;
833 return ref_map;
836 static int query_matches_negative_refspec(struct refspec *rs, struct refspec_item *query)
838 int i, matched_negative = 0;
839 int find_src = !query->src;
840 struct string_list reversed = STRING_LIST_INIT_NODUP;
841 const char *needle = find_src ? query->dst : query->src;
844 * Check whether the queried ref matches any negative refpsec. If so,
845 * then we should ultimately treat this as not matching the query at
846 * all.
848 * Note that negative refspecs always match the source, but the query
849 * item uses the destination. To handle this, we apply pattern
850 * refspecs in reverse to figure out if the query source matches any
851 * of the negative refspecs.
853 * The first loop finds and expands all positive refspecs
854 * matched by the queried ref.
856 * The second loop checks if any of the results of the first loop
857 * match any negative refspec.
859 for (i = 0; i < rs->nr; i++) {
860 struct refspec_item *refspec = &rs->items[i];
861 char *expn_name;
863 if (refspec->negative)
864 continue;
866 /* Note the reversal of src and dst */
867 if (refspec->pattern) {
868 const char *key = refspec->dst ? refspec->dst : refspec->src;
869 const char *value = refspec->src;
871 if (match_name_with_pattern(key, needle, value, &expn_name))
872 string_list_append_nodup(&reversed, expn_name);
873 } else if (refspec->matching) {
874 /* For the special matching refspec, any query should match */
875 string_list_append(&reversed, needle);
876 } else if (!refspec->src) {
877 BUG("refspec->src should not be null here");
878 } else if (!strcmp(needle, refspec->src)) {
879 string_list_append(&reversed, refspec->src);
883 for (i = 0; !matched_negative && i < reversed.nr; i++) {
884 if (omit_name_by_refspec(reversed.items[i].string, rs))
885 matched_negative = 1;
888 string_list_clear(&reversed, 0);
890 return matched_negative;
893 static void query_refspecs_multiple(struct refspec *rs,
894 struct refspec_item *query,
895 struct string_list *results)
897 int i;
898 int find_src = !query->src;
900 if (find_src && !query->dst)
901 BUG("query_refspecs_multiple: need either src or dst");
903 if (query_matches_negative_refspec(rs, query))
904 return;
906 for (i = 0; i < rs->nr; i++) {
907 struct refspec_item *refspec = &rs->items[i];
908 const char *key = find_src ? refspec->dst : refspec->src;
909 const char *value = find_src ? refspec->src : refspec->dst;
910 const char *needle = find_src ? query->dst : query->src;
911 char **result = find_src ? &query->src : &query->dst;
913 if (!refspec->dst || refspec->negative)
914 continue;
915 if (refspec->pattern) {
916 if (match_name_with_pattern(key, needle, value, result))
917 string_list_append_nodup(results, *result);
918 } else if (!strcmp(needle, key)) {
919 string_list_append(results, value);
924 int query_refspecs(struct refspec *rs, struct refspec_item *query)
926 int i;
927 int find_src = !query->src;
928 const char *needle = find_src ? query->dst : query->src;
929 char **result = find_src ? &query->src : &query->dst;
931 if (find_src && !query->dst)
932 BUG("query_refspecs: need either src or dst");
934 if (query_matches_negative_refspec(rs, query))
935 return -1;
937 for (i = 0; i < rs->nr; i++) {
938 struct refspec_item *refspec = &rs->items[i];
939 const char *key = find_src ? refspec->dst : refspec->src;
940 const char *value = find_src ? refspec->src : refspec->dst;
942 if (!refspec->dst || refspec->negative)
943 continue;
944 if (refspec->pattern) {
945 if (match_name_with_pattern(key, needle, value, result)) {
946 query->force = refspec->force;
947 return 0;
949 } else if (!strcmp(needle, key)) {
950 *result = xstrdup(value);
951 query->force = refspec->force;
952 return 0;
955 return -1;
958 char *apply_refspecs(struct refspec *rs, const char *name)
960 struct refspec_item query;
962 memset(&query, 0, sizeof(struct refspec_item));
963 query.src = (char *)name;
965 if (query_refspecs(rs, &query))
966 return NULL;
968 return query.dst;
971 int remote_find_tracking(struct remote *remote, struct refspec_item *refspec)
973 return query_refspecs(&remote->fetch, refspec);
976 static struct ref *alloc_ref_with_prefix(const char *prefix, size_t prefixlen,
977 const char *name)
979 size_t len = strlen(name);
980 struct ref *ref = xcalloc(1, st_add4(sizeof(*ref), prefixlen, len, 1));
981 memcpy(ref->name, prefix, prefixlen);
982 memcpy(ref->name + prefixlen, name, len);
983 return ref;
986 struct ref *alloc_ref(const char *name)
988 return alloc_ref_with_prefix("", 0, name);
991 struct ref *copy_ref(const struct ref *ref)
993 struct ref *cpy;
994 size_t len;
995 if (!ref)
996 return NULL;
997 len = st_add3(sizeof(struct ref), strlen(ref->name), 1);
998 cpy = xmalloc(len);
999 memcpy(cpy, ref, len);
1000 cpy->next = NULL;
1001 cpy->symref = xstrdup_or_null(ref->symref);
1002 cpy->remote_status = xstrdup_or_null(ref->remote_status);
1003 cpy->peer_ref = copy_ref(ref->peer_ref);
1004 return cpy;
1007 struct ref *copy_ref_list(const struct ref *ref)
1009 struct ref *ret = NULL;
1010 struct ref **tail = &ret;
1011 while (ref) {
1012 *tail = copy_ref(ref);
1013 ref = ref->next;
1014 tail = &((*tail)->next);
1016 return ret;
1019 void free_one_ref(struct ref *ref)
1021 if (!ref)
1022 return;
1023 free_one_ref(ref->peer_ref);
1024 free(ref->remote_status);
1025 free(ref->symref);
1026 free(ref);
1029 void free_refs(struct ref *ref)
1031 struct ref *next;
1032 while (ref) {
1033 next = ref->next;
1034 free_one_ref(ref);
1035 ref = next;
1039 int ref_compare_name(const void *va, const void *vb)
1041 const struct ref *a = va, *b = vb;
1042 return strcmp(a->name, b->name);
1045 static void *ref_list_get_next(const void *a)
1047 return ((const struct ref *)a)->next;
1050 static void ref_list_set_next(void *a, void *next)
1052 ((struct ref *)a)->next = next;
1055 void sort_ref_list(struct ref **l, int (*cmp)(const void *, const void *))
1057 *l = llist_mergesort(*l, ref_list_get_next, ref_list_set_next, cmp);
1060 int count_refspec_match(const char *pattern,
1061 struct ref *refs,
1062 struct ref **matched_ref)
1064 int patlen = strlen(pattern);
1065 struct ref *matched_weak = NULL;
1066 struct ref *matched = NULL;
1067 int weak_match = 0;
1068 int match = 0;
1070 for (weak_match = match = 0; refs; refs = refs->next) {
1071 char *name = refs->name;
1072 int namelen = strlen(name);
1074 if (!refname_match(pattern, name))
1075 continue;
1077 /* A match is "weak" if it is with refs outside
1078 * heads or tags, and did not specify the pattern
1079 * in full (e.g. "refs/remotes/origin/master") or at
1080 * least from the toplevel (e.g. "remotes/origin/master");
1081 * otherwise "git push $URL master" would result in
1082 * ambiguity between remotes/origin/master and heads/master
1083 * at the remote site.
1085 if (namelen != patlen &&
1086 patlen != namelen - 5 &&
1087 !starts_with(name, "refs/heads/") &&
1088 !starts_with(name, "refs/tags/")) {
1089 /* We want to catch the case where only weak
1090 * matches are found and there are multiple
1091 * matches, and where more than one strong
1092 * matches are found, as ambiguous. One
1093 * strong match with zero or more weak matches
1094 * are acceptable as a unique match.
1096 matched_weak = refs;
1097 weak_match++;
1099 else {
1100 matched = refs;
1101 match++;
1104 if (!matched) {
1105 if (matched_ref)
1106 *matched_ref = matched_weak;
1107 return weak_match;
1109 else {
1110 if (matched_ref)
1111 *matched_ref = matched;
1112 return match;
1116 static void tail_link_ref(struct ref *ref, struct ref ***tail)
1118 **tail = ref;
1119 while (ref->next)
1120 ref = ref->next;
1121 *tail = &ref->next;
1124 static struct ref *alloc_delete_ref(void)
1126 struct ref *ref = alloc_ref("(delete)");
1127 oidclr(&ref->new_oid);
1128 return ref;
1131 static int try_explicit_object_name(const char *name,
1132 struct ref **match)
1134 struct object_id oid;
1136 if (!*name) {
1137 if (match)
1138 *match = alloc_delete_ref();
1139 return 0;
1142 if (get_oid(name, &oid))
1143 return -1;
1145 if (match) {
1146 *match = alloc_ref(name);
1147 oidcpy(&(*match)->new_oid, &oid);
1149 return 0;
1152 static struct ref *make_linked_ref(const char *name, struct ref ***tail)
1154 struct ref *ret = alloc_ref(name);
1155 tail_link_ref(ret, tail);
1156 return ret;
1159 static char *guess_ref(const char *name, struct ref *peer)
1161 struct strbuf buf = STRBUF_INIT;
1163 const char *r = resolve_ref_unsafe(peer->name, RESOLVE_REF_READING,
1164 NULL, NULL);
1165 if (!r)
1166 return NULL;
1168 if (starts_with(r, "refs/heads/")) {
1169 strbuf_addstr(&buf, "refs/heads/");
1170 } else if (starts_with(r, "refs/tags/")) {
1171 strbuf_addstr(&buf, "refs/tags/");
1172 } else {
1173 return NULL;
1176 strbuf_addstr(&buf, name);
1177 return strbuf_detach(&buf, NULL);
1180 static int match_explicit_lhs(struct ref *src,
1181 struct refspec_item *rs,
1182 struct ref **match,
1183 int *allocated_match)
1185 switch (count_refspec_match(rs->src, src, match)) {
1186 case 1:
1187 if (allocated_match)
1188 *allocated_match = 0;
1189 return 0;
1190 case 0:
1191 /* The source could be in the get_sha1() format
1192 * not a reference name. :refs/other is a
1193 * way to delete 'other' ref at the remote end.
1195 if (try_explicit_object_name(rs->src, match) < 0)
1196 return error(_("src refspec %s does not match any"), rs->src);
1197 if (allocated_match)
1198 *allocated_match = 1;
1199 return 0;
1200 default:
1201 return error(_("src refspec %s matches more than one"), rs->src);
1205 static void show_push_unqualified_ref_name_error(const char *dst_value,
1206 const char *matched_src_name)
1208 struct object_id oid;
1209 enum object_type type;
1212 * TRANSLATORS: "matches '%s'%" is the <dst> part of "git push
1213 * <remote> <src>:<dst>" push, and "being pushed ('%s')" is
1214 * the <src>.
1216 error(_("The destination you provided is not a full refname (i.e.,\n"
1217 "starting with \"refs/\"). We tried to guess what you meant by:\n"
1218 "\n"
1219 "- Looking for a ref that matches '%s' on the remote side.\n"
1220 "- Checking if the <src> being pushed ('%s')\n"
1221 " is a ref in \"refs/{heads,tags}/\". If so we add a corresponding\n"
1222 " refs/{heads,tags}/ prefix on the remote side.\n"
1223 "\n"
1224 "Neither worked, so we gave up. You must fully qualify the ref."),
1225 dst_value, matched_src_name);
1227 if (!advice_enabled(ADVICE_PUSH_UNQUALIFIED_REF_NAME))
1228 return;
1230 if (get_oid(matched_src_name, &oid))
1231 BUG("'%s' is not a valid object, "
1232 "match_explicit_lhs() should catch this!",
1233 matched_src_name);
1234 type = oid_object_info(the_repository, &oid, NULL);
1235 if (type == OBJ_COMMIT) {
1236 advise(_("The <src> part of the refspec is a commit object.\n"
1237 "Did you mean to create a new branch by pushing to\n"
1238 "'%s:refs/heads/%s'?"),
1239 matched_src_name, dst_value);
1240 } else if (type == OBJ_TAG) {
1241 advise(_("The <src> part of the refspec is a tag object.\n"
1242 "Did you mean to create a new tag by pushing to\n"
1243 "'%s:refs/tags/%s'?"),
1244 matched_src_name, dst_value);
1245 } else if (type == OBJ_TREE) {
1246 advise(_("The <src> part of the refspec is a tree object.\n"
1247 "Did you mean to tag a new tree by pushing to\n"
1248 "'%s:refs/tags/%s'?"),
1249 matched_src_name, dst_value);
1250 } else if (type == OBJ_BLOB) {
1251 advise(_("The <src> part of the refspec is a blob object.\n"
1252 "Did you mean to tag a new blob by pushing to\n"
1253 "'%s:refs/tags/%s'?"),
1254 matched_src_name, dst_value);
1255 } else {
1256 BUG("'%s' should be commit/tag/tree/blob, is '%d'",
1257 matched_src_name, type);
1261 static int match_explicit(struct ref *src, struct ref *dst,
1262 struct ref ***dst_tail,
1263 struct refspec_item *rs)
1265 struct ref *matched_src, *matched_dst;
1266 int allocated_src;
1268 const char *dst_value = rs->dst;
1269 char *dst_guess;
1271 if (rs->pattern || rs->matching || rs->negative)
1272 return 0;
1274 matched_src = matched_dst = NULL;
1275 if (match_explicit_lhs(src, rs, &matched_src, &allocated_src) < 0)
1276 return -1;
1278 if (!dst_value) {
1279 int flag;
1281 dst_value = resolve_ref_unsafe(matched_src->name,
1282 RESOLVE_REF_READING,
1283 NULL, &flag);
1284 if (!dst_value ||
1285 ((flag & REF_ISSYMREF) &&
1286 !starts_with(dst_value, "refs/heads/")))
1287 die(_("%s cannot be resolved to branch"),
1288 matched_src->name);
1291 switch (count_refspec_match(dst_value, dst, &matched_dst)) {
1292 case 1:
1293 break;
1294 case 0:
1295 if (starts_with(dst_value, "refs/")) {
1296 matched_dst = make_linked_ref(dst_value, dst_tail);
1297 } else if (is_null_oid(&matched_src->new_oid)) {
1298 error(_("unable to delete '%s': remote ref does not exist"),
1299 dst_value);
1300 } else if ((dst_guess = guess_ref(dst_value, matched_src))) {
1301 matched_dst = make_linked_ref(dst_guess, dst_tail);
1302 free(dst_guess);
1303 } else {
1304 show_push_unqualified_ref_name_error(dst_value,
1305 matched_src->name);
1307 break;
1308 default:
1309 matched_dst = NULL;
1310 error(_("dst refspec %s matches more than one"),
1311 dst_value);
1312 break;
1314 if (!matched_dst)
1315 return -1;
1316 if (matched_dst->peer_ref)
1317 return error(_("dst ref %s receives from more than one src"),
1318 matched_dst->name);
1319 else {
1320 matched_dst->peer_ref = allocated_src ?
1321 matched_src :
1322 copy_ref(matched_src);
1323 matched_dst->force = rs->force;
1325 return 0;
1328 static int match_explicit_refs(struct ref *src, struct ref *dst,
1329 struct ref ***dst_tail, struct refspec *rs)
1331 int i, errs;
1332 for (i = errs = 0; i < rs->nr; i++)
1333 errs += match_explicit(src, dst, dst_tail, &rs->items[i]);
1334 return errs;
1337 static char *get_ref_match(const struct refspec *rs, const struct ref *ref,
1338 int send_mirror, int direction,
1339 const struct refspec_item **ret_pat)
1341 const struct refspec_item *pat;
1342 char *name;
1343 int i;
1344 int matching_refs = -1;
1345 for (i = 0; i < rs->nr; i++) {
1346 const struct refspec_item *item = &rs->items[i];
1348 if (item->negative)
1349 continue;
1351 if (item->matching &&
1352 (matching_refs == -1 || item->force)) {
1353 matching_refs = i;
1354 continue;
1357 if (item->pattern) {
1358 const char *dst_side = item->dst ? item->dst : item->src;
1359 int match;
1360 if (direction == FROM_SRC)
1361 match = match_name_with_pattern(item->src, ref->name, dst_side, &name);
1362 else
1363 match = match_name_with_pattern(dst_side, ref->name, item->src, &name);
1364 if (match) {
1365 matching_refs = i;
1366 break;
1370 if (matching_refs == -1)
1371 return NULL;
1373 pat = &rs->items[matching_refs];
1374 if (pat->matching) {
1376 * "matching refs"; traditionally we pushed everything
1377 * including refs outside refs/heads/ hierarchy, but
1378 * that does not make much sense these days.
1380 if (!send_mirror && !starts_with(ref->name, "refs/heads/"))
1381 return NULL;
1382 name = xstrdup(ref->name);
1384 if (ret_pat)
1385 *ret_pat = pat;
1386 return name;
1389 static struct ref **tail_ref(struct ref **head)
1391 struct ref **tail = head;
1392 while (*tail)
1393 tail = &((*tail)->next);
1394 return tail;
1397 struct tips {
1398 struct commit **tip;
1399 int nr, alloc;
1402 static void add_to_tips(struct tips *tips, const struct object_id *oid)
1404 struct commit *commit;
1406 if (is_null_oid(oid))
1407 return;
1408 commit = lookup_commit_reference_gently(the_repository, oid, 1);
1409 if (!commit || (commit->object.flags & TMP_MARK))
1410 return;
1411 commit->object.flags |= TMP_MARK;
1412 ALLOC_GROW(tips->tip, tips->nr + 1, tips->alloc);
1413 tips->tip[tips->nr++] = commit;
1416 static void add_missing_tags(struct ref *src, struct ref **dst, struct ref ***dst_tail)
1418 struct string_list dst_tag = STRING_LIST_INIT_NODUP;
1419 struct string_list src_tag = STRING_LIST_INIT_NODUP;
1420 struct string_list_item *item;
1421 struct ref *ref;
1422 struct tips sent_tips;
1425 * Collect everything we know they would have at the end of
1426 * this push, and collect all tags they have.
1428 memset(&sent_tips, 0, sizeof(sent_tips));
1429 for (ref = *dst; ref; ref = ref->next) {
1430 if (ref->peer_ref &&
1431 !is_null_oid(&ref->peer_ref->new_oid))
1432 add_to_tips(&sent_tips, &ref->peer_ref->new_oid);
1433 else
1434 add_to_tips(&sent_tips, &ref->old_oid);
1435 if (starts_with(ref->name, "refs/tags/"))
1436 string_list_append(&dst_tag, ref->name);
1438 clear_commit_marks_many(sent_tips.nr, sent_tips.tip, TMP_MARK);
1440 string_list_sort(&dst_tag);
1442 /* Collect tags they do not have. */
1443 for (ref = src; ref; ref = ref->next) {
1444 if (!starts_with(ref->name, "refs/tags/"))
1445 continue; /* not a tag */
1446 if (string_list_has_string(&dst_tag, ref->name))
1447 continue; /* they already have it */
1448 if (oid_object_info(the_repository, &ref->new_oid, NULL) != OBJ_TAG)
1449 continue; /* be conservative */
1450 item = string_list_append(&src_tag, ref->name);
1451 item->util = ref;
1453 string_list_clear(&dst_tag, 0);
1456 * At this point, src_tag lists tags that are missing from
1457 * dst, and sent_tips lists the tips we are pushing or those
1458 * that we know they already have. An element in the src_tag
1459 * that is an ancestor of any of the sent_tips needs to be
1460 * sent to the other side.
1462 if (sent_tips.nr) {
1463 const int reachable_flag = 1;
1464 struct commit_list *found_commits;
1465 struct commit **src_commits;
1466 int nr_src_commits = 0, alloc_src_commits = 16;
1467 ALLOC_ARRAY(src_commits, alloc_src_commits);
1469 for_each_string_list_item(item, &src_tag) {
1470 struct ref *ref = item->util;
1471 struct commit *commit;
1473 if (is_null_oid(&ref->new_oid))
1474 continue;
1475 commit = lookup_commit_reference_gently(the_repository,
1476 &ref->new_oid,
1478 if (!commit)
1479 /* not pushing a commit, which is not an error */
1480 continue;
1482 ALLOC_GROW(src_commits, nr_src_commits + 1, alloc_src_commits);
1483 src_commits[nr_src_commits++] = commit;
1486 found_commits = get_reachable_subset(sent_tips.tip, sent_tips.nr,
1487 src_commits, nr_src_commits,
1488 reachable_flag);
1490 for_each_string_list_item(item, &src_tag) {
1491 struct ref *dst_ref;
1492 struct ref *ref = item->util;
1493 struct commit *commit;
1495 if (is_null_oid(&ref->new_oid))
1496 continue;
1497 commit = lookup_commit_reference_gently(the_repository,
1498 &ref->new_oid,
1500 if (!commit)
1501 /* not pushing a commit, which is not an error */
1502 continue;
1505 * Is this tag, which they do not have, reachable from
1506 * any of the commits we are sending?
1508 if (!(commit->object.flags & reachable_flag))
1509 continue;
1511 /* Add it in */
1512 dst_ref = make_linked_ref(ref->name, dst_tail);
1513 oidcpy(&dst_ref->new_oid, &ref->new_oid);
1514 dst_ref->peer_ref = copy_ref(ref);
1517 clear_commit_marks_many(nr_src_commits, src_commits, reachable_flag);
1518 free(src_commits);
1519 free_commit_list(found_commits);
1522 string_list_clear(&src_tag, 0);
1523 free(sent_tips.tip);
1526 struct ref *find_ref_by_name(const struct ref *list, const char *name)
1528 for ( ; list; list = list->next)
1529 if (!strcmp(list->name, name))
1530 return (struct ref *)list;
1531 return NULL;
1534 static void prepare_ref_index(struct string_list *ref_index, struct ref *ref)
1536 for ( ; ref; ref = ref->next)
1537 string_list_append_nodup(ref_index, ref->name)->util = ref;
1539 string_list_sort(ref_index);
1543 * Given only the set of local refs, sanity-check the set of push
1544 * refspecs. We can't catch all errors that match_push_refs would,
1545 * but we can catch some errors early before even talking to the
1546 * remote side.
1548 int check_push_refs(struct ref *src, struct refspec *rs)
1550 int ret = 0;
1551 int i;
1553 for (i = 0; i < rs->nr; i++) {
1554 struct refspec_item *item = &rs->items[i];
1556 if (item->pattern || item->matching || item->negative)
1557 continue;
1559 ret |= match_explicit_lhs(src, item, NULL, NULL);
1562 return ret;
1566 * Given the set of refs the local repository has, the set of refs the
1567 * remote repository has, and the refspec used for push, determine
1568 * what remote refs we will update and with what value by setting
1569 * peer_ref (which object is being pushed) and force (if the push is
1570 * forced) in elements of "dst". The function may add new elements to
1571 * dst (e.g. pushing to a new branch, done in match_explicit_refs).
1573 int match_push_refs(struct ref *src, struct ref **dst,
1574 struct refspec *rs, int flags)
1576 int send_all = flags & MATCH_REFS_ALL;
1577 int send_mirror = flags & MATCH_REFS_MIRROR;
1578 int send_prune = flags & MATCH_REFS_PRUNE;
1579 int errs;
1580 struct ref *ref, **dst_tail = tail_ref(dst);
1581 struct string_list dst_ref_index = STRING_LIST_INIT_NODUP;
1583 /* If no refspec is provided, use the default ":" */
1584 if (!rs->nr)
1585 refspec_append(rs, ":");
1587 errs = match_explicit_refs(src, *dst, &dst_tail, rs);
1589 /* pick the remainder */
1590 for (ref = src; ref; ref = ref->next) {
1591 struct string_list_item *dst_item;
1592 struct ref *dst_peer;
1593 const struct refspec_item *pat = NULL;
1594 char *dst_name;
1596 dst_name = get_ref_match(rs, ref, send_mirror, FROM_SRC, &pat);
1597 if (!dst_name)
1598 continue;
1600 if (!dst_ref_index.nr)
1601 prepare_ref_index(&dst_ref_index, *dst);
1603 dst_item = string_list_lookup(&dst_ref_index, dst_name);
1604 dst_peer = dst_item ? dst_item->util : NULL;
1605 if (dst_peer) {
1606 if (dst_peer->peer_ref)
1607 /* We're already sending something to this ref. */
1608 goto free_name;
1609 } else {
1610 if (pat->matching && !(send_all || send_mirror))
1612 * Remote doesn't have it, and we have no
1613 * explicit pattern, and we don't have
1614 * --all or --mirror.
1616 goto free_name;
1618 /* Create a new one and link it */
1619 dst_peer = make_linked_ref(dst_name, &dst_tail);
1620 oidcpy(&dst_peer->new_oid, &ref->new_oid);
1621 string_list_insert(&dst_ref_index,
1622 dst_peer->name)->util = dst_peer;
1624 dst_peer->peer_ref = copy_ref(ref);
1625 dst_peer->force = pat->force;
1626 free_name:
1627 free(dst_name);
1630 string_list_clear(&dst_ref_index, 0);
1632 if (flags & MATCH_REFS_FOLLOW_TAGS)
1633 add_missing_tags(src, dst, &dst_tail);
1635 if (send_prune) {
1636 struct string_list src_ref_index = STRING_LIST_INIT_NODUP;
1637 /* check for missing refs on the remote */
1638 for (ref = *dst; ref; ref = ref->next) {
1639 char *src_name;
1641 if (ref->peer_ref)
1642 /* We're already sending something to this ref. */
1643 continue;
1645 src_name = get_ref_match(rs, ref, send_mirror, FROM_DST, NULL);
1646 if (src_name) {
1647 if (!src_ref_index.nr)
1648 prepare_ref_index(&src_ref_index, src);
1649 if (!string_list_has_string(&src_ref_index,
1650 src_name))
1651 ref->peer_ref = alloc_delete_ref();
1652 free(src_name);
1655 string_list_clear(&src_ref_index, 0);
1658 *dst = apply_negative_refspecs(*dst, rs);
1660 if (errs)
1661 return -1;
1662 return 0;
1665 void set_ref_status_for_push(struct ref *remote_refs, int send_mirror,
1666 int force_update)
1668 struct ref *ref;
1670 for (ref = remote_refs; ref; ref = ref->next) {
1671 int force_ref_update = ref->force || force_update;
1672 int reject_reason = 0;
1674 if (ref->peer_ref)
1675 oidcpy(&ref->new_oid, &ref->peer_ref->new_oid);
1676 else if (!send_mirror)
1677 continue;
1679 ref->deletion = is_null_oid(&ref->new_oid);
1680 if (!ref->deletion &&
1681 oideq(&ref->old_oid, &ref->new_oid)) {
1682 ref->status = REF_STATUS_UPTODATE;
1683 continue;
1687 * If the remote ref has moved and is now different
1688 * from what we expect, reject any push.
1690 * It also is an error if the user told us to check
1691 * with the remote-tracking branch to find the value
1692 * to expect, but we did not have such a tracking
1693 * branch.
1695 * If the tip of the remote-tracking ref is unreachable
1696 * from any reflog entry of its local ref indicating a
1697 * possible update since checkout; reject the push.
1699 if (ref->expect_old_sha1) {
1700 if (!oideq(&ref->old_oid, &ref->old_oid_expect))
1701 reject_reason = REF_STATUS_REJECT_STALE;
1702 else if (ref->check_reachable && ref->unreachable)
1703 reject_reason =
1704 REF_STATUS_REJECT_REMOTE_UPDATED;
1705 else
1707 * If the ref isn't stale, and is reachable
1708 * from one of the reflog entries of
1709 * the local branch, force the update.
1711 force_ref_update = 1;
1715 * If the update isn't already rejected then check
1716 * the usual "must fast-forward" rules.
1718 * Decide whether an individual refspec A:B can be
1719 * pushed. The push will succeed if any of the
1720 * following are true:
1722 * (1) the remote reference B does not exist
1724 * (2) the remote reference B is being removed (i.e.,
1725 * pushing :B where no source is specified)
1727 * (3) the destination is not under refs/tags/, and
1728 * if the old and new value is a commit, the new
1729 * is a descendant of the old.
1731 * (4) it is forced using the +A:B notation, or by
1732 * passing the --force argument
1735 if (!reject_reason && !ref->deletion && !is_null_oid(&ref->old_oid)) {
1736 if (starts_with(ref->name, "refs/tags/"))
1737 reject_reason = REF_STATUS_REJECT_ALREADY_EXISTS;
1738 else if (!has_object_file(&ref->old_oid))
1739 reject_reason = REF_STATUS_REJECT_FETCH_FIRST;
1740 else if (!lookup_commit_reference_gently(the_repository, &ref->old_oid, 1) ||
1741 !lookup_commit_reference_gently(the_repository, &ref->new_oid, 1))
1742 reject_reason = REF_STATUS_REJECT_NEEDS_FORCE;
1743 else if (!ref_newer(&ref->new_oid, &ref->old_oid))
1744 reject_reason = REF_STATUS_REJECT_NONFASTFORWARD;
1748 * "--force" will defeat any rejection implemented
1749 * by the rules above.
1751 if (!force_ref_update)
1752 ref->status = reject_reason;
1753 else if (reject_reason)
1754 ref->forced_update = 1;
1758 static void set_merge(struct remote_state *remote_state, struct branch *ret)
1760 struct remote *remote;
1761 char *ref;
1762 struct object_id oid;
1763 int i;
1765 if (!ret)
1766 return; /* no branch */
1767 if (ret->merge)
1768 return; /* already run */
1769 if (!ret->remote_name || !ret->merge_nr) {
1771 * no merge config; let's make sure we don't confuse callers
1772 * with a non-zero merge_nr but a NULL merge
1774 ret->merge_nr = 0;
1775 return;
1778 remote = remotes_remote_get(remote_state, ret->remote_name);
1780 CALLOC_ARRAY(ret->merge, ret->merge_nr);
1781 for (i = 0; i < ret->merge_nr; i++) {
1782 ret->merge[i] = xcalloc(1, sizeof(**ret->merge));
1783 ret->merge[i]->src = xstrdup(ret->merge_name[i]);
1784 if (!remote_find_tracking(remote, ret->merge[i]) ||
1785 strcmp(ret->remote_name, "."))
1786 continue;
1787 if (dwim_ref(ret->merge_name[i], strlen(ret->merge_name[i]),
1788 &oid, &ref, 0) == 1)
1789 ret->merge[i]->dst = ref;
1790 else
1791 ret->merge[i]->dst = xstrdup(ret->merge_name[i]);
1795 struct branch *branch_get(const char *name)
1797 struct branch *ret;
1799 read_config(the_repository);
1800 if (!name || !*name || !strcmp(name, "HEAD"))
1801 ret = the_repository->remote_state->current_branch;
1802 else
1803 ret = make_branch(the_repository->remote_state, name,
1804 strlen(name));
1805 set_merge(the_repository->remote_state, ret);
1806 return ret;
1809 int branch_has_merge_config(struct branch *branch)
1811 return branch && !!branch->merge;
1814 int branch_merge_matches(struct branch *branch,
1815 int i,
1816 const char *refname)
1818 if (!branch || i < 0 || i >= branch->merge_nr)
1819 return 0;
1820 return refname_match(branch->merge[i]->src, refname);
1823 __attribute__((format (printf,2,3)))
1824 static const char *error_buf(struct strbuf *err, const char *fmt, ...)
1826 if (err) {
1827 va_list ap;
1828 va_start(ap, fmt);
1829 strbuf_vaddf(err, fmt, ap);
1830 va_end(ap);
1832 return NULL;
1835 const char *branch_get_upstream(struct branch *branch, struct strbuf *err)
1837 if (!branch)
1838 return error_buf(err, _("HEAD does not point to a branch"));
1840 if (!branch->merge || !branch->merge[0]) {
1842 * no merge config; is it because the user didn't define any,
1843 * or because it is not a real branch, and get_branch
1844 * auto-vivified it?
1846 if (!ref_exists(branch->refname))
1847 return error_buf(err, _("no such branch: '%s'"),
1848 branch->name);
1849 return error_buf(err,
1850 _("no upstream configured for branch '%s'"),
1851 branch->name);
1854 if (!branch->merge[0]->dst)
1855 return error_buf(err,
1856 _("upstream branch '%s' not stored as a remote-tracking branch"),
1857 branch->merge[0]->src);
1859 return branch->merge[0]->dst;
1862 static const char *tracking_for_push_dest(struct remote *remote,
1863 const char *refname,
1864 struct strbuf *err)
1866 char *ret;
1868 ret = apply_refspecs(&remote->fetch, refname);
1869 if (!ret)
1870 return error_buf(err,
1871 _("push destination '%s' on remote '%s' has no local tracking branch"),
1872 refname, remote->name);
1873 return ret;
1876 static const char *branch_get_push_1(struct remote_state *remote_state,
1877 struct branch *branch, struct strbuf *err)
1879 struct remote *remote;
1881 remote = remotes_remote_get(
1882 remote_state,
1883 remotes_pushremote_for_branch(remote_state, branch, NULL));
1884 if (!remote)
1885 return error_buf(err,
1886 _("branch '%s' has no remote for pushing"),
1887 branch->name);
1889 if (remote->push.nr) {
1890 char *dst;
1891 const char *ret;
1893 dst = apply_refspecs(&remote->push, branch->refname);
1894 if (!dst)
1895 return error_buf(err,
1896 _("push refspecs for '%s' do not include '%s'"),
1897 remote->name, branch->name);
1899 ret = tracking_for_push_dest(remote, dst, err);
1900 free(dst);
1901 return ret;
1904 if (remote->mirror)
1905 return tracking_for_push_dest(remote, branch->refname, err);
1907 switch (push_default) {
1908 case PUSH_DEFAULT_NOTHING:
1909 return error_buf(err, _("push has no destination (push.default is 'nothing')"));
1911 case PUSH_DEFAULT_MATCHING:
1912 case PUSH_DEFAULT_CURRENT:
1913 return tracking_for_push_dest(remote, branch->refname, err);
1915 case PUSH_DEFAULT_UPSTREAM:
1916 return branch_get_upstream(branch, err);
1918 case PUSH_DEFAULT_UNSPECIFIED:
1919 case PUSH_DEFAULT_SIMPLE:
1921 const char *up, *cur;
1923 up = branch_get_upstream(branch, err);
1924 if (!up)
1925 return NULL;
1926 cur = tracking_for_push_dest(remote, branch->refname, err);
1927 if (!cur)
1928 return NULL;
1929 if (strcmp(cur, up))
1930 return error_buf(err,
1931 _("cannot resolve 'simple' push to a single destination"));
1932 return cur;
1936 BUG("unhandled push situation");
1939 const char *branch_get_push(struct branch *branch, struct strbuf *err)
1941 read_config(the_repository);
1942 die_on_missing_branch(the_repository, branch);
1944 if (!branch)
1945 return error_buf(err, _("HEAD does not point to a branch"));
1947 if (!branch->push_tracking_ref)
1948 branch->push_tracking_ref = branch_get_push_1(
1949 the_repository->remote_state, branch, err);
1950 return branch->push_tracking_ref;
1953 static int ignore_symref_update(const char *refname, struct strbuf *scratch)
1955 return !refs_read_symbolic_ref(get_main_ref_store(the_repository), refname, scratch);
1959 * Create and return a list of (struct ref) consisting of copies of
1960 * each remote_ref that matches refspec. refspec must be a pattern.
1961 * Fill in the copies' peer_ref to describe the local tracking refs to
1962 * which they map. Omit any references that would map to an existing
1963 * local symbolic ref.
1965 static struct ref *get_expanded_map(const struct ref *remote_refs,
1966 const struct refspec_item *refspec)
1968 struct strbuf scratch = STRBUF_INIT;
1969 const struct ref *ref;
1970 struct ref *ret = NULL;
1971 struct ref **tail = &ret;
1973 for (ref = remote_refs; ref; ref = ref->next) {
1974 char *expn_name = NULL;
1976 strbuf_reset(&scratch);
1978 if (strchr(ref->name, '^'))
1979 continue; /* a dereference item */
1980 if (match_name_with_pattern(refspec->src, ref->name,
1981 refspec->dst, &expn_name) &&
1982 !ignore_symref_update(expn_name, &scratch)) {
1983 struct ref *cpy = copy_ref(ref);
1985 cpy->peer_ref = alloc_ref(expn_name);
1986 if (refspec->force)
1987 cpy->peer_ref->force = 1;
1988 *tail = cpy;
1989 tail = &cpy->next;
1991 free(expn_name);
1994 strbuf_release(&scratch);
1995 return ret;
1998 static const struct ref *find_ref_by_name_abbrev(const struct ref *refs, const char *name)
2000 const struct ref *ref;
2001 const struct ref *best_match = NULL;
2002 int best_score = 0;
2004 for (ref = refs; ref; ref = ref->next) {
2005 int score = refname_match(name, ref->name);
2007 if (best_score < score) {
2008 best_match = ref;
2009 best_score = score;
2012 return best_match;
2015 struct ref *get_remote_ref(const struct ref *remote_refs, const char *name)
2017 const struct ref *ref = find_ref_by_name_abbrev(remote_refs, name);
2019 if (!ref)
2020 return NULL;
2022 return copy_ref(ref);
2025 static struct ref *get_local_ref(const char *name)
2027 if (!name || name[0] == '\0')
2028 return NULL;
2030 if (starts_with(name, "refs/"))
2031 return alloc_ref(name);
2033 if (starts_with(name, "heads/") ||
2034 starts_with(name, "tags/") ||
2035 starts_with(name, "remotes/"))
2036 return alloc_ref_with_prefix("refs/", 5, name);
2038 return alloc_ref_with_prefix("refs/heads/", 11, name);
2041 int get_fetch_map(const struct ref *remote_refs,
2042 const struct refspec_item *refspec,
2043 struct ref ***tail,
2044 int missing_ok)
2046 struct ref *ref_map, **rmp;
2048 if (refspec->negative)
2049 return 0;
2051 if (refspec->pattern) {
2052 ref_map = get_expanded_map(remote_refs, refspec);
2053 } else {
2054 const char *name = refspec->src[0] ? refspec->src : "HEAD";
2056 if (refspec->exact_sha1) {
2057 ref_map = alloc_ref(name);
2058 get_oid_hex(name, &ref_map->old_oid);
2059 ref_map->exact_oid = 1;
2060 } else {
2061 ref_map = get_remote_ref(remote_refs, name);
2063 if (!missing_ok && !ref_map)
2064 die(_("couldn't find remote ref %s"), name);
2065 if (ref_map) {
2066 ref_map->peer_ref = get_local_ref(refspec->dst);
2067 if (ref_map->peer_ref && refspec->force)
2068 ref_map->peer_ref->force = 1;
2072 for (rmp = &ref_map; *rmp; ) {
2073 if ((*rmp)->peer_ref) {
2074 if (!starts_with((*rmp)->peer_ref->name, "refs/") ||
2075 check_refname_format((*rmp)->peer_ref->name, 0)) {
2076 struct ref *ignore = *rmp;
2077 error(_("* Ignoring funny ref '%s' locally"),
2078 (*rmp)->peer_ref->name);
2079 *rmp = (*rmp)->next;
2080 free(ignore->peer_ref);
2081 free(ignore);
2082 continue;
2085 rmp = &((*rmp)->next);
2088 if (ref_map)
2089 tail_link_ref(ref_map, tail);
2091 return 0;
2094 int resolve_remote_symref(struct ref *ref, struct ref *list)
2096 if (!ref->symref)
2097 return 0;
2098 for (; list; list = list->next)
2099 if (!strcmp(ref->symref, list->name)) {
2100 oidcpy(&ref->old_oid, &list->old_oid);
2101 return 0;
2103 return 1;
2107 * Compute the commit ahead/behind values for the pair branch_name, base.
2109 * If abf is AHEAD_BEHIND_FULL, compute the full ahead/behind and return the
2110 * counts in *num_ours and *num_theirs. If abf is AHEAD_BEHIND_QUICK, skip
2111 * the (potentially expensive) a/b computation (*num_ours and *num_theirs are
2112 * set to zero).
2114 * Returns -1 if num_ours and num_theirs could not be filled in (e.g., ref
2115 * does not exist). Returns 0 if the commits are identical. Returns 1 if
2116 * commits are different.
2119 static int stat_branch_pair(const char *branch_name, const char *base,
2120 int *num_ours, int *num_theirs,
2121 enum ahead_behind_flags abf)
2123 struct object_id oid;
2124 struct commit *ours, *theirs;
2125 struct rev_info revs;
2126 struct strvec argv = STRVEC_INIT;
2128 /* Cannot stat if what we used to build on no longer exists */
2129 if (read_ref(base, &oid))
2130 return -1;
2131 theirs = lookup_commit_reference(the_repository, &oid);
2132 if (!theirs)
2133 return -1;
2135 if (read_ref(branch_name, &oid))
2136 return -1;
2137 ours = lookup_commit_reference(the_repository, &oid);
2138 if (!ours)
2139 return -1;
2141 *num_theirs = *num_ours = 0;
2143 /* are we the same? */
2144 if (theirs == ours)
2145 return 0;
2146 if (abf == AHEAD_BEHIND_QUICK)
2147 return 1;
2148 if (abf != AHEAD_BEHIND_FULL)
2149 BUG("stat_branch_pair: invalid abf '%d'", abf);
2151 /* Run "rev-list --left-right ours...theirs" internally... */
2152 strvec_push(&argv, ""); /* ignored */
2153 strvec_push(&argv, "--left-right");
2154 strvec_pushf(&argv, "%s...%s",
2155 oid_to_hex(&ours->object.oid),
2156 oid_to_hex(&theirs->object.oid));
2157 strvec_push(&argv, "--");
2159 repo_init_revisions(the_repository, &revs, NULL);
2160 setup_revisions(argv.nr, argv.v, &revs, NULL);
2161 if (prepare_revision_walk(&revs))
2162 die(_("revision walk setup failed"));
2164 /* ... and count the commits on each side. */
2165 while (1) {
2166 struct commit *c = get_revision(&revs);
2167 if (!c)
2168 break;
2169 if (c->object.flags & SYMMETRIC_LEFT)
2170 (*num_ours)++;
2171 else
2172 (*num_theirs)++;
2175 /* clear object flags smudged by the above traversal */
2176 clear_commit_marks(ours, ALL_REV_FLAGS);
2177 clear_commit_marks(theirs, ALL_REV_FLAGS);
2179 strvec_clear(&argv);
2180 release_revisions(&revs);
2181 return 1;
2185 * Lookup the tracking branch for the given branch and if present, optionally
2186 * compute the commit ahead/behind values for the pair.
2188 * If for_push is true, the tracking branch refers to the push branch,
2189 * otherwise it refers to the upstream branch.
2191 * The name of the tracking branch (or NULL if it is not defined) is
2192 * returned via *tracking_name, if it is not itself NULL.
2194 * If abf is AHEAD_BEHIND_FULL, compute the full ahead/behind and return the
2195 * counts in *num_ours and *num_theirs. If abf is AHEAD_BEHIND_QUICK, skip
2196 * the (potentially expensive) a/b computation (*num_ours and *num_theirs are
2197 * set to zero).
2199 * Returns -1 if num_ours and num_theirs could not be filled in (e.g., no
2200 * upstream defined, or ref does not exist). Returns 0 if the commits are
2201 * identical. Returns 1 if commits are different.
2203 int stat_tracking_info(struct branch *branch, int *num_ours, int *num_theirs,
2204 const char **tracking_name, int for_push,
2205 enum ahead_behind_flags abf)
2207 const char *base;
2209 /* Cannot stat unless we are marked to build on top of somebody else. */
2210 base = for_push ? branch_get_push(branch, NULL) :
2211 branch_get_upstream(branch, NULL);
2212 if (tracking_name)
2213 *tracking_name = base;
2214 if (!base)
2215 return -1;
2217 return stat_branch_pair(branch->refname, base, num_ours, num_theirs, abf);
2221 * Return true when there is anything to report, otherwise false.
2223 int format_tracking_info(struct branch *branch, struct strbuf *sb,
2224 enum ahead_behind_flags abf)
2226 int ours, theirs, sti;
2227 const char *full_base;
2228 char *base;
2229 int upstream_is_gone = 0;
2231 sti = stat_tracking_info(branch, &ours, &theirs, &full_base, 0, abf);
2232 if (sti < 0) {
2233 if (!full_base)
2234 return 0;
2235 upstream_is_gone = 1;
2238 base = shorten_unambiguous_ref(full_base, 0);
2239 if (upstream_is_gone) {
2240 strbuf_addf(sb,
2241 _("Your branch is based on '%s', but the upstream is gone.\n"),
2242 base);
2243 if (advice_enabled(ADVICE_STATUS_HINTS))
2244 strbuf_addstr(sb,
2245 _(" (use \"git branch --unset-upstream\" to fixup)\n"));
2246 } else if (!sti) {
2247 strbuf_addf(sb,
2248 _("Your branch is up to date with '%s'.\n"),
2249 base);
2250 } else if (abf == AHEAD_BEHIND_QUICK) {
2251 strbuf_addf(sb,
2252 _("Your branch and '%s' refer to different commits.\n"),
2253 base);
2254 if (advice_enabled(ADVICE_STATUS_HINTS))
2255 strbuf_addf(sb, _(" (use \"%s\" for details)\n"),
2256 "git status --ahead-behind");
2257 } else if (!theirs) {
2258 strbuf_addf(sb,
2259 Q_("Your branch is ahead of '%s' by %d commit.\n",
2260 "Your branch is ahead of '%s' by %d commits.\n",
2261 ours),
2262 base, ours);
2263 if (advice_enabled(ADVICE_STATUS_HINTS))
2264 strbuf_addstr(sb,
2265 _(" (use \"git push\" to publish your local commits)\n"));
2266 } else if (!ours) {
2267 strbuf_addf(sb,
2268 Q_("Your branch is behind '%s' by %d commit, "
2269 "and can be fast-forwarded.\n",
2270 "Your branch is behind '%s' by %d commits, "
2271 "and can be fast-forwarded.\n",
2272 theirs),
2273 base, theirs);
2274 if (advice_enabled(ADVICE_STATUS_HINTS))
2275 strbuf_addstr(sb,
2276 _(" (use \"git pull\" to update your local branch)\n"));
2277 } else {
2278 strbuf_addf(sb,
2279 Q_("Your branch and '%s' have diverged,\n"
2280 "and have %d and %d different commit each, "
2281 "respectively.\n",
2282 "Your branch and '%s' have diverged,\n"
2283 "and have %d and %d different commits each, "
2284 "respectively.\n",
2285 ours + theirs),
2286 base, ours, theirs);
2287 if (advice_enabled(ADVICE_STATUS_HINTS))
2288 strbuf_addstr(sb,
2289 _(" (use \"git pull\" to merge the remote branch into yours)\n"));
2291 free(base);
2292 return 1;
2295 static int one_local_ref(const char *refname, const struct object_id *oid,
2296 int flag, void *cb_data)
2298 struct ref ***local_tail = cb_data;
2299 struct ref *ref;
2301 /* we already know it starts with refs/ to get here */
2302 if (check_refname_format(refname + 5, 0))
2303 return 0;
2305 ref = alloc_ref(refname);
2306 oidcpy(&ref->new_oid, oid);
2307 **local_tail = ref;
2308 *local_tail = &ref->next;
2309 return 0;
2312 struct ref *get_local_heads(void)
2314 struct ref *local_refs = NULL, **local_tail = &local_refs;
2316 for_each_ref(one_local_ref, &local_tail);
2317 return local_refs;
2320 struct ref *guess_remote_head(const struct ref *head,
2321 const struct ref *refs,
2322 int all)
2324 const struct ref *r;
2325 struct ref *list = NULL;
2326 struct ref **tail = &list;
2328 if (!head)
2329 return NULL;
2332 * Some transports support directly peeking at
2333 * where HEAD points; if that is the case, then
2334 * we don't have to guess.
2336 if (head->symref)
2337 return copy_ref(find_ref_by_name(refs, head->symref));
2339 /* If a remote branch exists with the default branch name, let's use it. */
2340 if (!all) {
2341 char *ref = xstrfmt("refs/heads/%s",
2342 git_default_branch_name(0));
2344 r = find_ref_by_name(refs, ref);
2345 free(ref);
2346 if (r && oideq(&r->old_oid, &head->old_oid))
2347 return copy_ref(r);
2349 /* Fall back to the hard-coded historical default */
2350 r = find_ref_by_name(refs, "refs/heads/master");
2351 if (r && oideq(&r->old_oid, &head->old_oid))
2352 return copy_ref(r);
2355 /* Look for another ref that points there */
2356 for (r = refs; r; r = r->next) {
2357 if (r != head &&
2358 starts_with(r->name, "refs/heads/") &&
2359 oideq(&r->old_oid, &head->old_oid)) {
2360 *tail = copy_ref(r);
2361 tail = &((*tail)->next);
2362 if (!all)
2363 break;
2367 return list;
2370 struct stale_heads_info {
2371 struct string_list *ref_names;
2372 struct ref **stale_refs_tail;
2373 struct refspec *rs;
2376 static int get_stale_heads_cb(const char *refname, const struct object_id *oid,
2377 int flags, void *cb_data)
2379 struct stale_heads_info *info = cb_data;
2380 struct string_list matches = STRING_LIST_INIT_DUP;
2381 struct refspec_item query;
2382 int i, stale = 1;
2383 memset(&query, 0, sizeof(struct refspec_item));
2384 query.dst = (char *)refname;
2386 query_refspecs_multiple(info->rs, &query, &matches);
2387 if (matches.nr == 0)
2388 goto clean_exit; /* No matches */
2391 * If we did find a suitable refspec and it's not a symref and
2392 * it's not in the list of refs that currently exist in that
2393 * remote, we consider it to be stale. In order to deal with
2394 * overlapping refspecs, we need to go over all of the
2395 * matching refs.
2397 if (flags & REF_ISSYMREF)
2398 goto clean_exit;
2400 for (i = 0; stale && i < matches.nr; i++)
2401 if (string_list_has_string(info->ref_names, matches.items[i].string))
2402 stale = 0;
2404 if (stale) {
2405 struct ref *ref = make_linked_ref(refname, &info->stale_refs_tail);
2406 oidcpy(&ref->new_oid, oid);
2409 clean_exit:
2410 string_list_clear(&matches, 0);
2411 return 0;
2414 struct ref *get_stale_heads(struct refspec *rs, struct ref *fetch_map)
2416 struct ref *ref, *stale_refs = NULL;
2417 struct string_list ref_names = STRING_LIST_INIT_NODUP;
2418 struct stale_heads_info info;
2420 info.ref_names = &ref_names;
2421 info.stale_refs_tail = &stale_refs;
2422 info.rs = rs;
2423 for (ref = fetch_map; ref; ref = ref->next)
2424 string_list_append(&ref_names, ref->name);
2425 string_list_sort(&ref_names);
2426 for_each_ref(get_stale_heads_cb, &info);
2427 string_list_clear(&ref_names, 0);
2428 return stale_refs;
2432 * Compare-and-swap
2434 static void clear_cas_option(struct push_cas_option *cas)
2436 int i;
2438 for (i = 0; i < cas->nr; i++)
2439 free(cas->entry[i].refname);
2440 free(cas->entry);
2441 memset(cas, 0, sizeof(*cas));
2444 static struct push_cas *add_cas_entry(struct push_cas_option *cas,
2445 const char *refname,
2446 size_t refnamelen)
2448 struct push_cas *entry;
2449 ALLOC_GROW(cas->entry, cas->nr + 1, cas->alloc);
2450 entry = &cas->entry[cas->nr++];
2451 memset(entry, 0, sizeof(*entry));
2452 entry->refname = xmemdupz(refname, refnamelen);
2453 return entry;
2456 static int parse_push_cas_option(struct push_cas_option *cas, const char *arg, int unset)
2458 const char *colon;
2459 struct push_cas *entry;
2461 if (unset) {
2462 /* "--no-<option>" */
2463 clear_cas_option(cas);
2464 return 0;
2467 if (!arg) {
2468 /* just "--<option>" */
2469 cas->use_tracking_for_rest = 1;
2470 return 0;
2473 /* "--<option>=refname" or "--<option>=refname:value" */
2474 colon = strchrnul(arg, ':');
2475 entry = add_cas_entry(cas, arg, colon - arg);
2476 if (!*colon)
2477 entry->use_tracking = 1;
2478 else if (!colon[1])
2479 oidclr(&entry->expect);
2480 else if (get_oid(colon + 1, &entry->expect))
2481 return error(_("cannot parse expected object name '%s'"),
2482 colon + 1);
2483 return 0;
2486 int parseopt_push_cas_option(const struct option *opt, const char *arg, int unset)
2488 return parse_push_cas_option(opt->value, arg, unset);
2491 int is_empty_cas(const struct push_cas_option *cas)
2493 return !cas->use_tracking_for_rest && !cas->nr;
2497 * Look at remote.fetch refspec and see if we have a remote
2498 * tracking branch for the refname there. Fill the name of
2499 * the remote-tracking branch in *dst_refname, and the name
2500 * of the commit object at its tip in oid[].
2501 * If we cannot do so, return negative to signal an error.
2503 static int remote_tracking(struct remote *remote, const char *refname,
2504 struct object_id *oid, char **dst_refname)
2506 char *dst;
2508 dst = apply_refspecs(&remote->fetch, refname);
2509 if (!dst)
2510 return -1; /* no tracking ref for refname at remote */
2511 if (read_ref(dst, oid))
2512 return -1; /* we know what the tracking ref is but we cannot read it */
2514 *dst_refname = dst;
2515 return 0;
2519 * The struct "reflog_commit_array" and related helper functions
2520 * are used for collecting commits into an array during reflog
2521 * traversals in "check_and_collect_until()".
2523 struct reflog_commit_array {
2524 struct commit **item;
2525 size_t nr, alloc;
2528 #define REFLOG_COMMIT_ARRAY_INIT { 0 }
2530 /* Append a commit to the array. */
2531 static void append_commit(struct reflog_commit_array *arr,
2532 struct commit *commit)
2534 ALLOC_GROW(arr->item, arr->nr + 1, arr->alloc);
2535 arr->item[arr->nr++] = commit;
2538 /* Free and reset the array. */
2539 static void free_commit_array(struct reflog_commit_array *arr)
2541 FREE_AND_NULL(arr->item);
2542 arr->nr = arr->alloc = 0;
2545 struct check_and_collect_until_cb_data {
2546 struct commit *remote_commit;
2547 struct reflog_commit_array *local_commits;
2548 timestamp_t remote_reflog_timestamp;
2551 /* Get the timestamp of the latest entry. */
2552 static int peek_reflog(struct object_id *o_oid, struct object_id *n_oid,
2553 const char *ident, timestamp_t timestamp,
2554 int tz, const char *message, void *cb_data)
2556 timestamp_t *ts = cb_data;
2557 *ts = timestamp;
2558 return 1;
2561 static int check_and_collect_until(struct object_id *o_oid,
2562 struct object_id *n_oid,
2563 const char *ident, timestamp_t timestamp,
2564 int tz, const char *message, void *cb_data)
2566 struct commit *commit;
2567 struct check_and_collect_until_cb_data *cb = cb_data;
2569 /* An entry was found. */
2570 if (oideq(n_oid, &cb->remote_commit->object.oid))
2571 return 1;
2573 if ((commit = lookup_commit_reference(the_repository, n_oid)))
2574 append_commit(cb->local_commits, commit);
2577 * If the reflog entry timestamp is older than the remote ref's
2578 * latest reflog entry, there is no need to check or collect
2579 * entries older than this one.
2581 if (timestamp < cb->remote_reflog_timestamp)
2582 return -1;
2584 return 0;
2587 #define MERGE_BASES_BATCH_SIZE 8
2590 * Iterate through the reflog of the local ref to check if there is an entry
2591 * for the given remote-tracking ref; runs until the timestamp of an entry is
2592 * older than latest timestamp of remote-tracking ref's reflog. Any commits
2593 * are that seen along the way are collected into an array to check if the
2594 * remote-tracking ref is reachable from any of them.
2596 static int is_reachable_in_reflog(const char *local, const struct ref *remote)
2598 timestamp_t date;
2599 struct commit *commit;
2600 struct commit **chunk;
2601 struct check_and_collect_until_cb_data cb;
2602 struct reflog_commit_array arr = REFLOG_COMMIT_ARRAY_INIT;
2603 size_t size = 0;
2604 int ret = 0;
2606 commit = lookup_commit_reference(the_repository, &remote->old_oid);
2607 if (!commit)
2608 goto cleanup_return;
2611 * Get the timestamp from the latest entry
2612 * of the remote-tracking ref's reflog.
2614 for_each_reflog_ent_reverse(remote->tracking_ref, peek_reflog, &date);
2616 cb.remote_commit = commit;
2617 cb.local_commits = &arr;
2618 cb.remote_reflog_timestamp = date;
2619 ret = for_each_reflog_ent_reverse(local, check_and_collect_until, &cb);
2621 /* We found an entry in the reflog. */
2622 if (ret > 0)
2623 goto cleanup_return;
2626 * Check if the remote commit is reachable from any
2627 * of the commits in the collected array, in batches.
2629 for (chunk = arr.item; chunk < arr.item + arr.nr; chunk += size) {
2630 size = arr.item + arr.nr - chunk;
2631 if (MERGE_BASES_BATCH_SIZE < size)
2632 size = MERGE_BASES_BATCH_SIZE;
2634 if ((ret = in_merge_bases_many(commit, size, chunk)))
2635 break;
2638 cleanup_return:
2639 free_commit_array(&arr);
2640 return ret;
2644 * Check for reachability of a remote-tracking
2645 * ref in the reflog entries of its local ref.
2647 static void check_if_includes_upstream(struct ref *remote)
2649 struct ref *local = get_local_ref(remote->name);
2650 if (!local)
2651 return;
2653 if (is_reachable_in_reflog(local->name, remote) <= 0)
2654 remote->unreachable = 1;
2657 static void apply_cas(struct push_cas_option *cas,
2658 struct remote *remote,
2659 struct ref *ref)
2661 int i;
2663 /* Find an explicit --<option>=<name>[:<value>] entry */
2664 for (i = 0; i < cas->nr; i++) {
2665 struct push_cas *entry = &cas->entry[i];
2666 if (!refname_match(entry->refname, ref->name))
2667 continue;
2668 ref->expect_old_sha1 = 1;
2669 if (!entry->use_tracking)
2670 oidcpy(&ref->old_oid_expect, &entry->expect);
2671 else if (remote_tracking(remote, ref->name,
2672 &ref->old_oid_expect,
2673 &ref->tracking_ref))
2674 oidclr(&ref->old_oid_expect);
2675 else
2676 ref->check_reachable = cas->use_force_if_includes;
2677 return;
2680 /* Are we using "--<option>" to cover all? */
2681 if (!cas->use_tracking_for_rest)
2682 return;
2684 ref->expect_old_sha1 = 1;
2685 if (remote_tracking(remote, ref->name,
2686 &ref->old_oid_expect,
2687 &ref->tracking_ref))
2688 oidclr(&ref->old_oid_expect);
2689 else
2690 ref->check_reachable = cas->use_force_if_includes;
2693 void apply_push_cas(struct push_cas_option *cas,
2694 struct remote *remote,
2695 struct ref *remote_refs)
2697 struct ref *ref;
2698 for (ref = remote_refs; ref; ref = ref->next) {
2699 apply_cas(cas, remote, ref);
2702 * If "compare-and-swap" is in "use_tracking[_for_rest]"
2703 * mode, and if "--force-if-includes" was specified, run
2704 * the check.
2706 if (ref->check_reachable)
2707 check_if_includes_upstream(ref);
2711 struct remote_state *remote_state_new(void)
2713 struct remote_state *r = xmalloc(sizeof(*r));
2715 memset(r, 0, sizeof(*r));
2717 hashmap_init(&r->remotes_hash, remotes_hash_cmp, NULL, 0);
2718 hashmap_init(&r->branches_hash, branches_hash_cmp, NULL, 0);
2719 return r;
2722 void remote_state_clear(struct remote_state *remote_state)
2724 int i;
2726 for (i = 0; i < remote_state->remotes_nr; i++) {
2727 remote_clear(remote_state->remotes[i]);
2729 FREE_AND_NULL(remote_state->remotes);
2730 remote_state->remotes_alloc = 0;
2731 remote_state->remotes_nr = 0;
2733 hashmap_clear_and_free(&remote_state->remotes_hash, struct remote, ent);
2734 hashmap_clear_and_free(&remote_state->branches_hash, struct remote, ent);
2738 * Returns 1 if it was the last chop before ':'.
2740 static int chop_last_dir(char **remoteurl, int is_relative)
2742 char *rfind = find_last_dir_sep(*remoteurl);
2743 if (rfind) {
2744 *rfind = '\0';
2745 return 0;
2748 rfind = strrchr(*remoteurl, ':');
2749 if (rfind) {
2750 *rfind = '\0';
2751 return 1;
2754 if (is_relative || !strcmp(".", *remoteurl))
2755 die(_("cannot strip one component off url '%s'"),
2756 *remoteurl);
2758 free(*remoteurl);
2759 *remoteurl = xstrdup(".");
2760 return 0;
2763 char *relative_url(const char *remote_url, const char *url,
2764 const char *up_path)
2766 int is_relative = 0;
2767 int colonsep = 0;
2768 char *out;
2769 char *remoteurl;
2770 struct strbuf sb = STRBUF_INIT;
2771 size_t len;
2773 if (!url_is_local_not_ssh(url) || is_absolute_path(url))
2774 return xstrdup(url);
2776 len = strlen(remote_url);
2777 if (!len)
2778 BUG("invalid empty remote_url");
2780 remoteurl = xstrdup(remote_url);
2781 if (is_dir_sep(remoteurl[len-1]))
2782 remoteurl[len-1] = '\0';
2784 if (!url_is_local_not_ssh(remoteurl) || is_absolute_path(remoteurl))
2785 is_relative = 0;
2786 else {
2787 is_relative = 1;
2789 * Prepend a './' to ensure all relative
2790 * remoteurls start with './' or '../'
2792 if (!starts_with_dot_slash_native(remoteurl) &&
2793 !starts_with_dot_dot_slash_native(remoteurl)) {
2794 strbuf_reset(&sb);
2795 strbuf_addf(&sb, "./%s", remoteurl);
2796 free(remoteurl);
2797 remoteurl = strbuf_detach(&sb, NULL);
2801 * When the url starts with '../', remove that and the
2802 * last directory in remoteurl.
2804 while (url) {
2805 if (starts_with_dot_dot_slash_native(url)) {
2806 url += 3;
2807 colonsep |= chop_last_dir(&remoteurl, is_relative);
2808 } else if (starts_with_dot_slash_native(url))
2809 url += 2;
2810 else
2811 break;
2813 strbuf_reset(&sb);
2814 strbuf_addf(&sb, "%s%s%s", remoteurl, colonsep ? ":" : "/", url);
2815 if (ends_with(url, "/"))
2816 strbuf_setlen(&sb, sb.len - 1);
2817 free(remoteurl);
2819 if (starts_with_dot_slash_native(sb.buf))
2820 out = xstrdup(sb.buf + 2);
2821 else
2822 out = xstrdup(sb.buf);
2824 if (!up_path || !is_relative) {
2825 strbuf_release(&sb);
2826 return out;
2829 strbuf_reset(&sb);
2830 strbuf_addf(&sb, "%s%s", up_path, out);
2831 free(out);
2832 return strbuf_detach(&sb, NULL);