Merge branch 'ks/ref-filter-signature'
[alt-git.git] / remote.c
blob6e13993bdc5d6d7879340313e98d6c9e65e43a67
1 #include "git-compat-util.h"
2 #include "abspath.h"
3 #include "alloc.h"
4 #include "config.h"
5 #include "environment.h"
6 #include "gettext.h"
7 #include "hex.h"
8 #include "remote.h"
9 #include "urlmatch.h"
10 #include "refs.h"
11 #include "refspec.h"
12 #include "object-name.h"
13 #include "object-store-ll.h"
14 #include "path.h"
15 #include "commit.h"
16 #include "diff.h"
17 #include "revision.h"
18 #include "dir.h"
19 #include "tag.h"
20 #include "setup.h"
21 #include "string-list.h"
22 #include "strvec.h"
23 #include "commit-reach.h"
24 #include "advice.h"
25 #include "connect.h"
26 #include "parse-options.h"
28 enum map_direction { FROM_SRC, FROM_DST };
30 struct counted_string {
31 size_t len;
32 const char *s;
35 static int valid_remote(const struct remote *remote)
37 return (!!remote->url) || (!!remote->foreign_vcs);
40 static const char *alias_url(const char *url, struct rewrites *r)
42 int i, j;
43 struct counted_string *longest;
44 int longest_i;
46 longest = NULL;
47 longest_i = -1;
48 for (i = 0; i < r->rewrite_nr; i++) {
49 if (!r->rewrite[i])
50 continue;
51 for (j = 0; j < r->rewrite[i]->instead_of_nr; j++) {
52 if (starts_with(url, r->rewrite[i]->instead_of[j].s) &&
53 (!longest ||
54 longest->len < r->rewrite[i]->instead_of[j].len)) {
55 longest = &(r->rewrite[i]->instead_of[j]);
56 longest_i = i;
60 if (!longest)
61 return url;
63 return xstrfmt("%s%s", r->rewrite[longest_i]->base, url + longest->len);
66 static void add_url(struct remote *remote, const char *url)
68 ALLOC_GROW(remote->url, remote->url_nr + 1, remote->url_alloc);
69 remote->url[remote->url_nr++] = url;
72 static void add_pushurl(struct remote *remote, const char *pushurl)
74 ALLOC_GROW(remote->pushurl, remote->pushurl_nr + 1, remote->pushurl_alloc);
75 remote->pushurl[remote->pushurl_nr++] = pushurl;
78 static void add_pushurl_alias(struct remote_state *remote_state,
79 struct remote *remote, const char *url)
81 const char *pushurl = alias_url(url, &remote_state->rewrites_push);
82 if (pushurl != url)
83 add_pushurl(remote, pushurl);
86 static void add_url_alias(struct remote_state *remote_state,
87 struct remote *remote, const char *url)
89 add_url(remote, alias_url(url, &remote_state->rewrites));
90 add_pushurl_alias(remote_state, remote, url);
93 struct remotes_hash_key {
94 const char *str;
95 int len;
98 static int remotes_hash_cmp(const void *cmp_data UNUSED,
99 const struct hashmap_entry *eptr,
100 const struct hashmap_entry *entry_or_key,
101 const void *keydata)
103 const struct remote *a, *b;
104 const struct remotes_hash_key *key = keydata;
106 a = container_of(eptr, const struct remote, ent);
107 b = container_of(entry_or_key, const struct remote, ent);
109 if (key)
110 return strncmp(a->name, key->str, key->len) || a->name[key->len];
111 else
112 return strcmp(a->name, b->name);
115 static struct remote *make_remote(struct remote_state *remote_state,
116 const char *name, int len)
118 struct remote *ret;
119 struct remotes_hash_key lookup;
120 struct hashmap_entry lookup_entry, *e;
122 if (!len)
123 len = strlen(name);
125 lookup.str = name;
126 lookup.len = len;
127 hashmap_entry_init(&lookup_entry, memhash(name, len));
129 e = hashmap_get(&remote_state->remotes_hash, &lookup_entry, &lookup);
130 if (e)
131 return container_of(e, struct remote, ent);
133 CALLOC_ARRAY(ret, 1);
134 ret->prune = -1; /* unspecified */
135 ret->prune_tags = -1; /* unspecified */
136 ret->name = xstrndup(name, len);
137 refspec_init(&ret->push, REFSPEC_PUSH);
138 refspec_init(&ret->fetch, REFSPEC_FETCH);
140 ALLOC_GROW(remote_state->remotes, remote_state->remotes_nr + 1,
141 remote_state->remotes_alloc);
142 remote_state->remotes[remote_state->remotes_nr++] = ret;
144 hashmap_entry_init(&ret->ent, lookup_entry.hash);
145 if (hashmap_put_entry(&remote_state->remotes_hash, ret, ent))
146 BUG("hashmap_put overwrote entry after hashmap_get returned NULL");
147 return ret;
150 static void remote_clear(struct remote *remote)
152 int i;
154 free((char *)remote->name);
155 free((char *)remote->foreign_vcs);
157 for (i = 0; i < remote->url_nr; i++)
158 free((char *)remote->url[i]);
159 FREE_AND_NULL(remote->url);
161 for (i = 0; i < remote->pushurl_nr; i++)
162 free((char *)remote->pushurl[i]);
163 FREE_AND_NULL(remote->pushurl);
164 free((char *)remote->receivepack);
165 free((char *)remote->uploadpack);
166 FREE_AND_NULL(remote->http_proxy);
167 FREE_AND_NULL(remote->http_proxy_authmethod);
170 static void add_merge(struct branch *branch, const char *name)
172 ALLOC_GROW(branch->merge_name, branch->merge_nr + 1,
173 branch->merge_alloc);
174 branch->merge_name[branch->merge_nr++] = name;
177 struct branches_hash_key {
178 const char *str;
179 int len;
182 static int branches_hash_cmp(const void *cmp_data UNUSED,
183 const struct hashmap_entry *eptr,
184 const struct hashmap_entry *entry_or_key,
185 const void *keydata)
187 const struct branch *a, *b;
188 const struct branches_hash_key *key = keydata;
190 a = container_of(eptr, const struct branch, ent);
191 b = container_of(entry_or_key, const struct branch, ent);
193 if (key)
194 return strncmp(a->name, key->str, key->len) ||
195 a->name[key->len];
196 else
197 return strcmp(a->name, b->name);
200 static struct branch *find_branch(struct remote_state *remote_state,
201 const char *name, size_t len)
203 struct branches_hash_key lookup;
204 struct hashmap_entry lookup_entry, *e;
206 lookup.str = name;
207 lookup.len = len;
208 hashmap_entry_init(&lookup_entry, memhash(name, len));
210 e = hashmap_get(&remote_state->branches_hash, &lookup_entry, &lookup);
211 if (e)
212 return container_of(e, struct branch, ent);
214 return NULL;
217 static void die_on_missing_branch(struct repository *repo,
218 struct branch *branch)
220 /* branch == NULL is always valid because it represents detached HEAD. */
221 if (branch &&
222 branch != find_branch(repo->remote_state, branch->name,
223 strlen(branch->name)))
224 die("branch %s was not found in the repository", branch->name);
227 static struct branch *make_branch(struct remote_state *remote_state,
228 const char *name, size_t len)
230 struct branch *ret;
232 ret = find_branch(remote_state, name, len);
233 if (ret)
234 return ret;
236 CALLOC_ARRAY(ret, 1);
237 ret->name = xstrndup(name, len);
238 ret->refname = xstrfmt("refs/heads/%s", ret->name);
240 hashmap_entry_init(&ret->ent, memhash(name, len));
241 if (hashmap_put_entry(&remote_state->branches_hash, ret, ent))
242 BUG("hashmap_put overwrote entry after hashmap_get returned NULL");
243 return ret;
246 static struct rewrite *make_rewrite(struct rewrites *r,
247 const char *base, size_t len)
249 struct rewrite *ret;
250 int i;
252 for (i = 0; i < r->rewrite_nr; i++) {
253 if (len == r->rewrite[i]->baselen &&
254 !strncmp(base, r->rewrite[i]->base, len))
255 return r->rewrite[i];
258 ALLOC_GROW(r->rewrite, r->rewrite_nr + 1, r->rewrite_alloc);
259 CALLOC_ARRAY(ret, 1);
260 r->rewrite[r->rewrite_nr++] = ret;
261 ret->base = xstrndup(base, len);
262 ret->baselen = len;
263 return ret;
266 static void add_instead_of(struct rewrite *rewrite, const char *instead_of)
268 ALLOC_GROW(rewrite->instead_of, rewrite->instead_of_nr + 1, rewrite->instead_of_alloc);
269 rewrite->instead_of[rewrite->instead_of_nr].s = instead_of;
270 rewrite->instead_of[rewrite->instead_of_nr].len = strlen(instead_of);
271 rewrite->instead_of_nr++;
274 static const char *skip_spaces(const char *s)
276 while (isspace(*s))
277 s++;
278 return s;
281 static void read_remotes_file(struct remote_state *remote_state,
282 struct remote *remote)
284 struct strbuf buf = STRBUF_INIT;
285 FILE *f = fopen_or_warn(git_path("remotes/%s", remote->name), "r");
287 if (!f)
288 return;
289 remote->configured_in_repo = 1;
290 remote->origin = REMOTE_REMOTES;
291 while (strbuf_getline(&buf, f) != EOF) {
292 const char *v;
294 strbuf_rtrim(&buf);
296 if (skip_prefix(buf.buf, "URL:", &v))
297 add_url_alias(remote_state, remote,
298 xstrdup(skip_spaces(v)));
299 else if (skip_prefix(buf.buf, "Push:", &v))
300 refspec_append(&remote->push, skip_spaces(v));
301 else if (skip_prefix(buf.buf, "Pull:", &v))
302 refspec_append(&remote->fetch, skip_spaces(v));
304 strbuf_release(&buf);
305 fclose(f);
308 static void read_branches_file(struct remote_state *remote_state,
309 struct remote *remote)
311 char *frag;
312 struct strbuf buf = STRBUF_INIT;
313 FILE *f = fopen_or_warn(git_path("branches/%s", remote->name), "r");
315 if (!f)
316 return;
318 strbuf_getline_lf(&buf, f);
319 fclose(f);
320 strbuf_trim(&buf);
321 if (!buf.len) {
322 strbuf_release(&buf);
323 return;
326 remote->configured_in_repo = 1;
327 remote->origin = REMOTE_BRANCHES;
330 * The branches file would have URL and optionally
331 * #branch specified. The default (or specified) branch is
332 * fetched and stored in the local branch matching the
333 * remote name.
335 frag = strchr(buf.buf, '#');
336 if (frag)
337 *(frag++) = '\0';
338 else
339 frag = (char *)git_default_branch_name(0);
341 add_url_alias(remote_state, remote, strbuf_detach(&buf, NULL));
342 refspec_appendf(&remote->fetch, "refs/heads/%s:refs/heads/%s",
343 frag, remote->name);
346 * Cogito compatible push: push current HEAD to remote #branch
347 * (master if missing)
349 refspec_appendf(&remote->push, "HEAD:refs/heads/%s", frag);
350 remote->fetch_tags = 1; /* always auto-follow */
353 static int handle_config(const char *key, const char *value,
354 const struct config_context *ctx, void *cb)
356 const char *name;
357 size_t namelen;
358 const char *subkey;
359 struct remote *remote;
360 struct branch *branch;
361 struct remote_state *remote_state = cb;
362 const struct key_value_info *kvi = ctx->kvi;
364 if (parse_config_key(key, "branch", &name, &namelen, &subkey) >= 0) {
365 /* There is no subsection. */
366 if (!name)
367 return 0;
368 /* There is a subsection, but it is empty. */
369 if (!namelen)
370 return -1;
371 branch = make_branch(remote_state, name, namelen);
372 if (!strcmp(subkey, "remote")) {
373 return git_config_string(&branch->remote_name, key, value);
374 } else if (!strcmp(subkey, "pushremote")) {
375 return git_config_string(&branch->pushremote_name, key, value);
376 } else if (!strcmp(subkey, "merge")) {
377 if (!value)
378 return config_error_nonbool(key);
379 add_merge(branch, xstrdup(value));
381 return 0;
383 if (parse_config_key(key, "url", &name, &namelen, &subkey) >= 0) {
384 struct rewrite *rewrite;
385 if (!name)
386 return 0;
387 if (!strcmp(subkey, "insteadof")) {
388 if (!value)
389 return config_error_nonbool(key);
390 rewrite = make_rewrite(&remote_state->rewrites, name,
391 namelen);
392 add_instead_of(rewrite, xstrdup(value));
393 } else if (!strcmp(subkey, "pushinsteadof")) {
394 if (!value)
395 return config_error_nonbool(key);
396 rewrite = make_rewrite(&remote_state->rewrites_push,
397 name, namelen);
398 add_instead_of(rewrite, xstrdup(value));
402 if (parse_config_key(key, "remote", &name, &namelen, &subkey) < 0)
403 return 0;
405 /* Handle remote.* variables */
406 if (!name && !strcmp(subkey, "pushdefault"))
407 return git_config_string(&remote_state->pushremote_name, key,
408 value);
410 if (!name)
411 return 0;
412 /* Handle remote.<name>.* variables */
413 if (*name == '/') {
414 warning(_("config remote shorthand cannot begin with '/': %s"),
415 name);
416 return 0;
418 remote = make_remote(remote_state, name, namelen);
419 remote->origin = REMOTE_CONFIG;
420 if (kvi->scope == CONFIG_SCOPE_LOCAL ||
421 kvi->scope == CONFIG_SCOPE_WORKTREE)
422 remote->configured_in_repo = 1;
423 if (!strcmp(subkey, "mirror"))
424 remote->mirror = git_config_bool(key, value);
425 else if (!strcmp(subkey, "skipdefaultupdate"))
426 remote->skip_default_update = git_config_bool(key, value);
427 else if (!strcmp(subkey, "skipfetchall"))
428 remote->skip_default_update = git_config_bool(key, value);
429 else if (!strcmp(subkey, "prune"))
430 remote->prune = git_config_bool(key, value);
431 else if (!strcmp(subkey, "prunetags"))
432 remote->prune_tags = git_config_bool(key, value);
433 else if (!strcmp(subkey, "url")) {
434 const char *v;
435 if (git_config_string(&v, key, value))
436 return -1;
437 add_url(remote, v);
438 } else if (!strcmp(subkey, "pushurl")) {
439 const char *v;
440 if (git_config_string(&v, key, value))
441 return -1;
442 add_pushurl(remote, v);
443 } else if (!strcmp(subkey, "push")) {
444 const char *v;
445 if (git_config_string(&v, key, value))
446 return -1;
447 refspec_append(&remote->push, v);
448 free((char *)v);
449 } else if (!strcmp(subkey, "fetch")) {
450 const char *v;
451 if (git_config_string(&v, key, value))
452 return -1;
453 refspec_append(&remote->fetch, v);
454 free((char *)v);
455 } else if (!strcmp(subkey, "receivepack")) {
456 const char *v;
457 if (git_config_string(&v, key, value))
458 return -1;
459 if (!remote->receivepack)
460 remote->receivepack = v;
461 else
462 error(_("more than one receivepack given, using the first"));
463 } else if (!strcmp(subkey, "uploadpack")) {
464 const char *v;
465 if (git_config_string(&v, key, value))
466 return -1;
467 if (!remote->uploadpack)
468 remote->uploadpack = v;
469 else
470 error(_("more than one uploadpack given, using the first"));
471 } else if (!strcmp(subkey, "tagopt")) {
472 if (!strcmp(value, "--no-tags"))
473 remote->fetch_tags = -1;
474 else if (!strcmp(value, "--tags"))
475 remote->fetch_tags = 2;
476 } else if (!strcmp(subkey, "proxy")) {
477 return git_config_string((const char **)&remote->http_proxy,
478 key, value);
479 } else if (!strcmp(subkey, "proxyauthmethod")) {
480 return git_config_string((const char **)&remote->http_proxy_authmethod,
481 key, value);
482 } else if (!strcmp(subkey, "vcs")) {
483 return git_config_string(&remote->foreign_vcs, key, value);
485 return 0;
488 static void alias_all_urls(struct remote_state *remote_state)
490 int i, j;
491 for (i = 0; i < remote_state->remotes_nr; i++) {
492 int add_pushurl_aliases;
493 if (!remote_state->remotes[i])
494 continue;
495 for (j = 0; j < remote_state->remotes[i]->pushurl_nr; j++) {
496 remote_state->remotes[i]->pushurl[j] =
497 alias_url(remote_state->remotes[i]->pushurl[j],
498 &remote_state->rewrites);
500 add_pushurl_aliases = remote_state->remotes[i]->pushurl_nr == 0;
501 for (j = 0; j < remote_state->remotes[i]->url_nr; j++) {
502 if (add_pushurl_aliases)
503 add_pushurl_alias(
504 remote_state, remote_state->remotes[i],
505 remote_state->remotes[i]->url[j]);
506 remote_state->remotes[i]->url[j] =
507 alias_url(remote_state->remotes[i]->url[j],
508 &remote_state->rewrites);
513 static void read_config(struct repository *repo)
515 int flag;
517 if (repo->remote_state->initialized)
518 return;
519 repo->remote_state->initialized = 1;
521 repo->remote_state->current_branch = NULL;
522 if (startup_info->have_repository) {
523 const char *head_ref = refs_resolve_ref_unsafe(
524 get_main_ref_store(repo), "HEAD", 0, NULL, &flag);
525 if (head_ref && (flag & REF_ISSYMREF) &&
526 skip_prefix(head_ref, "refs/heads/", &head_ref)) {
527 repo->remote_state->current_branch = make_branch(
528 repo->remote_state, head_ref, strlen(head_ref));
531 repo_config(repo, handle_config, repo->remote_state);
532 alias_all_urls(repo->remote_state);
535 static int valid_remote_nick(const char *name)
537 if (!name[0] || is_dot_or_dotdot(name))
538 return 0;
540 /* remote nicknames cannot contain slashes */
541 while (*name)
542 if (is_dir_sep(*name++))
543 return 0;
544 return 1;
547 static const char *remotes_remote_for_branch(struct remote_state *remote_state,
548 struct branch *branch,
549 int *explicit)
551 if (branch && branch->remote_name) {
552 if (explicit)
553 *explicit = 1;
554 return branch->remote_name;
556 if (explicit)
557 *explicit = 0;
558 if (remote_state->remotes_nr == 1)
559 return remote_state->remotes[0]->name;
560 return "origin";
563 const char *remote_for_branch(struct branch *branch, int *explicit)
565 read_config(the_repository);
566 die_on_missing_branch(the_repository, branch);
568 return remotes_remote_for_branch(the_repository->remote_state, branch,
569 explicit);
572 static const char *
573 remotes_pushremote_for_branch(struct remote_state *remote_state,
574 struct branch *branch, int *explicit)
576 if (branch && branch->pushremote_name) {
577 if (explicit)
578 *explicit = 1;
579 return branch->pushremote_name;
581 if (remote_state->pushremote_name) {
582 if (explicit)
583 *explicit = 1;
584 return remote_state->pushremote_name;
586 return remotes_remote_for_branch(remote_state, branch, explicit);
589 const char *pushremote_for_branch(struct branch *branch, int *explicit)
591 read_config(the_repository);
592 die_on_missing_branch(the_repository, branch);
594 return remotes_pushremote_for_branch(the_repository->remote_state,
595 branch, explicit);
598 static struct remote *remotes_remote_get(struct remote_state *remote_state,
599 const char *name);
601 const char *remote_ref_for_branch(struct branch *branch, int for_push)
603 read_config(the_repository);
604 die_on_missing_branch(the_repository, branch);
606 if (branch) {
607 if (!for_push) {
608 if (branch->merge_nr) {
609 return branch->merge_name[0];
611 } else {
612 const char *dst,
613 *remote_name = remotes_pushremote_for_branch(
614 the_repository->remote_state, branch,
615 NULL);
616 struct remote *remote = remotes_remote_get(
617 the_repository->remote_state, remote_name);
619 if (remote && remote->push.nr &&
620 (dst = apply_refspecs(&remote->push,
621 branch->refname))) {
622 return dst;
626 return NULL;
629 static void validate_remote_url(struct remote *remote)
631 int i;
632 const char *value;
633 struct strbuf redacted = STRBUF_INIT;
634 int warn_not_die;
636 if (git_config_get_string_tmp("transfer.credentialsinurl", &value))
637 return;
639 if (!strcmp("warn", value))
640 warn_not_die = 1;
641 else if (!strcmp("die", value))
642 warn_not_die = 0;
643 else if (!strcmp("allow", value))
644 return;
645 else
646 die(_("unrecognized value transfer.credentialsInUrl: '%s'"), value);
648 for (i = 0; i < remote->url_nr; i++) {
649 struct url_info url_info = { 0 };
651 if (!url_normalize(remote->url[i], &url_info) ||
652 !url_info.passwd_off)
653 goto loop_cleanup;
655 strbuf_reset(&redacted);
656 strbuf_add(&redacted, url_info.url, url_info.passwd_off);
657 strbuf_addstr(&redacted, "<redacted>");
658 strbuf_addstr(&redacted,
659 url_info.url + url_info.passwd_off + url_info.passwd_len);
661 if (warn_not_die)
662 warning(_("URL '%s' uses plaintext credentials"), redacted.buf);
663 else
664 die(_("URL '%s' uses plaintext credentials"), redacted.buf);
666 loop_cleanup:
667 free(url_info.url);
670 strbuf_release(&redacted);
673 static struct remote *
674 remotes_remote_get_1(struct remote_state *remote_state, const char *name,
675 const char *(*get_default)(struct remote_state *,
676 struct branch *, int *))
678 struct remote *ret;
679 int name_given = 0;
681 if (name)
682 name_given = 1;
683 else
684 name = get_default(remote_state, remote_state->current_branch,
685 &name_given);
687 ret = make_remote(remote_state, name, 0);
688 if (valid_remote_nick(name) && have_git_dir()) {
689 if (!valid_remote(ret))
690 read_remotes_file(remote_state, ret);
691 if (!valid_remote(ret))
692 read_branches_file(remote_state, ret);
694 if (name_given && !valid_remote(ret))
695 add_url_alias(remote_state, ret, name);
696 if (!valid_remote(ret))
697 return NULL;
699 validate_remote_url(ret);
701 return ret;
704 static inline struct remote *
705 remotes_remote_get(struct remote_state *remote_state, const char *name)
707 return remotes_remote_get_1(remote_state, name,
708 remotes_remote_for_branch);
711 struct remote *remote_get(const char *name)
713 read_config(the_repository);
714 return remotes_remote_get(the_repository->remote_state, name);
717 static inline struct remote *
718 remotes_pushremote_get(struct remote_state *remote_state, const char *name)
720 return remotes_remote_get_1(remote_state, name,
721 remotes_pushremote_for_branch);
724 struct remote *pushremote_get(const char *name)
726 read_config(the_repository);
727 return remotes_pushremote_get(the_repository->remote_state, name);
730 int remote_is_configured(struct remote *remote, int in_repo)
732 if (!remote)
733 return 0;
734 if (in_repo)
735 return remote->configured_in_repo;
736 return !!remote->origin;
739 int for_each_remote(each_remote_fn fn, void *priv)
741 int i, result = 0;
742 read_config(the_repository);
743 for (i = 0; i < the_repository->remote_state->remotes_nr && !result;
744 i++) {
745 struct remote *remote =
746 the_repository->remote_state->remotes[i];
747 if (!remote)
748 continue;
749 result = fn(remote, priv);
751 return result;
754 static void handle_duplicate(struct ref *ref1, struct ref *ref2)
756 if (strcmp(ref1->name, ref2->name)) {
757 if (ref1->fetch_head_status != FETCH_HEAD_IGNORE &&
758 ref2->fetch_head_status != FETCH_HEAD_IGNORE) {
759 die(_("Cannot fetch both %s and %s to %s"),
760 ref1->name, ref2->name, ref2->peer_ref->name);
761 } else if (ref1->fetch_head_status != FETCH_HEAD_IGNORE &&
762 ref2->fetch_head_status == FETCH_HEAD_IGNORE) {
763 warning(_("%s usually tracks %s, not %s"),
764 ref2->peer_ref->name, ref2->name, ref1->name);
765 } else if (ref1->fetch_head_status == FETCH_HEAD_IGNORE &&
766 ref2->fetch_head_status == FETCH_HEAD_IGNORE) {
767 die(_("%s tracks both %s and %s"),
768 ref2->peer_ref->name, ref1->name, ref2->name);
769 } else {
771 * This last possibility doesn't occur because
772 * FETCH_HEAD_IGNORE entries always appear at
773 * the end of the list.
775 BUG("Internal error");
778 free(ref2->peer_ref);
779 free(ref2);
782 struct ref *ref_remove_duplicates(struct ref *ref_map)
784 struct string_list refs = STRING_LIST_INIT_NODUP;
785 struct ref *retval = NULL;
786 struct ref **p = &retval;
788 while (ref_map) {
789 struct ref *ref = ref_map;
791 ref_map = ref_map->next;
792 ref->next = NULL;
794 if (!ref->peer_ref) {
795 *p = ref;
796 p = &ref->next;
797 } else {
798 struct string_list_item *item =
799 string_list_insert(&refs, ref->peer_ref->name);
801 if (item->util) {
802 /* Entry already existed */
803 handle_duplicate((struct ref *)item->util, ref);
804 } else {
805 *p = ref;
806 p = &ref->next;
807 item->util = ref;
812 string_list_clear(&refs, 0);
813 return retval;
816 int remote_has_url(struct remote *remote, const char *url)
818 int i;
819 for (i = 0; i < remote->url_nr; i++) {
820 if (!strcmp(remote->url[i], url))
821 return 1;
823 return 0;
826 static int match_name_with_pattern(const char *key, const char *name,
827 const char *value, char **result)
829 const char *kstar = strchr(key, '*');
830 size_t klen;
831 size_t ksuffixlen;
832 size_t namelen;
833 int ret;
834 if (!kstar)
835 die(_("key '%s' of pattern had no '*'"), key);
836 klen = kstar - key;
837 ksuffixlen = strlen(kstar + 1);
838 namelen = strlen(name);
839 ret = !strncmp(name, key, klen) && namelen >= klen + ksuffixlen &&
840 !memcmp(name + namelen - ksuffixlen, kstar + 1, ksuffixlen);
841 if (ret && value) {
842 struct strbuf sb = STRBUF_INIT;
843 const char *vstar = strchr(value, '*');
844 if (!vstar)
845 die(_("value '%s' of pattern has no '*'"), value);
846 strbuf_add(&sb, value, vstar - value);
847 strbuf_add(&sb, name + klen, namelen - klen - ksuffixlen);
848 strbuf_addstr(&sb, vstar + 1);
849 *result = strbuf_detach(&sb, NULL);
851 return ret;
854 static int refspec_match(const struct refspec_item *refspec,
855 const char *name)
857 if (refspec->pattern)
858 return match_name_with_pattern(refspec->src, name, NULL, NULL);
860 return !strcmp(refspec->src, name);
863 int omit_name_by_refspec(const char *name, struct refspec *rs)
865 int i;
867 for (i = 0; i < rs->nr; i++) {
868 if (rs->items[i].negative && refspec_match(&rs->items[i], name))
869 return 1;
871 return 0;
874 struct ref *apply_negative_refspecs(struct ref *ref_map, struct refspec *rs)
876 struct ref **tail;
878 for (tail = &ref_map; *tail; ) {
879 struct ref *ref = *tail;
881 if (omit_name_by_refspec(ref->name, rs)) {
882 *tail = ref->next;
883 free(ref->peer_ref);
884 free(ref);
885 } else
886 tail = &ref->next;
889 return ref_map;
892 static int query_matches_negative_refspec(struct refspec *rs, struct refspec_item *query)
894 int i, matched_negative = 0;
895 int find_src = !query->src;
896 struct string_list reversed = STRING_LIST_INIT_DUP;
897 const char *needle = find_src ? query->dst : query->src;
900 * Check whether the queried ref matches any negative refpsec. If so,
901 * then we should ultimately treat this as not matching the query at
902 * all.
904 * Note that negative refspecs always match the source, but the query
905 * item uses the destination. To handle this, we apply pattern
906 * refspecs in reverse to figure out if the query source matches any
907 * of the negative refspecs.
909 * The first loop finds and expands all positive refspecs
910 * matched by the queried ref.
912 * The second loop checks if any of the results of the first loop
913 * match any negative refspec.
915 for (i = 0; i < rs->nr; i++) {
916 struct refspec_item *refspec = &rs->items[i];
917 char *expn_name;
919 if (refspec->negative)
920 continue;
922 /* Note the reversal of src and dst */
923 if (refspec->pattern) {
924 const char *key = refspec->dst ? refspec->dst : refspec->src;
925 const char *value = refspec->src;
927 if (match_name_with_pattern(key, needle, value, &expn_name))
928 string_list_append_nodup(&reversed, expn_name);
929 } else if (refspec->matching) {
930 /* For the special matching refspec, any query should match */
931 string_list_append(&reversed, needle);
932 } else if (!refspec->src) {
933 BUG("refspec->src should not be null here");
934 } else if (!strcmp(needle, refspec->src)) {
935 string_list_append(&reversed, refspec->src);
939 for (i = 0; !matched_negative && i < reversed.nr; i++) {
940 if (omit_name_by_refspec(reversed.items[i].string, rs))
941 matched_negative = 1;
944 string_list_clear(&reversed, 0);
946 return matched_negative;
949 static void query_refspecs_multiple(struct refspec *rs,
950 struct refspec_item *query,
951 struct string_list *results)
953 int i;
954 int find_src = !query->src;
956 if (find_src && !query->dst)
957 BUG("query_refspecs_multiple: need either src or dst");
959 if (query_matches_negative_refspec(rs, query))
960 return;
962 for (i = 0; i < rs->nr; i++) {
963 struct refspec_item *refspec = &rs->items[i];
964 const char *key = find_src ? refspec->dst : refspec->src;
965 const char *value = find_src ? refspec->src : refspec->dst;
966 const char *needle = find_src ? query->dst : query->src;
967 char **result = find_src ? &query->src : &query->dst;
969 if (!refspec->dst || refspec->negative)
970 continue;
971 if (refspec->pattern) {
972 if (match_name_with_pattern(key, needle, value, result))
973 string_list_append_nodup(results, *result);
974 } else if (!strcmp(needle, key)) {
975 string_list_append(results, value);
980 int query_refspecs(struct refspec *rs, struct refspec_item *query)
982 int i;
983 int find_src = !query->src;
984 const char *needle = find_src ? query->dst : query->src;
985 char **result = find_src ? &query->src : &query->dst;
987 if (find_src && !query->dst)
988 BUG("query_refspecs: need either src or dst");
990 if (query_matches_negative_refspec(rs, query))
991 return -1;
993 for (i = 0; i < rs->nr; i++) {
994 struct refspec_item *refspec = &rs->items[i];
995 const char *key = find_src ? refspec->dst : refspec->src;
996 const char *value = find_src ? refspec->src : refspec->dst;
998 if (!refspec->dst || refspec->negative)
999 continue;
1000 if (refspec->pattern) {
1001 if (match_name_with_pattern(key, needle, value, result)) {
1002 query->force = refspec->force;
1003 return 0;
1005 } else if (!strcmp(needle, key)) {
1006 *result = xstrdup(value);
1007 query->force = refspec->force;
1008 return 0;
1011 return -1;
1014 char *apply_refspecs(struct refspec *rs, const char *name)
1016 struct refspec_item query;
1018 memset(&query, 0, sizeof(struct refspec_item));
1019 query.src = (char *)name;
1021 if (query_refspecs(rs, &query))
1022 return NULL;
1024 return query.dst;
1027 int remote_find_tracking(struct remote *remote, struct refspec_item *refspec)
1029 return query_refspecs(&remote->fetch, refspec);
1032 static struct ref *alloc_ref_with_prefix(const char *prefix, size_t prefixlen,
1033 const char *name)
1035 size_t len = strlen(name);
1036 struct ref *ref = xcalloc(1, st_add4(sizeof(*ref), prefixlen, len, 1));
1037 memcpy(ref->name, prefix, prefixlen);
1038 memcpy(ref->name + prefixlen, name, len);
1039 return ref;
1042 struct ref *alloc_ref(const char *name)
1044 return alloc_ref_with_prefix("", 0, name);
1047 struct ref *copy_ref(const struct ref *ref)
1049 struct ref *cpy;
1050 size_t len;
1051 if (!ref)
1052 return NULL;
1053 len = st_add3(sizeof(struct ref), strlen(ref->name), 1);
1054 cpy = xmalloc(len);
1055 memcpy(cpy, ref, len);
1056 cpy->next = NULL;
1057 cpy->symref = xstrdup_or_null(ref->symref);
1058 cpy->remote_status = xstrdup_or_null(ref->remote_status);
1059 cpy->peer_ref = copy_ref(ref->peer_ref);
1060 return cpy;
1063 struct ref *copy_ref_list(const struct ref *ref)
1065 struct ref *ret = NULL;
1066 struct ref **tail = &ret;
1067 while (ref) {
1068 *tail = copy_ref(ref);
1069 ref = ref->next;
1070 tail = &((*tail)->next);
1072 return ret;
1075 void free_one_ref(struct ref *ref)
1077 if (!ref)
1078 return;
1079 free_one_ref(ref->peer_ref);
1080 free(ref->remote_status);
1081 free(ref->symref);
1082 free(ref);
1085 void free_refs(struct ref *ref)
1087 struct ref *next;
1088 while (ref) {
1089 next = ref->next;
1090 free_one_ref(ref);
1091 ref = next;
1095 int count_refspec_match(const char *pattern,
1096 struct ref *refs,
1097 struct ref **matched_ref)
1099 int patlen = strlen(pattern);
1100 struct ref *matched_weak = NULL;
1101 struct ref *matched = NULL;
1102 int weak_match = 0;
1103 int match = 0;
1105 for (weak_match = match = 0; refs; refs = refs->next) {
1106 char *name = refs->name;
1107 int namelen = strlen(name);
1109 if (!refname_match(pattern, name))
1110 continue;
1112 /* A match is "weak" if it is with refs outside
1113 * heads or tags, and did not specify the pattern
1114 * in full (e.g. "refs/remotes/origin/master") or at
1115 * least from the toplevel (e.g. "remotes/origin/master");
1116 * otherwise "git push $URL master" would result in
1117 * ambiguity between remotes/origin/master and heads/master
1118 * at the remote site.
1120 if (namelen != patlen &&
1121 patlen != namelen - 5 &&
1122 !starts_with(name, "refs/heads/") &&
1123 !starts_with(name, "refs/tags/")) {
1124 /* We want to catch the case where only weak
1125 * matches are found and there are multiple
1126 * matches, and where more than one strong
1127 * matches are found, as ambiguous. One
1128 * strong match with zero or more weak matches
1129 * are acceptable as a unique match.
1131 matched_weak = refs;
1132 weak_match++;
1134 else {
1135 matched = refs;
1136 match++;
1139 if (!matched) {
1140 if (matched_ref)
1141 *matched_ref = matched_weak;
1142 return weak_match;
1144 else {
1145 if (matched_ref)
1146 *matched_ref = matched;
1147 return match;
1151 static void tail_link_ref(struct ref *ref, struct ref ***tail)
1153 **tail = ref;
1154 while (ref->next)
1155 ref = ref->next;
1156 *tail = &ref->next;
1159 static struct ref *alloc_delete_ref(void)
1161 struct ref *ref = alloc_ref("(delete)");
1162 oidclr(&ref->new_oid);
1163 return ref;
1166 static int try_explicit_object_name(const char *name,
1167 struct ref **match)
1169 struct object_id oid;
1171 if (!*name) {
1172 if (match)
1173 *match = alloc_delete_ref();
1174 return 0;
1177 if (repo_get_oid(the_repository, name, &oid))
1178 return -1;
1180 if (match) {
1181 *match = alloc_ref(name);
1182 oidcpy(&(*match)->new_oid, &oid);
1184 return 0;
1187 static struct ref *make_linked_ref(const char *name, struct ref ***tail)
1189 struct ref *ret = alloc_ref(name);
1190 tail_link_ref(ret, tail);
1191 return ret;
1194 static char *guess_ref(const char *name, struct ref *peer)
1196 struct strbuf buf = STRBUF_INIT;
1198 const char *r = resolve_ref_unsafe(peer->name, RESOLVE_REF_READING,
1199 NULL, NULL);
1200 if (!r)
1201 return NULL;
1203 if (starts_with(r, "refs/heads/")) {
1204 strbuf_addstr(&buf, "refs/heads/");
1205 } else if (starts_with(r, "refs/tags/")) {
1206 strbuf_addstr(&buf, "refs/tags/");
1207 } else {
1208 return NULL;
1211 strbuf_addstr(&buf, name);
1212 return strbuf_detach(&buf, NULL);
1215 static int match_explicit_lhs(struct ref *src,
1216 struct refspec_item *rs,
1217 struct ref **match,
1218 int *allocated_match)
1220 switch (count_refspec_match(rs->src, src, match)) {
1221 case 1:
1222 if (allocated_match)
1223 *allocated_match = 0;
1224 return 0;
1225 case 0:
1226 /* The source could be in the get_sha1() format
1227 * not a reference name. :refs/other is a
1228 * way to delete 'other' ref at the remote end.
1230 if (try_explicit_object_name(rs->src, match) < 0)
1231 return error(_("src refspec %s does not match any"), rs->src);
1232 if (allocated_match)
1233 *allocated_match = 1;
1234 return 0;
1235 default:
1236 return error(_("src refspec %s matches more than one"), rs->src);
1240 static void show_push_unqualified_ref_name_error(const char *dst_value,
1241 const char *matched_src_name)
1243 struct object_id oid;
1244 enum object_type type;
1247 * TRANSLATORS: "matches '%s'%" is the <dst> part of "git push
1248 * <remote> <src>:<dst>" push, and "being pushed ('%s')" is
1249 * the <src>.
1251 error(_("The destination you provided is not a full refname (i.e.,\n"
1252 "starting with \"refs/\"). We tried to guess what you meant by:\n"
1253 "\n"
1254 "- Looking for a ref that matches '%s' on the remote side.\n"
1255 "- Checking if the <src> being pushed ('%s')\n"
1256 " is a ref in \"refs/{heads,tags}/\". If so we add a corresponding\n"
1257 " refs/{heads,tags}/ prefix on the remote side.\n"
1258 "\n"
1259 "Neither worked, so we gave up. You must fully qualify the ref."),
1260 dst_value, matched_src_name);
1262 if (!advice_enabled(ADVICE_PUSH_UNQUALIFIED_REF_NAME))
1263 return;
1265 if (repo_get_oid(the_repository, matched_src_name, &oid))
1266 BUG("'%s' is not a valid object, "
1267 "match_explicit_lhs() should catch this!",
1268 matched_src_name);
1269 type = oid_object_info(the_repository, &oid, NULL);
1270 if (type == OBJ_COMMIT) {
1271 advise(_("The <src> part of the refspec is a commit object.\n"
1272 "Did you mean to create a new branch by pushing to\n"
1273 "'%s:refs/heads/%s'?"),
1274 matched_src_name, dst_value);
1275 } else if (type == OBJ_TAG) {
1276 advise(_("The <src> part of the refspec is a tag object.\n"
1277 "Did you mean to create a new tag by pushing to\n"
1278 "'%s:refs/tags/%s'?"),
1279 matched_src_name, dst_value);
1280 } else if (type == OBJ_TREE) {
1281 advise(_("The <src> part of the refspec is a tree object.\n"
1282 "Did you mean to tag a new tree by pushing to\n"
1283 "'%s:refs/tags/%s'?"),
1284 matched_src_name, dst_value);
1285 } else if (type == OBJ_BLOB) {
1286 advise(_("The <src> part of the refspec is a blob object.\n"
1287 "Did you mean to tag a new blob by pushing to\n"
1288 "'%s:refs/tags/%s'?"),
1289 matched_src_name, dst_value);
1290 } else {
1291 BUG("'%s' should be commit/tag/tree/blob, is '%d'",
1292 matched_src_name, type);
1296 static int match_explicit(struct ref *src, struct ref *dst,
1297 struct ref ***dst_tail,
1298 struct refspec_item *rs)
1300 struct ref *matched_src, *matched_dst;
1301 int allocated_src;
1303 const char *dst_value = rs->dst;
1304 char *dst_guess;
1306 if (rs->pattern || rs->matching || rs->negative)
1307 return 0;
1309 matched_src = matched_dst = NULL;
1310 if (match_explicit_lhs(src, rs, &matched_src, &allocated_src) < 0)
1311 return -1;
1313 if (!dst_value) {
1314 int flag;
1316 dst_value = resolve_ref_unsafe(matched_src->name,
1317 RESOLVE_REF_READING,
1318 NULL, &flag);
1319 if (!dst_value ||
1320 ((flag & REF_ISSYMREF) &&
1321 !starts_with(dst_value, "refs/heads/")))
1322 die(_("%s cannot be resolved to branch"),
1323 matched_src->name);
1326 switch (count_refspec_match(dst_value, dst, &matched_dst)) {
1327 case 1:
1328 break;
1329 case 0:
1330 if (starts_with(dst_value, "refs/")) {
1331 matched_dst = make_linked_ref(dst_value, dst_tail);
1332 } else if (is_null_oid(&matched_src->new_oid)) {
1333 error(_("unable to delete '%s': remote ref does not exist"),
1334 dst_value);
1335 } else if ((dst_guess = guess_ref(dst_value, matched_src))) {
1336 matched_dst = make_linked_ref(dst_guess, dst_tail);
1337 free(dst_guess);
1338 } else {
1339 show_push_unqualified_ref_name_error(dst_value,
1340 matched_src->name);
1342 break;
1343 default:
1344 matched_dst = NULL;
1345 error(_("dst refspec %s matches more than one"),
1346 dst_value);
1347 break;
1349 if (!matched_dst)
1350 return -1;
1351 if (matched_dst->peer_ref)
1352 return error(_("dst ref %s receives from more than one src"),
1353 matched_dst->name);
1354 else {
1355 matched_dst->peer_ref = allocated_src ?
1356 matched_src :
1357 copy_ref(matched_src);
1358 matched_dst->force = rs->force;
1360 return 0;
1363 static int match_explicit_refs(struct ref *src, struct ref *dst,
1364 struct ref ***dst_tail, struct refspec *rs)
1366 int i, errs;
1367 for (i = errs = 0; i < rs->nr; i++)
1368 errs += match_explicit(src, dst, dst_tail, &rs->items[i]);
1369 return errs;
1372 static char *get_ref_match(const struct refspec *rs, const struct ref *ref,
1373 int send_mirror, int direction,
1374 const struct refspec_item **ret_pat)
1376 const struct refspec_item *pat;
1377 char *name;
1378 int i;
1379 int matching_refs = -1;
1380 for (i = 0; i < rs->nr; i++) {
1381 const struct refspec_item *item = &rs->items[i];
1383 if (item->negative)
1384 continue;
1386 if (item->matching &&
1387 (matching_refs == -1 || item->force)) {
1388 matching_refs = i;
1389 continue;
1392 if (item->pattern) {
1393 const char *dst_side = item->dst ? item->dst : item->src;
1394 int match;
1395 if (direction == FROM_SRC)
1396 match = match_name_with_pattern(item->src, ref->name, dst_side, &name);
1397 else
1398 match = match_name_with_pattern(dst_side, ref->name, item->src, &name);
1399 if (match) {
1400 matching_refs = i;
1401 break;
1405 if (matching_refs == -1)
1406 return NULL;
1408 pat = &rs->items[matching_refs];
1409 if (pat->matching) {
1411 * "matching refs"; traditionally we pushed everything
1412 * including refs outside refs/heads/ hierarchy, but
1413 * that does not make much sense these days.
1415 if (!send_mirror && !starts_with(ref->name, "refs/heads/"))
1416 return NULL;
1417 name = xstrdup(ref->name);
1419 if (ret_pat)
1420 *ret_pat = pat;
1421 return name;
1424 static struct ref **tail_ref(struct ref **head)
1426 struct ref **tail = head;
1427 while (*tail)
1428 tail = &((*tail)->next);
1429 return tail;
1432 struct tips {
1433 struct commit **tip;
1434 int nr, alloc;
1437 static void add_to_tips(struct tips *tips, const struct object_id *oid)
1439 struct commit *commit;
1441 if (is_null_oid(oid))
1442 return;
1443 commit = lookup_commit_reference_gently(the_repository, oid, 1);
1444 if (!commit || (commit->object.flags & TMP_MARK))
1445 return;
1446 commit->object.flags |= TMP_MARK;
1447 ALLOC_GROW(tips->tip, tips->nr + 1, tips->alloc);
1448 tips->tip[tips->nr++] = commit;
1451 static void add_missing_tags(struct ref *src, struct ref **dst, struct ref ***dst_tail)
1453 struct string_list dst_tag = STRING_LIST_INIT_NODUP;
1454 struct string_list src_tag = STRING_LIST_INIT_NODUP;
1455 struct string_list_item *item;
1456 struct ref *ref;
1457 struct tips sent_tips;
1460 * Collect everything we know they would have at the end of
1461 * this push, and collect all tags they have.
1463 memset(&sent_tips, 0, sizeof(sent_tips));
1464 for (ref = *dst; ref; ref = ref->next) {
1465 if (ref->peer_ref &&
1466 !is_null_oid(&ref->peer_ref->new_oid))
1467 add_to_tips(&sent_tips, &ref->peer_ref->new_oid);
1468 else
1469 add_to_tips(&sent_tips, &ref->old_oid);
1470 if (starts_with(ref->name, "refs/tags/"))
1471 string_list_append(&dst_tag, ref->name);
1473 clear_commit_marks_many(sent_tips.nr, sent_tips.tip, TMP_MARK);
1475 string_list_sort(&dst_tag);
1477 /* Collect tags they do not have. */
1478 for (ref = src; ref; ref = ref->next) {
1479 if (!starts_with(ref->name, "refs/tags/"))
1480 continue; /* not a tag */
1481 if (string_list_has_string(&dst_tag, ref->name))
1482 continue; /* they already have it */
1483 if (oid_object_info(the_repository, &ref->new_oid, NULL) != OBJ_TAG)
1484 continue; /* be conservative */
1485 item = string_list_append(&src_tag, ref->name);
1486 item->util = ref;
1488 string_list_clear(&dst_tag, 0);
1491 * At this point, src_tag lists tags that are missing from
1492 * dst, and sent_tips lists the tips we are pushing or those
1493 * that we know they already have. An element in the src_tag
1494 * that is an ancestor of any of the sent_tips needs to be
1495 * sent to the other side.
1497 if (sent_tips.nr) {
1498 const int reachable_flag = 1;
1499 struct commit_list *found_commits;
1500 struct commit **src_commits;
1501 int nr_src_commits = 0, alloc_src_commits = 16;
1502 ALLOC_ARRAY(src_commits, alloc_src_commits);
1504 for_each_string_list_item(item, &src_tag) {
1505 struct ref *ref = item->util;
1506 struct commit *commit;
1508 if (is_null_oid(&ref->new_oid))
1509 continue;
1510 commit = lookup_commit_reference_gently(the_repository,
1511 &ref->new_oid,
1513 if (!commit)
1514 /* not pushing a commit, which is not an error */
1515 continue;
1517 ALLOC_GROW(src_commits, nr_src_commits + 1, alloc_src_commits);
1518 src_commits[nr_src_commits++] = commit;
1521 found_commits = get_reachable_subset(sent_tips.tip, sent_tips.nr,
1522 src_commits, nr_src_commits,
1523 reachable_flag);
1525 for_each_string_list_item(item, &src_tag) {
1526 struct ref *dst_ref;
1527 struct ref *ref = item->util;
1528 struct commit *commit;
1530 if (is_null_oid(&ref->new_oid))
1531 continue;
1532 commit = lookup_commit_reference_gently(the_repository,
1533 &ref->new_oid,
1535 if (!commit)
1536 /* not pushing a commit, which is not an error */
1537 continue;
1540 * Is this tag, which they do not have, reachable from
1541 * any of the commits we are sending?
1543 if (!(commit->object.flags & reachable_flag))
1544 continue;
1546 /* Add it in */
1547 dst_ref = make_linked_ref(ref->name, dst_tail);
1548 oidcpy(&dst_ref->new_oid, &ref->new_oid);
1549 dst_ref->peer_ref = copy_ref(ref);
1552 clear_commit_marks_many(nr_src_commits, src_commits, reachable_flag);
1553 free(src_commits);
1554 free_commit_list(found_commits);
1557 string_list_clear(&src_tag, 0);
1558 free(sent_tips.tip);
1561 struct ref *find_ref_by_name(const struct ref *list, const char *name)
1563 for ( ; list; list = list->next)
1564 if (!strcmp(list->name, name))
1565 return (struct ref *)list;
1566 return NULL;
1569 static void prepare_ref_index(struct string_list *ref_index, struct ref *ref)
1571 for ( ; ref; ref = ref->next)
1572 string_list_append_nodup(ref_index, ref->name)->util = ref;
1574 string_list_sort(ref_index);
1578 * Given only the set of local refs, sanity-check the set of push
1579 * refspecs. We can't catch all errors that match_push_refs would,
1580 * but we can catch some errors early before even talking to the
1581 * remote side.
1583 int check_push_refs(struct ref *src, struct refspec *rs)
1585 int ret = 0;
1586 int i;
1588 for (i = 0; i < rs->nr; i++) {
1589 struct refspec_item *item = &rs->items[i];
1591 if (item->pattern || item->matching || item->negative)
1592 continue;
1594 ret |= match_explicit_lhs(src, item, NULL, NULL);
1597 return ret;
1601 * Given the set of refs the local repository has, the set of refs the
1602 * remote repository has, and the refspec used for push, determine
1603 * what remote refs we will update and with what value by setting
1604 * peer_ref (which object is being pushed) and force (if the push is
1605 * forced) in elements of "dst". The function may add new elements to
1606 * dst (e.g. pushing to a new branch, done in match_explicit_refs).
1608 int match_push_refs(struct ref *src, struct ref **dst,
1609 struct refspec *rs, int flags)
1611 int send_all = flags & MATCH_REFS_ALL;
1612 int send_mirror = flags & MATCH_REFS_MIRROR;
1613 int send_prune = flags & MATCH_REFS_PRUNE;
1614 int errs;
1615 struct ref *ref, **dst_tail = tail_ref(dst);
1616 struct string_list dst_ref_index = STRING_LIST_INIT_NODUP;
1618 /* If no refspec is provided, use the default ":" */
1619 if (!rs->nr)
1620 refspec_append(rs, ":");
1622 errs = match_explicit_refs(src, *dst, &dst_tail, rs);
1624 /* pick the remainder */
1625 for (ref = src; ref; ref = ref->next) {
1626 struct string_list_item *dst_item;
1627 struct ref *dst_peer;
1628 const struct refspec_item *pat = NULL;
1629 char *dst_name;
1631 dst_name = get_ref_match(rs, ref, send_mirror, FROM_SRC, &pat);
1632 if (!dst_name)
1633 continue;
1635 if (!dst_ref_index.nr)
1636 prepare_ref_index(&dst_ref_index, *dst);
1638 dst_item = string_list_lookup(&dst_ref_index, dst_name);
1639 dst_peer = dst_item ? dst_item->util : NULL;
1640 if (dst_peer) {
1641 if (dst_peer->peer_ref)
1642 /* We're already sending something to this ref. */
1643 goto free_name;
1644 } else {
1645 if (pat->matching && !(send_all || send_mirror))
1647 * Remote doesn't have it, and we have no
1648 * explicit pattern, and we don't have
1649 * --all or --mirror.
1651 goto free_name;
1653 /* Create a new one and link it */
1654 dst_peer = make_linked_ref(dst_name, &dst_tail);
1655 oidcpy(&dst_peer->new_oid, &ref->new_oid);
1656 string_list_insert(&dst_ref_index,
1657 dst_peer->name)->util = dst_peer;
1659 dst_peer->peer_ref = copy_ref(ref);
1660 dst_peer->force = pat->force;
1661 free_name:
1662 free(dst_name);
1665 string_list_clear(&dst_ref_index, 0);
1667 if (flags & MATCH_REFS_FOLLOW_TAGS)
1668 add_missing_tags(src, dst, &dst_tail);
1670 if (send_prune) {
1671 struct string_list src_ref_index = STRING_LIST_INIT_NODUP;
1672 /* check for missing refs on the remote */
1673 for (ref = *dst; ref; ref = ref->next) {
1674 char *src_name;
1676 if (ref->peer_ref)
1677 /* We're already sending something to this ref. */
1678 continue;
1680 src_name = get_ref_match(rs, ref, send_mirror, FROM_DST, NULL);
1681 if (src_name) {
1682 if (!src_ref_index.nr)
1683 prepare_ref_index(&src_ref_index, src);
1684 if (!string_list_has_string(&src_ref_index,
1685 src_name))
1686 ref->peer_ref = alloc_delete_ref();
1687 free(src_name);
1690 string_list_clear(&src_ref_index, 0);
1693 *dst = apply_negative_refspecs(*dst, rs);
1695 if (errs)
1696 return -1;
1697 return 0;
1700 void set_ref_status_for_push(struct ref *remote_refs, int send_mirror,
1701 int force_update)
1703 struct ref *ref;
1705 for (ref = remote_refs; ref; ref = ref->next) {
1706 int force_ref_update = ref->force || force_update;
1707 int reject_reason = 0;
1709 if (ref->peer_ref)
1710 oidcpy(&ref->new_oid, &ref->peer_ref->new_oid);
1711 else if (!send_mirror)
1712 continue;
1714 ref->deletion = is_null_oid(&ref->new_oid);
1715 if (!ref->deletion &&
1716 oideq(&ref->old_oid, &ref->new_oid)) {
1717 ref->status = REF_STATUS_UPTODATE;
1718 continue;
1722 * If the remote ref has moved and is now different
1723 * from what we expect, reject any push.
1725 * It also is an error if the user told us to check
1726 * with the remote-tracking branch to find the value
1727 * to expect, but we did not have such a tracking
1728 * branch.
1730 * If the tip of the remote-tracking ref is unreachable
1731 * from any reflog entry of its local ref indicating a
1732 * possible update since checkout; reject the push.
1734 if (ref->expect_old_sha1) {
1735 if (!oideq(&ref->old_oid, &ref->old_oid_expect))
1736 reject_reason = REF_STATUS_REJECT_STALE;
1737 else if (ref->check_reachable && ref->unreachable)
1738 reject_reason =
1739 REF_STATUS_REJECT_REMOTE_UPDATED;
1740 else
1742 * If the ref isn't stale, and is reachable
1743 * from one of the reflog entries of
1744 * the local branch, force the update.
1746 force_ref_update = 1;
1750 * If the update isn't already rejected then check
1751 * the usual "must fast-forward" rules.
1753 * Decide whether an individual refspec A:B can be
1754 * pushed. The push will succeed if any of the
1755 * following are true:
1757 * (1) the remote reference B does not exist
1759 * (2) the remote reference B is being removed (i.e.,
1760 * pushing :B where no source is specified)
1762 * (3) the destination is not under refs/tags/, and
1763 * if the old and new value is a commit, the new
1764 * is a descendant of the old.
1766 * (4) it is forced using the +A:B notation, or by
1767 * passing the --force argument
1770 if (!reject_reason && !ref->deletion && !is_null_oid(&ref->old_oid)) {
1771 if (starts_with(ref->name, "refs/tags/"))
1772 reject_reason = REF_STATUS_REJECT_ALREADY_EXISTS;
1773 else if (!repo_has_object_file(the_repository, &ref->old_oid))
1774 reject_reason = REF_STATUS_REJECT_FETCH_FIRST;
1775 else if (!lookup_commit_reference_gently(the_repository, &ref->old_oid, 1) ||
1776 !lookup_commit_reference_gently(the_repository, &ref->new_oid, 1))
1777 reject_reason = REF_STATUS_REJECT_NEEDS_FORCE;
1778 else if (!ref_newer(&ref->new_oid, &ref->old_oid))
1779 reject_reason = REF_STATUS_REJECT_NONFASTFORWARD;
1783 * "--force" will defeat any rejection implemented
1784 * by the rules above.
1786 if (!force_ref_update)
1787 ref->status = reject_reason;
1788 else if (reject_reason)
1789 ref->forced_update = 1;
1793 static void set_merge(struct remote_state *remote_state, struct branch *ret)
1795 struct remote *remote;
1796 char *ref;
1797 struct object_id oid;
1798 int i;
1800 if (!ret)
1801 return; /* no branch */
1802 if (ret->merge)
1803 return; /* already run */
1804 if (!ret->remote_name || !ret->merge_nr) {
1806 * no merge config; let's make sure we don't confuse callers
1807 * with a non-zero merge_nr but a NULL merge
1809 ret->merge_nr = 0;
1810 return;
1813 remote = remotes_remote_get(remote_state, ret->remote_name);
1815 CALLOC_ARRAY(ret->merge, ret->merge_nr);
1816 for (i = 0; i < ret->merge_nr; i++) {
1817 ret->merge[i] = xcalloc(1, sizeof(**ret->merge));
1818 ret->merge[i]->src = xstrdup(ret->merge_name[i]);
1819 if (!remote_find_tracking(remote, ret->merge[i]) ||
1820 strcmp(ret->remote_name, "."))
1821 continue;
1822 if (repo_dwim_ref(the_repository, ret->merge_name[i],
1823 strlen(ret->merge_name[i]), &oid, &ref,
1824 0) == 1)
1825 ret->merge[i]->dst = ref;
1826 else
1827 ret->merge[i]->dst = xstrdup(ret->merge_name[i]);
1831 struct branch *branch_get(const char *name)
1833 struct branch *ret;
1835 read_config(the_repository);
1836 if (!name || !*name || !strcmp(name, "HEAD"))
1837 ret = the_repository->remote_state->current_branch;
1838 else
1839 ret = make_branch(the_repository->remote_state, name,
1840 strlen(name));
1841 set_merge(the_repository->remote_state, ret);
1842 return ret;
1845 int branch_has_merge_config(struct branch *branch)
1847 return branch && !!branch->merge;
1850 int branch_merge_matches(struct branch *branch,
1851 int i,
1852 const char *refname)
1854 if (!branch || i < 0 || i >= branch->merge_nr)
1855 return 0;
1856 return refname_match(branch->merge[i]->src, refname);
1859 __attribute__((format (printf,2,3)))
1860 static const char *error_buf(struct strbuf *err, const char *fmt, ...)
1862 if (err) {
1863 va_list ap;
1864 va_start(ap, fmt);
1865 strbuf_vaddf(err, fmt, ap);
1866 va_end(ap);
1868 return NULL;
1871 const char *branch_get_upstream(struct branch *branch, struct strbuf *err)
1873 if (!branch)
1874 return error_buf(err, _("HEAD does not point to a branch"));
1876 if (!branch->merge || !branch->merge[0]) {
1878 * no merge config; is it because the user didn't define any,
1879 * or because it is not a real branch, and get_branch
1880 * auto-vivified it?
1882 if (!ref_exists(branch->refname))
1883 return error_buf(err, _("no such branch: '%s'"),
1884 branch->name);
1885 return error_buf(err,
1886 _("no upstream configured for branch '%s'"),
1887 branch->name);
1890 if (!branch->merge[0]->dst)
1891 return error_buf(err,
1892 _("upstream branch '%s' not stored as a remote-tracking branch"),
1893 branch->merge[0]->src);
1895 return branch->merge[0]->dst;
1898 static const char *tracking_for_push_dest(struct remote *remote,
1899 const char *refname,
1900 struct strbuf *err)
1902 char *ret;
1904 ret = apply_refspecs(&remote->fetch, refname);
1905 if (!ret)
1906 return error_buf(err,
1907 _("push destination '%s' on remote '%s' has no local tracking branch"),
1908 refname, remote->name);
1909 return ret;
1912 static const char *branch_get_push_1(struct remote_state *remote_state,
1913 struct branch *branch, struct strbuf *err)
1915 struct remote *remote;
1917 remote = remotes_remote_get(
1918 remote_state,
1919 remotes_pushremote_for_branch(remote_state, branch, NULL));
1920 if (!remote)
1921 return error_buf(err,
1922 _("branch '%s' has no remote for pushing"),
1923 branch->name);
1925 if (remote->push.nr) {
1926 char *dst;
1927 const char *ret;
1929 dst = apply_refspecs(&remote->push, branch->refname);
1930 if (!dst)
1931 return error_buf(err,
1932 _("push refspecs for '%s' do not include '%s'"),
1933 remote->name, branch->name);
1935 ret = tracking_for_push_dest(remote, dst, err);
1936 free(dst);
1937 return ret;
1940 if (remote->mirror)
1941 return tracking_for_push_dest(remote, branch->refname, err);
1943 switch (push_default) {
1944 case PUSH_DEFAULT_NOTHING:
1945 return error_buf(err, _("push has no destination (push.default is 'nothing')"));
1947 case PUSH_DEFAULT_MATCHING:
1948 case PUSH_DEFAULT_CURRENT:
1949 return tracking_for_push_dest(remote, branch->refname, err);
1951 case PUSH_DEFAULT_UPSTREAM:
1952 return branch_get_upstream(branch, err);
1954 case PUSH_DEFAULT_UNSPECIFIED:
1955 case PUSH_DEFAULT_SIMPLE:
1957 const char *up, *cur;
1959 up = branch_get_upstream(branch, err);
1960 if (!up)
1961 return NULL;
1962 cur = tracking_for_push_dest(remote, branch->refname, err);
1963 if (!cur)
1964 return NULL;
1965 if (strcmp(cur, up))
1966 return error_buf(err,
1967 _("cannot resolve 'simple' push to a single destination"));
1968 return cur;
1972 BUG("unhandled push situation");
1975 const char *branch_get_push(struct branch *branch, struct strbuf *err)
1977 read_config(the_repository);
1978 die_on_missing_branch(the_repository, branch);
1980 if (!branch)
1981 return error_buf(err, _("HEAD does not point to a branch"));
1983 if (!branch->push_tracking_ref)
1984 branch->push_tracking_ref = branch_get_push_1(
1985 the_repository->remote_state, branch, err);
1986 return branch->push_tracking_ref;
1989 static int ignore_symref_update(const char *refname, struct strbuf *scratch)
1991 return !refs_read_symbolic_ref(get_main_ref_store(the_repository), refname, scratch);
1995 * Create and return a list of (struct ref) consisting of copies of
1996 * each remote_ref that matches refspec. refspec must be a pattern.
1997 * Fill in the copies' peer_ref to describe the local tracking refs to
1998 * which they map. Omit any references that would map to an existing
1999 * local symbolic ref.
2001 static struct ref *get_expanded_map(const struct ref *remote_refs,
2002 const struct refspec_item *refspec)
2004 struct strbuf scratch = STRBUF_INIT;
2005 const struct ref *ref;
2006 struct ref *ret = NULL;
2007 struct ref **tail = &ret;
2009 for (ref = remote_refs; ref; ref = ref->next) {
2010 char *expn_name = NULL;
2012 strbuf_reset(&scratch);
2014 if (strchr(ref->name, '^'))
2015 continue; /* a dereference item */
2016 if (match_name_with_pattern(refspec->src, ref->name,
2017 refspec->dst, &expn_name) &&
2018 !ignore_symref_update(expn_name, &scratch)) {
2019 struct ref *cpy = copy_ref(ref);
2021 cpy->peer_ref = alloc_ref(expn_name);
2022 if (refspec->force)
2023 cpy->peer_ref->force = 1;
2024 *tail = cpy;
2025 tail = &cpy->next;
2027 free(expn_name);
2030 strbuf_release(&scratch);
2031 return ret;
2034 static const struct ref *find_ref_by_name_abbrev(const struct ref *refs, const char *name)
2036 const struct ref *ref;
2037 const struct ref *best_match = NULL;
2038 int best_score = 0;
2040 for (ref = refs; ref; ref = ref->next) {
2041 int score = refname_match(name, ref->name);
2043 if (best_score < score) {
2044 best_match = ref;
2045 best_score = score;
2048 return best_match;
2051 struct ref *get_remote_ref(const struct ref *remote_refs, const char *name)
2053 const struct ref *ref = find_ref_by_name_abbrev(remote_refs, name);
2055 if (!ref)
2056 return NULL;
2058 return copy_ref(ref);
2061 static struct ref *get_local_ref(const char *name)
2063 if (!name || name[0] == '\0')
2064 return NULL;
2066 if (starts_with(name, "refs/"))
2067 return alloc_ref(name);
2069 if (starts_with(name, "heads/") ||
2070 starts_with(name, "tags/") ||
2071 starts_with(name, "remotes/"))
2072 return alloc_ref_with_prefix("refs/", 5, name);
2074 return alloc_ref_with_prefix("refs/heads/", 11, name);
2077 int get_fetch_map(const struct ref *remote_refs,
2078 const struct refspec_item *refspec,
2079 struct ref ***tail,
2080 int missing_ok)
2082 struct ref *ref_map, **rmp;
2084 if (refspec->negative)
2085 return 0;
2087 if (refspec->pattern) {
2088 ref_map = get_expanded_map(remote_refs, refspec);
2089 } else {
2090 const char *name = refspec->src[0] ? refspec->src : "HEAD";
2092 if (refspec->exact_sha1) {
2093 ref_map = alloc_ref(name);
2094 get_oid_hex(name, &ref_map->old_oid);
2095 ref_map->exact_oid = 1;
2096 } else {
2097 ref_map = get_remote_ref(remote_refs, name);
2099 if (!missing_ok && !ref_map)
2100 die(_("couldn't find remote ref %s"), name);
2101 if (ref_map) {
2102 ref_map->peer_ref = get_local_ref(refspec->dst);
2103 if (ref_map->peer_ref && refspec->force)
2104 ref_map->peer_ref->force = 1;
2108 for (rmp = &ref_map; *rmp; ) {
2109 if ((*rmp)->peer_ref) {
2110 if (!starts_with((*rmp)->peer_ref->name, "refs/") ||
2111 check_refname_format((*rmp)->peer_ref->name, 0)) {
2112 struct ref *ignore = *rmp;
2113 error(_("* Ignoring funny ref '%s' locally"),
2114 (*rmp)->peer_ref->name);
2115 *rmp = (*rmp)->next;
2116 free(ignore->peer_ref);
2117 free(ignore);
2118 continue;
2121 rmp = &((*rmp)->next);
2124 if (ref_map)
2125 tail_link_ref(ref_map, tail);
2127 return 0;
2130 int resolve_remote_symref(struct ref *ref, struct ref *list)
2132 if (!ref->symref)
2133 return 0;
2134 for (; list; list = list->next)
2135 if (!strcmp(ref->symref, list->name)) {
2136 oidcpy(&ref->old_oid, &list->old_oid);
2137 return 0;
2139 return 1;
2143 * Compute the commit ahead/behind values for the pair branch_name, base.
2145 * If abf is AHEAD_BEHIND_FULL, compute the full ahead/behind and return the
2146 * counts in *num_ours and *num_theirs. If abf is AHEAD_BEHIND_QUICK, skip
2147 * the (potentially expensive) a/b computation (*num_ours and *num_theirs are
2148 * set to zero).
2150 * Returns -1 if num_ours and num_theirs could not be filled in (e.g., ref
2151 * does not exist). Returns 0 if the commits are identical. Returns 1 if
2152 * commits are different.
2155 static int stat_branch_pair(const char *branch_name, const char *base,
2156 int *num_ours, int *num_theirs,
2157 enum ahead_behind_flags abf)
2159 struct object_id oid;
2160 struct commit *ours, *theirs;
2161 struct rev_info revs;
2162 struct setup_revision_opt opt = {
2163 .free_removed_argv_elements = 1,
2165 struct strvec argv = STRVEC_INIT;
2167 /* Cannot stat if what we used to build on no longer exists */
2168 if (read_ref(base, &oid))
2169 return -1;
2170 theirs = lookup_commit_reference(the_repository, &oid);
2171 if (!theirs)
2172 return -1;
2174 if (read_ref(branch_name, &oid))
2175 return -1;
2176 ours = lookup_commit_reference(the_repository, &oid);
2177 if (!ours)
2178 return -1;
2180 *num_theirs = *num_ours = 0;
2182 /* are we the same? */
2183 if (theirs == ours)
2184 return 0;
2185 if (abf == AHEAD_BEHIND_QUICK)
2186 return 1;
2187 if (abf != AHEAD_BEHIND_FULL)
2188 BUG("stat_branch_pair: invalid abf '%d'", abf);
2190 /* Run "rev-list --left-right ours...theirs" internally... */
2191 strvec_push(&argv, ""); /* ignored */
2192 strvec_push(&argv, "--left-right");
2193 strvec_pushf(&argv, "%s...%s",
2194 oid_to_hex(&ours->object.oid),
2195 oid_to_hex(&theirs->object.oid));
2196 strvec_push(&argv, "--");
2198 repo_init_revisions(the_repository, &revs, NULL);
2199 setup_revisions(argv.nr, argv.v, &revs, &opt);
2200 if (prepare_revision_walk(&revs))
2201 die(_("revision walk setup failed"));
2203 /* ... and count the commits on each side. */
2204 while (1) {
2205 struct commit *c = get_revision(&revs);
2206 if (!c)
2207 break;
2208 if (c->object.flags & SYMMETRIC_LEFT)
2209 (*num_ours)++;
2210 else
2211 (*num_theirs)++;
2214 /* clear object flags smudged by the above traversal */
2215 clear_commit_marks(ours, ALL_REV_FLAGS);
2216 clear_commit_marks(theirs, ALL_REV_FLAGS);
2218 strvec_clear(&argv);
2219 release_revisions(&revs);
2220 return 1;
2224 * Lookup the tracking branch for the given branch and if present, optionally
2225 * compute the commit ahead/behind values for the pair.
2227 * If for_push is true, the tracking branch refers to the push branch,
2228 * otherwise it refers to the upstream branch.
2230 * The name of the tracking branch (or NULL if it is not defined) is
2231 * returned via *tracking_name, if it is not itself NULL.
2233 * If abf is AHEAD_BEHIND_FULL, compute the full ahead/behind and return the
2234 * counts in *num_ours and *num_theirs. If abf is AHEAD_BEHIND_QUICK, skip
2235 * the (potentially expensive) a/b computation (*num_ours and *num_theirs are
2236 * set to zero).
2238 * Returns -1 if num_ours and num_theirs could not be filled in (e.g., no
2239 * upstream defined, or ref does not exist). Returns 0 if the commits are
2240 * identical. Returns 1 if commits are different.
2242 int stat_tracking_info(struct branch *branch, int *num_ours, int *num_theirs,
2243 const char **tracking_name, int for_push,
2244 enum ahead_behind_flags abf)
2246 const char *base;
2248 /* Cannot stat unless we are marked to build on top of somebody else. */
2249 base = for_push ? branch_get_push(branch, NULL) :
2250 branch_get_upstream(branch, NULL);
2251 if (tracking_name)
2252 *tracking_name = base;
2253 if (!base)
2254 return -1;
2256 return stat_branch_pair(branch->refname, base, num_ours, num_theirs, abf);
2260 * Return true when there is anything to report, otherwise false.
2262 int format_tracking_info(struct branch *branch, struct strbuf *sb,
2263 enum ahead_behind_flags abf)
2265 int ours, theirs, sti;
2266 const char *full_base;
2267 char *base;
2268 int upstream_is_gone = 0;
2270 sti = stat_tracking_info(branch, &ours, &theirs, &full_base, 0, abf);
2271 if (sti < 0) {
2272 if (!full_base)
2273 return 0;
2274 upstream_is_gone = 1;
2277 base = shorten_unambiguous_ref(full_base, 0);
2278 if (upstream_is_gone) {
2279 strbuf_addf(sb,
2280 _("Your branch is based on '%s', but the upstream is gone.\n"),
2281 base);
2282 if (advice_enabled(ADVICE_STATUS_HINTS))
2283 strbuf_addstr(sb,
2284 _(" (use \"git branch --unset-upstream\" to fixup)\n"));
2285 } else if (!sti) {
2286 strbuf_addf(sb,
2287 _("Your branch is up to date with '%s'.\n"),
2288 base);
2289 } else if (abf == AHEAD_BEHIND_QUICK) {
2290 strbuf_addf(sb,
2291 _("Your branch and '%s' refer to different commits.\n"),
2292 base);
2293 if (advice_enabled(ADVICE_STATUS_HINTS))
2294 strbuf_addf(sb, _(" (use \"%s\" for details)\n"),
2295 "git status --ahead-behind");
2296 } else if (!theirs) {
2297 strbuf_addf(sb,
2298 Q_("Your branch is ahead of '%s' by %d commit.\n",
2299 "Your branch is ahead of '%s' by %d commits.\n",
2300 ours),
2301 base, ours);
2302 if (advice_enabled(ADVICE_STATUS_HINTS))
2303 strbuf_addstr(sb,
2304 _(" (use \"git push\" to publish your local commits)\n"));
2305 } else if (!ours) {
2306 strbuf_addf(sb,
2307 Q_("Your branch is behind '%s' by %d commit, "
2308 "and can be fast-forwarded.\n",
2309 "Your branch is behind '%s' by %d commits, "
2310 "and can be fast-forwarded.\n",
2311 theirs),
2312 base, theirs);
2313 if (advice_enabled(ADVICE_STATUS_HINTS))
2314 strbuf_addstr(sb,
2315 _(" (use \"git pull\" to update your local branch)\n"));
2316 } else {
2317 strbuf_addf(sb,
2318 Q_("Your branch and '%s' have diverged,\n"
2319 "and have %d and %d different commit each, "
2320 "respectively.\n",
2321 "Your branch and '%s' have diverged,\n"
2322 "and have %d and %d different commits each, "
2323 "respectively.\n",
2324 ours + theirs),
2325 base, ours, theirs);
2326 if (advice_enabled(ADVICE_STATUS_HINTS))
2327 strbuf_addstr(sb,
2328 _(" (use \"git pull\" to merge the remote branch into yours)\n"));
2330 free(base);
2331 return 1;
2334 static int one_local_ref(const char *refname, const struct object_id *oid,
2335 int flag UNUSED,
2336 void *cb_data)
2338 struct ref ***local_tail = cb_data;
2339 struct ref *ref;
2341 /* we already know it starts with refs/ to get here */
2342 if (check_refname_format(refname + 5, 0))
2343 return 0;
2345 ref = alloc_ref(refname);
2346 oidcpy(&ref->new_oid, oid);
2347 **local_tail = ref;
2348 *local_tail = &ref->next;
2349 return 0;
2352 struct ref *get_local_heads(void)
2354 struct ref *local_refs = NULL, **local_tail = &local_refs;
2356 for_each_ref(one_local_ref, &local_tail);
2357 return local_refs;
2360 struct ref *guess_remote_head(const struct ref *head,
2361 const struct ref *refs,
2362 int all)
2364 const struct ref *r;
2365 struct ref *list = NULL;
2366 struct ref **tail = &list;
2368 if (!head)
2369 return NULL;
2372 * Some transports support directly peeking at
2373 * where HEAD points; if that is the case, then
2374 * we don't have to guess.
2376 if (head->symref)
2377 return copy_ref(find_ref_by_name(refs, head->symref));
2379 /* If a remote branch exists with the default branch name, let's use it. */
2380 if (!all) {
2381 char *ref = xstrfmt("refs/heads/%s",
2382 git_default_branch_name(0));
2384 r = find_ref_by_name(refs, ref);
2385 free(ref);
2386 if (r && oideq(&r->old_oid, &head->old_oid))
2387 return copy_ref(r);
2389 /* Fall back to the hard-coded historical default */
2390 r = find_ref_by_name(refs, "refs/heads/master");
2391 if (r && oideq(&r->old_oid, &head->old_oid))
2392 return copy_ref(r);
2395 /* Look for another ref that points there */
2396 for (r = refs; r; r = r->next) {
2397 if (r != head &&
2398 starts_with(r->name, "refs/heads/") &&
2399 oideq(&r->old_oid, &head->old_oid)) {
2400 *tail = copy_ref(r);
2401 tail = &((*tail)->next);
2402 if (!all)
2403 break;
2407 return list;
2410 struct stale_heads_info {
2411 struct string_list *ref_names;
2412 struct ref **stale_refs_tail;
2413 struct refspec *rs;
2416 static int get_stale_heads_cb(const char *refname, const struct object_id *oid,
2417 int flags, void *cb_data)
2419 struct stale_heads_info *info = cb_data;
2420 struct string_list matches = STRING_LIST_INIT_DUP;
2421 struct refspec_item query;
2422 int i, stale = 1;
2423 memset(&query, 0, sizeof(struct refspec_item));
2424 query.dst = (char *)refname;
2426 query_refspecs_multiple(info->rs, &query, &matches);
2427 if (matches.nr == 0)
2428 goto clean_exit; /* No matches */
2431 * If we did find a suitable refspec and it's not a symref and
2432 * it's not in the list of refs that currently exist in that
2433 * remote, we consider it to be stale. In order to deal with
2434 * overlapping refspecs, we need to go over all of the
2435 * matching refs.
2437 if (flags & REF_ISSYMREF)
2438 goto clean_exit;
2440 for (i = 0; stale && i < matches.nr; i++)
2441 if (string_list_has_string(info->ref_names, matches.items[i].string))
2442 stale = 0;
2444 if (stale) {
2445 struct ref *ref = make_linked_ref(refname, &info->stale_refs_tail);
2446 oidcpy(&ref->new_oid, oid);
2449 clean_exit:
2450 string_list_clear(&matches, 0);
2451 return 0;
2454 struct ref *get_stale_heads(struct refspec *rs, struct ref *fetch_map)
2456 struct ref *ref, *stale_refs = NULL;
2457 struct string_list ref_names = STRING_LIST_INIT_NODUP;
2458 struct stale_heads_info info;
2460 info.ref_names = &ref_names;
2461 info.stale_refs_tail = &stale_refs;
2462 info.rs = rs;
2463 for (ref = fetch_map; ref; ref = ref->next)
2464 string_list_append(&ref_names, ref->name);
2465 string_list_sort(&ref_names);
2466 for_each_ref(get_stale_heads_cb, &info);
2467 string_list_clear(&ref_names, 0);
2468 return stale_refs;
2472 * Compare-and-swap
2474 static void clear_cas_option(struct push_cas_option *cas)
2476 int i;
2478 for (i = 0; i < cas->nr; i++)
2479 free(cas->entry[i].refname);
2480 free(cas->entry);
2481 memset(cas, 0, sizeof(*cas));
2484 static struct push_cas *add_cas_entry(struct push_cas_option *cas,
2485 const char *refname,
2486 size_t refnamelen)
2488 struct push_cas *entry;
2489 ALLOC_GROW(cas->entry, cas->nr + 1, cas->alloc);
2490 entry = &cas->entry[cas->nr++];
2491 memset(entry, 0, sizeof(*entry));
2492 entry->refname = xmemdupz(refname, refnamelen);
2493 return entry;
2496 static int parse_push_cas_option(struct push_cas_option *cas, const char *arg, int unset)
2498 const char *colon;
2499 struct push_cas *entry;
2501 if (unset) {
2502 /* "--no-<option>" */
2503 clear_cas_option(cas);
2504 return 0;
2507 if (!arg) {
2508 /* just "--<option>" */
2509 cas->use_tracking_for_rest = 1;
2510 return 0;
2513 /* "--<option>=refname" or "--<option>=refname:value" */
2514 colon = strchrnul(arg, ':');
2515 entry = add_cas_entry(cas, arg, colon - arg);
2516 if (!*colon)
2517 entry->use_tracking = 1;
2518 else if (!colon[1])
2519 oidclr(&entry->expect);
2520 else if (repo_get_oid(the_repository, colon + 1, &entry->expect))
2521 return error(_("cannot parse expected object name '%s'"),
2522 colon + 1);
2523 return 0;
2526 int parseopt_push_cas_option(const struct option *opt, const char *arg, int unset)
2528 return parse_push_cas_option(opt->value, arg, unset);
2531 int is_empty_cas(const struct push_cas_option *cas)
2533 return !cas->use_tracking_for_rest && !cas->nr;
2537 * Look at remote.fetch refspec and see if we have a remote
2538 * tracking branch for the refname there. Fill the name of
2539 * the remote-tracking branch in *dst_refname, and the name
2540 * of the commit object at its tip in oid[].
2541 * If we cannot do so, return negative to signal an error.
2543 static int remote_tracking(struct remote *remote, const char *refname,
2544 struct object_id *oid, char **dst_refname)
2546 char *dst;
2548 dst = apply_refspecs(&remote->fetch, refname);
2549 if (!dst)
2550 return -1; /* no tracking ref for refname at remote */
2551 if (read_ref(dst, oid))
2552 return -1; /* we know what the tracking ref is but we cannot read it */
2554 *dst_refname = dst;
2555 return 0;
2559 * The struct "reflog_commit_array" and related helper functions
2560 * are used for collecting commits into an array during reflog
2561 * traversals in "check_and_collect_until()".
2563 struct reflog_commit_array {
2564 struct commit **item;
2565 size_t nr, alloc;
2568 #define REFLOG_COMMIT_ARRAY_INIT { 0 }
2570 /* Append a commit to the array. */
2571 static void append_commit(struct reflog_commit_array *arr,
2572 struct commit *commit)
2574 ALLOC_GROW(arr->item, arr->nr + 1, arr->alloc);
2575 arr->item[arr->nr++] = commit;
2578 /* Free and reset the array. */
2579 static void free_commit_array(struct reflog_commit_array *arr)
2581 FREE_AND_NULL(arr->item);
2582 arr->nr = arr->alloc = 0;
2585 struct check_and_collect_until_cb_data {
2586 struct commit *remote_commit;
2587 struct reflog_commit_array *local_commits;
2588 timestamp_t remote_reflog_timestamp;
2591 /* Get the timestamp of the latest entry. */
2592 static int peek_reflog(struct object_id *o_oid UNUSED,
2593 struct object_id *n_oid UNUSED,
2594 const char *ident UNUSED,
2595 timestamp_t timestamp, int tz UNUSED,
2596 const char *message UNUSED, void *cb_data)
2598 timestamp_t *ts = cb_data;
2599 *ts = timestamp;
2600 return 1;
2603 static int check_and_collect_until(struct object_id *o_oid UNUSED,
2604 struct object_id *n_oid,
2605 const char *ident UNUSED,
2606 timestamp_t timestamp, int tz UNUSED,
2607 const char *message UNUSED, void *cb_data)
2609 struct commit *commit;
2610 struct check_and_collect_until_cb_data *cb = cb_data;
2612 /* An entry was found. */
2613 if (oideq(n_oid, &cb->remote_commit->object.oid))
2614 return 1;
2616 if ((commit = lookup_commit_reference(the_repository, n_oid)))
2617 append_commit(cb->local_commits, commit);
2620 * If the reflog entry timestamp is older than the remote ref's
2621 * latest reflog entry, there is no need to check or collect
2622 * entries older than this one.
2624 if (timestamp < cb->remote_reflog_timestamp)
2625 return -1;
2627 return 0;
2630 #define MERGE_BASES_BATCH_SIZE 8
2633 * Iterate through the reflog of the local ref to check if there is an entry
2634 * for the given remote-tracking ref; runs until the timestamp of an entry is
2635 * older than latest timestamp of remote-tracking ref's reflog. Any commits
2636 * are that seen along the way are collected into an array to check if the
2637 * remote-tracking ref is reachable from any of them.
2639 static int is_reachable_in_reflog(const char *local, const struct ref *remote)
2641 timestamp_t date;
2642 struct commit *commit;
2643 struct commit **chunk;
2644 struct check_and_collect_until_cb_data cb;
2645 struct reflog_commit_array arr = REFLOG_COMMIT_ARRAY_INIT;
2646 size_t size = 0;
2647 int ret = 0;
2649 commit = lookup_commit_reference(the_repository, &remote->old_oid);
2650 if (!commit)
2651 goto cleanup_return;
2654 * Get the timestamp from the latest entry
2655 * of the remote-tracking ref's reflog.
2657 for_each_reflog_ent_reverse(remote->tracking_ref, peek_reflog, &date);
2659 cb.remote_commit = commit;
2660 cb.local_commits = &arr;
2661 cb.remote_reflog_timestamp = date;
2662 ret = for_each_reflog_ent_reverse(local, check_and_collect_until, &cb);
2664 /* We found an entry in the reflog. */
2665 if (ret > 0)
2666 goto cleanup_return;
2669 * Check if the remote commit is reachable from any
2670 * of the commits in the collected array, in batches.
2672 for (chunk = arr.item; chunk < arr.item + arr.nr; chunk += size) {
2673 size = arr.item + arr.nr - chunk;
2674 if (MERGE_BASES_BATCH_SIZE < size)
2675 size = MERGE_BASES_BATCH_SIZE;
2677 if ((ret = repo_in_merge_bases_many(the_repository, commit, size, chunk)))
2678 break;
2681 cleanup_return:
2682 free_commit_array(&arr);
2683 return ret;
2687 * Check for reachability of a remote-tracking
2688 * ref in the reflog entries of its local ref.
2690 static void check_if_includes_upstream(struct ref *remote)
2692 struct ref *local = get_local_ref(remote->name);
2693 if (!local)
2694 return;
2696 if (is_reachable_in_reflog(local->name, remote) <= 0)
2697 remote->unreachable = 1;
2700 static void apply_cas(struct push_cas_option *cas,
2701 struct remote *remote,
2702 struct ref *ref)
2704 int i;
2706 /* Find an explicit --<option>=<name>[:<value>] entry */
2707 for (i = 0; i < cas->nr; i++) {
2708 struct push_cas *entry = &cas->entry[i];
2709 if (!refname_match(entry->refname, ref->name))
2710 continue;
2711 ref->expect_old_sha1 = 1;
2712 if (!entry->use_tracking)
2713 oidcpy(&ref->old_oid_expect, &entry->expect);
2714 else if (remote_tracking(remote, ref->name,
2715 &ref->old_oid_expect,
2716 &ref->tracking_ref))
2717 oidclr(&ref->old_oid_expect);
2718 else
2719 ref->check_reachable = cas->use_force_if_includes;
2720 return;
2723 /* Are we using "--<option>" to cover all? */
2724 if (!cas->use_tracking_for_rest)
2725 return;
2727 ref->expect_old_sha1 = 1;
2728 if (remote_tracking(remote, ref->name,
2729 &ref->old_oid_expect,
2730 &ref->tracking_ref))
2731 oidclr(&ref->old_oid_expect);
2732 else
2733 ref->check_reachable = cas->use_force_if_includes;
2736 void apply_push_cas(struct push_cas_option *cas,
2737 struct remote *remote,
2738 struct ref *remote_refs)
2740 struct ref *ref;
2741 for (ref = remote_refs; ref; ref = ref->next) {
2742 apply_cas(cas, remote, ref);
2745 * If "compare-and-swap" is in "use_tracking[_for_rest]"
2746 * mode, and if "--force-if-includes" was specified, run
2747 * the check.
2749 if (ref->check_reachable)
2750 check_if_includes_upstream(ref);
2754 struct remote_state *remote_state_new(void)
2756 struct remote_state *r = xmalloc(sizeof(*r));
2758 memset(r, 0, sizeof(*r));
2760 hashmap_init(&r->remotes_hash, remotes_hash_cmp, NULL, 0);
2761 hashmap_init(&r->branches_hash, branches_hash_cmp, NULL, 0);
2762 return r;
2765 void remote_state_clear(struct remote_state *remote_state)
2767 int i;
2769 for (i = 0; i < remote_state->remotes_nr; i++)
2770 remote_clear(remote_state->remotes[i]);
2771 FREE_AND_NULL(remote_state->remotes);
2772 remote_state->remotes_alloc = 0;
2773 remote_state->remotes_nr = 0;
2775 hashmap_clear_and_free(&remote_state->remotes_hash, struct remote, ent);
2776 hashmap_clear_and_free(&remote_state->branches_hash, struct remote, ent);
2780 * Returns 1 if it was the last chop before ':'.
2782 static int chop_last_dir(char **remoteurl, int is_relative)
2784 char *rfind = find_last_dir_sep(*remoteurl);
2785 if (rfind) {
2786 *rfind = '\0';
2787 return 0;
2790 rfind = strrchr(*remoteurl, ':');
2791 if (rfind) {
2792 *rfind = '\0';
2793 return 1;
2796 if (is_relative || !strcmp(".", *remoteurl))
2797 die(_("cannot strip one component off url '%s'"),
2798 *remoteurl);
2800 free(*remoteurl);
2801 *remoteurl = xstrdup(".");
2802 return 0;
2805 char *relative_url(const char *remote_url, const char *url,
2806 const char *up_path)
2808 int is_relative = 0;
2809 int colonsep = 0;
2810 char *out;
2811 char *remoteurl;
2812 struct strbuf sb = STRBUF_INIT;
2813 size_t len;
2815 if (!url_is_local_not_ssh(url) || is_absolute_path(url))
2816 return xstrdup(url);
2818 len = strlen(remote_url);
2819 if (!len)
2820 BUG("invalid empty remote_url");
2822 remoteurl = xstrdup(remote_url);
2823 if (is_dir_sep(remoteurl[len-1]))
2824 remoteurl[len-1] = '\0';
2826 if (!url_is_local_not_ssh(remoteurl) || is_absolute_path(remoteurl))
2827 is_relative = 0;
2828 else {
2829 is_relative = 1;
2831 * Prepend a './' to ensure all relative
2832 * remoteurls start with './' or '../'
2834 if (!starts_with_dot_slash_native(remoteurl) &&
2835 !starts_with_dot_dot_slash_native(remoteurl)) {
2836 strbuf_reset(&sb);
2837 strbuf_addf(&sb, "./%s", remoteurl);
2838 free(remoteurl);
2839 remoteurl = strbuf_detach(&sb, NULL);
2843 * When the url starts with '../', remove that and the
2844 * last directory in remoteurl.
2846 while (*url) {
2847 if (starts_with_dot_dot_slash_native(url)) {
2848 url += 3;
2849 colonsep |= chop_last_dir(&remoteurl, is_relative);
2850 } else if (starts_with_dot_slash_native(url))
2851 url += 2;
2852 else
2853 break;
2855 strbuf_reset(&sb);
2856 strbuf_addf(&sb, "%s%s%s", remoteurl, colonsep ? ":" : "/", url);
2857 if (ends_with(url, "/"))
2858 strbuf_setlen(&sb, sb.len - 1);
2859 free(remoteurl);
2861 if (starts_with_dot_slash_native(sb.buf))
2862 out = xstrdup(sb.buf + 2);
2863 else
2864 out = xstrdup(sb.buf);
2866 if (!up_path || !is_relative) {
2867 strbuf_release(&sb);
2868 return out;
2871 strbuf_reset(&sb);
2872 strbuf_addf(&sb, "%s%s", up_path, out);
2873 free(out);
2874 return strbuf_detach(&sb, NULL);