gc: don't translate literal commands
[git/debian.git] / remote.c
blob1ee2b145d07f7247d8f6e7476e020174520e9faf
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]);
151 FREE_AND_NULL(remote->url);
153 for (i = 0; i < remote->pushurl_nr; i++)
154 free((char *)remote->pushurl[i]);
155 FREE_AND_NULL(remote->pushurl);
156 free((char *)remote->receivepack);
157 free((char *)remote->uploadpack);
158 FREE_AND_NULL(remote->http_proxy);
159 FREE_AND_NULL(remote->http_proxy_authmethod);
162 static void add_merge(struct branch *branch, const char *name)
164 ALLOC_GROW(branch->merge_name, branch->merge_nr + 1,
165 branch->merge_alloc);
166 branch->merge_name[branch->merge_nr++] = name;
169 struct branches_hash_key {
170 const char *str;
171 int len;
174 static int branches_hash_cmp(const void *unused_cmp_data,
175 const struct hashmap_entry *eptr,
176 const struct hashmap_entry *entry_or_key,
177 const void *keydata)
179 const struct branch *a, *b;
180 const struct branches_hash_key *key = keydata;
182 a = container_of(eptr, const struct branch, ent);
183 b = container_of(entry_or_key, const struct branch, ent);
185 if (key)
186 return strncmp(a->name, key->str, key->len) ||
187 a->name[key->len];
188 else
189 return strcmp(a->name, b->name);
192 static struct branch *find_branch(struct remote_state *remote_state,
193 const char *name, size_t len)
195 struct branches_hash_key lookup;
196 struct hashmap_entry lookup_entry, *e;
198 lookup.str = name;
199 lookup.len = len;
200 hashmap_entry_init(&lookup_entry, memhash(name, len));
202 e = hashmap_get(&remote_state->branches_hash, &lookup_entry, &lookup);
203 if (e)
204 return container_of(e, struct branch, ent);
206 return NULL;
209 static void die_on_missing_branch(struct repository *repo,
210 struct branch *branch)
212 /* branch == NULL is always valid because it represents detached HEAD. */
213 if (branch &&
214 branch != find_branch(repo->remote_state, branch->name,
215 strlen(branch->name)))
216 die("branch %s was not found in the repository", branch->name);
219 static struct branch *make_branch(struct remote_state *remote_state,
220 const char *name, size_t len)
222 struct branch *ret;
224 ret = find_branch(remote_state, name, len);
225 if (ret)
226 return ret;
228 CALLOC_ARRAY(ret, 1);
229 ret->name = xstrndup(name, len);
230 ret->refname = xstrfmt("refs/heads/%s", ret->name);
232 hashmap_entry_init(&ret->ent, memhash(name, len));
233 if (hashmap_put_entry(&remote_state->branches_hash, ret, ent))
234 BUG("hashmap_put overwrote entry after hashmap_get returned NULL");
235 return ret;
238 static struct rewrite *make_rewrite(struct rewrites *r,
239 const char *base, size_t len)
241 struct rewrite *ret;
242 int i;
244 for (i = 0; i < r->rewrite_nr; i++) {
245 if (len == r->rewrite[i]->baselen &&
246 !strncmp(base, r->rewrite[i]->base, len))
247 return r->rewrite[i];
250 ALLOC_GROW(r->rewrite, r->rewrite_nr + 1, r->rewrite_alloc);
251 CALLOC_ARRAY(ret, 1);
252 r->rewrite[r->rewrite_nr++] = ret;
253 ret->base = xstrndup(base, len);
254 ret->baselen = len;
255 return ret;
258 static void add_instead_of(struct rewrite *rewrite, const char *instead_of)
260 ALLOC_GROW(rewrite->instead_of, rewrite->instead_of_nr + 1, rewrite->instead_of_alloc);
261 rewrite->instead_of[rewrite->instead_of_nr].s = instead_of;
262 rewrite->instead_of[rewrite->instead_of_nr].len = strlen(instead_of);
263 rewrite->instead_of_nr++;
266 static const char *skip_spaces(const char *s)
268 while (isspace(*s))
269 s++;
270 return s;
273 static void read_remotes_file(struct remote_state *remote_state,
274 struct remote *remote)
276 struct strbuf buf = STRBUF_INIT;
277 FILE *f = fopen_or_warn(git_path("remotes/%s", remote->name), "r");
279 if (!f)
280 return;
281 remote->configured_in_repo = 1;
282 remote->origin = REMOTE_REMOTES;
283 while (strbuf_getline(&buf, f) != EOF) {
284 const char *v;
286 strbuf_rtrim(&buf);
288 if (skip_prefix(buf.buf, "URL:", &v))
289 add_url_alias(remote_state, remote,
290 xstrdup(skip_spaces(v)));
291 else if (skip_prefix(buf.buf, "Push:", &v))
292 refspec_append(&remote->push, skip_spaces(v));
293 else if (skip_prefix(buf.buf, "Pull:", &v))
294 refspec_append(&remote->fetch, skip_spaces(v));
296 strbuf_release(&buf);
297 fclose(f);
300 static void read_branches_file(struct remote_state *remote_state,
301 struct remote *remote)
303 char *frag;
304 struct strbuf buf = STRBUF_INIT;
305 FILE *f = fopen_or_warn(git_path("branches/%s", remote->name), "r");
307 if (!f)
308 return;
310 strbuf_getline_lf(&buf, f);
311 fclose(f);
312 strbuf_trim(&buf);
313 if (!buf.len) {
314 strbuf_release(&buf);
315 return;
318 remote->configured_in_repo = 1;
319 remote->origin = REMOTE_BRANCHES;
322 * The branches file would have URL and optionally
323 * #branch specified. The default (or specified) branch is
324 * fetched and stored in the local branch matching the
325 * remote name.
327 frag = strchr(buf.buf, '#');
328 if (frag)
329 *(frag++) = '\0';
330 else
331 frag = (char *)git_default_branch_name(0);
333 add_url_alias(remote_state, remote, strbuf_detach(&buf, NULL));
334 refspec_appendf(&remote->fetch, "refs/heads/%s:refs/heads/%s",
335 frag, remote->name);
338 * Cogito compatible push: push current HEAD to remote #branch
339 * (master if missing)
341 refspec_appendf(&remote->push, "HEAD:refs/heads/%s", frag);
342 remote->fetch_tags = 1; /* always auto-follow */
345 static int handle_config(const char *key, const char *value, void *cb)
347 const char *name;
348 size_t namelen;
349 const char *subkey;
350 struct remote *remote;
351 struct branch *branch;
352 struct remote_state *remote_state = cb;
354 if (parse_config_key(key, "branch", &name, &namelen, &subkey) >= 0) {
355 /* There is no subsection. */
356 if (!name)
357 return 0;
358 /* There is a subsection, but it is empty. */
359 if (!namelen)
360 return -1;
361 branch = make_branch(remote_state, name, namelen);
362 if (!strcmp(subkey, "remote")) {
363 return git_config_string(&branch->remote_name, key, value);
364 } else if (!strcmp(subkey, "pushremote")) {
365 return git_config_string(&branch->pushremote_name, key, value);
366 } else if (!strcmp(subkey, "merge")) {
367 if (!value)
368 return config_error_nonbool(key);
369 add_merge(branch, xstrdup(value));
371 return 0;
373 if (parse_config_key(key, "url", &name, &namelen, &subkey) >= 0) {
374 struct rewrite *rewrite;
375 if (!name)
376 return 0;
377 if (!strcmp(subkey, "insteadof")) {
378 if (!value)
379 return config_error_nonbool(key);
380 rewrite = make_rewrite(&remote_state->rewrites, name,
381 namelen);
382 add_instead_of(rewrite, xstrdup(value));
383 } else if (!strcmp(subkey, "pushinsteadof")) {
384 if (!value)
385 return config_error_nonbool(key);
386 rewrite = make_rewrite(&remote_state->rewrites_push,
387 name, namelen);
388 add_instead_of(rewrite, xstrdup(value));
392 if (parse_config_key(key, "remote", &name, &namelen, &subkey) < 0)
393 return 0;
395 /* Handle remote.* variables */
396 if (!name && !strcmp(subkey, "pushdefault"))
397 return git_config_string(&remote_state->pushremote_name, key,
398 value);
400 if (!name)
401 return 0;
402 /* Handle remote.<name>.* variables */
403 if (*name == '/') {
404 warning(_("config remote shorthand cannot begin with '/': %s"),
405 name);
406 return 0;
408 remote = make_remote(remote_state, name, namelen);
409 remote->origin = REMOTE_CONFIG;
410 if (current_config_scope() == CONFIG_SCOPE_LOCAL ||
411 current_config_scope() == CONFIG_SCOPE_WORKTREE)
412 remote->configured_in_repo = 1;
413 if (!strcmp(subkey, "mirror"))
414 remote->mirror = git_config_bool(key, value);
415 else if (!strcmp(subkey, "skipdefaultupdate"))
416 remote->skip_default_update = git_config_bool(key, value);
417 else if (!strcmp(subkey, "skipfetchall"))
418 remote->skip_default_update = git_config_bool(key, value);
419 else if (!strcmp(subkey, "prune"))
420 remote->prune = git_config_bool(key, value);
421 else if (!strcmp(subkey, "prunetags"))
422 remote->prune_tags = git_config_bool(key, value);
423 else if (!strcmp(subkey, "url")) {
424 const char *v;
425 if (git_config_string(&v, key, value))
426 return -1;
427 add_url(remote, v);
428 } else if (!strcmp(subkey, "pushurl")) {
429 const char *v;
430 if (git_config_string(&v, key, value))
431 return -1;
432 add_pushurl(remote, v);
433 } else if (!strcmp(subkey, "push")) {
434 const char *v;
435 if (git_config_string(&v, key, value))
436 return -1;
437 refspec_append(&remote->push, v);
438 free((char *)v);
439 } else if (!strcmp(subkey, "fetch")) {
440 const char *v;
441 if (git_config_string(&v, key, value))
442 return -1;
443 refspec_append(&remote->fetch, v);
444 free((char *)v);
445 } else if (!strcmp(subkey, "receivepack")) {
446 const char *v;
447 if (git_config_string(&v, key, value))
448 return -1;
449 if (!remote->receivepack)
450 remote->receivepack = v;
451 else
452 error(_("more than one receivepack given, using the first"));
453 } else if (!strcmp(subkey, "uploadpack")) {
454 const char *v;
455 if (git_config_string(&v, key, value))
456 return -1;
457 if (!remote->uploadpack)
458 remote->uploadpack = v;
459 else
460 error(_("more than one uploadpack given, using the first"));
461 } else if (!strcmp(subkey, "tagopt")) {
462 if (!strcmp(value, "--no-tags"))
463 remote->fetch_tags = -1;
464 else if (!strcmp(value, "--tags"))
465 remote->fetch_tags = 2;
466 } else if (!strcmp(subkey, "proxy")) {
467 return git_config_string((const char **)&remote->http_proxy,
468 key, value);
469 } else if (!strcmp(subkey, "proxyauthmethod")) {
470 return git_config_string((const char **)&remote->http_proxy_authmethod,
471 key, value);
472 } else if (!strcmp(subkey, "vcs")) {
473 return git_config_string(&remote->foreign_vcs, key, value);
475 return 0;
478 static void alias_all_urls(struct remote_state *remote_state)
480 int i, j;
481 for (i = 0; i < remote_state->remotes_nr; i++) {
482 int add_pushurl_aliases;
483 if (!remote_state->remotes[i])
484 continue;
485 for (j = 0; j < remote_state->remotes[i]->pushurl_nr; j++) {
486 remote_state->remotes[i]->pushurl[j] =
487 alias_url(remote_state->remotes[i]->pushurl[j],
488 &remote_state->rewrites);
490 add_pushurl_aliases = remote_state->remotes[i]->pushurl_nr == 0;
491 for (j = 0; j < remote_state->remotes[i]->url_nr; j++) {
492 if (add_pushurl_aliases)
493 add_pushurl_alias(
494 remote_state, remote_state->remotes[i],
495 remote_state->remotes[i]->url[j]);
496 remote_state->remotes[i]->url[j] =
497 alias_url(remote_state->remotes[i]->url[j],
498 &remote_state->rewrites);
503 static void read_config(struct repository *repo)
505 int flag;
507 if (repo->remote_state->initialized)
508 return;
509 repo->remote_state->initialized = 1;
511 repo->remote_state->current_branch = NULL;
512 if (startup_info->have_repository) {
513 const char *head_ref = refs_resolve_ref_unsafe(
514 get_main_ref_store(repo), "HEAD", 0, NULL, &flag);
515 if (head_ref && (flag & REF_ISSYMREF) &&
516 skip_prefix(head_ref, "refs/heads/", &head_ref)) {
517 repo->remote_state->current_branch = make_branch(
518 repo->remote_state, head_ref, strlen(head_ref));
521 repo_config(repo, handle_config, repo->remote_state);
522 alias_all_urls(repo->remote_state);
525 static int valid_remote_nick(const char *name)
527 if (!name[0] || is_dot_or_dotdot(name))
528 return 0;
530 /* remote nicknames cannot contain slashes */
531 while (*name)
532 if (is_dir_sep(*name++))
533 return 0;
534 return 1;
537 static const char *remotes_remote_for_branch(struct remote_state *remote_state,
538 struct branch *branch,
539 int *explicit)
541 if (branch && branch->remote_name) {
542 if (explicit)
543 *explicit = 1;
544 return branch->remote_name;
546 if (explicit)
547 *explicit = 0;
548 if (remote_state->remotes_nr == 1)
549 return remote_state->remotes[0]->name;
550 return "origin";
553 const char *remote_for_branch(struct branch *branch, int *explicit)
555 read_config(the_repository);
556 die_on_missing_branch(the_repository, branch);
558 return remotes_remote_for_branch(the_repository->remote_state, branch,
559 explicit);
562 static const char *
563 remotes_pushremote_for_branch(struct remote_state *remote_state,
564 struct branch *branch, int *explicit)
566 if (branch && branch->pushremote_name) {
567 if (explicit)
568 *explicit = 1;
569 return branch->pushremote_name;
571 if (remote_state->pushremote_name) {
572 if (explicit)
573 *explicit = 1;
574 return remote_state->pushremote_name;
576 return remotes_remote_for_branch(remote_state, branch, explicit);
579 const char *pushremote_for_branch(struct branch *branch, int *explicit)
581 read_config(the_repository);
582 die_on_missing_branch(the_repository, branch);
584 return remotes_pushremote_for_branch(the_repository->remote_state,
585 branch, explicit);
588 static struct remote *remotes_remote_get(struct remote_state *remote_state,
589 const char *name);
591 const char *remote_ref_for_branch(struct branch *branch, int for_push)
593 read_config(the_repository);
594 die_on_missing_branch(the_repository, branch);
596 if (branch) {
597 if (!for_push) {
598 if (branch->merge_nr) {
599 return branch->merge_name[0];
601 } else {
602 const char *dst,
603 *remote_name = remotes_pushremote_for_branch(
604 the_repository->remote_state, branch,
605 NULL);
606 struct remote *remote = remotes_remote_get(
607 the_repository->remote_state, remote_name);
609 if (remote && remote->push.nr &&
610 (dst = apply_refspecs(&remote->push,
611 branch->refname))) {
612 return dst;
616 return NULL;
619 static void validate_remote_url(struct remote *remote)
621 int i;
622 const char *value;
623 struct strbuf redacted = STRBUF_INIT;
624 int warn_not_die;
626 if (git_config_get_string_tmp("transfer.credentialsinurl", &value))
627 return;
629 if (!strcmp("warn", value))
630 warn_not_die = 1;
631 else if (!strcmp("die", value))
632 warn_not_die = 0;
633 else if (!strcmp("allow", value))
634 return;
635 else
636 die(_("unrecognized value transfer.credentialsInUrl: '%s'"), value);
638 for (i = 0; i < remote->url_nr; i++) {
639 struct url_info url_info = { 0 };
641 if (!url_normalize(remote->url[i], &url_info) ||
642 !url_info.passwd_off)
643 goto loop_cleanup;
645 strbuf_reset(&redacted);
646 strbuf_add(&redacted, url_info.url, url_info.passwd_off);
647 strbuf_addstr(&redacted, "<redacted>");
648 strbuf_addstr(&redacted,
649 url_info.url + url_info.passwd_off + url_info.passwd_len);
651 if (warn_not_die)
652 warning(_("URL '%s' uses plaintext credentials"), redacted.buf);
653 else
654 die(_("URL '%s' uses plaintext credentials"), redacted.buf);
656 loop_cleanup:
657 free(url_info.url);
660 strbuf_release(&redacted);
663 static struct remote *
664 remotes_remote_get_1(struct remote_state *remote_state, const char *name,
665 const char *(*get_default)(struct remote_state *,
666 struct branch *, int *))
668 struct remote *ret;
669 int name_given = 0;
671 if (name)
672 name_given = 1;
673 else
674 name = get_default(remote_state, remote_state->current_branch,
675 &name_given);
677 ret = make_remote(remote_state, name, 0);
678 if (valid_remote_nick(name) && have_git_dir()) {
679 if (!valid_remote(ret))
680 read_remotes_file(remote_state, ret);
681 if (!valid_remote(ret))
682 read_branches_file(remote_state, ret);
684 if (name_given && !valid_remote(ret))
685 add_url_alias(remote_state, ret, name);
686 if (!valid_remote(ret))
687 return NULL;
689 validate_remote_url(ret);
691 return ret;
694 static inline struct remote *
695 remotes_remote_get(struct remote_state *remote_state, const char *name)
697 return remotes_remote_get_1(remote_state, name,
698 remotes_remote_for_branch);
701 struct remote *remote_get(const char *name)
703 read_config(the_repository);
704 return remotes_remote_get(the_repository->remote_state, name);
707 static inline struct remote *
708 remotes_pushremote_get(struct remote_state *remote_state, const char *name)
710 return remotes_remote_get_1(remote_state, name,
711 remotes_pushremote_for_branch);
714 struct remote *pushremote_get(const char *name)
716 read_config(the_repository);
717 return remotes_pushremote_get(the_repository->remote_state, name);
720 int remote_is_configured(struct remote *remote, int in_repo)
722 if (!remote)
723 return 0;
724 if (in_repo)
725 return remote->configured_in_repo;
726 return !!remote->origin;
729 int for_each_remote(each_remote_fn fn, void *priv)
731 int i, result = 0;
732 read_config(the_repository);
733 for (i = 0; i < the_repository->remote_state->remotes_nr && !result;
734 i++) {
735 struct remote *remote =
736 the_repository->remote_state->remotes[i];
737 if (!remote)
738 continue;
739 result = fn(remote, priv);
741 return result;
744 static void handle_duplicate(struct ref *ref1, struct ref *ref2)
746 if (strcmp(ref1->name, ref2->name)) {
747 if (ref1->fetch_head_status != FETCH_HEAD_IGNORE &&
748 ref2->fetch_head_status != FETCH_HEAD_IGNORE) {
749 die(_("Cannot fetch both %s and %s to %s"),
750 ref1->name, ref2->name, ref2->peer_ref->name);
751 } else if (ref1->fetch_head_status != FETCH_HEAD_IGNORE &&
752 ref2->fetch_head_status == FETCH_HEAD_IGNORE) {
753 warning(_("%s usually tracks %s, not %s"),
754 ref2->peer_ref->name, ref2->name, ref1->name);
755 } else if (ref1->fetch_head_status == FETCH_HEAD_IGNORE &&
756 ref2->fetch_head_status == FETCH_HEAD_IGNORE) {
757 die(_("%s tracks both %s and %s"),
758 ref2->peer_ref->name, ref1->name, ref2->name);
759 } else {
761 * This last possibility doesn't occur because
762 * FETCH_HEAD_IGNORE entries always appear at
763 * the end of the list.
765 BUG("Internal error");
768 free(ref2->peer_ref);
769 free(ref2);
772 struct ref *ref_remove_duplicates(struct ref *ref_map)
774 struct string_list refs = STRING_LIST_INIT_NODUP;
775 struct ref *retval = NULL;
776 struct ref **p = &retval;
778 while (ref_map) {
779 struct ref *ref = ref_map;
781 ref_map = ref_map->next;
782 ref->next = NULL;
784 if (!ref->peer_ref) {
785 *p = ref;
786 p = &ref->next;
787 } else {
788 struct string_list_item *item =
789 string_list_insert(&refs, ref->peer_ref->name);
791 if (item->util) {
792 /* Entry already existed */
793 handle_duplicate((struct ref *)item->util, ref);
794 } else {
795 *p = ref;
796 p = &ref->next;
797 item->util = ref;
802 string_list_clear(&refs, 0);
803 return retval;
806 int remote_has_url(struct remote *remote, const char *url)
808 int i;
809 for (i = 0; i < remote->url_nr; i++) {
810 if (!strcmp(remote->url[i], url))
811 return 1;
813 return 0;
816 static int match_name_with_pattern(const char *key, const char *name,
817 const char *value, char **result)
819 const char *kstar = strchr(key, '*');
820 size_t klen;
821 size_t ksuffixlen;
822 size_t namelen;
823 int ret;
824 if (!kstar)
825 die(_("key '%s' of pattern had no '*'"), key);
826 klen = kstar - key;
827 ksuffixlen = strlen(kstar + 1);
828 namelen = strlen(name);
829 ret = !strncmp(name, key, klen) && namelen >= klen + ksuffixlen &&
830 !memcmp(name + namelen - ksuffixlen, kstar + 1, ksuffixlen);
831 if (ret && value) {
832 struct strbuf sb = STRBUF_INIT;
833 const char *vstar = strchr(value, '*');
834 if (!vstar)
835 die(_("value '%s' of pattern has no '*'"), value);
836 strbuf_add(&sb, value, vstar - value);
837 strbuf_add(&sb, name + klen, namelen - klen - ksuffixlen);
838 strbuf_addstr(&sb, vstar + 1);
839 *result = strbuf_detach(&sb, NULL);
841 return ret;
844 static int refspec_match(const struct refspec_item *refspec,
845 const char *name)
847 if (refspec->pattern)
848 return match_name_with_pattern(refspec->src, name, NULL, NULL);
850 return !strcmp(refspec->src, name);
853 int omit_name_by_refspec(const char *name, struct refspec *rs)
855 int i;
857 for (i = 0; i < rs->nr; i++) {
858 if (rs->items[i].negative && refspec_match(&rs->items[i], name))
859 return 1;
861 return 0;
864 struct ref *apply_negative_refspecs(struct ref *ref_map, struct refspec *rs)
866 struct ref **tail;
868 for (tail = &ref_map; *tail; ) {
869 struct ref *ref = *tail;
871 if (omit_name_by_refspec(ref->name, rs)) {
872 *tail = ref->next;
873 free(ref->peer_ref);
874 free(ref);
875 } else
876 tail = &ref->next;
879 return ref_map;
882 static int query_matches_negative_refspec(struct refspec *rs, struct refspec_item *query)
884 int i, matched_negative = 0;
885 int find_src = !query->src;
886 struct string_list reversed = STRING_LIST_INIT_NODUP;
887 const char *needle = find_src ? query->dst : query->src;
890 * Check whether the queried ref matches any negative refpsec. If so,
891 * then we should ultimately treat this as not matching the query at
892 * all.
894 * Note that negative refspecs always match the source, but the query
895 * item uses the destination. To handle this, we apply pattern
896 * refspecs in reverse to figure out if the query source matches any
897 * of the negative refspecs.
899 * The first loop finds and expands all positive refspecs
900 * matched by the queried ref.
902 * The second loop checks if any of the results of the first loop
903 * match any negative refspec.
905 for (i = 0; i < rs->nr; i++) {
906 struct refspec_item *refspec = &rs->items[i];
907 char *expn_name;
909 if (refspec->negative)
910 continue;
912 /* Note the reversal of src and dst */
913 if (refspec->pattern) {
914 const char *key = refspec->dst ? refspec->dst : refspec->src;
915 const char *value = refspec->src;
917 if (match_name_with_pattern(key, needle, value, &expn_name))
918 string_list_append_nodup(&reversed, expn_name);
919 } else if (refspec->matching) {
920 /* For the special matching refspec, any query should match */
921 string_list_append(&reversed, needle);
922 } else if (!refspec->src) {
923 BUG("refspec->src should not be null here");
924 } else if (!strcmp(needle, refspec->src)) {
925 string_list_append(&reversed, refspec->src);
929 for (i = 0; !matched_negative && i < reversed.nr; i++) {
930 if (omit_name_by_refspec(reversed.items[i].string, rs))
931 matched_negative = 1;
934 string_list_clear(&reversed, 0);
936 return matched_negative;
939 static void query_refspecs_multiple(struct refspec *rs,
940 struct refspec_item *query,
941 struct string_list *results)
943 int i;
944 int find_src = !query->src;
946 if (find_src && !query->dst)
947 BUG("query_refspecs_multiple: need either src or dst");
949 if (query_matches_negative_refspec(rs, query))
950 return;
952 for (i = 0; i < rs->nr; i++) {
953 struct refspec_item *refspec = &rs->items[i];
954 const char *key = find_src ? refspec->dst : refspec->src;
955 const char *value = find_src ? refspec->src : refspec->dst;
956 const char *needle = find_src ? query->dst : query->src;
957 char **result = find_src ? &query->src : &query->dst;
959 if (!refspec->dst || refspec->negative)
960 continue;
961 if (refspec->pattern) {
962 if (match_name_with_pattern(key, needle, value, result))
963 string_list_append_nodup(results, *result);
964 } else if (!strcmp(needle, key)) {
965 string_list_append(results, value);
970 int query_refspecs(struct refspec *rs, struct refspec_item *query)
972 int i;
973 int find_src = !query->src;
974 const char *needle = find_src ? query->dst : query->src;
975 char **result = find_src ? &query->src : &query->dst;
977 if (find_src && !query->dst)
978 BUG("query_refspecs: need either src or dst");
980 if (query_matches_negative_refspec(rs, query))
981 return -1;
983 for (i = 0; i < rs->nr; i++) {
984 struct refspec_item *refspec = &rs->items[i];
985 const char *key = find_src ? refspec->dst : refspec->src;
986 const char *value = find_src ? refspec->src : refspec->dst;
988 if (!refspec->dst || refspec->negative)
989 continue;
990 if (refspec->pattern) {
991 if (match_name_with_pattern(key, needle, value, result)) {
992 query->force = refspec->force;
993 return 0;
995 } else if (!strcmp(needle, key)) {
996 *result = xstrdup(value);
997 query->force = refspec->force;
998 return 0;
1001 return -1;
1004 char *apply_refspecs(struct refspec *rs, const char *name)
1006 struct refspec_item query;
1008 memset(&query, 0, sizeof(struct refspec_item));
1009 query.src = (char *)name;
1011 if (query_refspecs(rs, &query))
1012 return NULL;
1014 return query.dst;
1017 int remote_find_tracking(struct remote *remote, struct refspec_item *refspec)
1019 return query_refspecs(&remote->fetch, refspec);
1022 static struct ref *alloc_ref_with_prefix(const char *prefix, size_t prefixlen,
1023 const char *name)
1025 size_t len = strlen(name);
1026 struct ref *ref = xcalloc(1, st_add4(sizeof(*ref), prefixlen, len, 1));
1027 memcpy(ref->name, prefix, prefixlen);
1028 memcpy(ref->name + prefixlen, name, len);
1029 return ref;
1032 struct ref *alloc_ref(const char *name)
1034 return alloc_ref_with_prefix("", 0, name);
1037 struct ref *copy_ref(const struct ref *ref)
1039 struct ref *cpy;
1040 size_t len;
1041 if (!ref)
1042 return NULL;
1043 len = st_add3(sizeof(struct ref), strlen(ref->name), 1);
1044 cpy = xmalloc(len);
1045 memcpy(cpy, ref, len);
1046 cpy->next = NULL;
1047 cpy->symref = xstrdup_or_null(ref->symref);
1048 cpy->remote_status = xstrdup_or_null(ref->remote_status);
1049 cpy->peer_ref = copy_ref(ref->peer_ref);
1050 return cpy;
1053 struct ref *copy_ref_list(const struct ref *ref)
1055 struct ref *ret = NULL;
1056 struct ref **tail = &ret;
1057 while (ref) {
1058 *tail = copy_ref(ref);
1059 ref = ref->next;
1060 tail = &((*tail)->next);
1062 return ret;
1065 void free_one_ref(struct ref *ref)
1067 if (!ref)
1068 return;
1069 free_one_ref(ref->peer_ref);
1070 free(ref->remote_status);
1071 free(ref->symref);
1072 free(ref);
1075 void free_refs(struct ref *ref)
1077 struct ref *next;
1078 while (ref) {
1079 next = ref->next;
1080 free_one_ref(ref);
1081 ref = next;
1085 int ref_compare_name(const void *va, const void *vb)
1087 const struct ref *a = va, *b = vb;
1088 return strcmp(a->name, b->name);
1091 static void *ref_list_get_next(const void *a)
1093 return ((const struct ref *)a)->next;
1096 static void ref_list_set_next(void *a, void *next)
1098 ((struct ref *)a)->next = next;
1101 void sort_ref_list(struct ref **l, int (*cmp)(const void *, const void *))
1103 *l = llist_mergesort(*l, ref_list_get_next, ref_list_set_next, cmp);
1106 int count_refspec_match(const char *pattern,
1107 struct ref *refs,
1108 struct ref **matched_ref)
1110 int patlen = strlen(pattern);
1111 struct ref *matched_weak = NULL;
1112 struct ref *matched = NULL;
1113 int weak_match = 0;
1114 int match = 0;
1116 for (weak_match = match = 0; refs; refs = refs->next) {
1117 char *name = refs->name;
1118 int namelen = strlen(name);
1120 if (!refname_match(pattern, name))
1121 continue;
1123 /* A match is "weak" if it is with refs outside
1124 * heads or tags, and did not specify the pattern
1125 * in full (e.g. "refs/remotes/origin/master") or at
1126 * least from the toplevel (e.g. "remotes/origin/master");
1127 * otherwise "git push $URL master" would result in
1128 * ambiguity between remotes/origin/master and heads/master
1129 * at the remote site.
1131 if (namelen != patlen &&
1132 patlen != namelen - 5 &&
1133 !starts_with(name, "refs/heads/") &&
1134 !starts_with(name, "refs/tags/")) {
1135 /* We want to catch the case where only weak
1136 * matches are found and there are multiple
1137 * matches, and where more than one strong
1138 * matches are found, as ambiguous. One
1139 * strong match with zero or more weak matches
1140 * are acceptable as a unique match.
1142 matched_weak = refs;
1143 weak_match++;
1145 else {
1146 matched = refs;
1147 match++;
1150 if (!matched) {
1151 if (matched_ref)
1152 *matched_ref = matched_weak;
1153 return weak_match;
1155 else {
1156 if (matched_ref)
1157 *matched_ref = matched;
1158 return match;
1162 static void tail_link_ref(struct ref *ref, struct ref ***tail)
1164 **tail = ref;
1165 while (ref->next)
1166 ref = ref->next;
1167 *tail = &ref->next;
1170 static struct ref *alloc_delete_ref(void)
1172 struct ref *ref = alloc_ref("(delete)");
1173 oidclr(&ref->new_oid);
1174 return ref;
1177 static int try_explicit_object_name(const char *name,
1178 struct ref **match)
1180 struct object_id oid;
1182 if (!*name) {
1183 if (match)
1184 *match = alloc_delete_ref();
1185 return 0;
1188 if (get_oid(name, &oid))
1189 return -1;
1191 if (match) {
1192 *match = alloc_ref(name);
1193 oidcpy(&(*match)->new_oid, &oid);
1195 return 0;
1198 static struct ref *make_linked_ref(const char *name, struct ref ***tail)
1200 struct ref *ret = alloc_ref(name);
1201 tail_link_ref(ret, tail);
1202 return ret;
1205 static char *guess_ref(const char *name, struct ref *peer)
1207 struct strbuf buf = STRBUF_INIT;
1209 const char *r = resolve_ref_unsafe(peer->name, RESOLVE_REF_READING,
1210 NULL, NULL);
1211 if (!r)
1212 return NULL;
1214 if (starts_with(r, "refs/heads/")) {
1215 strbuf_addstr(&buf, "refs/heads/");
1216 } else if (starts_with(r, "refs/tags/")) {
1217 strbuf_addstr(&buf, "refs/tags/");
1218 } else {
1219 return NULL;
1222 strbuf_addstr(&buf, name);
1223 return strbuf_detach(&buf, NULL);
1226 static int match_explicit_lhs(struct ref *src,
1227 struct refspec_item *rs,
1228 struct ref **match,
1229 int *allocated_match)
1231 switch (count_refspec_match(rs->src, src, match)) {
1232 case 1:
1233 if (allocated_match)
1234 *allocated_match = 0;
1235 return 0;
1236 case 0:
1237 /* The source could be in the get_sha1() format
1238 * not a reference name. :refs/other is a
1239 * way to delete 'other' ref at the remote end.
1241 if (try_explicit_object_name(rs->src, match) < 0)
1242 return error(_("src refspec %s does not match any"), rs->src);
1243 if (allocated_match)
1244 *allocated_match = 1;
1245 return 0;
1246 default:
1247 return error(_("src refspec %s matches more than one"), rs->src);
1251 static void show_push_unqualified_ref_name_error(const char *dst_value,
1252 const char *matched_src_name)
1254 struct object_id oid;
1255 enum object_type type;
1258 * TRANSLATORS: "matches '%s'%" is the <dst> part of "git push
1259 * <remote> <src>:<dst>" push, and "being pushed ('%s')" is
1260 * the <src>.
1262 error(_("The destination you provided is not a full refname (i.e.,\n"
1263 "starting with \"refs/\"). We tried to guess what you meant by:\n"
1264 "\n"
1265 "- Looking for a ref that matches '%s' on the remote side.\n"
1266 "- Checking if the <src> being pushed ('%s')\n"
1267 " is a ref in \"refs/{heads,tags}/\". If so we add a corresponding\n"
1268 " refs/{heads,tags}/ prefix on the remote side.\n"
1269 "\n"
1270 "Neither worked, so we gave up. You must fully qualify the ref."),
1271 dst_value, matched_src_name);
1273 if (!advice_enabled(ADVICE_PUSH_UNQUALIFIED_REF_NAME))
1274 return;
1276 if (get_oid(matched_src_name, &oid))
1277 BUG("'%s' is not a valid object, "
1278 "match_explicit_lhs() should catch this!",
1279 matched_src_name);
1280 type = oid_object_info(the_repository, &oid, NULL);
1281 if (type == OBJ_COMMIT) {
1282 advise(_("The <src> part of the refspec is a commit object.\n"
1283 "Did you mean to create a new branch by pushing to\n"
1284 "'%s:refs/heads/%s'?"),
1285 matched_src_name, dst_value);
1286 } else if (type == OBJ_TAG) {
1287 advise(_("The <src> part of the refspec is a tag object.\n"
1288 "Did you mean to create a new tag by pushing to\n"
1289 "'%s:refs/tags/%s'?"),
1290 matched_src_name, dst_value);
1291 } else if (type == OBJ_TREE) {
1292 advise(_("The <src> part of the refspec is a tree object.\n"
1293 "Did you mean to tag a new tree by pushing to\n"
1294 "'%s:refs/tags/%s'?"),
1295 matched_src_name, dst_value);
1296 } else if (type == OBJ_BLOB) {
1297 advise(_("The <src> part of the refspec is a blob object.\n"
1298 "Did you mean to tag a new blob by pushing to\n"
1299 "'%s:refs/tags/%s'?"),
1300 matched_src_name, dst_value);
1301 } else {
1302 BUG("'%s' should be commit/tag/tree/blob, is '%d'",
1303 matched_src_name, type);
1307 static int match_explicit(struct ref *src, struct ref *dst,
1308 struct ref ***dst_tail,
1309 struct refspec_item *rs)
1311 struct ref *matched_src, *matched_dst;
1312 int allocated_src;
1314 const char *dst_value = rs->dst;
1315 char *dst_guess;
1317 if (rs->pattern || rs->matching || rs->negative)
1318 return 0;
1320 matched_src = matched_dst = NULL;
1321 if (match_explicit_lhs(src, rs, &matched_src, &allocated_src) < 0)
1322 return -1;
1324 if (!dst_value) {
1325 int flag;
1327 dst_value = resolve_ref_unsafe(matched_src->name,
1328 RESOLVE_REF_READING,
1329 NULL, &flag);
1330 if (!dst_value ||
1331 ((flag & REF_ISSYMREF) &&
1332 !starts_with(dst_value, "refs/heads/")))
1333 die(_("%s cannot be resolved to branch"),
1334 matched_src->name);
1337 switch (count_refspec_match(dst_value, dst, &matched_dst)) {
1338 case 1:
1339 break;
1340 case 0:
1341 if (starts_with(dst_value, "refs/")) {
1342 matched_dst = make_linked_ref(dst_value, dst_tail);
1343 } else if (is_null_oid(&matched_src->new_oid)) {
1344 error(_("unable to delete '%s': remote ref does not exist"),
1345 dst_value);
1346 } else if ((dst_guess = guess_ref(dst_value, matched_src))) {
1347 matched_dst = make_linked_ref(dst_guess, dst_tail);
1348 free(dst_guess);
1349 } else {
1350 show_push_unqualified_ref_name_error(dst_value,
1351 matched_src->name);
1353 break;
1354 default:
1355 matched_dst = NULL;
1356 error(_("dst refspec %s matches more than one"),
1357 dst_value);
1358 break;
1360 if (!matched_dst)
1361 return -1;
1362 if (matched_dst->peer_ref)
1363 return error(_("dst ref %s receives from more than one src"),
1364 matched_dst->name);
1365 else {
1366 matched_dst->peer_ref = allocated_src ?
1367 matched_src :
1368 copy_ref(matched_src);
1369 matched_dst->force = rs->force;
1371 return 0;
1374 static int match_explicit_refs(struct ref *src, struct ref *dst,
1375 struct ref ***dst_tail, struct refspec *rs)
1377 int i, errs;
1378 for (i = errs = 0; i < rs->nr; i++)
1379 errs += match_explicit(src, dst, dst_tail, &rs->items[i]);
1380 return errs;
1383 static char *get_ref_match(const struct refspec *rs, const struct ref *ref,
1384 int send_mirror, int direction,
1385 const struct refspec_item **ret_pat)
1387 const struct refspec_item *pat;
1388 char *name;
1389 int i;
1390 int matching_refs = -1;
1391 for (i = 0; i < rs->nr; i++) {
1392 const struct refspec_item *item = &rs->items[i];
1394 if (item->negative)
1395 continue;
1397 if (item->matching &&
1398 (matching_refs == -1 || item->force)) {
1399 matching_refs = i;
1400 continue;
1403 if (item->pattern) {
1404 const char *dst_side = item->dst ? item->dst : item->src;
1405 int match;
1406 if (direction == FROM_SRC)
1407 match = match_name_with_pattern(item->src, ref->name, dst_side, &name);
1408 else
1409 match = match_name_with_pattern(dst_side, ref->name, item->src, &name);
1410 if (match) {
1411 matching_refs = i;
1412 break;
1416 if (matching_refs == -1)
1417 return NULL;
1419 pat = &rs->items[matching_refs];
1420 if (pat->matching) {
1422 * "matching refs"; traditionally we pushed everything
1423 * including refs outside refs/heads/ hierarchy, but
1424 * that does not make much sense these days.
1426 if (!send_mirror && !starts_with(ref->name, "refs/heads/"))
1427 return NULL;
1428 name = xstrdup(ref->name);
1430 if (ret_pat)
1431 *ret_pat = pat;
1432 return name;
1435 static struct ref **tail_ref(struct ref **head)
1437 struct ref **tail = head;
1438 while (*tail)
1439 tail = &((*tail)->next);
1440 return tail;
1443 struct tips {
1444 struct commit **tip;
1445 int nr, alloc;
1448 static void add_to_tips(struct tips *tips, const struct object_id *oid)
1450 struct commit *commit;
1452 if (is_null_oid(oid))
1453 return;
1454 commit = lookup_commit_reference_gently(the_repository, oid, 1);
1455 if (!commit || (commit->object.flags & TMP_MARK))
1456 return;
1457 commit->object.flags |= TMP_MARK;
1458 ALLOC_GROW(tips->tip, tips->nr + 1, tips->alloc);
1459 tips->tip[tips->nr++] = commit;
1462 static void add_missing_tags(struct ref *src, struct ref **dst, struct ref ***dst_tail)
1464 struct string_list dst_tag = STRING_LIST_INIT_NODUP;
1465 struct string_list src_tag = STRING_LIST_INIT_NODUP;
1466 struct string_list_item *item;
1467 struct ref *ref;
1468 struct tips sent_tips;
1471 * Collect everything we know they would have at the end of
1472 * this push, and collect all tags they have.
1474 memset(&sent_tips, 0, sizeof(sent_tips));
1475 for (ref = *dst; ref; ref = ref->next) {
1476 if (ref->peer_ref &&
1477 !is_null_oid(&ref->peer_ref->new_oid))
1478 add_to_tips(&sent_tips, &ref->peer_ref->new_oid);
1479 else
1480 add_to_tips(&sent_tips, &ref->old_oid);
1481 if (starts_with(ref->name, "refs/tags/"))
1482 string_list_append(&dst_tag, ref->name);
1484 clear_commit_marks_many(sent_tips.nr, sent_tips.tip, TMP_MARK);
1486 string_list_sort(&dst_tag);
1488 /* Collect tags they do not have. */
1489 for (ref = src; ref; ref = ref->next) {
1490 if (!starts_with(ref->name, "refs/tags/"))
1491 continue; /* not a tag */
1492 if (string_list_has_string(&dst_tag, ref->name))
1493 continue; /* they already have it */
1494 if (oid_object_info(the_repository, &ref->new_oid, NULL) != OBJ_TAG)
1495 continue; /* be conservative */
1496 item = string_list_append(&src_tag, ref->name);
1497 item->util = ref;
1499 string_list_clear(&dst_tag, 0);
1502 * At this point, src_tag lists tags that are missing from
1503 * dst, and sent_tips lists the tips we are pushing or those
1504 * that we know they already have. An element in the src_tag
1505 * that is an ancestor of any of the sent_tips needs to be
1506 * sent to the other side.
1508 if (sent_tips.nr) {
1509 const int reachable_flag = 1;
1510 struct commit_list *found_commits;
1511 struct commit **src_commits;
1512 int nr_src_commits = 0, alloc_src_commits = 16;
1513 ALLOC_ARRAY(src_commits, alloc_src_commits);
1515 for_each_string_list_item(item, &src_tag) {
1516 struct ref *ref = item->util;
1517 struct commit *commit;
1519 if (is_null_oid(&ref->new_oid))
1520 continue;
1521 commit = lookup_commit_reference_gently(the_repository,
1522 &ref->new_oid,
1524 if (!commit)
1525 /* not pushing a commit, which is not an error */
1526 continue;
1528 ALLOC_GROW(src_commits, nr_src_commits + 1, alloc_src_commits);
1529 src_commits[nr_src_commits++] = commit;
1532 found_commits = get_reachable_subset(sent_tips.tip, sent_tips.nr,
1533 src_commits, nr_src_commits,
1534 reachable_flag);
1536 for_each_string_list_item(item, &src_tag) {
1537 struct ref *dst_ref;
1538 struct ref *ref = item->util;
1539 struct commit *commit;
1541 if (is_null_oid(&ref->new_oid))
1542 continue;
1543 commit = lookup_commit_reference_gently(the_repository,
1544 &ref->new_oid,
1546 if (!commit)
1547 /* not pushing a commit, which is not an error */
1548 continue;
1551 * Is this tag, which they do not have, reachable from
1552 * any of the commits we are sending?
1554 if (!(commit->object.flags & reachable_flag))
1555 continue;
1557 /* Add it in */
1558 dst_ref = make_linked_ref(ref->name, dst_tail);
1559 oidcpy(&dst_ref->new_oid, &ref->new_oid);
1560 dst_ref->peer_ref = copy_ref(ref);
1563 clear_commit_marks_many(nr_src_commits, src_commits, reachable_flag);
1564 free(src_commits);
1565 free_commit_list(found_commits);
1568 string_list_clear(&src_tag, 0);
1569 free(sent_tips.tip);
1572 struct ref *find_ref_by_name(const struct ref *list, const char *name)
1574 for ( ; list; list = list->next)
1575 if (!strcmp(list->name, name))
1576 return (struct ref *)list;
1577 return NULL;
1580 static void prepare_ref_index(struct string_list *ref_index, struct ref *ref)
1582 for ( ; ref; ref = ref->next)
1583 string_list_append_nodup(ref_index, ref->name)->util = ref;
1585 string_list_sort(ref_index);
1589 * Given only the set of local refs, sanity-check the set of push
1590 * refspecs. We can't catch all errors that match_push_refs would,
1591 * but we can catch some errors early before even talking to the
1592 * remote side.
1594 int check_push_refs(struct ref *src, struct refspec *rs)
1596 int ret = 0;
1597 int i;
1599 for (i = 0; i < rs->nr; i++) {
1600 struct refspec_item *item = &rs->items[i];
1602 if (item->pattern || item->matching || item->negative)
1603 continue;
1605 ret |= match_explicit_lhs(src, item, NULL, NULL);
1608 return ret;
1612 * Given the set of refs the local repository has, the set of refs the
1613 * remote repository has, and the refspec used for push, determine
1614 * what remote refs we will update and with what value by setting
1615 * peer_ref (which object is being pushed) and force (if the push is
1616 * forced) in elements of "dst". The function may add new elements to
1617 * dst (e.g. pushing to a new branch, done in match_explicit_refs).
1619 int match_push_refs(struct ref *src, struct ref **dst,
1620 struct refspec *rs, int flags)
1622 int send_all = flags & MATCH_REFS_ALL;
1623 int send_mirror = flags & MATCH_REFS_MIRROR;
1624 int send_prune = flags & MATCH_REFS_PRUNE;
1625 int errs;
1626 struct ref *ref, **dst_tail = tail_ref(dst);
1627 struct string_list dst_ref_index = STRING_LIST_INIT_NODUP;
1629 /* If no refspec is provided, use the default ":" */
1630 if (!rs->nr)
1631 refspec_append(rs, ":");
1633 errs = match_explicit_refs(src, *dst, &dst_tail, rs);
1635 /* pick the remainder */
1636 for (ref = src; ref; ref = ref->next) {
1637 struct string_list_item *dst_item;
1638 struct ref *dst_peer;
1639 const struct refspec_item *pat = NULL;
1640 char *dst_name;
1642 dst_name = get_ref_match(rs, ref, send_mirror, FROM_SRC, &pat);
1643 if (!dst_name)
1644 continue;
1646 if (!dst_ref_index.nr)
1647 prepare_ref_index(&dst_ref_index, *dst);
1649 dst_item = string_list_lookup(&dst_ref_index, dst_name);
1650 dst_peer = dst_item ? dst_item->util : NULL;
1651 if (dst_peer) {
1652 if (dst_peer->peer_ref)
1653 /* We're already sending something to this ref. */
1654 goto free_name;
1655 } else {
1656 if (pat->matching && !(send_all || send_mirror))
1658 * Remote doesn't have it, and we have no
1659 * explicit pattern, and we don't have
1660 * --all or --mirror.
1662 goto free_name;
1664 /* Create a new one and link it */
1665 dst_peer = make_linked_ref(dst_name, &dst_tail);
1666 oidcpy(&dst_peer->new_oid, &ref->new_oid);
1667 string_list_insert(&dst_ref_index,
1668 dst_peer->name)->util = dst_peer;
1670 dst_peer->peer_ref = copy_ref(ref);
1671 dst_peer->force = pat->force;
1672 free_name:
1673 free(dst_name);
1676 string_list_clear(&dst_ref_index, 0);
1678 if (flags & MATCH_REFS_FOLLOW_TAGS)
1679 add_missing_tags(src, dst, &dst_tail);
1681 if (send_prune) {
1682 struct string_list src_ref_index = STRING_LIST_INIT_NODUP;
1683 /* check for missing refs on the remote */
1684 for (ref = *dst; ref; ref = ref->next) {
1685 char *src_name;
1687 if (ref->peer_ref)
1688 /* We're already sending something to this ref. */
1689 continue;
1691 src_name = get_ref_match(rs, ref, send_mirror, FROM_DST, NULL);
1692 if (src_name) {
1693 if (!src_ref_index.nr)
1694 prepare_ref_index(&src_ref_index, src);
1695 if (!string_list_has_string(&src_ref_index,
1696 src_name))
1697 ref->peer_ref = alloc_delete_ref();
1698 free(src_name);
1701 string_list_clear(&src_ref_index, 0);
1704 *dst = apply_negative_refspecs(*dst, rs);
1706 if (errs)
1707 return -1;
1708 return 0;
1711 void set_ref_status_for_push(struct ref *remote_refs, int send_mirror,
1712 int force_update)
1714 struct ref *ref;
1716 for (ref = remote_refs; ref; ref = ref->next) {
1717 int force_ref_update = ref->force || force_update;
1718 int reject_reason = 0;
1720 if (ref->peer_ref)
1721 oidcpy(&ref->new_oid, &ref->peer_ref->new_oid);
1722 else if (!send_mirror)
1723 continue;
1725 ref->deletion = is_null_oid(&ref->new_oid);
1726 if (!ref->deletion &&
1727 oideq(&ref->old_oid, &ref->new_oid)) {
1728 ref->status = REF_STATUS_UPTODATE;
1729 continue;
1733 * If the remote ref has moved and is now different
1734 * from what we expect, reject any push.
1736 * It also is an error if the user told us to check
1737 * with the remote-tracking branch to find the value
1738 * to expect, but we did not have such a tracking
1739 * branch.
1741 * If the tip of the remote-tracking ref is unreachable
1742 * from any reflog entry of its local ref indicating a
1743 * possible update since checkout; reject the push.
1745 if (ref->expect_old_sha1) {
1746 if (!oideq(&ref->old_oid, &ref->old_oid_expect))
1747 reject_reason = REF_STATUS_REJECT_STALE;
1748 else if (ref->check_reachable && ref->unreachable)
1749 reject_reason =
1750 REF_STATUS_REJECT_REMOTE_UPDATED;
1751 else
1753 * If the ref isn't stale, and is reachable
1754 * from one of the reflog entries of
1755 * the local branch, force the update.
1757 force_ref_update = 1;
1761 * If the update isn't already rejected then check
1762 * the usual "must fast-forward" rules.
1764 * Decide whether an individual refspec A:B can be
1765 * pushed. The push will succeed if any of the
1766 * following are true:
1768 * (1) the remote reference B does not exist
1770 * (2) the remote reference B is being removed (i.e.,
1771 * pushing :B where no source is specified)
1773 * (3) the destination is not under refs/tags/, and
1774 * if the old and new value is a commit, the new
1775 * is a descendant of the old.
1777 * (4) it is forced using the +A:B notation, or by
1778 * passing the --force argument
1781 if (!reject_reason && !ref->deletion && !is_null_oid(&ref->old_oid)) {
1782 if (starts_with(ref->name, "refs/tags/"))
1783 reject_reason = REF_STATUS_REJECT_ALREADY_EXISTS;
1784 else if (!has_object_file(&ref->old_oid))
1785 reject_reason = REF_STATUS_REJECT_FETCH_FIRST;
1786 else if (!lookup_commit_reference_gently(the_repository, &ref->old_oid, 1) ||
1787 !lookup_commit_reference_gently(the_repository, &ref->new_oid, 1))
1788 reject_reason = REF_STATUS_REJECT_NEEDS_FORCE;
1789 else if (!ref_newer(&ref->new_oid, &ref->old_oid))
1790 reject_reason = REF_STATUS_REJECT_NONFASTFORWARD;
1794 * "--force" will defeat any rejection implemented
1795 * by the rules above.
1797 if (!force_ref_update)
1798 ref->status = reject_reason;
1799 else if (reject_reason)
1800 ref->forced_update = 1;
1804 static void set_merge(struct remote_state *remote_state, struct branch *ret)
1806 struct remote *remote;
1807 char *ref;
1808 struct object_id oid;
1809 int i;
1811 if (!ret)
1812 return; /* no branch */
1813 if (ret->merge)
1814 return; /* already run */
1815 if (!ret->remote_name || !ret->merge_nr) {
1817 * no merge config; let's make sure we don't confuse callers
1818 * with a non-zero merge_nr but a NULL merge
1820 ret->merge_nr = 0;
1821 return;
1824 remote = remotes_remote_get(remote_state, ret->remote_name);
1826 CALLOC_ARRAY(ret->merge, ret->merge_nr);
1827 for (i = 0; i < ret->merge_nr; i++) {
1828 ret->merge[i] = xcalloc(1, sizeof(**ret->merge));
1829 ret->merge[i]->src = xstrdup(ret->merge_name[i]);
1830 if (!remote_find_tracking(remote, ret->merge[i]) ||
1831 strcmp(ret->remote_name, "."))
1832 continue;
1833 if (dwim_ref(ret->merge_name[i], strlen(ret->merge_name[i]),
1834 &oid, &ref, 0) == 1)
1835 ret->merge[i]->dst = ref;
1836 else
1837 ret->merge[i]->dst = xstrdup(ret->merge_name[i]);
1841 struct branch *branch_get(const char *name)
1843 struct branch *ret;
1845 read_config(the_repository);
1846 if (!name || !*name || !strcmp(name, "HEAD"))
1847 ret = the_repository->remote_state->current_branch;
1848 else
1849 ret = make_branch(the_repository->remote_state, name,
1850 strlen(name));
1851 set_merge(the_repository->remote_state, ret);
1852 return ret;
1855 int branch_has_merge_config(struct branch *branch)
1857 return branch && !!branch->merge;
1860 int branch_merge_matches(struct branch *branch,
1861 int i,
1862 const char *refname)
1864 if (!branch || i < 0 || i >= branch->merge_nr)
1865 return 0;
1866 return refname_match(branch->merge[i]->src, refname);
1869 __attribute__((format (printf,2,3)))
1870 static const char *error_buf(struct strbuf *err, const char *fmt, ...)
1872 if (err) {
1873 va_list ap;
1874 va_start(ap, fmt);
1875 strbuf_vaddf(err, fmt, ap);
1876 va_end(ap);
1878 return NULL;
1881 const char *branch_get_upstream(struct branch *branch, struct strbuf *err)
1883 if (!branch)
1884 return error_buf(err, _("HEAD does not point to a branch"));
1886 if (!branch->merge || !branch->merge[0]) {
1888 * no merge config; is it because the user didn't define any,
1889 * or because it is not a real branch, and get_branch
1890 * auto-vivified it?
1892 if (!ref_exists(branch->refname))
1893 return error_buf(err, _("no such branch: '%s'"),
1894 branch->name);
1895 return error_buf(err,
1896 _("no upstream configured for branch '%s'"),
1897 branch->name);
1900 if (!branch->merge[0]->dst)
1901 return error_buf(err,
1902 _("upstream branch '%s' not stored as a remote-tracking branch"),
1903 branch->merge[0]->src);
1905 return branch->merge[0]->dst;
1908 static const char *tracking_for_push_dest(struct remote *remote,
1909 const char *refname,
1910 struct strbuf *err)
1912 char *ret;
1914 ret = apply_refspecs(&remote->fetch, refname);
1915 if (!ret)
1916 return error_buf(err,
1917 _("push destination '%s' on remote '%s' has no local tracking branch"),
1918 refname, remote->name);
1919 return ret;
1922 static const char *branch_get_push_1(struct remote_state *remote_state,
1923 struct branch *branch, struct strbuf *err)
1925 struct remote *remote;
1927 remote = remotes_remote_get(
1928 remote_state,
1929 remotes_pushremote_for_branch(remote_state, branch, NULL));
1930 if (!remote)
1931 return error_buf(err,
1932 _("branch '%s' has no remote for pushing"),
1933 branch->name);
1935 if (remote->push.nr) {
1936 char *dst;
1937 const char *ret;
1939 dst = apply_refspecs(&remote->push, branch->refname);
1940 if (!dst)
1941 return error_buf(err,
1942 _("push refspecs for '%s' do not include '%s'"),
1943 remote->name, branch->name);
1945 ret = tracking_for_push_dest(remote, dst, err);
1946 free(dst);
1947 return ret;
1950 if (remote->mirror)
1951 return tracking_for_push_dest(remote, branch->refname, err);
1953 switch (push_default) {
1954 case PUSH_DEFAULT_NOTHING:
1955 return error_buf(err, _("push has no destination (push.default is 'nothing')"));
1957 case PUSH_DEFAULT_MATCHING:
1958 case PUSH_DEFAULT_CURRENT:
1959 return tracking_for_push_dest(remote, branch->refname, err);
1961 case PUSH_DEFAULT_UPSTREAM:
1962 return branch_get_upstream(branch, err);
1964 case PUSH_DEFAULT_UNSPECIFIED:
1965 case PUSH_DEFAULT_SIMPLE:
1967 const char *up, *cur;
1969 up = branch_get_upstream(branch, err);
1970 if (!up)
1971 return NULL;
1972 cur = tracking_for_push_dest(remote, branch->refname, err);
1973 if (!cur)
1974 return NULL;
1975 if (strcmp(cur, up))
1976 return error_buf(err,
1977 _("cannot resolve 'simple' push to a single destination"));
1978 return cur;
1982 BUG("unhandled push situation");
1985 const char *branch_get_push(struct branch *branch, struct strbuf *err)
1987 read_config(the_repository);
1988 die_on_missing_branch(the_repository, branch);
1990 if (!branch)
1991 return error_buf(err, _("HEAD does not point to a branch"));
1993 if (!branch->push_tracking_ref)
1994 branch->push_tracking_ref = branch_get_push_1(
1995 the_repository->remote_state, branch, err);
1996 return branch->push_tracking_ref;
1999 static int ignore_symref_update(const char *refname, struct strbuf *scratch)
2001 return !refs_read_symbolic_ref(get_main_ref_store(the_repository), refname, scratch);
2005 * Create and return a list of (struct ref) consisting of copies of
2006 * each remote_ref that matches refspec. refspec must be a pattern.
2007 * Fill in the copies' peer_ref to describe the local tracking refs to
2008 * which they map. Omit any references that would map to an existing
2009 * local symbolic ref.
2011 static struct ref *get_expanded_map(const struct ref *remote_refs,
2012 const struct refspec_item *refspec)
2014 struct strbuf scratch = STRBUF_INIT;
2015 const struct ref *ref;
2016 struct ref *ret = NULL;
2017 struct ref **tail = &ret;
2019 for (ref = remote_refs; ref; ref = ref->next) {
2020 char *expn_name = NULL;
2022 strbuf_reset(&scratch);
2024 if (strchr(ref->name, '^'))
2025 continue; /* a dereference item */
2026 if (match_name_with_pattern(refspec->src, ref->name,
2027 refspec->dst, &expn_name) &&
2028 !ignore_symref_update(expn_name, &scratch)) {
2029 struct ref *cpy = copy_ref(ref);
2031 cpy->peer_ref = alloc_ref(expn_name);
2032 if (refspec->force)
2033 cpy->peer_ref->force = 1;
2034 *tail = cpy;
2035 tail = &cpy->next;
2037 free(expn_name);
2040 strbuf_release(&scratch);
2041 return ret;
2044 static const struct ref *find_ref_by_name_abbrev(const struct ref *refs, const char *name)
2046 const struct ref *ref;
2047 const struct ref *best_match = NULL;
2048 int best_score = 0;
2050 for (ref = refs; ref; ref = ref->next) {
2051 int score = refname_match(name, ref->name);
2053 if (best_score < score) {
2054 best_match = ref;
2055 best_score = score;
2058 return best_match;
2061 struct ref *get_remote_ref(const struct ref *remote_refs, const char *name)
2063 const struct ref *ref = find_ref_by_name_abbrev(remote_refs, name);
2065 if (!ref)
2066 return NULL;
2068 return copy_ref(ref);
2071 static struct ref *get_local_ref(const char *name)
2073 if (!name || name[0] == '\0')
2074 return NULL;
2076 if (starts_with(name, "refs/"))
2077 return alloc_ref(name);
2079 if (starts_with(name, "heads/") ||
2080 starts_with(name, "tags/") ||
2081 starts_with(name, "remotes/"))
2082 return alloc_ref_with_prefix("refs/", 5, name);
2084 return alloc_ref_with_prefix("refs/heads/", 11, name);
2087 int get_fetch_map(const struct ref *remote_refs,
2088 const struct refspec_item *refspec,
2089 struct ref ***tail,
2090 int missing_ok)
2092 struct ref *ref_map, **rmp;
2094 if (refspec->negative)
2095 return 0;
2097 if (refspec->pattern) {
2098 ref_map = get_expanded_map(remote_refs, refspec);
2099 } else {
2100 const char *name = refspec->src[0] ? refspec->src : "HEAD";
2102 if (refspec->exact_sha1) {
2103 ref_map = alloc_ref(name);
2104 get_oid_hex(name, &ref_map->old_oid);
2105 ref_map->exact_oid = 1;
2106 } else {
2107 ref_map = get_remote_ref(remote_refs, name);
2109 if (!missing_ok && !ref_map)
2110 die(_("couldn't find remote ref %s"), name);
2111 if (ref_map) {
2112 ref_map->peer_ref = get_local_ref(refspec->dst);
2113 if (ref_map->peer_ref && refspec->force)
2114 ref_map->peer_ref->force = 1;
2118 for (rmp = &ref_map; *rmp; ) {
2119 if ((*rmp)->peer_ref) {
2120 if (!starts_with((*rmp)->peer_ref->name, "refs/") ||
2121 check_refname_format((*rmp)->peer_ref->name, 0)) {
2122 struct ref *ignore = *rmp;
2123 error(_("* Ignoring funny ref '%s' locally"),
2124 (*rmp)->peer_ref->name);
2125 *rmp = (*rmp)->next;
2126 free(ignore->peer_ref);
2127 free(ignore);
2128 continue;
2131 rmp = &((*rmp)->next);
2134 if (ref_map)
2135 tail_link_ref(ref_map, tail);
2137 return 0;
2140 int resolve_remote_symref(struct ref *ref, struct ref *list)
2142 if (!ref->symref)
2143 return 0;
2144 for (; list; list = list->next)
2145 if (!strcmp(ref->symref, list->name)) {
2146 oidcpy(&ref->old_oid, &list->old_oid);
2147 return 0;
2149 return 1;
2153 * Compute the commit ahead/behind values for the pair branch_name, base.
2155 * If abf is AHEAD_BEHIND_FULL, compute the full ahead/behind and return the
2156 * counts in *num_ours and *num_theirs. If abf is AHEAD_BEHIND_QUICK, skip
2157 * the (potentially expensive) a/b computation (*num_ours and *num_theirs are
2158 * set to zero).
2160 * Returns -1 if num_ours and num_theirs could not be filled in (e.g., ref
2161 * does not exist). Returns 0 if the commits are identical. Returns 1 if
2162 * commits are different.
2165 static int stat_branch_pair(const char *branch_name, const char *base,
2166 int *num_ours, int *num_theirs,
2167 enum ahead_behind_flags abf)
2169 struct object_id oid;
2170 struct commit *ours, *theirs;
2171 struct rev_info revs;
2172 struct strvec argv = STRVEC_INIT;
2174 /* Cannot stat if what we used to build on no longer exists */
2175 if (read_ref(base, &oid))
2176 return -1;
2177 theirs = lookup_commit_reference(the_repository, &oid);
2178 if (!theirs)
2179 return -1;
2181 if (read_ref(branch_name, &oid))
2182 return -1;
2183 ours = lookup_commit_reference(the_repository, &oid);
2184 if (!ours)
2185 return -1;
2187 *num_theirs = *num_ours = 0;
2189 /* are we the same? */
2190 if (theirs == ours)
2191 return 0;
2192 if (abf == AHEAD_BEHIND_QUICK)
2193 return 1;
2194 if (abf != AHEAD_BEHIND_FULL)
2195 BUG("stat_branch_pair: invalid abf '%d'", abf);
2197 /* Run "rev-list --left-right ours...theirs" internally... */
2198 strvec_push(&argv, ""); /* ignored */
2199 strvec_push(&argv, "--left-right");
2200 strvec_pushf(&argv, "%s...%s",
2201 oid_to_hex(&ours->object.oid),
2202 oid_to_hex(&theirs->object.oid));
2203 strvec_push(&argv, "--");
2205 repo_init_revisions(the_repository, &revs, NULL);
2206 setup_revisions(argv.nr, argv.v, &revs, NULL);
2207 if (prepare_revision_walk(&revs))
2208 die(_("revision walk setup failed"));
2210 /* ... and count the commits on each side. */
2211 while (1) {
2212 struct commit *c = get_revision(&revs);
2213 if (!c)
2214 break;
2215 if (c->object.flags & SYMMETRIC_LEFT)
2216 (*num_ours)++;
2217 else
2218 (*num_theirs)++;
2221 /* clear object flags smudged by the above traversal */
2222 clear_commit_marks(ours, ALL_REV_FLAGS);
2223 clear_commit_marks(theirs, ALL_REV_FLAGS);
2225 strvec_clear(&argv);
2226 release_revisions(&revs);
2227 return 1;
2231 * Lookup the tracking branch for the given branch and if present, optionally
2232 * compute the commit ahead/behind values for the pair.
2234 * If for_push is true, the tracking branch refers to the push branch,
2235 * otherwise it refers to the upstream branch.
2237 * The name of the tracking branch (or NULL if it is not defined) is
2238 * returned via *tracking_name, if it is not itself NULL.
2240 * If abf is AHEAD_BEHIND_FULL, compute the full ahead/behind and return the
2241 * counts in *num_ours and *num_theirs. If abf is AHEAD_BEHIND_QUICK, skip
2242 * the (potentially expensive) a/b computation (*num_ours and *num_theirs are
2243 * set to zero).
2245 * Returns -1 if num_ours and num_theirs could not be filled in (e.g., no
2246 * upstream defined, or ref does not exist). Returns 0 if the commits are
2247 * identical. Returns 1 if commits are different.
2249 int stat_tracking_info(struct branch *branch, int *num_ours, int *num_theirs,
2250 const char **tracking_name, int for_push,
2251 enum ahead_behind_flags abf)
2253 const char *base;
2255 /* Cannot stat unless we are marked to build on top of somebody else. */
2256 base = for_push ? branch_get_push(branch, NULL) :
2257 branch_get_upstream(branch, NULL);
2258 if (tracking_name)
2259 *tracking_name = base;
2260 if (!base)
2261 return -1;
2263 return stat_branch_pair(branch->refname, base, num_ours, num_theirs, abf);
2267 * Return true when there is anything to report, otherwise false.
2269 int format_tracking_info(struct branch *branch, struct strbuf *sb,
2270 enum ahead_behind_flags abf)
2272 int ours, theirs, sti;
2273 const char *full_base;
2274 char *base;
2275 int upstream_is_gone = 0;
2277 sti = stat_tracking_info(branch, &ours, &theirs, &full_base, 0, abf);
2278 if (sti < 0) {
2279 if (!full_base)
2280 return 0;
2281 upstream_is_gone = 1;
2284 base = shorten_unambiguous_ref(full_base, 0);
2285 if (upstream_is_gone) {
2286 strbuf_addf(sb,
2287 _("Your branch is based on '%s', but the upstream is gone.\n"),
2288 base);
2289 if (advice_enabled(ADVICE_STATUS_HINTS))
2290 strbuf_addstr(sb,
2291 _(" (use \"git branch --unset-upstream\" to fixup)\n"));
2292 } else if (!sti) {
2293 strbuf_addf(sb,
2294 _("Your branch is up to date with '%s'.\n"),
2295 base);
2296 } else if (abf == AHEAD_BEHIND_QUICK) {
2297 strbuf_addf(sb,
2298 _("Your branch and '%s' refer to different commits.\n"),
2299 base);
2300 if (advice_enabled(ADVICE_STATUS_HINTS))
2301 strbuf_addf(sb, _(" (use \"%s\" for details)\n"),
2302 "git status --ahead-behind");
2303 } else if (!theirs) {
2304 strbuf_addf(sb,
2305 Q_("Your branch is ahead of '%s' by %d commit.\n",
2306 "Your branch is ahead of '%s' by %d commits.\n",
2307 ours),
2308 base, ours);
2309 if (advice_enabled(ADVICE_STATUS_HINTS))
2310 strbuf_addstr(sb,
2311 _(" (use \"git push\" to publish your local commits)\n"));
2312 } else if (!ours) {
2313 strbuf_addf(sb,
2314 Q_("Your branch is behind '%s' by %d commit, "
2315 "and can be fast-forwarded.\n",
2316 "Your branch is behind '%s' by %d commits, "
2317 "and can be fast-forwarded.\n",
2318 theirs),
2319 base, theirs);
2320 if (advice_enabled(ADVICE_STATUS_HINTS))
2321 strbuf_addstr(sb,
2322 _(" (use \"git pull\" to update your local branch)\n"));
2323 } else {
2324 strbuf_addf(sb,
2325 Q_("Your branch and '%s' have diverged,\n"
2326 "and have %d and %d different commit each, "
2327 "respectively.\n",
2328 "Your branch and '%s' have diverged,\n"
2329 "and have %d and %d different commits each, "
2330 "respectively.\n",
2331 ours + theirs),
2332 base, ours, theirs);
2333 if (advice_enabled(ADVICE_STATUS_HINTS))
2334 strbuf_addstr(sb,
2335 _(" (use \"git pull\" to merge the remote branch into yours)\n"));
2337 free(base);
2338 return 1;
2341 static int one_local_ref(const char *refname, const struct object_id *oid,
2342 int flag, void *cb_data)
2344 struct ref ***local_tail = cb_data;
2345 struct ref *ref;
2347 /* we already know it starts with refs/ to get here */
2348 if (check_refname_format(refname + 5, 0))
2349 return 0;
2351 ref = alloc_ref(refname);
2352 oidcpy(&ref->new_oid, oid);
2353 **local_tail = ref;
2354 *local_tail = &ref->next;
2355 return 0;
2358 struct ref *get_local_heads(void)
2360 struct ref *local_refs = NULL, **local_tail = &local_refs;
2362 for_each_ref(one_local_ref, &local_tail);
2363 return local_refs;
2366 struct ref *guess_remote_head(const struct ref *head,
2367 const struct ref *refs,
2368 int all)
2370 const struct ref *r;
2371 struct ref *list = NULL;
2372 struct ref **tail = &list;
2374 if (!head)
2375 return NULL;
2378 * Some transports support directly peeking at
2379 * where HEAD points; if that is the case, then
2380 * we don't have to guess.
2382 if (head->symref)
2383 return copy_ref(find_ref_by_name(refs, head->symref));
2385 /* If a remote branch exists with the default branch name, let's use it. */
2386 if (!all) {
2387 char *ref = xstrfmt("refs/heads/%s",
2388 git_default_branch_name(0));
2390 r = find_ref_by_name(refs, ref);
2391 free(ref);
2392 if (r && oideq(&r->old_oid, &head->old_oid))
2393 return copy_ref(r);
2395 /* Fall back to the hard-coded historical default */
2396 r = find_ref_by_name(refs, "refs/heads/master");
2397 if (r && oideq(&r->old_oid, &head->old_oid))
2398 return copy_ref(r);
2401 /* Look for another ref that points there */
2402 for (r = refs; r; r = r->next) {
2403 if (r != head &&
2404 starts_with(r->name, "refs/heads/") &&
2405 oideq(&r->old_oid, &head->old_oid)) {
2406 *tail = copy_ref(r);
2407 tail = &((*tail)->next);
2408 if (!all)
2409 break;
2413 return list;
2416 struct stale_heads_info {
2417 struct string_list *ref_names;
2418 struct ref **stale_refs_tail;
2419 struct refspec *rs;
2422 static int get_stale_heads_cb(const char *refname, const struct object_id *oid,
2423 int flags, void *cb_data)
2425 struct stale_heads_info *info = cb_data;
2426 struct string_list matches = STRING_LIST_INIT_DUP;
2427 struct refspec_item query;
2428 int i, stale = 1;
2429 memset(&query, 0, sizeof(struct refspec_item));
2430 query.dst = (char *)refname;
2432 query_refspecs_multiple(info->rs, &query, &matches);
2433 if (matches.nr == 0)
2434 goto clean_exit; /* No matches */
2437 * If we did find a suitable refspec and it's not a symref and
2438 * it's not in the list of refs that currently exist in that
2439 * remote, we consider it to be stale. In order to deal with
2440 * overlapping refspecs, we need to go over all of the
2441 * matching refs.
2443 if (flags & REF_ISSYMREF)
2444 goto clean_exit;
2446 for (i = 0; stale && i < matches.nr; i++)
2447 if (string_list_has_string(info->ref_names, matches.items[i].string))
2448 stale = 0;
2450 if (stale) {
2451 struct ref *ref = make_linked_ref(refname, &info->stale_refs_tail);
2452 oidcpy(&ref->new_oid, oid);
2455 clean_exit:
2456 string_list_clear(&matches, 0);
2457 return 0;
2460 struct ref *get_stale_heads(struct refspec *rs, struct ref *fetch_map)
2462 struct ref *ref, *stale_refs = NULL;
2463 struct string_list ref_names = STRING_LIST_INIT_NODUP;
2464 struct stale_heads_info info;
2466 info.ref_names = &ref_names;
2467 info.stale_refs_tail = &stale_refs;
2468 info.rs = rs;
2469 for (ref = fetch_map; ref; ref = ref->next)
2470 string_list_append(&ref_names, ref->name);
2471 string_list_sort(&ref_names);
2472 for_each_ref(get_stale_heads_cb, &info);
2473 string_list_clear(&ref_names, 0);
2474 return stale_refs;
2478 * Compare-and-swap
2480 static void clear_cas_option(struct push_cas_option *cas)
2482 int i;
2484 for (i = 0; i < cas->nr; i++)
2485 free(cas->entry[i].refname);
2486 free(cas->entry);
2487 memset(cas, 0, sizeof(*cas));
2490 static struct push_cas *add_cas_entry(struct push_cas_option *cas,
2491 const char *refname,
2492 size_t refnamelen)
2494 struct push_cas *entry;
2495 ALLOC_GROW(cas->entry, cas->nr + 1, cas->alloc);
2496 entry = &cas->entry[cas->nr++];
2497 memset(entry, 0, sizeof(*entry));
2498 entry->refname = xmemdupz(refname, refnamelen);
2499 return entry;
2502 static int parse_push_cas_option(struct push_cas_option *cas, const char *arg, int unset)
2504 const char *colon;
2505 struct push_cas *entry;
2507 if (unset) {
2508 /* "--no-<option>" */
2509 clear_cas_option(cas);
2510 return 0;
2513 if (!arg) {
2514 /* just "--<option>" */
2515 cas->use_tracking_for_rest = 1;
2516 return 0;
2519 /* "--<option>=refname" or "--<option>=refname:value" */
2520 colon = strchrnul(arg, ':');
2521 entry = add_cas_entry(cas, arg, colon - arg);
2522 if (!*colon)
2523 entry->use_tracking = 1;
2524 else if (!colon[1])
2525 oidclr(&entry->expect);
2526 else if (get_oid(colon + 1, &entry->expect))
2527 return error(_("cannot parse expected object name '%s'"),
2528 colon + 1);
2529 return 0;
2532 int parseopt_push_cas_option(const struct option *opt, const char *arg, int unset)
2534 return parse_push_cas_option(opt->value, arg, unset);
2537 int is_empty_cas(const struct push_cas_option *cas)
2539 return !cas->use_tracking_for_rest && !cas->nr;
2543 * Look at remote.fetch refspec and see if we have a remote
2544 * tracking branch for the refname there. Fill the name of
2545 * the remote-tracking branch in *dst_refname, and the name
2546 * of the commit object at its tip in oid[].
2547 * If we cannot do so, return negative to signal an error.
2549 static int remote_tracking(struct remote *remote, const char *refname,
2550 struct object_id *oid, char **dst_refname)
2552 char *dst;
2554 dst = apply_refspecs(&remote->fetch, refname);
2555 if (!dst)
2556 return -1; /* no tracking ref for refname at remote */
2557 if (read_ref(dst, oid))
2558 return -1; /* we know what the tracking ref is but we cannot read it */
2560 *dst_refname = dst;
2561 return 0;
2565 * The struct "reflog_commit_array" and related helper functions
2566 * are used for collecting commits into an array during reflog
2567 * traversals in "check_and_collect_until()".
2569 struct reflog_commit_array {
2570 struct commit **item;
2571 size_t nr, alloc;
2574 #define REFLOG_COMMIT_ARRAY_INIT { 0 }
2576 /* Append a commit to the array. */
2577 static void append_commit(struct reflog_commit_array *arr,
2578 struct commit *commit)
2580 ALLOC_GROW(arr->item, arr->nr + 1, arr->alloc);
2581 arr->item[arr->nr++] = commit;
2584 /* Free and reset the array. */
2585 static void free_commit_array(struct reflog_commit_array *arr)
2587 FREE_AND_NULL(arr->item);
2588 arr->nr = arr->alloc = 0;
2591 struct check_and_collect_until_cb_data {
2592 struct commit *remote_commit;
2593 struct reflog_commit_array *local_commits;
2594 timestamp_t remote_reflog_timestamp;
2597 /* Get the timestamp of the latest entry. */
2598 static int peek_reflog(struct object_id *o_oid, struct object_id *n_oid,
2599 const char *ident, timestamp_t timestamp,
2600 int tz, const char *message, void *cb_data)
2602 timestamp_t *ts = cb_data;
2603 *ts = timestamp;
2604 return 1;
2607 static int check_and_collect_until(struct object_id *o_oid,
2608 struct object_id *n_oid,
2609 const char *ident, timestamp_t timestamp,
2610 int tz, const char *message, void *cb_data)
2612 struct commit *commit;
2613 struct check_and_collect_until_cb_data *cb = cb_data;
2615 /* An entry was found. */
2616 if (oideq(n_oid, &cb->remote_commit->object.oid))
2617 return 1;
2619 if ((commit = lookup_commit_reference(the_repository, n_oid)))
2620 append_commit(cb->local_commits, commit);
2623 * If the reflog entry timestamp is older than the remote ref's
2624 * latest reflog entry, there is no need to check or collect
2625 * entries older than this one.
2627 if (timestamp < cb->remote_reflog_timestamp)
2628 return -1;
2630 return 0;
2633 #define MERGE_BASES_BATCH_SIZE 8
2636 * Iterate through the reflog of the local ref to check if there is an entry
2637 * for the given remote-tracking ref; runs until the timestamp of an entry is
2638 * older than latest timestamp of remote-tracking ref's reflog. Any commits
2639 * are that seen along the way are collected into an array to check if the
2640 * remote-tracking ref is reachable from any of them.
2642 static int is_reachable_in_reflog(const char *local, const struct ref *remote)
2644 timestamp_t date;
2645 struct commit *commit;
2646 struct commit **chunk;
2647 struct check_and_collect_until_cb_data cb;
2648 struct reflog_commit_array arr = REFLOG_COMMIT_ARRAY_INIT;
2649 size_t size = 0;
2650 int ret = 0;
2652 commit = lookup_commit_reference(the_repository, &remote->old_oid);
2653 if (!commit)
2654 goto cleanup_return;
2657 * Get the timestamp from the latest entry
2658 * of the remote-tracking ref's reflog.
2660 for_each_reflog_ent_reverse(remote->tracking_ref, peek_reflog, &date);
2662 cb.remote_commit = commit;
2663 cb.local_commits = &arr;
2664 cb.remote_reflog_timestamp = date;
2665 ret = for_each_reflog_ent_reverse(local, check_and_collect_until, &cb);
2667 /* We found an entry in the reflog. */
2668 if (ret > 0)
2669 goto cleanup_return;
2672 * Check if the remote commit is reachable from any
2673 * of the commits in the collected array, in batches.
2675 for (chunk = arr.item; chunk < arr.item + arr.nr; chunk += size) {
2676 size = arr.item + arr.nr - chunk;
2677 if (MERGE_BASES_BATCH_SIZE < size)
2678 size = MERGE_BASES_BATCH_SIZE;
2680 if ((ret = in_merge_bases_many(commit, size, chunk)))
2681 break;
2684 cleanup_return:
2685 free_commit_array(&arr);
2686 return ret;
2690 * Check for reachability of a remote-tracking
2691 * ref in the reflog entries of its local ref.
2693 static void check_if_includes_upstream(struct ref *remote)
2695 struct ref *local = get_local_ref(remote->name);
2696 if (!local)
2697 return;
2699 if (is_reachable_in_reflog(local->name, remote) <= 0)
2700 remote->unreachable = 1;
2703 static void apply_cas(struct push_cas_option *cas,
2704 struct remote *remote,
2705 struct ref *ref)
2707 int i;
2709 /* Find an explicit --<option>=<name>[:<value>] entry */
2710 for (i = 0; i < cas->nr; i++) {
2711 struct push_cas *entry = &cas->entry[i];
2712 if (!refname_match(entry->refname, ref->name))
2713 continue;
2714 ref->expect_old_sha1 = 1;
2715 if (!entry->use_tracking)
2716 oidcpy(&ref->old_oid_expect, &entry->expect);
2717 else if (remote_tracking(remote, ref->name,
2718 &ref->old_oid_expect,
2719 &ref->tracking_ref))
2720 oidclr(&ref->old_oid_expect);
2721 else
2722 ref->check_reachable = cas->use_force_if_includes;
2723 return;
2726 /* Are we using "--<option>" to cover all? */
2727 if (!cas->use_tracking_for_rest)
2728 return;
2730 ref->expect_old_sha1 = 1;
2731 if (remote_tracking(remote, ref->name,
2732 &ref->old_oid_expect,
2733 &ref->tracking_ref))
2734 oidclr(&ref->old_oid_expect);
2735 else
2736 ref->check_reachable = cas->use_force_if_includes;
2739 void apply_push_cas(struct push_cas_option *cas,
2740 struct remote *remote,
2741 struct ref *remote_refs)
2743 struct ref *ref;
2744 for (ref = remote_refs; ref; ref = ref->next) {
2745 apply_cas(cas, remote, ref);
2748 * If "compare-and-swap" is in "use_tracking[_for_rest]"
2749 * mode, and if "--force-if-includes" was specified, run
2750 * the check.
2752 if (ref->check_reachable)
2753 check_if_includes_upstream(ref);
2757 struct remote_state *remote_state_new(void)
2759 struct remote_state *r = xmalloc(sizeof(*r));
2761 memset(r, 0, sizeof(*r));
2763 hashmap_init(&r->remotes_hash, remotes_hash_cmp, NULL, 0);
2764 hashmap_init(&r->branches_hash, branches_hash_cmp, NULL, 0);
2765 return r;
2768 void remote_state_clear(struct remote_state *remote_state)
2770 int i;
2772 for (i = 0; i < remote_state->remotes_nr; i++)
2773 remote_clear(remote_state->remotes[i]);
2774 FREE_AND_NULL(remote_state->remotes);
2775 remote_state->remotes_alloc = 0;
2776 remote_state->remotes_nr = 0;
2778 hashmap_clear_and_free(&remote_state->remotes_hash, struct remote, ent);
2779 hashmap_clear_and_free(&remote_state->branches_hash, struct remote, ent);
2783 * Returns 1 if it was the last chop before ':'.
2785 static int chop_last_dir(char **remoteurl, int is_relative)
2787 char *rfind = find_last_dir_sep(*remoteurl);
2788 if (rfind) {
2789 *rfind = '\0';
2790 return 0;
2793 rfind = strrchr(*remoteurl, ':');
2794 if (rfind) {
2795 *rfind = '\0';
2796 return 1;
2799 if (is_relative || !strcmp(".", *remoteurl))
2800 die(_("cannot strip one component off url '%s'"),
2801 *remoteurl);
2803 free(*remoteurl);
2804 *remoteurl = xstrdup(".");
2805 return 0;
2808 char *relative_url(const char *remote_url, const char *url,
2809 const char *up_path)
2811 int is_relative = 0;
2812 int colonsep = 0;
2813 char *out;
2814 char *remoteurl;
2815 struct strbuf sb = STRBUF_INIT;
2816 size_t len;
2818 if (!url_is_local_not_ssh(url) || is_absolute_path(url))
2819 return xstrdup(url);
2821 len = strlen(remote_url);
2822 if (!len)
2823 BUG("invalid empty remote_url");
2825 remoteurl = xstrdup(remote_url);
2826 if (is_dir_sep(remoteurl[len-1]))
2827 remoteurl[len-1] = '\0';
2829 if (!url_is_local_not_ssh(remoteurl) || is_absolute_path(remoteurl))
2830 is_relative = 0;
2831 else {
2832 is_relative = 1;
2834 * Prepend a './' to ensure all relative
2835 * remoteurls start with './' or '../'
2837 if (!starts_with_dot_slash_native(remoteurl) &&
2838 !starts_with_dot_dot_slash_native(remoteurl)) {
2839 strbuf_reset(&sb);
2840 strbuf_addf(&sb, "./%s", remoteurl);
2841 free(remoteurl);
2842 remoteurl = strbuf_detach(&sb, NULL);
2846 * When the url starts with '../', remove that and the
2847 * last directory in remoteurl.
2849 while (*url) {
2850 if (starts_with_dot_dot_slash_native(url)) {
2851 url += 3;
2852 colonsep |= chop_last_dir(&remoteurl, is_relative);
2853 } else if (starts_with_dot_slash_native(url))
2854 url += 2;
2855 else
2856 break;
2858 strbuf_reset(&sb);
2859 strbuf_addf(&sb, "%s%s%s", remoteurl, colonsep ? ":" : "/", url);
2860 if (ends_with(url, "/"))
2861 strbuf_setlen(&sb, sb.len - 1);
2862 free(remoteurl);
2864 if (starts_with_dot_slash_native(sb.buf))
2865 out = xstrdup(sb.buf + 2);
2866 else
2867 out = xstrdup(sb.buf);
2869 if (!up_path || !is_relative) {
2870 strbuf_release(&sb);
2871 return out;
2874 strbuf_reset(&sb);
2875 strbuf_addf(&sb, "%s%s", up_path, out);
2876 free(out);
2877 return strbuf_detach(&sb, NULL);