Merge branch 'zh/read-cache-copy-name-entry-fix'
[alt-git.git] / remote.c
blob5824b08eb5af91cac34f19d674ec9039d1a8a2f1
1 #include "cache.h"
2 #include "config.h"
3 #include "remote.h"
4 #include "urlmatch.h"
5 #include "refs.h"
6 #include "refspec.h"
7 #include "object-store.h"
8 #include "commit.h"
9 #include "diff.h"
10 #include "revision.h"
11 #include "dir.h"
12 #include "tag.h"
13 #include "string-list.h"
14 #include "mergesort.h"
15 #include "strvec.h"
16 #include "commit-reach.h"
17 #include "advice.h"
18 #include "connect.h"
20 enum map_direction { FROM_SRC, FROM_DST };
22 struct counted_string {
23 size_t len;
24 const char *s;
27 static int valid_remote(const struct remote *remote)
29 return (!!remote->url) || (!!remote->foreign_vcs);
32 static const char *alias_url(const char *url, struct rewrites *r)
34 int i, j;
35 struct counted_string *longest;
36 int longest_i;
38 longest = NULL;
39 longest_i = -1;
40 for (i = 0; i < r->rewrite_nr; i++) {
41 if (!r->rewrite[i])
42 continue;
43 for (j = 0; j < r->rewrite[i]->instead_of_nr; j++) {
44 if (starts_with(url, r->rewrite[i]->instead_of[j].s) &&
45 (!longest ||
46 longest->len < r->rewrite[i]->instead_of[j].len)) {
47 longest = &(r->rewrite[i]->instead_of[j]);
48 longest_i = i;
52 if (!longest)
53 return url;
55 return xstrfmt("%s%s", r->rewrite[longest_i]->base, url + longest->len);
58 static void add_url(struct remote *remote, const char *url)
60 ALLOC_GROW(remote->url, remote->url_nr + 1, remote->url_alloc);
61 remote->url[remote->url_nr++] = url;
64 static void add_pushurl(struct remote *remote, const char *pushurl)
66 ALLOC_GROW(remote->pushurl, remote->pushurl_nr + 1, remote->pushurl_alloc);
67 remote->pushurl[remote->pushurl_nr++] = pushurl;
70 static void add_pushurl_alias(struct remote_state *remote_state,
71 struct remote *remote, const char *url)
73 const char *pushurl = alias_url(url, &remote_state->rewrites_push);
74 if (pushurl != url)
75 add_pushurl(remote, pushurl);
78 static void add_url_alias(struct remote_state *remote_state,
79 struct remote *remote, const char *url)
81 add_url(remote, alias_url(url, &remote_state->rewrites));
82 add_pushurl_alias(remote_state, remote, url);
85 struct remotes_hash_key {
86 const char *str;
87 int len;
90 static int remotes_hash_cmp(const void *unused_cmp_data,
91 const struct hashmap_entry *eptr,
92 const struct hashmap_entry *entry_or_key,
93 const void *keydata)
95 const struct remote *a, *b;
96 const struct remotes_hash_key *key = keydata;
98 a = container_of(eptr, const struct remote, ent);
99 b = container_of(entry_or_key, const struct remote, ent);
101 if (key)
102 return strncmp(a->name, key->str, key->len) || a->name[key->len];
103 else
104 return strcmp(a->name, b->name);
107 static struct remote *make_remote(struct remote_state *remote_state,
108 const char *name, int len)
110 struct remote *ret;
111 struct remotes_hash_key lookup;
112 struct hashmap_entry lookup_entry, *e;
114 if (!len)
115 len = strlen(name);
117 lookup.str = name;
118 lookup.len = len;
119 hashmap_entry_init(&lookup_entry, memhash(name, len));
121 e = hashmap_get(&remote_state->remotes_hash, &lookup_entry, &lookup);
122 if (e)
123 return container_of(e, struct remote, ent);
125 CALLOC_ARRAY(ret, 1);
126 ret->prune = -1; /* unspecified */
127 ret->prune_tags = -1; /* unspecified */
128 ret->name = xstrndup(name, len);
129 refspec_init(&ret->push, REFSPEC_PUSH);
130 refspec_init(&ret->fetch, REFSPEC_FETCH);
132 ALLOC_GROW(remote_state->remotes, remote_state->remotes_nr + 1,
133 remote_state->remotes_alloc);
134 remote_state->remotes[remote_state->remotes_nr++] = ret;
136 hashmap_entry_init(&ret->ent, lookup_entry.hash);
137 if (hashmap_put_entry(&remote_state->remotes_hash, ret, ent))
138 BUG("hashmap_put overwrote entry after hashmap_get returned NULL");
139 return ret;
142 static void remote_clear(struct remote *remote)
144 int i;
146 free((char *)remote->name);
147 free((char *)remote->foreign_vcs);
149 for (i = 0; i < remote->url_nr; i++) {
150 free((char *)remote->url[i]);
152 FREE_AND_NULL(remote->pushurl);
154 for (i = 0; i < remote->pushurl_nr; i++) {
155 free((char *)remote->pushurl[i]);
157 FREE_AND_NULL(remote->pushurl);
158 free((char *)remote->receivepack);
159 free((char *)remote->uploadpack);
160 FREE_AND_NULL(remote->http_proxy);
161 FREE_AND_NULL(remote->http_proxy_authmethod);
164 static void add_merge(struct branch *branch, const char *name)
166 ALLOC_GROW(branch->merge_name, branch->merge_nr + 1,
167 branch->merge_alloc);
168 branch->merge_name[branch->merge_nr++] = name;
171 struct branches_hash_key {
172 const char *str;
173 int len;
176 static int branches_hash_cmp(const void *unused_cmp_data,
177 const struct hashmap_entry *eptr,
178 const struct hashmap_entry *entry_or_key,
179 const void *keydata)
181 const struct branch *a, *b;
182 const struct branches_hash_key *key = keydata;
184 a = container_of(eptr, const struct branch, ent);
185 b = container_of(entry_or_key, const struct branch, ent);
187 if (key)
188 return strncmp(a->name, key->str, key->len) ||
189 a->name[key->len];
190 else
191 return strcmp(a->name, b->name);
194 static struct branch *find_branch(struct remote_state *remote_state,
195 const char *name, size_t len)
197 struct branches_hash_key lookup;
198 struct hashmap_entry lookup_entry, *e;
200 lookup.str = name;
201 lookup.len = len;
202 hashmap_entry_init(&lookup_entry, memhash(name, len));
204 e = hashmap_get(&remote_state->branches_hash, &lookup_entry, &lookup);
205 if (e)
206 return container_of(e, struct branch, ent);
208 return NULL;
211 static void die_on_missing_branch(struct repository *repo,
212 struct branch *branch)
214 /* branch == NULL is always valid because it represents detached HEAD. */
215 if (branch &&
216 branch != find_branch(repo->remote_state, branch->name,
217 strlen(branch->name)))
218 die("branch %s was not found in the repository", branch->name);
221 static struct branch *make_branch(struct remote_state *remote_state,
222 const char *name, size_t len)
224 struct branch *ret;
226 ret = find_branch(remote_state, name, len);
227 if (ret)
228 return ret;
230 CALLOC_ARRAY(ret, 1);
231 ret->name = xstrndup(name, len);
232 ret->refname = xstrfmt("refs/heads/%s", ret->name);
234 hashmap_entry_init(&ret->ent, memhash(name, len));
235 if (hashmap_put_entry(&remote_state->branches_hash, ret, ent))
236 BUG("hashmap_put overwrote entry after hashmap_get returned NULL");
237 return ret;
240 static struct rewrite *make_rewrite(struct rewrites *r,
241 const char *base, size_t len)
243 struct rewrite *ret;
244 int i;
246 for (i = 0; i < r->rewrite_nr; i++) {
247 if (len == r->rewrite[i]->baselen &&
248 !strncmp(base, r->rewrite[i]->base, len))
249 return r->rewrite[i];
252 ALLOC_GROW(r->rewrite, r->rewrite_nr + 1, r->rewrite_alloc);
253 CALLOC_ARRAY(ret, 1);
254 r->rewrite[r->rewrite_nr++] = ret;
255 ret->base = xstrndup(base, len);
256 ret->baselen = len;
257 return ret;
260 static void add_instead_of(struct rewrite *rewrite, const char *instead_of)
262 ALLOC_GROW(rewrite->instead_of, rewrite->instead_of_nr + 1, rewrite->instead_of_alloc);
263 rewrite->instead_of[rewrite->instead_of_nr].s = instead_of;
264 rewrite->instead_of[rewrite->instead_of_nr].len = strlen(instead_of);
265 rewrite->instead_of_nr++;
268 static const char *skip_spaces(const char *s)
270 while (isspace(*s))
271 s++;
272 return s;
275 static void read_remotes_file(struct remote_state *remote_state,
276 struct remote *remote)
278 struct strbuf buf = STRBUF_INIT;
279 FILE *f = fopen_or_warn(git_path("remotes/%s", remote->name), "r");
281 if (!f)
282 return;
283 remote->configured_in_repo = 1;
284 remote->origin = REMOTE_REMOTES;
285 while (strbuf_getline(&buf, f) != EOF) {
286 const char *v;
288 strbuf_rtrim(&buf);
290 if (skip_prefix(buf.buf, "URL:", &v))
291 add_url_alias(remote_state, remote,
292 xstrdup(skip_spaces(v)));
293 else if (skip_prefix(buf.buf, "Push:", &v))
294 refspec_append(&remote->push, skip_spaces(v));
295 else if (skip_prefix(buf.buf, "Pull:", &v))
296 refspec_append(&remote->fetch, skip_spaces(v));
298 strbuf_release(&buf);
299 fclose(f);
302 static void read_branches_file(struct remote_state *remote_state,
303 struct remote *remote)
305 char *frag;
306 struct strbuf buf = STRBUF_INIT;
307 FILE *f = fopen_or_warn(git_path("branches/%s", remote->name), "r");
309 if (!f)
310 return;
312 strbuf_getline_lf(&buf, f);
313 fclose(f);
314 strbuf_trim(&buf);
315 if (!buf.len) {
316 strbuf_release(&buf);
317 return;
320 remote->configured_in_repo = 1;
321 remote->origin = REMOTE_BRANCHES;
324 * The branches file would have URL and optionally
325 * #branch specified. The default (or specified) branch is
326 * fetched and stored in the local branch matching the
327 * remote name.
329 frag = strchr(buf.buf, '#');
330 if (frag)
331 *(frag++) = '\0';
332 else
333 frag = (char *)git_default_branch_name(0);
335 add_url_alias(remote_state, remote, strbuf_detach(&buf, NULL));
336 refspec_appendf(&remote->fetch, "refs/heads/%s:refs/heads/%s",
337 frag, remote->name);
340 * Cogito compatible push: push current HEAD to remote #branch
341 * (master if missing)
343 refspec_appendf(&remote->push, "HEAD:refs/heads/%s", frag);
344 remote->fetch_tags = 1; /* always auto-follow */
347 static int handle_config(const char *key, const char *value, void *cb)
349 const char *name;
350 size_t namelen;
351 const char *subkey;
352 struct remote *remote;
353 struct branch *branch;
354 struct remote_state *remote_state = cb;
356 if (parse_config_key(key, "branch", &name, &namelen, &subkey) >= 0) {
357 /* There is no subsection. */
358 if (!name)
359 return 0;
360 /* There is a subsection, but it is empty. */
361 if (!namelen)
362 return -1;
363 branch = make_branch(remote_state, name, namelen);
364 if (!strcmp(subkey, "remote")) {
365 return git_config_string(&branch->remote_name, key, value);
366 } else if (!strcmp(subkey, "pushremote")) {
367 return git_config_string(&branch->pushremote_name, key, value);
368 } else if (!strcmp(subkey, "merge")) {
369 if (!value)
370 return config_error_nonbool(key);
371 add_merge(branch, xstrdup(value));
373 return 0;
375 if (parse_config_key(key, "url", &name, &namelen, &subkey) >= 0) {
376 struct rewrite *rewrite;
377 if (!name)
378 return 0;
379 if (!strcmp(subkey, "insteadof")) {
380 if (!value)
381 return config_error_nonbool(key);
382 rewrite = make_rewrite(&remote_state->rewrites, name,
383 namelen);
384 add_instead_of(rewrite, xstrdup(value));
385 } else if (!strcmp(subkey, "pushinsteadof")) {
386 if (!value)
387 return config_error_nonbool(key);
388 rewrite = make_rewrite(&remote_state->rewrites_push,
389 name, namelen);
390 add_instead_of(rewrite, xstrdup(value));
394 if (parse_config_key(key, "remote", &name, &namelen, &subkey) < 0)
395 return 0;
397 /* Handle remote.* variables */
398 if (!name && !strcmp(subkey, "pushdefault"))
399 return git_config_string(&remote_state->pushremote_name, key,
400 value);
402 if (!name)
403 return 0;
404 /* Handle remote.<name>.* variables */
405 if (*name == '/') {
406 warning(_("config remote shorthand cannot begin with '/': %s"),
407 name);
408 return 0;
410 remote = make_remote(remote_state, name, namelen);
411 remote->origin = REMOTE_CONFIG;
412 if (current_config_scope() == CONFIG_SCOPE_LOCAL ||
413 current_config_scope() == CONFIG_SCOPE_WORKTREE)
414 remote->configured_in_repo = 1;
415 if (!strcmp(subkey, "mirror"))
416 remote->mirror = git_config_bool(key, value);
417 else if (!strcmp(subkey, "skipdefaultupdate"))
418 remote->skip_default_update = git_config_bool(key, value);
419 else if (!strcmp(subkey, "skipfetchall"))
420 remote->skip_default_update = git_config_bool(key, value);
421 else if (!strcmp(subkey, "prune"))
422 remote->prune = git_config_bool(key, value);
423 else if (!strcmp(subkey, "prunetags"))
424 remote->prune_tags = git_config_bool(key, value);
425 else if (!strcmp(subkey, "url")) {
426 const char *v;
427 if (git_config_string(&v, key, value))
428 return -1;
429 add_url(remote, v);
430 } else if (!strcmp(subkey, "pushurl")) {
431 const char *v;
432 if (git_config_string(&v, key, value))
433 return -1;
434 add_pushurl(remote, v);
435 } else if (!strcmp(subkey, "push")) {
436 const char *v;
437 if (git_config_string(&v, key, value))
438 return -1;
439 refspec_append(&remote->push, v);
440 free((char *)v);
441 } else if (!strcmp(subkey, "fetch")) {
442 const char *v;
443 if (git_config_string(&v, key, value))
444 return -1;
445 refspec_append(&remote->fetch, v);
446 free((char *)v);
447 } else if (!strcmp(subkey, "receivepack")) {
448 const char *v;
449 if (git_config_string(&v, key, value))
450 return -1;
451 if (!remote->receivepack)
452 remote->receivepack = v;
453 else
454 error(_("more than one receivepack given, using the first"));
455 } else if (!strcmp(subkey, "uploadpack")) {
456 const char *v;
457 if (git_config_string(&v, key, value))
458 return -1;
459 if (!remote->uploadpack)
460 remote->uploadpack = v;
461 else
462 error(_("more than one uploadpack given, using the first"));
463 } else if (!strcmp(subkey, "tagopt")) {
464 if (!strcmp(value, "--no-tags"))
465 remote->fetch_tags = -1;
466 else if (!strcmp(value, "--tags"))
467 remote->fetch_tags = 2;
468 } else if (!strcmp(subkey, "proxy")) {
469 return git_config_string((const char **)&remote->http_proxy,
470 key, value);
471 } else if (!strcmp(subkey, "proxyauthmethod")) {
472 return git_config_string((const char **)&remote->http_proxy_authmethod,
473 key, value);
474 } else if (!strcmp(subkey, "vcs")) {
475 return git_config_string(&remote->foreign_vcs, key, value);
477 return 0;
480 static void alias_all_urls(struct remote_state *remote_state)
482 int i, j;
483 for (i = 0; i < remote_state->remotes_nr; i++) {
484 int add_pushurl_aliases;
485 if (!remote_state->remotes[i])
486 continue;
487 for (j = 0; j < remote_state->remotes[i]->pushurl_nr; j++) {
488 remote_state->remotes[i]->pushurl[j] =
489 alias_url(remote_state->remotes[i]->pushurl[j],
490 &remote_state->rewrites);
492 add_pushurl_aliases = remote_state->remotes[i]->pushurl_nr == 0;
493 for (j = 0; j < remote_state->remotes[i]->url_nr; j++) {
494 if (add_pushurl_aliases)
495 add_pushurl_alias(
496 remote_state, remote_state->remotes[i],
497 remote_state->remotes[i]->url[j]);
498 remote_state->remotes[i]->url[j] =
499 alias_url(remote_state->remotes[i]->url[j],
500 &remote_state->rewrites);
505 static void read_config(struct repository *repo)
507 int flag;
509 if (repo->remote_state->initialized)
510 return;
511 repo->remote_state->initialized = 1;
513 repo->remote_state->current_branch = NULL;
514 if (startup_info->have_repository) {
515 const char *head_ref = refs_resolve_ref_unsafe(
516 get_main_ref_store(repo), "HEAD", 0, NULL, &flag);
517 if (head_ref && (flag & REF_ISSYMREF) &&
518 skip_prefix(head_ref, "refs/heads/", &head_ref)) {
519 repo->remote_state->current_branch = make_branch(
520 repo->remote_state, head_ref, strlen(head_ref));
523 repo_config(repo, handle_config, repo->remote_state);
524 alias_all_urls(repo->remote_state);
527 static int valid_remote_nick(const char *name)
529 if (!name[0] || is_dot_or_dotdot(name))
530 return 0;
532 /* remote nicknames cannot contain slashes */
533 while (*name)
534 if (is_dir_sep(*name++))
535 return 0;
536 return 1;
539 static const char *remotes_remote_for_branch(struct remote_state *remote_state,
540 struct branch *branch,
541 int *explicit)
543 if (branch && branch->remote_name) {
544 if (explicit)
545 *explicit = 1;
546 return branch->remote_name;
548 if (explicit)
549 *explicit = 0;
550 if (remote_state->remotes_nr == 1)
551 return remote_state->remotes[0]->name;
552 return "origin";
555 const char *remote_for_branch(struct branch *branch, int *explicit)
557 read_config(the_repository);
558 die_on_missing_branch(the_repository, branch);
560 return remotes_remote_for_branch(the_repository->remote_state, branch,
561 explicit);
564 static const char *
565 remotes_pushremote_for_branch(struct remote_state *remote_state,
566 struct branch *branch, int *explicit)
568 if (branch && branch->pushremote_name) {
569 if (explicit)
570 *explicit = 1;
571 return branch->pushremote_name;
573 if (remote_state->pushremote_name) {
574 if (explicit)
575 *explicit = 1;
576 return remote_state->pushremote_name;
578 return remotes_remote_for_branch(remote_state, branch, explicit);
581 const char *pushremote_for_branch(struct branch *branch, int *explicit)
583 read_config(the_repository);
584 die_on_missing_branch(the_repository, branch);
586 return remotes_pushremote_for_branch(the_repository->remote_state,
587 branch, explicit);
590 static struct remote *remotes_remote_get(struct remote_state *remote_state,
591 const char *name);
593 const char *remote_ref_for_branch(struct branch *branch, int for_push)
595 read_config(the_repository);
596 die_on_missing_branch(the_repository, branch);
598 if (branch) {
599 if (!for_push) {
600 if (branch->merge_nr) {
601 return branch->merge_name[0];
603 } else {
604 const char *dst,
605 *remote_name = remotes_pushremote_for_branch(
606 the_repository->remote_state, branch,
607 NULL);
608 struct remote *remote = remotes_remote_get(
609 the_repository->remote_state, remote_name);
611 if (remote && remote->push.nr &&
612 (dst = apply_refspecs(&remote->push,
613 branch->refname))) {
614 return dst;
618 return NULL;
621 static void validate_remote_url(struct remote *remote)
623 int i;
624 const char *value;
625 struct strbuf redacted = STRBUF_INIT;
626 int warn_not_die;
628 if (git_config_get_string_tmp("fetch.credentialsinurl", &value))
629 return;
631 if (!strcmp("warn", value))
632 warn_not_die = 1;
633 else if (!strcmp("die", value))
634 warn_not_die = 0;
635 else if (!strcmp("allow", value))
636 return;
637 else
638 die(_("unrecognized value fetch.credentialsInURL: '%s'"), value);
640 for (i = 0; i < remote->url_nr; i++) {
641 struct url_info url_info = { 0 };
643 if (!url_normalize(remote->url[i], &url_info) ||
644 !url_info.passwd_off)
645 goto loop_cleanup;
647 strbuf_reset(&redacted);
648 strbuf_add(&redacted, url_info.url, url_info.passwd_off);
649 strbuf_addstr(&redacted, "<redacted>");
650 strbuf_addstr(&redacted,
651 url_info.url + url_info.passwd_off + url_info.passwd_len);
653 if (warn_not_die)
654 warning(_("URL '%s' uses plaintext credentials"), redacted.buf);
655 else
656 die(_("URL '%s' uses plaintext credentials"), redacted.buf);
658 loop_cleanup:
659 free(url_info.url);
662 strbuf_release(&redacted);
665 static struct remote *
666 remotes_remote_get_1(struct remote_state *remote_state, const char *name,
667 const char *(*get_default)(struct remote_state *,
668 struct branch *, int *))
670 struct remote *ret;
671 int name_given = 0;
673 if (name)
674 name_given = 1;
675 else
676 name = get_default(remote_state, remote_state->current_branch,
677 &name_given);
679 ret = make_remote(remote_state, name, 0);
680 if (valid_remote_nick(name) && have_git_dir()) {
681 if (!valid_remote(ret))
682 read_remotes_file(remote_state, ret);
683 if (!valid_remote(ret))
684 read_branches_file(remote_state, ret);
686 if (name_given && !valid_remote(ret))
687 add_url_alias(remote_state, ret, name);
688 if (!valid_remote(ret))
689 return NULL;
691 validate_remote_url(ret);
693 return ret;
696 static inline struct remote *
697 remotes_remote_get(struct remote_state *remote_state, const char *name)
699 return remotes_remote_get_1(remote_state, name,
700 remotes_remote_for_branch);
703 struct remote *remote_get(const char *name)
705 read_config(the_repository);
706 return remotes_remote_get(the_repository->remote_state, name);
709 static inline struct remote *
710 remotes_pushremote_get(struct remote_state *remote_state, const char *name)
712 return remotes_remote_get_1(remote_state, name,
713 remotes_pushremote_for_branch);
716 struct remote *pushremote_get(const char *name)
718 read_config(the_repository);
719 return remotes_pushremote_get(the_repository->remote_state, name);
722 int remote_is_configured(struct remote *remote, int in_repo)
724 if (!remote)
725 return 0;
726 if (in_repo)
727 return remote->configured_in_repo;
728 return !!remote->origin;
731 int for_each_remote(each_remote_fn fn, void *priv)
733 int i, result = 0;
734 read_config(the_repository);
735 for (i = 0; i < the_repository->remote_state->remotes_nr && !result;
736 i++) {
737 struct remote *remote =
738 the_repository->remote_state->remotes[i];
739 if (!remote)
740 continue;
741 result = fn(remote, priv);
743 return result;
746 static void handle_duplicate(struct ref *ref1, struct ref *ref2)
748 if (strcmp(ref1->name, ref2->name)) {
749 if (ref1->fetch_head_status != FETCH_HEAD_IGNORE &&
750 ref2->fetch_head_status != FETCH_HEAD_IGNORE) {
751 die(_("Cannot fetch both %s and %s to %s"),
752 ref1->name, ref2->name, ref2->peer_ref->name);
753 } else if (ref1->fetch_head_status != FETCH_HEAD_IGNORE &&
754 ref2->fetch_head_status == FETCH_HEAD_IGNORE) {
755 warning(_("%s usually tracks %s, not %s"),
756 ref2->peer_ref->name, ref2->name, ref1->name);
757 } else if (ref1->fetch_head_status == FETCH_HEAD_IGNORE &&
758 ref2->fetch_head_status == FETCH_HEAD_IGNORE) {
759 die(_("%s tracks both %s and %s"),
760 ref2->peer_ref->name, ref1->name, ref2->name);
761 } else {
763 * This last possibility doesn't occur because
764 * FETCH_HEAD_IGNORE entries always appear at
765 * the end of the list.
767 BUG("Internal error");
770 free(ref2->peer_ref);
771 free(ref2);
774 struct ref *ref_remove_duplicates(struct ref *ref_map)
776 struct string_list refs = STRING_LIST_INIT_NODUP;
777 struct ref *retval = NULL;
778 struct ref **p = &retval;
780 while (ref_map) {
781 struct ref *ref = ref_map;
783 ref_map = ref_map->next;
784 ref->next = NULL;
786 if (!ref->peer_ref) {
787 *p = ref;
788 p = &ref->next;
789 } else {
790 struct string_list_item *item =
791 string_list_insert(&refs, ref->peer_ref->name);
793 if (item->util) {
794 /* Entry already existed */
795 handle_duplicate((struct ref *)item->util, ref);
796 } else {
797 *p = ref;
798 p = &ref->next;
799 item->util = ref;
804 string_list_clear(&refs, 0);
805 return retval;
808 int remote_has_url(struct remote *remote, const char *url)
810 int i;
811 for (i = 0; i < remote->url_nr; i++) {
812 if (!strcmp(remote->url[i], url))
813 return 1;
815 return 0;
818 static int match_name_with_pattern(const char *key, const char *name,
819 const char *value, char **result)
821 const char *kstar = strchr(key, '*');
822 size_t klen;
823 size_t ksuffixlen;
824 size_t namelen;
825 int ret;
826 if (!kstar)
827 die(_("key '%s' of pattern had no '*'"), key);
828 klen = kstar - key;
829 ksuffixlen = strlen(kstar + 1);
830 namelen = strlen(name);
831 ret = !strncmp(name, key, klen) && namelen >= klen + ksuffixlen &&
832 !memcmp(name + namelen - ksuffixlen, kstar + 1, ksuffixlen);
833 if (ret && value) {
834 struct strbuf sb = STRBUF_INIT;
835 const char *vstar = strchr(value, '*');
836 if (!vstar)
837 die(_("value '%s' of pattern has no '*'"), value);
838 strbuf_add(&sb, value, vstar - value);
839 strbuf_add(&sb, name + klen, namelen - klen - ksuffixlen);
840 strbuf_addstr(&sb, vstar + 1);
841 *result = strbuf_detach(&sb, NULL);
843 return ret;
846 static int refspec_match(const struct refspec_item *refspec,
847 const char *name)
849 if (refspec->pattern)
850 return match_name_with_pattern(refspec->src, name, NULL, NULL);
852 return !strcmp(refspec->src, name);
855 static int omit_name_by_refspec(const char *name, struct refspec *rs)
857 int i;
859 for (i = 0; i < rs->nr; i++) {
860 if (rs->items[i].negative && refspec_match(&rs->items[i], name))
861 return 1;
863 return 0;
866 struct ref *apply_negative_refspecs(struct ref *ref_map, struct refspec *rs)
868 struct ref **tail;
870 for (tail = &ref_map; *tail; ) {
871 struct ref *ref = *tail;
873 if (omit_name_by_refspec(ref->name, rs)) {
874 *tail = ref->next;
875 free(ref->peer_ref);
876 free(ref);
877 } else
878 tail = &ref->next;
881 return ref_map;
884 static int query_matches_negative_refspec(struct refspec *rs, struct refspec_item *query)
886 int i, matched_negative = 0;
887 int find_src = !query->src;
888 struct string_list reversed = STRING_LIST_INIT_NODUP;
889 const char *needle = find_src ? query->dst : query->src;
892 * Check whether the queried ref matches any negative refpsec. If so,
893 * then we should ultimately treat this as not matching the query at
894 * all.
896 * Note that negative refspecs always match the source, but the query
897 * item uses the destination. To handle this, we apply pattern
898 * refspecs in reverse to figure out if the query source matches any
899 * of the negative refspecs.
901 * The first loop finds and expands all positive refspecs
902 * matched by the queried ref.
904 * The second loop checks if any of the results of the first loop
905 * match any negative refspec.
907 for (i = 0; i < rs->nr; i++) {
908 struct refspec_item *refspec = &rs->items[i];
909 char *expn_name;
911 if (refspec->negative)
912 continue;
914 /* Note the reversal of src and dst */
915 if (refspec->pattern) {
916 const char *key = refspec->dst ? refspec->dst : refspec->src;
917 const char *value = refspec->src;
919 if (match_name_with_pattern(key, needle, value, &expn_name))
920 string_list_append_nodup(&reversed, expn_name);
921 } else if (refspec->matching) {
922 /* For the special matching refspec, any query should match */
923 string_list_append(&reversed, needle);
924 } else if (!refspec->src) {
925 BUG("refspec->src should not be null here");
926 } else if (!strcmp(needle, refspec->src)) {
927 string_list_append(&reversed, refspec->src);
931 for (i = 0; !matched_negative && i < reversed.nr; i++) {
932 if (omit_name_by_refspec(reversed.items[i].string, rs))
933 matched_negative = 1;
936 string_list_clear(&reversed, 0);
938 return matched_negative;
941 static void query_refspecs_multiple(struct refspec *rs,
942 struct refspec_item *query,
943 struct string_list *results)
945 int i;
946 int find_src = !query->src;
948 if (find_src && !query->dst)
949 BUG("query_refspecs_multiple: need either src or dst");
951 if (query_matches_negative_refspec(rs, query))
952 return;
954 for (i = 0; i < rs->nr; i++) {
955 struct refspec_item *refspec = &rs->items[i];
956 const char *key = find_src ? refspec->dst : refspec->src;
957 const char *value = find_src ? refspec->src : refspec->dst;
958 const char *needle = find_src ? query->dst : query->src;
959 char **result = find_src ? &query->src : &query->dst;
961 if (!refspec->dst || refspec->negative)
962 continue;
963 if (refspec->pattern) {
964 if (match_name_with_pattern(key, needle, value, result))
965 string_list_append_nodup(results, *result);
966 } else if (!strcmp(needle, key)) {
967 string_list_append(results, value);
972 int query_refspecs(struct refspec *rs, struct refspec_item *query)
974 int i;
975 int find_src = !query->src;
976 const char *needle = find_src ? query->dst : query->src;
977 char **result = find_src ? &query->src : &query->dst;
979 if (find_src && !query->dst)
980 BUG("query_refspecs: need either src or dst");
982 if (query_matches_negative_refspec(rs, query))
983 return -1;
985 for (i = 0; i < rs->nr; i++) {
986 struct refspec_item *refspec = &rs->items[i];
987 const char *key = find_src ? refspec->dst : refspec->src;
988 const char *value = find_src ? refspec->src : refspec->dst;
990 if (!refspec->dst || refspec->negative)
991 continue;
992 if (refspec->pattern) {
993 if (match_name_with_pattern(key, needle, value, result)) {
994 query->force = refspec->force;
995 return 0;
997 } else if (!strcmp(needle, key)) {
998 *result = xstrdup(value);
999 query->force = refspec->force;
1000 return 0;
1003 return -1;
1006 char *apply_refspecs(struct refspec *rs, const char *name)
1008 struct refspec_item query;
1010 memset(&query, 0, sizeof(struct refspec_item));
1011 query.src = (char *)name;
1013 if (query_refspecs(rs, &query))
1014 return NULL;
1016 return query.dst;
1019 int remote_find_tracking(struct remote *remote, struct refspec_item *refspec)
1021 return query_refspecs(&remote->fetch, refspec);
1024 static struct ref *alloc_ref_with_prefix(const char *prefix, size_t prefixlen,
1025 const char *name)
1027 size_t len = strlen(name);
1028 struct ref *ref = xcalloc(1, st_add4(sizeof(*ref), prefixlen, len, 1));
1029 memcpy(ref->name, prefix, prefixlen);
1030 memcpy(ref->name + prefixlen, name, len);
1031 return ref;
1034 struct ref *alloc_ref(const char *name)
1036 return alloc_ref_with_prefix("", 0, name);
1039 struct ref *copy_ref(const struct ref *ref)
1041 struct ref *cpy;
1042 size_t len;
1043 if (!ref)
1044 return NULL;
1045 len = st_add3(sizeof(struct ref), strlen(ref->name), 1);
1046 cpy = xmalloc(len);
1047 memcpy(cpy, ref, len);
1048 cpy->next = NULL;
1049 cpy->symref = xstrdup_or_null(ref->symref);
1050 cpy->remote_status = xstrdup_or_null(ref->remote_status);
1051 cpy->peer_ref = copy_ref(ref->peer_ref);
1052 return cpy;
1055 struct ref *copy_ref_list(const struct ref *ref)
1057 struct ref *ret = NULL;
1058 struct ref **tail = &ret;
1059 while (ref) {
1060 *tail = copy_ref(ref);
1061 ref = ref->next;
1062 tail = &((*tail)->next);
1064 return ret;
1067 void free_one_ref(struct ref *ref)
1069 if (!ref)
1070 return;
1071 free_one_ref(ref->peer_ref);
1072 free(ref->remote_status);
1073 free(ref->symref);
1074 free(ref);
1077 void free_refs(struct ref *ref)
1079 struct ref *next;
1080 while (ref) {
1081 next = ref->next;
1082 free_one_ref(ref);
1083 ref = next;
1087 int ref_compare_name(const void *va, const void *vb)
1089 const struct ref *a = va, *b = vb;
1090 return strcmp(a->name, b->name);
1093 static void *ref_list_get_next(const void *a)
1095 return ((const struct ref *)a)->next;
1098 static void ref_list_set_next(void *a, void *next)
1100 ((struct ref *)a)->next = next;
1103 void sort_ref_list(struct ref **l, int (*cmp)(const void *, const void *))
1105 *l = llist_mergesort(*l, ref_list_get_next, ref_list_set_next, cmp);
1108 int count_refspec_match(const char *pattern,
1109 struct ref *refs,
1110 struct ref **matched_ref)
1112 int patlen = strlen(pattern);
1113 struct ref *matched_weak = NULL;
1114 struct ref *matched = NULL;
1115 int weak_match = 0;
1116 int match = 0;
1118 for (weak_match = match = 0; refs; refs = refs->next) {
1119 char *name = refs->name;
1120 int namelen = strlen(name);
1122 if (!refname_match(pattern, name))
1123 continue;
1125 /* A match is "weak" if it is with refs outside
1126 * heads or tags, and did not specify the pattern
1127 * in full (e.g. "refs/remotes/origin/master") or at
1128 * least from the toplevel (e.g. "remotes/origin/master");
1129 * otherwise "git push $URL master" would result in
1130 * ambiguity between remotes/origin/master and heads/master
1131 * at the remote site.
1133 if (namelen != patlen &&
1134 patlen != namelen - 5 &&
1135 !starts_with(name, "refs/heads/") &&
1136 !starts_with(name, "refs/tags/")) {
1137 /* We want to catch the case where only weak
1138 * matches are found and there are multiple
1139 * matches, and where more than one strong
1140 * matches are found, as ambiguous. One
1141 * strong match with zero or more weak matches
1142 * are acceptable as a unique match.
1144 matched_weak = refs;
1145 weak_match++;
1147 else {
1148 matched = refs;
1149 match++;
1152 if (!matched) {
1153 if (matched_ref)
1154 *matched_ref = matched_weak;
1155 return weak_match;
1157 else {
1158 if (matched_ref)
1159 *matched_ref = matched;
1160 return match;
1164 static void tail_link_ref(struct ref *ref, struct ref ***tail)
1166 **tail = ref;
1167 while (ref->next)
1168 ref = ref->next;
1169 *tail = &ref->next;
1172 static struct ref *alloc_delete_ref(void)
1174 struct ref *ref = alloc_ref("(delete)");
1175 oidclr(&ref->new_oid);
1176 return ref;
1179 static int try_explicit_object_name(const char *name,
1180 struct ref **match)
1182 struct object_id oid;
1184 if (!*name) {
1185 if (match)
1186 *match = alloc_delete_ref();
1187 return 0;
1190 if (get_oid(name, &oid))
1191 return -1;
1193 if (match) {
1194 *match = alloc_ref(name);
1195 oidcpy(&(*match)->new_oid, &oid);
1197 return 0;
1200 static struct ref *make_linked_ref(const char *name, struct ref ***tail)
1202 struct ref *ret = alloc_ref(name);
1203 tail_link_ref(ret, tail);
1204 return ret;
1207 static char *guess_ref(const char *name, struct ref *peer)
1209 struct strbuf buf = STRBUF_INIT;
1211 const char *r = resolve_ref_unsafe(peer->name, RESOLVE_REF_READING,
1212 NULL, NULL);
1213 if (!r)
1214 return NULL;
1216 if (starts_with(r, "refs/heads/")) {
1217 strbuf_addstr(&buf, "refs/heads/");
1218 } else if (starts_with(r, "refs/tags/")) {
1219 strbuf_addstr(&buf, "refs/tags/");
1220 } else {
1221 return NULL;
1224 strbuf_addstr(&buf, name);
1225 return strbuf_detach(&buf, NULL);
1228 static int match_explicit_lhs(struct ref *src,
1229 struct refspec_item *rs,
1230 struct ref **match,
1231 int *allocated_match)
1233 switch (count_refspec_match(rs->src, src, match)) {
1234 case 1:
1235 if (allocated_match)
1236 *allocated_match = 0;
1237 return 0;
1238 case 0:
1239 /* The source could be in the get_sha1() format
1240 * not a reference name. :refs/other is a
1241 * way to delete 'other' ref at the remote end.
1243 if (try_explicit_object_name(rs->src, match) < 0)
1244 return error(_("src refspec %s does not match any"), rs->src);
1245 if (allocated_match)
1246 *allocated_match = 1;
1247 return 0;
1248 default:
1249 return error(_("src refspec %s matches more than one"), rs->src);
1253 static void show_push_unqualified_ref_name_error(const char *dst_value,
1254 const char *matched_src_name)
1256 struct object_id oid;
1257 enum object_type type;
1260 * TRANSLATORS: "matches '%s'%" is the <dst> part of "git push
1261 * <remote> <src>:<dst>" push, and "being pushed ('%s')" is
1262 * the <src>.
1264 error(_("The destination you provided is not a full refname (i.e.,\n"
1265 "starting with \"refs/\"). We tried to guess what you meant by:\n"
1266 "\n"
1267 "- Looking for a ref that matches '%s' on the remote side.\n"
1268 "- Checking if the <src> being pushed ('%s')\n"
1269 " is a ref in \"refs/{heads,tags}/\". If so we add a corresponding\n"
1270 " refs/{heads,tags}/ prefix on the remote side.\n"
1271 "\n"
1272 "Neither worked, so we gave up. You must fully qualify the ref."),
1273 dst_value, matched_src_name);
1275 if (!advice_enabled(ADVICE_PUSH_UNQUALIFIED_REF_NAME))
1276 return;
1278 if (get_oid(matched_src_name, &oid))
1279 BUG("'%s' is not a valid object, "
1280 "match_explicit_lhs() should catch this!",
1281 matched_src_name);
1282 type = oid_object_info(the_repository, &oid, NULL);
1283 if (type == OBJ_COMMIT) {
1284 advise(_("The <src> part of the refspec is a commit object.\n"
1285 "Did you mean to create a new branch by pushing to\n"
1286 "'%s:refs/heads/%s'?"),
1287 matched_src_name, dst_value);
1288 } else if (type == OBJ_TAG) {
1289 advise(_("The <src> part of the refspec is a tag object.\n"
1290 "Did you mean to create a new tag by pushing to\n"
1291 "'%s:refs/tags/%s'?"),
1292 matched_src_name, dst_value);
1293 } else if (type == OBJ_TREE) {
1294 advise(_("The <src> part of the refspec is a tree object.\n"
1295 "Did you mean to tag a new tree by pushing to\n"
1296 "'%s:refs/tags/%s'?"),
1297 matched_src_name, dst_value);
1298 } else if (type == OBJ_BLOB) {
1299 advise(_("The <src> part of the refspec is a blob object.\n"
1300 "Did you mean to tag a new blob by pushing to\n"
1301 "'%s:refs/tags/%s'?"),
1302 matched_src_name, dst_value);
1303 } else {
1304 BUG("'%s' should be commit/tag/tree/blob, is '%d'",
1305 matched_src_name, type);
1309 static int match_explicit(struct ref *src, struct ref *dst,
1310 struct ref ***dst_tail,
1311 struct refspec_item *rs)
1313 struct ref *matched_src, *matched_dst;
1314 int allocated_src;
1316 const char *dst_value = rs->dst;
1317 char *dst_guess;
1319 if (rs->pattern || rs->matching || rs->negative)
1320 return 0;
1322 matched_src = matched_dst = NULL;
1323 if (match_explicit_lhs(src, rs, &matched_src, &allocated_src) < 0)
1324 return -1;
1326 if (!dst_value) {
1327 int flag;
1329 dst_value = resolve_ref_unsafe(matched_src->name,
1330 RESOLVE_REF_READING,
1331 NULL, &flag);
1332 if (!dst_value ||
1333 ((flag & REF_ISSYMREF) &&
1334 !starts_with(dst_value, "refs/heads/")))
1335 die(_("%s cannot be resolved to branch"),
1336 matched_src->name);
1339 switch (count_refspec_match(dst_value, dst, &matched_dst)) {
1340 case 1:
1341 break;
1342 case 0:
1343 if (starts_with(dst_value, "refs/")) {
1344 matched_dst = make_linked_ref(dst_value, dst_tail);
1345 } else if (is_null_oid(&matched_src->new_oid)) {
1346 error(_("unable to delete '%s': remote ref does not exist"),
1347 dst_value);
1348 } else if ((dst_guess = guess_ref(dst_value, matched_src))) {
1349 matched_dst = make_linked_ref(dst_guess, dst_tail);
1350 free(dst_guess);
1351 } else {
1352 show_push_unqualified_ref_name_error(dst_value,
1353 matched_src->name);
1355 break;
1356 default:
1357 matched_dst = NULL;
1358 error(_("dst refspec %s matches more than one"),
1359 dst_value);
1360 break;
1362 if (!matched_dst)
1363 return -1;
1364 if (matched_dst->peer_ref)
1365 return error(_("dst ref %s receives from more than one src"),
1366 matched_dst->name);
1367 else {
1368 matched_dst->peer_ref = allocated_src ?
1369 matched_src :
1370 copy_ref(matched_src);
1371 matched_dst->force = rs->force;
1373 return 0;
1376 static int match_explicit_refs(struct ref *src, struct ref *dst,
1377 struct ref ***dst_tail, struct refspec *rs)
1379 int i, errs;
1380 for (i = errs = 0; i < rs->nr; i++)
1381 errs += match_explicit(src, dst, dst_tail, &rs->items[i]);
1382 return errs;
1385 static char *get_ref_match(const struct refspec *rs, const struct ref *ref,
1386 int send_mirror, int direction,
1387 const struct refspec_item **ret_pat)
1389 const struct refspec_item *pat;
1390 char *name;
1391 int i;
1392 int matching_refs = -1;
1393 for (i = 0; i < rs->nr; i++) {
1394 const struct refspec_item *item = &rs->items[i];
1396 if (item->negative)
1397 continue;
1399 if (item->matching &&
1400 (matching_refs == -1 || item->force)) {
1401 matching_refs = i;
1402 continue;
1405 if (item->pattern) {
1406 const char *dst_side = item->dst ? item->dst : item->src;
1407 int match;
1408 if (direction == FROM_SRC)
1409 match = match_name_with_pattern(item->src, ref->name, dst_side, &name);
1410 else
1411 match = match_name_with_pattern(dst_side, ref->name, item->src, &name);
1412 if (match) {
1413 matching_refs = i;
1414 break;
1418 if (matching_refs == -1)
1419 return NULL;
1421 pat = &rs->items[matching_refs];
1422 if (pat->matching) {
1424 * "matching refs"; traditionally we pushed everything
1425 * including refs outside refs/heads/ hierarchy, but
1426 * that does not make much sense these days.
1428 if (!send_mirror && !starts_with(ref->name, "refs/heads/"))
1429 return NULL;
1430 name = xstrdup(ref->name);
1432 if (ret_pat)
1433 *ret_pat = pat;
1434 return name;
1437 static struct ref **tail_ref(struct ref **head)
1439 struct ref **tail = head;
1440 while (*tail)
1441 tail = &((*tail)->next);
1442 return tail;
1445 struct tips {
1446 struct commit **tip;
1447 int nr, alloc;
1450 static void add_to_tips(struct tips *tips, const struct object_id *oid)
1452 struct commit *commit;
1454 if (is_null_oid(oid))
1455 return;
1456 commit = lookup_commit_reference_gently(the_repository, oid, 1);
1457 if (!commit || (commit->object.flags & TMP_MARK))
1458 return;
1459 commit->object.flags |= TMP_MARK;
1460 ALLOC_GROW(tips->tip, tips->nr + 1, tips->alloc);
1461 tips->tip[tips->nr++] = commit;
1464 static void add_missing_tags(struct ref *src, struct ref **dst, struct ref ***dst_tail)
1466 struct string_list dst_tag = STRING_LIST_INIT_NODUP;
1467 struct string_list src_tag = STRING_LIST_INIT_NODUP;
1468 struct string_list_item *item;
1469 struct ref *ref;
1470 struct tips sent_tips;
1473 * Collect everything we know they would have at the end of
1474 * this push, and collect all tags they have.
1476 memset(&sent_tips, 0, sizeof(sent_tips));
1477 for (ref = *dst; ref; ref = ref->next) {
1478 if (ref->peer_ref &&
1479 !is_null_oid(&ref->peer_ref->new_oid))
1480 add_to_tips(&sent_tips, &ref->peer_ref->new_oid);
1481 else
1482 add_to_tips(&sent_tips, &ref->old_oid);
1483 if (starts_with(ref->name, "refs/tags/"))
1484 string_list_append(&dst_tag, ref->name);
1486 clear_commit_marks_many(sent_tips.nr, sent_tips.tip, TMP_MARK);
1488 string_list_sort(&dst_tag);
1490 /* Collect tags they do not have. */
1491 for (ref = src; ref; ref = ref->next) {
1492 if (!starts_with(ref->name, "refs/tags/"))
1493 continue; /* not a tag */
1494 if (string_list_has_string(&dst_tag, ref->name))
1495 continue; /* they already have it */
1496 if (oid_object_info(the_repository, &ref->new_oid, NULL) != OBJ_TAG)
1497 continue; /* be conservative */
1498 item = string_list_append(&src_tag, ref->name);
1499 item->util = ref;
1501 string_list_clear(&dst_tag, 0);
1504 * At this point, src_tag lists tags that are missing from
1505 * dst, and sent_tips lists the tips we are pushing or those
1506 * that we know they already have. An element in the src_tag
1507 * that is an ancestor of any of the sent_tips needs to be
1508 * sent to the other side.
1510 if (sent_tips.nr) {
1511 const int reachable_flag = 1;
1512 struct commit_list *found_commits;
1513 struct commit **src_commits;
1514 int nr_src_commits = 0, alloc_src_commits = 16;
1515 ALLOC_ARRAY(src_commits, alloc_src_commits);
1517 for_each_string_list_item(item, &src_tag) {
1518 struct ref *ref = item->util;
1519 struct commit *commit;
1521 if (is_null_oid(&ref->new_oid))
1522 continue;
1523 commit = lookup_commit_reference_gently(the_repository,
1524 &ref->new_oid,
1526 if (!commit)
1527 /* not pushing a commit, which is not an error */
1528 continue;
1530 ALLOC_GROW(src_commits, nr_src_commits + 1, alloc_src_commits);
1531 src_commits[nr_src_commits++] = commit;
1534 found_commits = get_reachable_subset(sent_tips.tip, sent_tips.nr,
1535 src_commits, nr_src_commits,
1536 reachable_flag);
1538 for_each_string_list_item(item, &src_tag) {
1539 struct ref *dst_ref;
1540 struct ref *ref = item->util;
1541 struct commit *commit;
1543 if (is_null_oid(&ref->new_oid))
1544 continue;
1545 commit = lookup_commit_reference_gently(the_repository,
1546 &ref->new_oid,
1548 if (!commit)
1549 /* not pushing a commit, which is not an error */
1550 continue;
1553 * Is this tag, which they do not have, reachable from
1554 * any of the commits we are sending?
1556 if (!(commit->object.flags & reachable_flag))
1557 continue;
1559 /* Add it in */
1560 dst_ref = make_linked_ref(ref->name, dst_tail);
1561 oidcpy(&dst_ref->new_oid, &ref->new_oid);
1562 dst_ref->peer_ref = copy_ref(ref);
1565 clear_commit_marks_many(nr_src_commits, src_commits, reachable_flag);
1566 free(src_commits);
1567 free_commit_list(found_commits);
1570 string_list_clear(&src_tag, 0);
1571 free(sent_tips.tip);
1574 struct ref *find_ref_by_name(const struct ref *list, const char *name)
1576 for ( ; list; list = list->next)
1577 if (!strcmp(list->name, name))
1578 return (struct ref *)list;
1579 return NULL;
1582 static void prepare_ref_index(struct string_list *ref_index, struct ref *ref)
1584 for ( ; ref; ref = ref->next)
1585 string_list_append_nodup(ref_index, ref->name)->util = ref;
1587 string_list_sort(ref_index);
1591 * Given only the set of local refs, sanity-check the set of push
1592 * refspecs. We can't catch all errors that match_push_refs would,
1593 * but we can catch some errors early before even talking to the
1594 * remote side.
1596 int check_push_refs(struct ref *src, struct refspec *rs)
1598 int ret = 0;
1599 int i;
1601 for (i = 0; i < rs->nr; i++) {
1602 struct refspec_item *item = &rs->items[i];
1604 if (item->pattern || item->matching || item->negative)
1605 continue;
1607 ret |= match_explicit_lhs(src, item, NULL, NULL);
1610 return ret;
1614 * Given the set of refs the local repository has, the set of refs the
1615 * remote repository has, and the refspec used for push, determine
1616 * what remote refs we will update and with what value by setting
1617 * peer_ref (which object is being pushed) and force (if the push is
1618 * forced) in elements of "dst". The function may add new elements to
1619 * dst (e.g. pushing to a new branch, done in match_explicit_refs).
1621 int match_push_refs(struct ref *src, struct ref **dst,
1622 struct refspec *rs, int flags)
1624 int send_all = flags & MATCH_REFS_ALL;
1625 int send_mirror = flags & MATCH_REFS_MIRROR;
1626 int send_prune = flags & MATCH_REFS_PRUNE;
1627 int errs;
1628 struct ref *ref, **dst_tail = tail_ref(dst);
1629 struct string_list dst_ref_index = STRING_LIST_INIT_NODUP;
1631 /* If no refspec is provided, use the default ":" */
1632 if (!rs->nr)
1633 refspec_append(rs, ":");
1635 errs = match_explicit_refs(src, *dst, &dst_tail, rs);
1637 /* pick the remainder */
1638 for (ref = src; ref; ref = ref->next) {
1639 struct string_list_item *dst_item;
1640 struct ref *dst_peer;
1641 const struct refspec_item *pat = NULL;
1642 char *dst_name;
1644 dst_name = get_ref_match(rs, ref, send_mirror, FROM_SRC, &pat);
1645 if (!dst_name)
1646 continue;
1648 if (!dst_ref_index.nr)
1649 prepare_ref_index(&dst_ref_index, *dst);
1651 dst_item = string_list_lookup(&dst_ref_index, dst_name);
1652 dst_peer = dst_item ? dst_item->util : NULL;
1653 if (dst_peer) {
1654 if (dst_peer->peer_ref)
1655 /* We're already sending something to this ref. */
1656 goto free_name;
1657 } else {
1658 if (pat->matching && !(send_all || send_mirror))
1660 * Remote doesn't have it, and we have no
1661 * explicit pattern, and we don't have
1662 * --all or --mirror.
1664 goto free_name;
1666 /* Create a new one and link it */
1667 dst_peer = make_linked_ref(dst_name, &dst_tail);
1668 oidcpy(&dst_peer->new_oid, &ref->new_oid);
1669 string_list_insert(&dst_ref_index,
1670 dst_peer->name)->util = dst_peer;
1672 dst_peer->peer_ref = copy_ref(ref);
1673 dst_peer->force = pat->force;
1674 free_name:
1675 free(dst_name);
1678 string_list_clear(&dst_ref_index, 0);
1680 if (flags & MATCH_REFS_FOLLOW_TAGS)
1681 add_missing_tags(src, dst, &dst_tail);
1683 if (send_prune) {
1684 struct string_list src_ref_index = STRING_LIST_INIT_NODUP;
1685 /* check for missing refs on the remote */
1686 for (ref = *dst; ref; ref = ref->next) {
1687 char *src_name;
1689 if (ref->peer_ref)
1690 /* We're already sending something to this ref. */
1691 continue;
1693 src_name = get_ref_match(rs, ref, send_mirror, FROM_DST, NULL);
1694 if (src_name) {
1695 if (!src_ref_index.nr)
1696 prepare_ref_index(&src_ref_index, src);
1697 if (!string_list_has_string(&src_ref_index,
1698 src_name))
1699 ref->peer_ref = alloc_delete_ref();
1700 free(src_name);
1703 string_list_clear(&src_ref_index, 0);
1706 *dst = apply_negative_refspecs(*dst, rs);
1708 if (errs)
1709 return -1;
1710 return 0;
1713 void set_ref_status_for_push(struct ref *remote_refs, int send_mirror,
1714 int force_update)
1716 struct ref *ref;
1718 for (ref = remote_refs; ref; ref = ref->next) {
1719 int force_ref_update = ref->force || force_update;
1720 int reject_reason = 0;
1722 if (ref->peer_ref)
1723 oidcpy(&ref->new_oid, &ref->peer_ref->new_oid);
1724 else if (!send_mirror)
1725 continue;
1727 ref->deletion = is_null_oid(&ref->new_oid);
1728 if (!ref->deletion &&
1729 oideq(&ref->old_oid, &ref->new_oid)) {
1730 ref->status = REF_STATUS_UPTODATE;
1731 continue;
1735 * If the remote ref has moved and is now different
1736 * from what we expect, reject any push.
1738 * It also is an error if the user told us to check
1739 * with the remote-tracking branch to find the value
1740 * to expect, but we did not have such a tracking
1741 * branch.
1743 * If the tip of the remote-tracking ref is unreachable
1744 * from any reflog entry of its local ref indicating a
1745 * possible update since checkout; reject the push.
1747 if (ref->expect_old_sha1) {
1748 if (!oideq(&ref->old_oid, &ref->old_oid_expect))
1749 reject_reason = REF_STATUS_REJECT_STALE;
1750 else if (ref->check_reachable && ref->unreachable)
1751 reject_reason =
1752 REF_STATUS_REJECT_REMOTE_UPDATED;
1753 else
1755 * If the ref isn't stale, and is reachable
1756 * from one of the reflog entries of
1757 * the local branch, force the update.
1759 force_ref_update = 1;
1763 * If the update isn't already rejected then check
1764 * the usual "must fast-forward" rules.
1766 * Decide whether an individual refspec A:B can be
1767 * pushed. The push will succeed if any of the
1768 * following are true:
1770 * (1) the remote reference B does not exist
1772 * (2) the remote reference B is being removed (i.e.,
1773 * pushing :B where no source is specified)
1775 * (3) the destination is not under refs/tags/, and
1776 * if the old and new value is a commit, the new
1777 * is a descendant of the old.
1779 * (4) it is forced using the +A:B notation, or by
1780 * passing the --force argument
1783 if (!reject_reason && !ref->deletion && !is_null_oid(&ref->old_oid)) {
1784 if (starts_with(ref->name, "refs/tags/"))
1785 reject_reason = REF_STATUS_REJECT_ALREADY_EXISTS;
1786 else if (!has_object_file(&ref->old_oid))
1787 reject_reason = REF_STATUS_REJECT_FETCH_FIRST;
1788 else if (!lookup_commit_reference_gently(the_repository, &ref->old_oid, 1) ||
1789 !lookup_commit_reference_gently(the_repository, &ref->new_oid, 1))
1790 reject_reason = REF_STATUS_REJECT_NEEDS_FORCE;
1791 else if (!ref_newer(&ref->new_oid, &ref->old_oid))
1792 reject_reason = REF_STATUS_REJECT_NONFASTFORWARD;
1796 * "--force" will defeat any rejection implemented
1797 * by the rules above.
1799 if (!force_ref_update)
1800 ref->status = reject_reason;
1801 else if (reject_reason)
1802 ref->forced_update = 1;
1806 static void set_merge(struct remote_state *remote_state, struct branch *ret)
1808 struct remote *remote;
1809 char *ref;
1810 struct object_id oid;
1811 int i;
1813 if (!ret)
1814 return; /* no branch */
1815 if (ret->merge)
1816 return; /* already run */
1817 if (!ret->remote_name || !ret->merge_nr) {
1819 * no merge config; let's make sure we don't confuse callers
1820 * with a non-zero merge_nr but a NULL merge
1822 ret->merge_nr = 0;
1823 return;
1826 remote = remotes_remote_get(remote_state, ret->remote_name);
1828 CALLOC_ARRAY(ret->merge, ret->merge_nr);
1829 for (i = 0; i < ret->merge_nr; i++) {
1830 ret->merge[i] = xcalloc(1, sizeof(**ret->merge));
1831 ret->merge[i]->src = xstrdup(ret->merge_name[i]);
1832 if (!remote_find_tracking(remote, ret->merge[i]) ||
1833 strcmp(ret->remote_name, "."))
1834 continue;
1835 if (dwim_ref(ret->merge_name[i], strlen(ret->merge_name[i]),
1836 &oid, &ref, 0) == 1)
1837 ret->merge[i]->dst = ref;
1838 else
1839 ret->merge[i]->dst = xstrdup(ret->merge_name[i]);
1843 struct branch *branch_get(const char *name)
1845 struct branch *ret;
1847 read_config(the_repository);
1848 if (!name || !*name || !strcmp(name, "HEAD"))
1849 ret = the_repository->remote_state->current_branch;
1850 else
1851 ret = make_branch(the_repository->remote_state, name,
1852 strlen(name));
1853 set_merge(the_repository->remote_state, ret);
1854 return ret;
1857 int branch_has_merge_config(struct branch *branch)
1859 return branch && !!branch->merge;
1862 int branch_merge_matches(struct branch *branch,
1863 int i,
1864 const char *refname)
1866 if (!branch || i < 0 || i >= branch->merge_nr)
1867 return 0;
1868 return refname_match(branch->merge[i]->src, refname);
1871 __attribute__((format (printf,2,3)))
1872 static const char *error_buf(struct strbuf *err, const char *fmt, ...)
1874 if (err) {
1875 va_list ap;
1876 va_start(ap, fmt);
1877 strbuf_vaddf(err, fmt, ap);
1878 va_end(ap);
1880 return NULL;
1883 const char *branch_get_upstream(struct branch *branch, struct strbuf *err)
1885 if (!branch)
1886 return error_buf(err, _("HEAD does not point to a branch"));
1888 if (!branch->merge || !branch->merge[0]) {
1890 * no merge config; is it because the user didn't define any,
1891 * or because it is not a real branch, and get_branch
1892 * auto-vivified it?
1894 if (!ref_exists(branch->refname))
1895 return error_buf(err, _("no such branch: '%s'"),
1896 branch->name);
1897 return error_buf(err,
1898 _("no upstream configured for branch '%s'"),
1899 branch->name);
1902 if (!branch->merge[0]->dst)
1903 return error_buf(err,
1904 _("upstream branch '%s' not stored as a remote-tracking branch"),
1905 branch->merge[0]->src);
1907 return branch->merge[0]->dst;
1910 static const char *tracking_for_push_dest(struct remote *remote,
1911 const char *refname,
1912 struct strbuf *err)
1914 char *ret;
1916 ret = apply_refspecs(&remote->fetch, refname);
1917 if (!ret)
1918 return error_buf(err,
1919 _("push destination '%s' on remote '%s' has no local tracking branch"),
1920 refname, remote->name);
1921 return ret;
1924 static const char *branch_get_push_1(struct remote_state *remote_state,
1925 struct branch *branch, struct strbuf *err)
1927 struct remote *remote;
1929 remote = remotes_remote_get(
1930 remote_state,
1931 remotes_pushremote_for_branch(remote_state, branch, NULL));
1932 if (!remote)
1933 return error_buf(err,
1934 _("branch '%s' has no remote for pushing"),
1935 branch->name);
1937 if (remote->push.nr) {
1938 char *dst;
1939 const char *ret;
1941 dst = apply_refspecs(&remote->push, branch->refname);
1942 if (!dst)
1943 return error_buf(err,
1944 _("push refspecs for '%s' do not include '%s'"),
1945 remote->name, branch->name);
1947 ret = tracking_for_push_dest(remote, dst, err);
1948 free(dst);
1949 return ret;
1952 if (remote->mirror)
1953 return tracking_for_push_dest(remote, branch->refname, err);
1955 switch (push_default) {
1956 case PUSH_DEFAULT_NOTHING:
1957 return error_buf(err, _("push has no destination (push.default is 'nothing')"));
1959 case PUSH_DEFAULT_MATCHING:
1960 case PUSH_DEFAULT_CURRENT:
1961 return tracking_for_push_dest(remote, branch->refname, err);
1963 case PUSH_DEFAULT_UPSTREAM:
1964 return branch_get_upstream(branch, err);
1966 case PUSH_DEFAULT_UNSPECIFIED:
1967 case PUSH_DEFAULT_SIMPLE:
1969 const char *up, *cur;
1971 up = branch_get_upstream(branch, err);
1972 if (!up)
1973 return NULL;
1974 cur = tracking_for_push_dest(remote, branch->refname, err);
1975 if (!cur)
1976 return NULL;
1977 if (strcmp(cur, up))
1978 return error_buf(err,
1979 _("cannot resolve 'simple' push to a single destination"));
1980 return cur;
1984 BUG("unhandled push situation");
1987 const char *branch_get_push(struct branch *branch, struct strbuf *err)
1989 read_config(the_repository);
1990 die_on_missing_branch(the_repository, branch);
1992 if (!branch)
1993 return error_buf(err, _("HEAD does not point to a branch"));
1995 if (!branch->push_tracking_ref)
1996 branch->push_tracking_ref = branch_get_push_1(
1997 the_repository->remote_state, branch, err);
1998 return branch->push_tracking_ref;
2001 static int ignore_symref_update(const char *refname, struct strbuf *scratch)
2003 return !refs_read_symbolic_ref(get_main_ref_store(the_repository), refname, scratch);
2007 * Create and return a list of (struct ref) consisting of copies of
2008 * each remote_ref that matches refspec. refspec must be a pattern.
2009 * Fill in the copies' peer_ref to describe the local tracking refs to
2010 * which they map. Omit any references that would map to an existing
2011 * local symbolic ref.
2013 static struct ref *get_expanded_map(const struct ref *remote_refs,
2014 const struct refspec_item *refspec)
2016 struct strbuf scratch = STRBUF_INIT;
2017 const struct ref *ref;
2018 struct ref *ret = NULL;
2019 struct ref **tail = &ret;
2021 for (ref = remote_refs; ref; ref = ref->next) {
2022 char *expn_name = NULL;
2024 strbuf_reset(&scratch);
2026 if (strchr(ref->name, '^'))
2027 continue; /* a dereference item */
2028 if (match_name_with_pattern(refspec->src, ref->name,
2029 refspec->dst, &expn_name) &&
2030 !ignore_symref_update(expn_name, &scratch)) {
2031 struct ref *cpy = copy_ref(ref);
2033 cpy->peer_ref = alloc_ref(expn_name);
2034 if (refspec->force)
2035 cpy->peer_ref->force = 1;
2036 *tail = cpy;
2037 tail = &cpy->next;
2039 free(expn_name);
2042 strbuf_release(&scratch);
2043 return ret;
2046 static const struct ref *find_ref_by_name_abbrev(const struct ref *refs, const char *name)
2048 const struct ref *ref;
2049 const struct ref *best_match = NULL;
2050 int best_score = 0;
2052 for (ref = refs; ref; ref = ref->next) {
2053 int score = refname_match(name, ref->name);
2055 if (best_score < score) {
2056 best_match = ref;
2057 best_score = score;
2060 return best_match;
2063 struct ref *get_remote_ref(const struct ref *remote_refs, const char *name)
2065 const struct ref *ref = find_ref_by_name_abbrev(remote_refs, name);
2067 if (!ref)
2068 return NULL;
2070 return copy_ref(ref);
2073 static struct ref *get_local_ref(const char *name)
2075 if (!name || name[0] == '\0')
2076 return NULL;
2078 if (starts_with(name, "refs/"))
2079 return alloc_ref(name);
2081 if (starts_with(name, "heads/") ||
2082 starts_with(name, "tags/") ||
2083 starts_with(name, "remotes/"))
2084 return alloc_ref_with_prefix("refs/", 5, name);
2086 return alloc_ref_with_prefix("refs/heads/", 11, name);
2089 int get_fetch_map(const struct ref *remote_refs,
2090 const struct refspec_item *refspec,
2091 struct ref ***tail,
2092 int missing_ok)
2094 struct ref *ref_map, **rmp;
2096 if (refspec->negative)
2097 return 0;
2099 if (refspec->pattern) {
2100 ref_map = get_expanded_map(remote_refs, refspec);
2101 } else {
2102 const char *name = refspec->src[0] ? refspec->src : "HEAD";
2104 if (refspec->exact_sha1) {
2105 ref_map = alloc_ref(name);
2106 get_oid_hex(name, &ref_map->old_oid);
2107 ref_map->exact_oid = 1;
2108 } else {
2109 ref_map = get_remote_ref(remote_refs, name);
2111 if (!missing_ok && !ref_map)
2112 die(_("couldn't find remote ref %s"), name);
2113 if (ref_map) {
2114 ref_map->peer_ref = get_local_ref(refspec->dst);
2115 if (ref_map->peer_ref && refspec->force)
2116 ref_map->peer_ref->force = 1;
2120 for (rmp = &ref_map; *rmp; ) {
2121 if ((*rmp)->peer_ref) {
2122 if (!starts_with((*rmp)->peer_ref->name, "refs/") ||
2123 check_refname_format((*rmp)->peer_ref->name, 0)) {
2124 struct ref *ignore = *rmp;
2125 error(_("* Ignoring funny ref '%s' locally"),
2126 (*rmp)->peer_ref->name);
2127 *rmp = (*rmp)->next;
2128 free(ignore->peer_ref);
2129 free(ignore);
2130 continue;
2133 rmp = &((*rmp)->next);
2136 if (ref_map)
2137 tail_link_ref(ref_map, tail);
2139 return 0;
2142 int resolve_remote_symref(struct ref *ref, struct ref *list)
2144 if (!ref->symref)
2145 return 0;
2146 for (; list; list = list->next)
2147 if (!strcmp(ref->symref, list->name)) {
2148 oidcpy(&ref->old_oid, &list->old_oid);
2149 return 0;
2151 return 1;
2155 * Compute the commit ahead/behind values for the pair branch_name, base.
2157 * If abf is AHEAD_BEHIND_FULL, compute the full ahead/behind and return the
2158 * counts in *num_ours and *num_theirs. If abf is AHEAD_BEHIND_QUICK, skip
2159 * the (potentially expensive) a/b computation (*num_ours and *num_theirs are
2160 * set to zero).
2162 * Returns -1 if num_ours and num_theirs could not be filled in (e.g., ref
2163 * does not exist). Returns 0 if the commits are identical. Returns 1 if
2164 * commits are different.
2167 static int stat_branch_pair(const char *branch_name, const char *base,
2168 int *num_ours, int *num_theirs,
2169 enum ahead_behind_flags abf)
2171 struct object_id oid;
2172 struct commit *ours, *theirs;
2173 struct rev_info revs;
2174 struct strvec argv = STRVEC_INIT;
2176 /* Cannot stat if what we used to build on no longer exists */
2177 if (read_ref(base, &oid))
2178 return -1;
2179 theirs = lookup_commit_reference(the_repository, &oid);
2180 if (!theirs)
2181 return -1;
2183 if (read_ref(branch_name, &oid))
2184 return -1;
2185 ours = lookup_commit_reference(the_repository, &oid);
2186 if (!ours)
2187 return -1;
2189 *num_theirs = *num_ours = 0;
2191 /* are we the same? */
2192 if (theirs == ours)
2193 return 0;
2194 if (abf == AHEAD_BEHIND_QUICK)
2195 return 1;
2196 if (abf != AHEAD_BEHIND_FULL)
2197 BUG("stat_branch_pair: invalid abf '%d'", abf);
2199 /* Run "rev-list --left-right ours...theirs" internally... */
2200 strvec_push(&argv, ""); /* ignored */
2201 strvec_push(&argv, "--left-right");
2202 strvec_pushf(&argv, "%s...%s",
2203 oid_to_hex(&ours->object.oid),
2204 oid_to_hex(&theirs->object.oid));
2205 strvec_push(&argv, "--");
2207 repo_init_revisions(the_repository, &revs, NULL);
2208 setup_revisions(argv.nr, argv.v, &revs, NULL);
2209 if (prepare_revision_walk(&revs))
2210 die(_("revision walk setup failed"));
2212 /* ... and count the commits on each side. */
2213 while (1) {
2214 struct commit *c = get_revision(&revs);
2215 if (!c)
2216 break;
2217 if (c->object.flags & SYMMETRIC_LEFT)
2218 (*num_ours)++;
2219 else
2220 (*num_theirs)++;
2223 /* clear object flags smudged by the above traversal */
2224 clear_commit_marks(ours, ALL_REV_FLAGS);
2225 clear_commit_marks(theirs, ALL_REV_FLAGS);
2227 strvec_clear(&argv);
2228 release_revisions(&revs);
2229 return 1;
2233 * Lookup the tracking branch for the given branch and if present, optionally
2234 * compute the commit ahead/behind values for the pair.
2236 * If for_push is true, the tracking branch refers to the push branch,
2237 * otherwise it refers to the upstream branch.
2239 * The name of the tracking branch (or NULL if it is not defined) is
2240 * returned via *tracking_name, if it is not itself NULL.
2242 * If abf is AHEAD_BEHIND_FULL, compute the full ahead/behind and return the
2243 * counts in *num_ours and *num_theirs. If abf is AHEAD_BEHIND_QUICK, skip
2244 * the (potentially expensive) a/b computation (*num_ours and *num_theirs are
2245 * set to zero).
2247 * Returns -1 if num_ours and num_theirs could not be filled in (e.g., no
2248 * upstream defined, or ref does not exist). Returns 0 if the commits are
2249 * identical. Returns 1 if commits are different.
2251 int stat_tracking_info(struct branch *branch, int *num_ours, int *num_theirs,
2252 const char **tracking_name, int for_push,
2253 enum ahead_behind_flags abf)
2255 const char *base;
2257 /* Cannot stat unless we are marked to build on top of somebody else. */
2258 base = for_push ? branch_get_push(branch, NULL) :
2259 branch_get_upstream(branch, NULL);
2260 if (tracking_name)
2261 *tracking_name = base;
2262 if (!base)
2263 return -1;
2265 return stat_branch_pair(branch->refname, base, num_ours, num_theirs, abf);
2269 * Return true when there is anything to report, otherwise false.
2271 int format_tracking_info(struct branch *branch, struct strbuf *sb,
2272 enum ahead_behind_flags abf)
2274 int ours, theirs, sti;
2275 const char *full_base;
2276 char *base;
2277 int upstream_is_gone = 0;
2279 sti = stat_tracking_info(branch, &ours, &theirs, &full_base, 0, abf);
2280 if (sti < 0) {
2281 if (!full_base)
2282 return 0;
2283 upstream_is_gone = 1;
2286 base = shorten_unambiguous_ref(full_base, 0);
2287 if (upstream_is_gone) {
2288 strbuf_addf(sb,
2289 _("Your branch is based on '%s', but the upstream is gone.\n"),
2290 base);
2291 if (advice_enabled(ADVICE_STATUS_HINTS))
2292 strbuf_addstr(sb,
2293 _(" (use \"git branch --unset-upstream\" to fixup)\n"));
2294 } else if (!sti) {
2295 strbuf_addf(sb,
2296 _("Your branch is up to date with '%s'.\n"),
2297 base);
2298 } else if (abf == AHEAD_BEHIND_QUICK) {
2299 strbuf_addf(sb,
2300 _("Your branch and '%s' refer to different commits.\n"),
2301 base);
2302 if (advice_enabled(ADVICE_STATUS_HINTS))
2303 strbuf_addf(sb, _(" (use \"%s\" for details)\n"),
2304 "git status --ahead-behind");
2305 } else if (!theirs) {
2306 strbuf_addf(sb,
2307 Q_("Your branch is ahead of '%s' by %d commit.\n",
2308 "Your branch is ahead of '%s' by %d commits.\n",
2309 ours),
2310 base, ours);
2311 if (advice_enabled(ADVICE_STATUS_HINTS))
2312 strbuf_addstr(sb,
2313 _(" (use \"git push\" to publish your local commits)\n"));
2314 } else if (!ours) {
2315 strbuf_addf(sb,
2316 Q_("Your branch is behind '%s' by %d commit, "
2317 "and can be fast-forwarded.\n",
2318 "Your branch is behind '%s' by %d commits, "
2319 "and can be fast-forwarded.\n",
2320 theirs),
2321 base, theirs);
2322 if (advice_enabled(ADVICE_STATUS_HINTS))
2323 strbuf_addstr(sb,
2324 _(" (use \"git pull\" to update your local branch)\n"));
2325 } else {
2326 strbuf_addf(sb,
2327 Q_("Your branch and '%s' have diverged,\n"
2328 "and have %d and %d different commit each, "
2329 "respectively.\n",
2330 "Your branch and '%s' have diverged,\n"
2331 "and have %d and %d different commits each, "
2332 "respectively.\n",
2333 ours + theirs),
2334 base, ours, theirs);
2335 if (advice_enabled(ADVICE_STATUS_HINTS))
2336 strbuf_addstr(sb,
2337 _(" (use \"git pull\" to merge the remote branch into yours)\n"));
2339 free(base);
2340 return 1;
2343 static int one_local_ref(const char *refname, const struct object_id *oid,
2344 int flag, void *cb_data)
2346 struct ref ***local_tail = cb_data;
2347 struct ref *ref;
2349 /* we already know it starts with refs/ to get here */
2350 if (check_refname_format(refname + 5, 0))
2351 return 0;
2353 ref = alloc_ref(refname);
2354 oidcpy(&ref->new_oid, oid);
2355 **local_tail = ref;
2356 *local_tail = &ref->next;
2357 return 0;
2360 struct ref *get_local_heads(void)
2362 struct ref *local_refs = NULL, **local_tail = &local_refs;
2364 for_each_ref(one_local_ref, &local_tail);
2365 return local_refs;
2368 struct ref *guess_remote_head(const struct ref *head,
2369 const struct ref *refs,
2370 int all)
2372 const struct ref *r;
2373 struct ref *list = NULL;
2374 struct ref **tail = &list;
2376 if (!head)
2377 return NULL;
2380 * Some transports support directly peeking at
2381 * where HEAD points; if that is the case, then
2382 * we don't have to guess.
2384 if (head->symref)
2385 return copy_ref(find_ref_by_name(refs, head->symref));
2387 /* If a remote branch exists with the default branch name, let's use it. */
2388 if (!all) {
2389 char *ref = xstrfmt("refs/heads/%s",
2390 git_default_branch_name(0));
2392 r = find_ref_by_name(refs, ref);
2393 free(ref);
2394 if (r && oideq(&r->old_oid, &head->old_oid))
2395 return copy_ref(r);
2397 /* Fall back to the hard-coded historical default */
2398 r = find_ref_by_name(refs, "refs/heads/master");
2399 if (r && oideq(&r->old_oid, &head->old_oid))
2400 return copy_ref(r);
2403 /* Look for another ref that points there */
2404 for (r = refs; r; r = r->next) {
2405 if (r != head &&
2406 starts_with(r->name, "refs/heads/") &&
2407 oideq(&r->old_oid, &head->old_oid)) {
2408 *tail = copy_ref(r);
2409 tail = &((*tail)->next);
2410 if (!all)
2411 break;
2415 return list;
2418 struct stale_heads_info {
2419 struct string_list *ref_names;
2420 struct ref **stale_refs_tail;
2421 struct refspec *rs;
2424 static int get_stale_heads_cb(const char *refname, const struct object_id *oid,
2425 int flags, void *cb_data)
2427 struct stale_heads_info *info = cb_data;
2428 struct string_list matches = STRING_LIST_INIT_DUP;
2429 struct refspec_item query;
2430 int i, stale = 1;
2431 memset(&query, 0, sizeof(struct refspec_item));
2432 query.dst = (char *)refname;
2434 query_refspecs_multiple(info->rs, &query, &matches);
2435 if (matches.nr == 0)
2436 goto clean_exit; /* No matches */
2439 * If we did find a suitable refspec and it's not a symref and
2440 * it's not in the list of refs that currently exist in that
2441 * remote, we consider it to be stale. In order to deal with
2442 * overlapping refspecs, we need to go over all of the
2443 * matching refs.
2445 if (flags & REF_ISSYMREF)
2446 goto clean_exit;
2448 for (i = 0; stale && i < matches.nr; i++)
2449 if (string_list_has_string(info->ref_names, matches.items[i].string))
2450 stale = 0;
2452 if (stale) {
2453 struct ref *ref = make_linked_ref(refname, &info->stale_refs_tail);
2454 oidcpy(&ref->new_oid, oid);
2457 clean_exit:
2458 string_list_clear(&matches, 0);
2459 return 0;
2462 struct ref *get_stale_heads(struct refspec *rs, struct ref *fetch_map)
2464 struct ref *ref, *stale_refs = NULL;
2465 struct string_list ref_names = STRING_LIST_INIT_NODUP;
2466 struct stale_heads_info info;
2468 info.ref_names = &ref_names;
2469 info.stale_refs_tail = &stale_refs;
2470 info.rs = rs;
2471 for (ref = fetch_map; ref; ref = ref->next)
2472 string_list_append(&ref_names, ref->name);
2473 string_list_sort(&ref_names);
2474 for_each_ref(get_stale_heads_cb, &info);
2475 string_list_clear(&ref_names, 0);
2476 return stale_refs;
2480 * Compare-and-swap
2482 static void clear_cas_option(struct push_cas_option *cas)
2484 int i;
2486 for (i = 0; i < cas->nr; i++)
2487 free(cas->entry[i].refname);
2488 free(cas->entry);
2489 memset(cas, 0, sizeof(*cas));
2492 static struct push_cas *add_cas_entry(struct push_cas_option *cas,
2493 const char *refname,
2494 size_t refnamelen)
2496 struct push_cas *entry;
2497 ALLOC_GROW(cas->entry, cas->nr + 1, cas->alloc);
2498 entry = &cas->entry[cas->nr++];
2499 memset(entry, 0, sizeof(*entry));
2500 entry->refname = xmemdupz(refname, refnamelen);
2501 return entry;
2504 static int parse_push_cas_option(struct push_cas_option *cas, const char *arg, int unset)
2506 const char *colon;
2507 struct push_cas *entry;
2509 if (unset) {
2510 /* "--no-<option>" */
2511 clear_cas_option(cas);
2512 return 0;
2515 if (!arg) {
2516 /* just "--<option>" */
2517 cas->use_tracking_for_rest = 1;
2518 return 0;
2521 /* "--<option>=refname" or "--<option>=refname:value" */
2522 colon = strchrnul(arg, ':');
2523 entry = add_cas_entry(cas, arg, colon - arg);
2524 if (!*colon)
2525 entry->use_tracking = 1;
2526 else if (!colon[1])
2527 oidclr(&entry->expect);
2528 else if (get_oid(colon + 1, &entry->expect))
2529 return error(_("cannot parse expected object name '%s'"),
2530 colon + 1);
2531 return 0;
2534 int parseopt_push_cas_option(const struct option *opt, const char *arg, int unset)
2536 return parse_push_cas_option(opt->value, arg, unset);
2539 int is_empty_cas(const struct push_cas_option *cas)
2541 return !cas->use_tracking_for_rest && !cas->nr;
2545 * Look at remote.fetch refspec and see if we have a remote
2546 * tracking branch for the refname there. Fill the name of
2547 * the remote-tracking branch in *dst_refname, and the name
2548 * of the commit object at its tip in oid[].
2549 * If we cannot do so, return negative to signal an error.
2551 static int remote_tracking(struct remote *remote, const char *refname,
2552 struct object_id *oid, char **dst_refname)
2554 char *dst;
2556 dst = apply_refspecs(&remote->fetch, refname);
2557 if (!dst)
2558 return -1; /* no tracking ref for refname at remote */
2559 if (read_ref(dst, oid))
2560 return -1; /* we know what the tracking ref is but we cannot read it */
2562 *dst_refname = dst;
2563 return 0;
2567 * The struct "reflog_commit_array" and related helper functions
2568 * are used for collecting commits into an array during reflog
2569 * traversals in "check_and_collect_until()".
2571 struct reflog_commit_array {
2572 struct commit **item;
2573 size_t nr, alloc;
2576 #define REFLOG_COMMIT_ARRAY_INIT { 0 }
2578 /* Append a commit to the array. */
2579 static void append_commit(struct reflog_commit_array *arr,
2580 struct commit *commit)
2582 ALLOC_GROW(arr->item, arr->nr + 1, arr->alloc);
2583 arr->item[arr->nr++] = commit;
2586 /* Free and reset the array. */
2587 static void free_commit_array(struct reflog_commit_array *arr)
2589 FREE_AND_NULL(arr->item);
2590 arr->nr = arr->alloc = 0;
2593 struct check_and_collect_until_cb_data {
2594 struct commit *remote_commit;
2595 struct reflog_commit_array *local_commits;
2596 timestamp_t remote_reflog_timestamp;
2599 /* Get the timestamp of the latest entry. */
2600 static int peek_reflog(struct object_id *o_oid, struct object_id *n_oid,
2601 const char *ident, timestamp_t timestamp,
2602 int tz, const char *message, void *cb_data)
2604 timestamp_t *ts = cb_data;
2605 *ts = timestamp;
2606 return 1;
2609 static int check_and_collect_until(struct object_id *o_oid,
2610 struct object_id *n_oid,
2611 const char *ident, timestamp_t timestamp,
2612 int tz, const char *message, void *cb_data)
2614 struct commit *commit;
2615 struct check_and_collect_until_cb_data *cb = cb_data;
2617 /* An entry was found. */
2618 if (oideq(n_oid, &cb->remote_commit->object.oid))
2619 return 1;
2621 if ((commit = lookup_commit_reference(the_repository, n_oid)))
2622 append_commit(cb->local_commits, commit);
2625 * If the reflog entry timestamp is older than the remote ref's
2626 * latest reflog entry, there is no need to check or collect
2627 * entries older than this one.
2629 if (timestamp < cb->remote_reflog_timestamp)
2630 return -1;
2632 return 0;
2635 #define MERGE_BASES_BATCH_SIZE 8
2638 * Iterate through the reflog of the local ref to check if there is an entry
2639 * for the given remote-tracking ref; runs until the timestamp of an entry is
2640 * older than latest timestamp of remote-tracking ref's reflog. Any commits
2641 * are that seen along the way are collected into an array to check if the
2642 * remote-tracking ref is reachable from any of them.
2644 static int is_reachable_in_reflog(const char *local, const struct ref *remote)
2646 timestamp_t date;
2647 struct commit *commit;
2648 struct commit **chunk;
2649 struct check_and_collect_until_cb_data cb;
2650 struct reflog_commit_array arr = REFLOG_COMMIT_ARRAY_INIT;
2651 size_t size = 0;
2652 int ret = 0;
2654 commit = lookup_commit_reference(the_repository, &remote->old_oid);
2655 if (!commit)
2656 goto cleanup_return;
2659 * Get the timestamp from the latest entry
2660 * of the remote-tracking ref's reflog.
2662 for_each_reflog_ent_reverse(remote->tracking_ref, peek_reflog, &date);
2664 cb.remote_commit = commit;
2665 cb.local_commits = &arr;
2666 cb.remote_reflog_timestamp = date;
2667 ret = for_each_reflog_ent_reverse(local, check_and_collect_until, &cb);
2669 /* We found an entry in the reflog. */
2670 if (ret > 0)
2671 goto cleanup_return;
2674 * Check if the remote commit is reachable from any
2675 * of the commits in the collected array, in batches.
2677 for (chunk = arr.item; chunk < arr.item + arr.nr; chunk += size) {
2678 size = arr.item + arr.nr - chunk;
2679 if (MERGE_BASES_BATCH_SIZE < size)
2680 size = MERGE_BASES_BATCH_SIZE;
2682 if ((ret = in_merge_bases_many(commit, size, chunk)))
2683 break;
2686 cleanup_return:
2687 free_commit_array(&arr);
2688 return ret;
2692 * Check for reachability of a remote-tracking
2693 * ref in the reflog entries of its local ref.
2695 static void check_if_includes_upstream(struct ref *remote)
2697 struct ref *local = get_local_ref(remote->name);
2698 if (!local)
2699 return;
2701 if (is_reachable_in_reflog(local->name, remote) <= 0)
2702 remote->unreachable = 1;
2705 static void apply_cas(struct push_cas_option *cas,
2706 struct remote *remote,
2707 struct ref *ref)
2709 int i;
2711 /* Find an explicit --<option>=<name>[:<value>] entry */
2712 for (i = 0; i < cas->nr; i++) {
2713 struct push_cas *entry = &cas->entry[i];
2714 if (!refname_match(entry->refname, ref->name))
2715 continue;
2716 ref->expect_old_sha1 = 1;
2717 if (!entry->use_tracking)
2718 oidcpy(&ref->old_oid_expect, &entry->expect);
2719 else if (remote_tracking(remote, ref->name,
2720 &ref->old_oid_expect,
2721 &ref->tracking_ref))
2722 oidclr(&ref->old_oid_expect);
2723 else
2724 ref->check_reachable = cas->use_force_if_includes;
2725 return;
2728 /* Are we using "--<option>" to cover all? */
2729 if (!cas->use_tracking_for_rest)
2730 return;
2732 ref->expect_old_sha1 = 1;
2733 if (remote_tracking(remote, ref->name,
2734 &ref->old_oid_expect,
2735 &ref->tracking_ref))
2736 oidclr(&ref->old_oid_expect);
2737 else
2738 ref->check_reachable = cas->use_force_if_includes;
2741 void apply_push_cas(struct push_cas_option *cas,
2742 struct remote *remote,
2743 struct ref *remote_refs)
2745 struct ref *ref;
2746 for (ref = remote_refs; ref; ref = ref->next) {
2747 apply_cas(cas, remote, ref);
2750 * If "compare-and-swap" is in "use_tracking[_for_rest]"
2751 * mode, and if "--force-if-includes" was specified, run
2752 * the check.
2754 if (ref->check_reachable)
2755 check_if_includes_upstream(ref);
2759 struct remote_state *remote_state_new(void)
2761 struct remote_state *r = xmalloc(sizeof(*r));
2763 memset(r, 0, sizeof(*r));
2765 hashmap_init(&r->remotes_hash, remotes_hash_cmp, NULL, 0);
2766 hashmap_init(&r->branches_hash, branches_hash_cmp, NULL, 0);
2767 return r;
2770 void remote_state_clear(struct remote_state *remote_state)
2772 int i;
2774 for (i = 0; i < remote_state->remotes_nr; i++) {
2775 remote_clear(remote_state->remotes[i]);
2777 FREE_AND_NULL(remote_state->remotes);
2778 remote_state->remotes_alloc = 0;
2779 remote_state->remotes_nr = 0;
2781 hashmap_clear_and_free(&remote_state->remotes_hash, struct remote, ent);
2782 hashmap_clear_and_free(&remote_state->branches_hash, struct remote, ent);
2786 * Returns 1 if it was the last chop before ':'.
2788 static int chop_last_dir(char **remoteurl, int is_relative)
2790 char *rfind = find_last_dir_sep(*remoteurl);
2791 if (rfind) {
2792 *rfind = '\0';
2793 return 0;
2796 rfind = strrchr(*remoteurl, ':');
2797 if (rfind) {
2798 *rfind = '\0';
2799 return 1;
2802 if (is_relative || !strcmp(".", *remoteurl))
2803 die(_("cannot strip one component off url '%s'"),
2804 *remoteurl);
2806 free(*remoteurl);
2807 *remoteurl = xstrdup(".");
2808 return 0;
2811 char *relative_url(const char *remote_url, const char *url,
2812 const char *up_path)
2814 int is_relative = 0;
2815 int colonsep = 0;
2816 char *out;
2817 char *remoteurl;
2818 struct strbuf sb = STRBUF_INIT;
2819 size_t len;
2821 if (!url_is_local_not_ssh(url) || is_absolute_path(url))
2822 return xstrdup(url);
2824 len = strlen(remote_url);
2825 if (!len)
2826 BUG("invalid empty remote_url");
2828 remoteurl = xstrdup(remote_url);
2829 if (is_dir_sep(remoteurl[len-1]))
2830 remoteurl[len-1] = '\0';
2832 if (!url_is_local_not_ssh(remoteurl) || is_absolute_path(remoteurl))
2833 is_relative = 0;
2834 else {
2835 is_relative = 1;
2837 * Prepend a './' to ensure all relative
2838 * remoteurls start with './' or '../'
2840 if (!starts_with_dot_slash_native(remoteurl) &&
2841 !starts_with_dot_dot_slash_native(remoteurl)) {
2842 strbuf_reset(&sb);
2843 strbuf_addf(&sb, "./%s", remoteurl);
2844 free(remoteurl);
2845 remoteurl = strbuf_detach(&sb, NULL);
2849 * When the url starts with '../', remove that and the
2850 * last directory in remoteurl.
2852 while (url) {
2853 if (starts_with_dot_dot_slash_native(url)) {
2854 url += 3;
2855 colonsep |= chop_last_dir(&remoteurl, is_relative);
2856 } else if (starts_with_dot_slash_native(url))
2857 url += 2;
2858 else
2859 break;
2861 strbuf_reset(&sb);
2862 strbuf_addf(&sb, "%s%s%s", remoteurl, colonsep ? ":" : "/", url);
2863 if (ends_with(url, "/"))
2864 strbuf_setlen(&sb, sb.len - 1);
2865 free(remoteurl);
2867 if (starts_with_dot_slash_native(sb.buf))
2868 out = xstrdup(sb.buf + 2);
2869 else
2870 out = xstrdup(sb.buf);
2872 if (!up_path || !is_relative) {
2873 strbuf_release(&sb);
2874 return out;
2877 strbuf_reset(&sb);
2878 strbuf_addf(&sb, "%s%s", up_path, out);
2879 free(out);
2880 return strbuf_detach(&sb, NULL);