line-log: always allocate the output prefix
[git.git] / remote.c
blobd319f28757cdddf9588b79f9dc47c7f5aea4c2bc
1 #include "git-compat-util.h"
2 #include "abspath.h"
3 #include "config.h"
4 #include "environment.h"
5 #include "gettext.h"
6 #include "hex.h"
7 #include "remote.h"
8 #include "urlmatch.h"
9 #include "refs.h"
10 #include "refspec.h"
11 #include "object-name.h"
12 #include "object-store-ll.h"
13 #include "path.h"
14 #include "commit.h"
15 #include "diff.h"
16 #include "revision.h"
17 #include "dir.h"
18 #include "setup.h"
19 #include "string-list.h"
20 #include "strvec.h"
21 #include "commit-reach.h"
22 #include "advice.h"
23 #include "connect.h"
24 #include "parse-options.h"
26 enum map_direction { FROM_SRC, FROM_DST };
28 struct counted_string {
29 size_t len;
30 const char *s;
33 static int valid_remote(const struct remote *remote)
35 return (!!remote->url) || (!!remote->foreign_vcs);
38 static const char *alias_url(const char *url, struct rewrites *r)
40 int i, j;
41 struct counted_string *longest;
42 int longest_i;
44 longest = NULL;
45 longest_i = -1;
46 for (i = 0; i < r->rewrite_nr; i++) {
47 if (!r->rewrite[i])
48 continue;
49 for (j = 0; j < r->rewrite[i]->instead_of_nr; j++) {
50 if (starts_with(url, r->rewrite[i]->instead_of[j].s) &&
51 (!longest ||
52 longest->len < r->rewrite[i]->instead_of[j].len)) {
53 longest = &(r->rewrite[i]->instead_of[j]);
54 longest_i = i;
58 if (!longest)
59 return url;
61 return xstrfmt("%s%s", r->rewrite[longest_i]->base, url + longest->len);
64 static void add_url(struct remote *remote, const char *url)
66 ALLOC_GROW(remote->url, remote->url_nr + 1, remote->url_alloc);
67 remote->url[remote->url_nr++] = url;
70 static void add_pushurl(struct remote *remote, const char *pushurl)
72 ALLOC_GROW(remote->pushurl, remote->pushurl_nr + 1, remote->pushurl_alloc);
73 remote->pushurl[remote->pushurl_nr++] = pushurl;
76 static void add_pushurl_alias(struct remote_state *remote_state,
77 struct remote *remote, const char *url)
79 const char *pushurl = alias_url(url, &remote_state->rewrites_push);
80 if (pushurl != url)
81 add_pushurl(remote, pushurl);
84 static void add_url_alias(struct remote_state *remote_state,
85 struct remote *remote, const char *url)
87 add_url(remote, alias_url(url, &remote_state->rewrites));
88 add_pushurl_alias(remote_state, remote, url);
91 struct remotes_hash_key {
92 const char *str;
93 int len;
96 static int remotes_hash_cmp(const void *cmp_data UNUSED,
97 const struct hashmap_entry *eptr,
98 const struct hashmap_entry *entry_or_key,
99 const void *keydata)
101 const struct remote *a, *b;
102 const struct remotes_hash_key *key = keydata;
104 a = container_of(eptr, const struct remote, ent);
105 b = container_of(entry_or_key, const struct remote, ent);
107 if (key)
108 return !!xstrncmpz(a->name, key->str, key->len);
109 else
110 return strcmp(a->name, b->name);
113 static struct remote *make_remote(struct remote_state *remote_state,
114 const char *name, int len)
116 struct remote *ret;
117 struct remotes_hash_key lookup;
118 struct hashmap_entry lookup_entry, *e;
120 if (!len)
121 len = strlen(name);
123 lookup.str = name;
124 lookup.len = len;
125 hashmap_entry_init(&lookup_entry, memhash(name, len));
127 e = hashmap_get(&remote_state->remotes_hash, &lookup_entry, &lookup);
128 if (e)
129 return container_of(e, struct remote, ent);
131 CALLOC_ARRAY(ret, 1);
132 ret->prune = -1; /* unspecified */
133 ret->prune_tags = -1; /* unspecified */
134 ret->name = xstrndup(name, len);
135 refspec_init(&ret->push, REFSPEC_PUSH);
136 refspec_init(&ret->fetch, REFSPEC_FETCH);
138 ALLOC_GROW(remote_state->remotes, remote_state->remotes_nr + 1,
139 remote_state->remotes_alloc);
140 remote_state->remotes[remote_state->remotes_nr++] = ret;
142 hashmap_entry_init(&ret->ent, lookup_entry.hash);
143 if (hashmap_put_entry(&remote_state->remotes_hash, ret, ent))
144 BUG("hashmap_put overwrote entry after hashmap_get returned NULL");
145 return ret;
148 static void remote_clear(struct remote *remote)
150 int i;
152 free((char *)remote->name);
153 free((char *)remote->foreign_vcs);
155 for (i = 0; i < remote->url_nr; i++)
156 free((char *)remote->url[i]);
157 FREE_AND_NULL(remote->url);
159 for (i = 0; i < remote->pushurl_nr; i++)
160 free((char *)remote->pushurl[i]);
161 FREE_AND_NULL(remote->pushurl);
162 free((char *)remote->receivepack);
163 free((char *)remote->uploadpack);
164 FREE_AND_NULL(remote->http_proxy);
165 FREE_AND_NULL(remote->http_proxy_authmethod);
168 static void add_merge(struct branch *branch, const char *name)
170 ALLOC_GROW(branch->merge_name, branch->merge_nr + 1,
171 branch->merge_alloc);
172 branch->merge_name[branch->merge_nr++] = name;
175 struct branches_hash_key {
176 const char *str;
177 int len;
180 static int branches_hash_cmp(const void *cmp_data UNUSED,
181 const struct hashmap_entry *eptr,
182 const struct hashmap_entry *entry_or_key,
183 const void *keydata)
185 const struct branch *a, *b;
186 const struct branches_hash_key *key = keydata;
188 a = container_of(eptr, const struct branch, ent);
189 b = container_of(entry_or_key, const struct branch, ent);
191 if (key)
192 return !!xstrncmpz(a->name, key->str, key->len);
193 else
194 return strcmp(a->name, b->name);
197 static struct branch *find_branch(struct remote_state *remote_state,
198 const char *name, size_t len)
200 struct branches_hash_key lookup;
201 struct hashmap_entry lookup_entry, *e;
203 lookup.str = name;
204 lookup.len = len;
205 hashmap_entry_init(&lookup_entry, memhash(name, len));
207 e = hashmap_get(&remote_state->branches_hash, &lookup_entry, &lookup);
208 if (e)
209 return container_of(e, struct branch, ent);
211 return NULL;
214 static void die_on_missing_branch(struct repository *repo,
215 struct branch *branch)
217 /* branch == NULL is always valid because it represents detached HEAD. */
218 if (branch &&
219 branch != find_branch(repo->remote_state, branch->name,
220 strlen(branch->name)))
221 die("branch %s was not found in the repository", branch->name);
224 static struct branch *make_branch(struct remote_state *remote_state,
225 const char *name, size_t len)
227 struct branch *ret;
229 ret = find_branch(remote_state, name, len);
230 if (ret)
231 return ret;
233 CALLOC_ARRAY(ret, 1);
234 ret->name = xstrndup(name, len);
235 ret->refname = xstrfmt("refs/heads/%s", ret->name);
237 hashmap_entry_init(&ret->ent, memhash(name, len));
238 if (hashmap_put_entry(&remote_state->branches_hash, ret, ent))
239 BUG("hashmap_put overwrote entry after hashmap_get returned NULL");
240 return ret;
243 static struct rewrite *make_rewrite(struct rewrites *r,
244 const char *base, size_t len)
246 struct rewrite *ret;
247 int i;
249 for (i = 0; i < r->rewrite_nr; i++) {
250 if (len == r->rewrite[i]->baselen &&
251 !strncmp(base, r->rewrite[i]->base, len))
252 return r->rewrite[i];
255 ALLOC_GROW(r->rewrite, r->rewrite_nr + 1, r->rewrite_alloc);
256 CALLOC_ARRAY(ret, 1);
257 r->rewrite[r->rewrite_nr++] = ret;
258 ret->base = xstrndup(base, len);
259 ret->baselen = len;
260 return ret;
263 static void add_instead_of(struct rewrite *rewrite, const char *instead_of)
265 ALLOC_GROW(rewrite->instead_of, rewrite->instead_of_nr + 1, rewrite->instead_of_alloc);
266 rewrite->instead_of[rewrite->instead_of_nr].s = instead_of;
267 rewrite->instead_of[rewrite->instead_of_nr].len = strlen(instead_of);
268 rewrite->instead_of_nr++;
271 static const char *skip_spaces(const char *s)
273 while (isspace(*s))
274 s++;
275 return s;
278 static void read_remotes_file(struct remote_state *remote_state,
279 struct remote *remote)
281 struct strbuf buf = STRBUF_INIT;
282 FILE *f = fopen_or_warn(git_path("remotes/%s", remote->name), "r");
284 if (!f)
285 return;
286 remote->configured_in_repo = 1;
287 remote->origin = REMOTE_REMOTES;
288 while (strbuf_getline(&buf, f) != EOF) {
289 const char *v;
291 strbuf_rtrim(&buf);
293 if (skip_prefix(buf.buf, "URL:", &v))
294 add_url_alias(remote_state, remote,
295 xstrdup(skip_spaces(v)));
296 else if (skip_prefix(buf.buf, "Push:", &v))
297 refspec_append(&remote->push, skip_spaces(v));
298 else if (skip_prefix(buf.buf, "Pull:", &v))
299 refspec_append(&remote->fetch, skip_spaces(v));
301 strbuf_release(&buf);
302 fclose(f);
305 static void read_branches_file(struct remote_state *remote_state,
306 struct remote *remote)
308 char *frag;
309 struct strbuf buf = STRBUF_INIT;
310 FILE *f = fopen_or_warn(git_path("branches/%s", remote->name), "r");
312 if (!f)
313 return;
315 strbuf_getline_lf(&buf, f);
316 fclose(f);
317 strbuf_trim(&buf);
318 if (!buf.len) {
319 strbuf_release(&buf);
320 return;
323 remote->configured_in_repo = 1;
324 remote->origin = REMOTE_BRANCHES;
327 * The branches file would have URL and optionally
328 * #branch specified. The default (or specified) branch is
329 * fetched and stored in the local branch matching the
330 * remote name.
332 frag = strchr(buf.buf, '#');
333 if (frag)
334 *(frag++) = '\0';
335 else
336 frag = (char *)git_default_branch_name(0);
338 add_url_alias(remote_state, remote, strbuf_detach(&buf, NULL));
339 refspec_appendf(&remote->fetch, "refs/heads/%s:refs/heads/%s",
340 frag, remote->name);
343 * Cogito compatible push: push current HEAD to remote #branch
344 * (master if missing)
346 refspec_appendf(&remote->push, "HEAD:refs/heads/%s", frag);
347 remote->fetch_tags = 1; /* always auto-follow */
350 static int handle_config(const char *key, const char *value,
351 const struct config_context *ctx, void *cb)
353 const char *name;
354 size_t namelen;
355 const char *subkey;
356 struct remote *remote;
357 struct branch *branch;
358 struct remote_state *remote_state = cb;
359 const struct key_value_info *kvi = ctx->kvi;
361 if (parse_config_key(key, "branch", &name, &namelen, &subkey) >= 0) {
362 /* There is no subsection. */
363 if (!name)
364 return 0;
365 /* There is a subsection, but it is empty. */
366 if (!namelen)
367 return -1;
368 branch = make_branch(remote_state, name, namelen);
369 if (!strcmp(subkey, "remote")) {
370 return git_config_string(&branch->remote_name, key, value);
371 } else if (!strcmp(subkey, "pushremote")) {
372 return git_config_string(&branch->pushremote_name, key, value);
373 } else if (!strcmp(subkey, "merge")) {
374 if (!value)
375 return config_error_nonbool(key);
376 add_merge(branch, xstrdup(value));
378 return 0;
380 if (parse_config_key(key, "url", &name, &namelen, &subkey) >= 0) {
381 struct rewrite *rewrite;
382 if (!name)
383 return 0;
384 if (!strcmp(subkey, "insteadof")) {
385 if (!value)
386 return config_error_nonbool(key);
387 rewrite = make_rewrite(&remote_state->rewrites, name,
388 namelen);
389 add_instead_of(rewrite, xstrdup(value));
390 } else if (!strcmp(subkey, "pushinsteadof")) {
391 if (!value)
392 return config_error_nonbool(key);
393 rewrite = make_rewrite(&remote_state->rewrites_push,
394 name, namelen);
395 add_instead_of(rewrite, xstrdup(value));
399 if (parse_config_key(key, "remote", &name, &namelen, &subkey) < 0)
400 return 0;
402 /* Handle remote.* variables */
403 if (!name && !strcmp(subkey, "pushdefault"))
404 return git_config_string(&remote_state->pushremote_name, key,
405 value);
407 if (!name)
408 return 0;
409 /* Handle remote.<name>.* variables */
410 if (*name == '/') {
411 warning(_("config remote shorthand cannot begin with '/': %s"),
412 name);
413 return 0;
415 remote = make_remote(remote_state, name, namelen);
416 remote->origin = REMOTE_CONFIG;
417 if (kvi->scope == CONFIG_SCOPE_LOCAL ||
418 kvi->scope == CONFIG_SCOPE_WORKTREE)
419 remote->configured_in_repo = 1;
420 if (!strcmp(subkey, "mirror"))
421 remote->mirror = git_config_bool(key, value);
422 else if (!strcmp(subkey, "skipdefaultupdate"))
423 remote->skip_default_update = git_config_bool(key, value);
424 else if (!strcmp(subkey, "skipfetchall"))
425 remote->skip_default_update = git_config_bool(key, value);
426 else if (!strcmp(subkey, "prune"))
427 remote->prune = git_config_bool(key, value);
428 else if (!strcmp(subkey, "prunetags"))
429 remote->prune_tags = git_config_bool(key, value);
430 else if (!strcmp(subkey, "url")) {
431 char *v;
432 if (git_config_string(&v, key, value))
433 return -1;
434 add_url(remote, v);
435 } else if (!strcmp(subkey, "pushurl")) {
436 char *v;
437 if (git_config_string(&v, key, value))
438 return -1;
439 add_pushurl(remote, v);
440 } else if (!strcmp(subkey, "push")) {
441 char *v;
442 if (git_config_string(&v, key, value))
443 return -1;
444 refspec_append(&remote->push, v);
445 free(v);
446 } else if (!strcmp(subkey, "fetch")) {
447 char *v;
448 if (git_config_string(&v, key, value))
449 return -1;
450 refspec_append(&remote->fetch, v);
451 free(v);
452 } else if (!strcmp(subkey, "receivepack")) {
453 char *v;
454 if (git_config_string(&v, key, value))
455 return -1;
456 if (!remote->receivepack)
457 remote->receivepack = v;
458 else
459 error(_("more than one receivepack given, using the first"));
460 } else if (!strcmp(subkey, "uploadpack")) {
461 char *v;
462 if (git_config_string(&v, key, value))
463 return -1;
464 if (!remote->uploadpack)
465 remote->uploadpack = v;
466 else
467 error(_("more than one uploadpack given, using the first"));
468 } else if (!strcmp(subkey, "tagopt")) {
469 if (!strcmp(value, "--no-tags"))
470 remote->fetch_tags = -1;
471 else if (!strcmp(value, "--tags"))
472 remote->fetch_tags = 2;
473 } else if (!strcmp(subkey, "proxy")) {
474 return git_config_string(&remote->http_proxy,
475 key, value);
476 } else if (!strcmp(subkey, "proxyauthmethod")) {
477 return git_config_string(&remote->http_proxy_authmethod,
478 key, value);
479 } else if (!strcmp(subkey, "vcs")) {
480 return git_config_string(&remote->foreign_vcs, key, value);
482 return 0;
485 static void alias_all_urls(struct remote_state *remote_state)
487 int i, j;
488 for (i = 0; i < remote_state->remotes_nr; i++) {
489 int add_pushurl_aliases;
490 if (!remote_state->remotes[i])
491 continue;
492 for (j = 0; j < remote_state->remotes[i]->pushurl_nr; j++) {
493 remote_state->remotes[i]->pushurl[j] =
494 alias_url(remote_state->remotes[i]->pushurl[j],
495 &remote_state->rewrites);
497 add_pushurl_aliases = remote_state->remotes[i]->pushurl_nr == 0;
498 for (j = 0; j < remote_state->remotes[i]->url_nr; j++) {
499 if (add_pushurl_aliases)
500 add_pushurl_alias(
501 remote_state, remote_state->remotes[i],
502 remote_state->remotes[i]->url[j]);
503 remote_state->remotes[i]->url[j] =
504 alias_url(remote_state->remotes[i]->url[j],
505 &remote_state->rewrites);
510 static void read_config(struct repository *repo, int early)
512 int flag;
514 if (repo->remote_state->initialized)
515 return;
516 repo->remote_state->initialized = 1;
518 repo->remote_state->current_branch = NULL;
519 if (startup_info->have_repository && !early) {
520 const char *head_ref = refs_resolve_ref_unsafe(
521 get_main_ref_store(repo), "HEAD", 0, NULL, &flag);
522 if (head_ref && (flag & REF_ISSYMREF) &&
523 skip_prefix(head_ref, "refs/heads/", &head_ref)) {
524 repo->remote_state->current_branch = make_branch(
525 repo->remote_state, head_ref, strlen(head_ref));
528 repo_config(repo, handle_config, repo->remote_state);
529 alias_all_urls(repo->remote_state);
532 static int valid_remote_nick(const char *name)
534 if (!name[0] || is_dot_or_dotdot(name))
535 return 0;
537 /* remote nicknames cannot contain slashes */
538 while (*name)
539 if (is_dir_sep(*name++))
540 return 0;
541 return 1;
544 static const char *remotes_remote_for_branch(struct remote_state *remote_state,
545 struct branch *branch,
546 int *explicit)
548 if (branch && branch->remote_name) {
549 if (explicit)
550 *explicit = 1;
551 return branch->remote_name;
553 if (explicit)
554 *explicit = 0;
555 if (remote_state->remotes_nr == 1)
556 return remote_state->remotes[0]->name;
557 return "origin";
560 const char *remote_for_branch(struct branch *branch, int *explicit)
562 read_config(the_repository, 0);
563 die_on_missing_branch(the_repository, branch);
565 return remotes_remote_for_branch(the_repository->remote_state, branch,
566 explicit);
569 static const char *
570 remotes_pushremote_for_branch(struct remote_state *remote_state,
571 struct branch *branch, int *explicit)
573 if (branch && branch->pushremote_name) {
574 if (explicit)
575 *explicit = 1;
576 return branch->pushremote_name;
578 if (remote_state->pushremote_name) {
579 if (explicit)
580 *explicit = 1;
581 return remote_state->pushremote_name;
583 return remotes_remote_for_branch(remote_state, branch, explicit);
586 const char *pushremote_for_branch(struct branch *branch, int *explicit)
588 read_config(the_repository, 0);
589 die_on_missing_branch(the_repository, branch);
591 return remotes_pushremote_for_branch(the_repository->remote_state,
592 branch, explicit);
595 static struct remote *remotes_remote_get(struct remote_state *remote_state,
596 const char *name);
598 const char *remote_ref_for_branch(struct branch *branch, int for_push)
600 read_config(the_repository, 0);
601 die_on_missing_branch(the_repository, branch);
603 if (branch) {
604 if (!for_push) {
605 if (branch->merge_nr) {
606 return branch->merge_name[0];
608 } else {
609 const char *dst,
610 *remote_name = remotes_pushremote_for_branch(
611 the_repository->remote_state, branch,
612 NULL);
613 struct remote *remote = remotes_remote_get(
614 the_repository->remote_state, remote_name);
616 if (remote && remote->push.nr &&
617 (dst = apply_refspecs(&remote->push,
618 branch->refname))) {
619 return dst;
623 return NULL;
626 static void validate_remote_url(struct remote *remote)
628 int i;
629 const char *value;
630 struct strbuf redacted = STRBUF_INIT;
631 int warn_not_die;
633 if (git_config_get_string_tmp("transfer.credentialsinurl", &value))
634 return;
636 if (!strcmp("warn", value))
637 warn_not_die = 1;
638 else if (!strcmp("die", value))
639 warn_not_die = 0;
640 else if (!strcmp("allow", value))
641 return;
642 else
643 die(_("unrecognized value transfer.credentialsInUrl: '%s'"), value);
645 for (i = 0; i < remote->url_nr; i++) {
646 struct url_info url_info = { 0 };
648 if (!url_normalize(remote->url[i], &url_info) ||
649 !url_info.passwd_off)
650 goto loop_cleanup;
652 strbuf_reset(&redacted);
653 strbuf_add(&redacted, url_info.url, url_info.passwd_off);
654 strbuf_addstr(&redacted, "<redacted>");
655 strbuf_addstr(&redacted,
656 url_info.url + url_info.passwd_off + url_info.passwd_len);
658 if (warn_not_die)
659 warning(_("URL '%s' uses plaintext credentials"), redacted.buf);
660 else
661 die(_("URL '%s' uses plaintext credentials"), redacted.buf);
663 loop_cleanup:
664 free(url_info.url);
667 strbuf_release(&redacted);
670 static struct remote *
671 remotes_remote_get_1(struct remote_state *remote_state, const char *name,
672 const char *(*get_default)(struct remote_state *,
673 struct branch *, int *))
675 struct remote *ret;
676 int name_given = 0;
678 if (name)
679 name_given = 1;
680 else
681 name = get_default(remote_state, remote_state->current_branch,
682 &name_given);
684 ret = make_remote(remote_state, name, 0);
685 if (valid_remote_nick(name) && have_git_dir()) {
686 if (!valid_remote(ret))
687 read_remotes_file(remote_state, ret);
688 if (!valid_remote(ret))
689 read_branches_file(remote_state, ret);
691 if (name_given && !valid_remote(ret))
692 add_url_alias(remote_state, ret, name);
693 if (!valid_remote(ret))
694 return NULL;
696 validate_remote_url(ret);
698 return ret;
701 static inline struct remote *
702 remotes_remote_get(struct remote_state *remote_state, const char *name)
704 return remotes_remote_get_1(remote_state, name,
705 remotes_remote_for_branch);
708 struct remote *remote_get(const char *name)
710 read_config(the_repository, 0);
711 return remotes_remote_get(the_repository->remote_state, name);
714 struct remote *remote_get_early(const char *name)
716 read_config(the_repository, 1);
717 return remotes_remote_get(the_repository->remote_state, name);
720 static inline struct remote *
721 remotes_pushremote_get(struct remote_state *remote_state, const char *name)
723 return remotes_remote_get_1(remote_state, name,
724 remotes_pushremote_for_branch);
727 struct remote *pushremote_get(const char *name)
729 read_config(the_repository, 0);
730 return remotes_pushremote_get(the_repository->remote_state, name);
733 int remote_is_configured(struct remote *remote, int in_repo)
735 if (!remote)
736 return 0;
737 if (in_repo)
738 return remote->configured_in_repo;
739 return !!remote->origin;
742 int for_each_remote(each_remote_fn fn, void *priv)
744 int i, result = 0;
745 read_config(the_repository, 0);
746 for (i = 0; i < the_repository->remote_state->remotes_nr && !result;
747 i++) {
748 struct remote *remote =
749 the_repository->remote_state->remotes[i];
750 if (!remote)
751 continue;
752 result = fn(remote, priv);
754 return result;
757 static void handle_duplicate(struct ref *ref1, struct ref *ref2)
759 if (strcmp(ref1->name, ref2->name)) {
760 if (ref1->fetch_head_status != FETCH_HEAD_IGNORE &&
761 ref2->fetch_head_status != FETCH_HEAD_IGNORE) {
762 die(_("Cannot fetch both %s and %s to %s"),
763 ref1->name, ref2->name, ref2->peer_ref->name);
764 } else if (ref1->fetch_head_status != FETCH_HEAD_IGNORE &&
765 ref2->fetch_head_status == FETCH_HEAD_IGNORE) {
766 warning(_("%s usually tracks %s, not %s"),
767 ref2->peer_ref->name, ref2->name, ref1->name);
768 } else if (ref1->fetch_head_status == FETCH_HEAD_IGNORE &&
769 ref2->fetch_head_status == FETCH_HEAD_IGNORE) {
770 die(_("%s tracks both %s and %s"),
771 ref2->peer_ref->name, ref1->name, ref2->name);
772 } else {
774 * This last possibility doesn't occur because
775 * FETCH_HEAD_IGNORE entries always appear at
776 * the end of the list.
778 BUG("Internal error");
781 free(ref2->peer_ref);
782 free(ref2);
785 struct ref *ref_remove_duplicates(struct ref *ref_map)
787 struct string_list refs = STRING_LIST_INIT_NODUP;
788 struct ref *retval = NULL;
789 struct ref **p = &retval;
791 while (ref_map) {
792 struct ref *ref = ref_map;
794 ref_map = ref_map->next;
795 ref->next = NULL;
797 if (!ref->peer_ref) {
798 *p = ref;
799 p = &ref->next;
800 } else {
801 struct string_list_item *item =
802 string_list_insert(&refs, ref->peer_ref->name);
804 if (item->util) {
805 /* Entry already existed */
806 handle_duplicate((struct ref *)item->util, ref);
807 } else {
808 *p = ref;
809 p = &ref->next;
810 item->util = ref;
815 string_list_clear(&refs, 0);
816 return retval;
819 int remote_has_url(struct remote *remote, const char *url)
821 int i;
822 for (i = 0; i < remote->url_nr; i++) {
823 if (!strcmp(remote->url[i], url))
824 return 1;
826 return 0;
829 static int match_name_with_pattern(const char *key, const char *name,
830 const char *value, char **result)
832 const char *kstar = strchr(key, '*');
833 size_t klen;
834 size_t ksuffixlen;
835 size_t namelen;
836 int ret;
837 if (!kstar)
838 die(_("key '%s' of pattern had no '*'"), key);
839 klen = kstar - key;
840 ksuffixlen = strlen(kstar + 1);
841 namelen = strlen(name);
842 ret = !strncmp(name, key, klen) && namelen >= klen + ksuffixlen &&
843 !memcmp(name + namelen - ksuffixlen, kstar + 1, ksuffixlen);
844 if (ret && value) {
845 struct strbuf sb = STRBUF_INIT;
846 const char *vstar = strchr(value, '*');
847 if (!vstar)
848 die(_("value '%s' of pattern has no '*'"), value);
849 strbuf_add(&sb, value, vstar - value);
850 strbuf_add(&sb, name + klen, namelen - klen - ksuffixlen);
851 strbuf_addstr(&sb, vstar + 1);
852 *result = strbuf_detach(&sb, NULL);
854 return ret;
857 static int refspec_match(const struct refspec_item *refspec,
858 const char *name)
860 if (refspec->pattern)
861 return match_name_with_pattern(refspec->src, name, NULL, NULL);
863 return !strcmp(refspec->src, name);
866 int omit_name_by_refspec(const char *name, struct refspec *rs)
868 int i;
870 for (i = 0; i < rs->nr; i++) {
871 if (rs->items[i].negative && refspec_match(&rs->items[i], name))
872 return 1;
874 return 0;
877 struct ref *apply_negative_refspecs(struct ref *ref_map, struct refspec *rs)
879 struct ref **tail;
881 for (tail = &ref_map; *tail; ) {
882 struct ref *ref = *tail;
884 if (omit_name_by_refspec(ref->name, rs)) {
885 *tail = ref->next;
886 free(ref->peer_ref);
887 free(ref);
888 } else
889 tail = &ref->next;
892 return ref_map;
895 static int query_matches_negative_refspec(struct refspec *rs, struct refspec_item *query)
897 int i, matched_negative = 0;
898 int find_src = !query->src;
899 struct string_list reversed = STRING_LIST_INIT_DUP;
900 const char *needle = find_src ? query->dst : query->src;
903 * Check whether the queried ref matches any negative refpsec. If so,
904 * then we should ultimately treat this as not matching the query at
905 * all.
907 * Note that negative refspecs always match the source, but the query
908 * item uses the destination. To handle this, we apply pattern
909 * refspecs in reverse to figure out if the query source matches any
910 * of the negative refspecs.
912 * The first loop finds and expands all positive refspecs
913 * matched by the queried ref.
915 * The second loop checks if any of the results of the first loop
916 * match any negative refspec.
918 for (i = 0; i < rs->nr; i++) {
919 struct refspec_item *refspec = &rs->items[i];
920 char *expn_name;
922 if (refspec->negative)
923 continue;
925 /* Note the reversal of src and dst */
926 if (refspec->pattern) {
927 const char *key = refspec->dst ? refspec->dst : refspec->src;
928 const char *value = refspec->src;
930 if (match_name_with_pattern(key, needle, value, &expn_name))
931 string_list_append_nodup(&reversed, expn_name);
932 } else if (refspec->matching) {
933 /* For the special matching refspec, any query should match */
934 string_list_append(&reversed, needle);
935 } else if (!refspec->src) {
936 BUG("refspec->src should not be null here");
937 } else if (!strcmp(needle, refspec->src)) {
938 string_list_append(&reversed, refspec->src);
942 for (i = 0; !matched_negative && i < reversed.nr; i++) {
943 if (omit_name_by_refspec(reversed.items[i].string, rs))
944 matched_negative = 1;
947 string_list_clear(&reversed, 0);
949 return matched_negative;
952 static void query_refspecs_multiple(struct refspec *rs,
953 struct refspec_item *query,
954 struct string_list *results)
956 int i;
957 int find_src = !query->src;
959 if (find_src && !query->dst)
960 BUG("query_refspecs_multiple: need either src or dst");
962 if (query_matches_negative_refspec(rs, query))
963 return;
965 for (i = 0; i < rs->nr; i++) {
966 struct refspec_item *refspec = &rs->items[i];
967 const char *key = find_src ? refspec->dst : refspec->src;
968 const char *value = find_src ? refspec->src : refspec->dst;
969 const char *needle = find_src ? query->dst : query->src;
970 char **result = find_src ? &query->src : &query->dst;
972 if (!refspec->dst || refspec->negative)
973 continue;
974 if (refspec->pattern) {
975 if (match_name_with_pattern(key, needle, value, result))
976 string_list_append_nodup(results, *result);
977 } else if (!strcmp(needle, key)) {
978 string_list_append(results, value);
983 int query_refspecs(struct refspec *rs, struct refspec_item *query)
985 int i;
986 int find_src = !query->src;
987 const char *needle = find_src ? query->dst : query->src;
988 char **result = find_src ? &query->src : &query->dst;
990 if (find_src && !query->dst)
991 BUG("query_refspecs: need either src or dst");
993 if (query_matches_negative_refspec(rs, query))
994 return -1;
996 for (i = 0; i < rs->nr; i++) {
997 struct refspec_item *refspec = &rs->items[i];
998 const char *key = find_src ? refspec->dst : refspec->src;
999 const char *value = find_src ? refspec->src : refspec->dst;
1001 if (!refspec->dst || refspec->negative)
1002 continue;
1003 if (refspec->pattern) {
1004 if (match_name_with_pattern(key, needle, value, result)) {
1005 query->force = refspec->force;
1006 return 0;
1008 } else if (!strcmp(needle, key)) {
1009 *result = xstrdup(value);
1010 query->force = refspec->force;
1011 return 0;
1014 return -1;
1017 char *apply_refspecs(struct refspec *rs, const char *name)
1019 struct refspec_item query;
1021 memset(&query, 0, sizeof(struct refspec_item));
1022 query.src = (char *)name;
1024 if (query_refspecs(rs, &query))
1025 return NULL;
1027 return query.dst;
1030 int remote_find_tracking(struct remote *remote, struct refspec_item *refspec)
1032 return query_refspecs(&remote->fetch, refspec);
1035 static struct ref *alloc_ref_with_prefix(const char *prefix, size_t prefixlen,
1036 const char *name)
1038 size_t len = strlen(name);
1039 struct ref *ref = xcalloc(1, st_add4(sizeof(*ref), prefixlen, len, 1));
1040 memcpy(ref->name, prefix, prefixlen);
1041 memcpy(ref->name + prefixlen, name, len);
1042 return ref;
1045 struct ref *alloc_ref(const char *name)
1047 return alloc_ref_with_prefix("", 0, name);
1050 struct ref *copy_ref(const struct ref *ref)
1052 struct ref *cpy;
1053 size_t len;
1054 if (!ref)
1055 return NULL;
1056 len = st_add3(sizeof(struct ref), strlen(ref->name), 1);
1057 cpy = xmalloc(len);
1058 memcpy(cpy, ref, len);
1059 cpy->next = NULL;
1060 cpy->symref = xstrdup_or_null(ref->symref);
1061 cpy->remote_status = xstrdup_or_null(ref->remote_status);
1062 cpy->peer_ref = copy_ref(ref->peer_ref);
1063 return cpy;
1066 struct ref *copy_ref_list(const struct ref *ref)
1068 struct ref *ret = NULL;
1069 struct ref **tail = &ret;
1070 while (ref) {
1071 *tail = copy_ref(ref);
1072 ref = ref->next;
1073 tail = &((*tail)->next);
1075 return ret;
1078 void free_one_ref(struct ref *ref)
1080 if (!ref)
1081 return;
1082 free_one_ref(ref->peer_ref);
1083 free(ref->remote_status);
1084 free(ref->symref);
1085 free(ref);
1088 void free_refs(struct ref *ref)
1090 struct ref *next;
1091 while (ref) {
1092 next = ref->next;
1093 free_one_ref(ref);
1094 ref = next;
1098 int count_refspec_match(const char *pattern,
1099 struct ref *refs,
1100 struct ref **matched_ref)
1102 int patlen = strlen(pattern);
1103 struct ref *matched_weak = NULL;
1104 struct ref *matched = NULL;
1105 int weak_match = 0;
1106 int match = 0;
1108 for (weak_match = match = 0; refs; refs = refs->next) {
1109 char *name = refs->name;
1110 int namelen = strlen(name);
1112 if (!refname_match(pattern, name))
1113 continue;
1115 /* A match is "weak" if it is with refs outside
1116 * heads or tags, and did not specify the pattern
1117 * in full (e.g. "refs/remotes/origin/master") or at
1118 * least from the toplevel (e.g. "remotes/origin/master");
1119 * otherwise "git push $URL master" would result in
1120 * ambiguity between remotes/origin/master and heads/master
1121 * at the remote site.
1123 if (namelen != patlen &&
1124 patlen != namelen - 5 &&
1125 !starts_with(name, "refs/heads/") &&
1126 !starts_with(name, "refs/tags/")) {
1127 /* We want to catch the case where only weak
1128 * matches are found and there are multiple
1129 * matches, and where more than one strong
1130 * matches are found, as ambiguous. One
1131 * strong match with zero or more weak matches
1132 * are acceptable as a unique match.
1134 matched_weak = refs;
1135 weak_match++;
1137 else {
1138 matched = refs;
1139 match++;
1142 if (!matched) {
1143 if (matched_ref)
1144 *matched_ref = matched_weak;
1145 return weak_match;
1147 else {
1148 if (matched_ref)
1149 *matched_ref = matched;
1150 return match;
1154 static void tail_link_ref(struct ref *ref, struct ref ***tail)
1156 **tail = ref;
1157 while (ref->next)
1158 ref = ref->next;
1159 *tail = &ref->next;
1162 static struct ref *alloc_delete_ref(void)
1164 struct ref *ref = alloc_ref("(delete)");
1165 oidclr(&ref->new_oid);
1166 return ref;
1169 static int try_explicit_object_name(const char *name,
1170 struct ref **match)
1172 struct object_id oid;
1174 if (!*name) {
1175 if (match)
1176 *match = alloc_delete_ref();
1177 return 0;
1180 if (repo_get_oid(the_repository, name, &oid))
1181 return -1;
1183 if (match) {
1184 *match = alloc_ref(name);
1185 oidcpy(&(*match)->new_oid, &oid);
1187 return 0;
1190 static struct ref *make_linked_ref(const char *name, struct ref ***tail)
1192 struct ref *ret = alloc_ref(name);
1193 tail_link_ref(ret, tail);
1194 return ret;
1197 static char *guess_ref(const char *name, struct ref *peer)
1199 struct strbuf buf = STRBUF_INIT;
1201 const char *r = refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
1202 peer->name,
1203 RESOLVE_REF_READING,
1204 NULL, NULL);
1205 if (!r)
1206 return NULL;
1208 if (starts_with(r, "refs/heads/")) {
1209 strbuf_addstr(&buf, "refs/heads/");
1210 } else if (starts_with(r, "refs/tags/")) {
1211 strbuf_addstr(&buf, "refs/tags/");
1212 } else {
1213 return NULL;
1216 strbuf_addstr(&buf, name);
1217 return strbuf_detach(&buf, NULL);
1220 static int match_explicit_lhs(struct ref *src,
1221 struct refspec_item *rs,
1222 struct ref **match,
1223 int *allocated_match)
1225 switch (count_refspec_match(rs->src, src, match)) {
1226 case 1:
1227 if (allocated_match)
1228 *allocated_match = 0;
1229 return 0;
1230 case 0:
1231 /* The source could be in the get_sha1() format
1232 * not a reference name. :refs/other is a
1233 * way to delete 'other' ref at the remote end.
1235 if (try_explicit_object_name(rs->src, match) < 0)
1236 return error(_("src refspec %s does not match any"), rs->src);
1237 if (allocated_match)
1238 *allocated_match = 1;
1239 return 0;
1240 default:
1241 return error(_("src refspec %s matches more than one"), rs->src);
1245 static void show_push_unqualified_ref_name_error(const char *dst_value,
1246 const char *matched_src_name)
1248 struct object_id oid;
1249 enum object_type type;
1252 * TRANSLATORS: "matches '%s'%" is the <dst> part of "git push
1253 * <remote> <src>:<dst>" push, and "being pushed ('%s')" is
1254 * the <src>.
1256 error(_("The destination you provided is not a full refname (i.e.,\n"
1257 "starting with \"refs/\"). We tried to guess what you meant by:\n"
1258 "\n"
1259 "- Looking for a ref that matches '%s' on the remote side.\n"
1260 "- Checking if the <src> being pushed ('%s')\n"
1261 " is a ref in \"refs/{heads,tags}/\". If so we add a corresponding\n"
1262 " refs/{heads,tags}/ prefix on the remote side.\n"
1263 "\n"
1264 "Neither worked, so we gave up. You must fully qualify the ref."),
1265 dst_value, matched_src_name);
1267 if (!advice_enabled(ADVICE_PUSH_UNQUALIFIED_REF_NAME))
1268 return;
1270 if (repo_get_oid(the_repository, matched_src_name, &oid))
1271 BUG("'%s' is not a valid object, "
1272 "match_explicit_lhs() should catch this!",
1273 matched_src_name);
1274 type = oid_object_info(the_repository, &oid, NULL);
1275 if (type == OBJ_COMMIT) {
1276 advise(_("The <src> part of the refspec is a commit object.\n"
1277 "Did you mean to create a new branch by pushing to\n"
1278 "'%s:refs/heads/%s'?"),
1279 matched_src_name, dst_value);
1280 } else if (type == OBJ_TAG) {
1281 advise(_("The <src> part of the refspec is a tag object.\n"
1282 "Did you mean to create a new tag by pushing to\n"
1283 "'%s:refs/tags/%s'?"),
1284 matched_src_name, dst_value);
1285 } else if (type == OBJ_TREE) {
1286 advise(_("The <src> part of the refspec is a tree object.\n"
1287 "Did you mean to tag a new tree by pushing to\n"
1288 "'%s:refs/tags/%s'?"),
1289 matched_src_name, dst_value);
1290 } else if (type == OBJ_BLOB) {
1291 advise(_("The <src> part of the refspec is a blob object.\n"
1292 "Did you mean to tag a new blob by pushing to\n"
1293 "'%s:refs/tags/%s'?"),
1294 matched_src_name, dst_value);
1295 } else {
1296 BUG("'%s' should be commit/tag/tree/blob, is '%d'",
1297 matched_src_name, type);
1301 static int match_explicit(struct ref *src, struct ref *dst,
1302 struct ref ***dst_tail,
1303 struct refspec_item *rs)
1305 struct ref *matched_src, *matched_dst;
1306 int allocated_src;
1308 const char *dst_value = rs->dst;
1309 char *dst_guess;
1311 if (rs->pattern || rs->matching || rs->negative)
1312 return 0;
1314 matched_src = matched_dst = NULL;
1315 if (match_explicit_lhs(src, rs, &matched_src, &allocated_src) < 0)
1316 return -1;
1318 if (!dst_value) {
1319 int flag;
1321 dst_value = refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
1322 matched_src->name,
1323 RESOLVE_REF_READING,
1324 NULL, &flag);
1325 if (!dst_value ||
1326 ((flag & REF_ISSYMREF) &&
1327 !starts_with(dst_value, "refs/heads/")))
1328 die(_("%s cannot be resolved to branch"),
1329 matched_src->name);
1332 switch (count_refspec_match(dst_value, dst, &matched_dst)) {
1333 case 1:
1334 break;
1335 case 0:
1336 if (starts_with(dst_value, "refs/")) {
1337 matched_dst = make_linked_ref(dst_value, dst_tail);
1338 } else if (is_null_oid(&matched_src->new_oid)) {
1339 error(_("unable to delete '%s': remote ref does not exist"),
1340 dst_value);
1341 } else if ((dst_guess = guess_ref(dst_value, matched_src))) {
1342 matched_dst = make_linked_ref(dst_guess, dst_tail);
1343 free(dst_guess);
1344 } else {
1345 show_push_unqualified_ref_name_error(dst_value,
1346 matched_src->name);
1348 break;
1349 default:
1350 matched_dst = NULL;
1351 error(_("dst refspec %s matches more than one"),
1352 dst_value);
1353 break;
1355 if (!matched_dst)
1356 return -1;
1357 if (matched_dst->peer_ref)
1358 return error(_("dst ref %s receives from more than one src"),
1359 matched_dst->name);
1360 else {
1361 matched_dst->peer_ref = allocated_src ?
1362 matched_src :
1363 copy_ref(matched_src);
1364 matched_dst->force = rs->force;
1366 return 0;
1369 static int match_explicit_refs(struct ref *src, struct ref *dst,
1370 struct ref ***dst_tail, struct refspec *rs)
1372 int i, errs;
1373 for (i = errs = 0; i < rs->nr; i++)
1374 errs += match_explicit(src, dst, dst_tail, &rs->items[i]);
1375 return errs;
1378 static char *get_ref_match(const struct refspec *rs, const struct ref *ref,
1379 int send_mirror, int direction,
1380 const struct refspec_item **ret_pat)
1382 const struct refspec_item *pat;
1383 char *name;
1384 int i;
1385 int matching_refs = -1;
1386 for (i = 0; i < rs->nr; i++) {
1387 const struct refspec_item *item = &rs->items[i];
1389 if (item->negative)
1390 continue;
1392 if (item->matching &&
1393 (matching_refs == -1 || item->force)) {
1394 matching_refs = i;
1395 continue;
1398 if (item->pattern) {
1399 const char *dst_side = item->dst ? item->dst : item->src;
1400 int match;
1401 if (direction == FROM_SRC)
1402 match = match_name_with_pattern(item->src, ref->name, dst_side, &name);
1403 else
1404 match = match_name_with_pattern(dst_side, ref->name, item->src, &name);
1405 if (match) {
1406 matching_refs = i;
1407 break;
1411 if (matching_refs == -1)
1412 return NULL;
1414 pat = &rs->items[matching_refs];
1415 if (pat->matching) {
1417 * "matching refs"; traditionally we pushed everything
1418 * including refs outside refs/heads/ hierarchy, but
1419 * that does not make much sense these days.
1421 if (!send_mirror && !starts_with(ref->name, "refs/heads/"))
1422 return NULL;
1423 name = xstrdup(ref->name);
1425 if (ret_pat)
1426 *ret_pat = pat;
1427 return name;
1430 static struct ref **tail_ref(struct ref **head)
1432 struct ref **tail = head;
1433 while (*tail)
1434 tail = &((*tail)->next);
1435 return tail;
1438 struct tips {
1439 struct commit **tip;
1440 int nr, alloc;
1443 static void add_to_tips(struct tips *tips, const struct object_id *oid)
1445 struct commit *commit;
1447 if (is_null_oid(oid))
1448 return;
1449 commit = lookup_commit_reference_gently(the_repository, oid, 1);
1450 if (!commit || (commit->object.flags & TMP_MARK))
1451 return;
1452 commit->object.flags |= TMP_MARK;
1453 ALLOC_GROW(tips->tip, tips->nr + 1, tips->alloc);
1454 tips->tip[tips->nr++] = commit;
1457 static void add_missing_tags(struct ref *src, struct ref **dst, struct ref ***dst_tail)
1459 struct string_list dst_tag = STRING_LIST_INIT_NODUP;
1460 struct string_list src_tag = STRING_LIST_INIT_NODUP;
1461 struct string_list_item *item;
1462 struct ref *ref;
1463 struct tips sent_tips;
1466 * Collect everything we know they would have at the end of
1467 * this push, and collect all tags they have.
1469 memset(&sent_tips, 0, sizeof(sent_tips));
1470 for (ref = *dst; ref; ref = ref->next) {
1471 if (ref->peer_ref &&
1472 !is_null_oid(&ref->peer_ref->new_oid))
1473 add_to_tips(&sent_tips, &ref->peer_ref->new_oid);
1474 else
1475 add_to_tips(&sent_tips, &ref->old_oid);
1476 if (starts_with(ref->name, "refs/tags/"))
1477 string_list_append(&dst_tag, ref->name);
1479 clear_commit_marks_many(sent_tips.nr, sent_tips.tip, TMP_MARK);
1481 string_list_sort(&dst_tag);
1483 /* Collect tags they do not have. */
1484 for (ref = src; ref; ref = ref->next) {
1485 if (!starts_with(ref->name, "refs/tags/"))
1486 continue; /* not a tag */
1487 if (string_list_has_string(&dst_tag, ref->name))
1488 continue; /* they already have it */
1489 if (oid_object_info(the_repository, &ref->new_oid, NULL) != OBJ_TAG)
1490 continue; /* be conservative */
1491 item = string_list_append(&src_tag, ref->name);
1492 item->util = ref;
1494 string_list_clear(&dst_tag, 0);
1497 * At this point, src_tag lists tags that are missing from
1498 * dst, and sent_tips lists the tips we are pushing or those
1499 * that we know they already have. An element in the src_tag
1500 * that is an ancestor of any of the sent_tips needs to be
1501 * sent to the other side.
1503 if (sent_tips.nr) {
1504 const int reachable_flag = 1;
1505 struct commit_list *found_commits;
1506 struct commit **src_commits;
1507 int nr_src_commits = 0, alloc_src_commits = 16;
1508 ALLOC_ARRAY(src_commits, alloc_src_commits);
1510 for_each_string_list_item(item, &src_tag) {
1511 struct ref *ref = item->util;
1512 struct commit *commit;
1514 if (is_null_oid(&ref->new_oid))
1515 continue;
1516 commit = lookup_commit_reference_gently(the_repository,
1517 &ref->new_oid,
1519 if (!commit)
1520 /* not pushing a commit, which is not an error */
1521 continue;
1523 ALLOC_GROW(src_commits, nr_src_commits + 1, alloc_src_commits);
1524 src_commits[nr_src_commits++] = commit;
1527 found_commits = get_reachable_subset(sent_tips.tip, sent_tips.nr,
1528 src_commits, nr_src_commits,
1529 reachable_flag);
1531 for_each_string_list_item(item, &src_tag) {
1532 struct ref *dst_ref;
1533 struct ref *ref = item->util;
1534 struct commit *commit;
1536 if (is_null_oid(&ref->new_oid))
1537 continue;
1538 commit = lookup_commit_reference_gently(the_repository,
1539 &ref->new_oid,
1541 if (!commit)
1542 /* not pushing a commit, which is not an error */
1543 continue;
1546 * Is this tag, which they do not have, reachable from
1547 * any of the commits we are sending?
1549 if (!(commit->object.flags & reachable_flag))
1550 continue;
1552 /* Add it in */
1553 dst_ref = make_linked_ref(ref->name, dst_tail);
1554 oidcpy(&dst_ref->new_oid, &ref->new_oid);
1555 dst_ref->peer_ref = copy_ref(ref);
1558 clear_commit_marks_many(nr_src_commits, src_commits, reachable_flag);
1559 free(src_commits);
1560 free_commit_list(found_commits);
1563 string_list_clear(&src_tag, 0);
1564 free(sent_tips.tip);
1567 struct ref *find_ref_by_name(const struct ref *list, const char *name)
1569 for ( ; list; list = list->next)
1570 if (!strcmp(list->name, name))
1571 return (struct ref *)list;
1572 return NULL;
1575 static void prepare_ref_index(struct string_list *ref_index, struct ref *ref)
1577 for ( ; ref; ref = ref->next)
1578 string_list_append_nodup(ref_index, ref->name)->util = ref;
1580 string_list_sort(ref_index);
1584 * Given only the set of local refs, sanity-check the set of push
1585 * refspecs. We can't catch all errors that match_push_refs would,
1586 * but we can catch some errors early before even talking to the
1587 * remote side.
1589 int check_push_refs(struct ref *src, struct refspec *rs)
1591 int ret = 0;
1592 int i;
1594 for (i = 0; i < rs->nr; i++) {
1595 struct refspec_item *item = &rs->items[i];
1597 if (item->pattern || item->matching || item->negative)
1598 continue;
1600 ret |= match_explicit_lhs(src, item, NULL, NULL);
1603 return ret;
1607 * Given the set of refs the local repository has, the set of refs the
1608 * remote repository has, and the refspec used for push, determine
1609 * what remote refs we will update and with what value by setting
1610 * peer_ref (which object is being pushed) and force (if the push is
1611 * forced) in elements of "dst". The function may add new elements to
1612 * dst (e.g. pushing to a new branch, done in match_explicit_refs).
1614 int match_push_refs(struct ref *src, struct ref **dst,
1615 struct refspec *rs, int flags)
1617 int send_all = flags & MATCH_REFS_ALL;
1618 int send_mirror = flags & MATCH_REFS_MIRROR;
1619 int send_prune = flags & MATCH_REFS_PRUNE;
1620 int errs;
1621 struct ref *ref, **dst_tail = tail_ref(dst);
1622 struct string_list dst_ref_index = STRING_LIST_INIT_NODUP;
1624 /* If no refspec is provided, use the default ":" */
1625 if (!rs->nr)
1626 refspec_append(rs, ":");
1628 errs = match_explicit_refs(src, *dst, &dst_tail, rs);
1630 /* pick the remainder */
1631 for (ref = src; ref; ref = ref->next) {
1632 struct string_list_item *dst_item;
1633 struct ref *dst_peer;
1634 const struct refspec_item *pat = NULL;
1635 char *dst_name;
1637 dst_name = get_ref_match(rs, ref, send_mirror, FROM_SRC, &pat);
1638 if (!dst_name)
1639 continue;
1641 if (!dst_ref_index.nr)
1642 prepare_ref_index(&dst_ref_index, *dst);
1644 dst_item = string_list_lookup(&dst_ref_index, dst_name);
1645 dst_peer = dst_item ? dst_item->util : NULL;
1646 if (dst_peer) {
1647 if (dst_peer->peer_ref)
1648 /* We're already sending something to this ref. */
1649 goto free_name;
1650 } else {
1651 if (pat->matching && !(send_all || send_mirror))
1653 * Remote doesn't have it, and we have no
1654 * explicit pattern, and we don't have
1655 * --all or --mirror.
1657 goto free_name;
1659 /* Create a new one and link it */
1660 dst_peer = make_linked_ref(dst_name, &dst_tail);
1661 oidcpy(&dst_peer->new_oid, &ref->new_oid);
1662 string_list_insert(&dst_ref_index,
1663 dst_peer->name)->util = dst_peer;
1665 dst_peer->peer_ref = copy_ref(ref);
1666 dst_peer->force = pat->force;
1667 free_name:
1668 free(dst_name);
1671 string_list_clear(&dst_ref_index, 0);
1673 if (flags & MATCH_REFS_FOLLOW_TAGS)
1674 add_missing_tags(src, dst, &dst_tail);
1676 if (send_prune) {
1677 struct string_list src_ref_index = STRING_LIST_INIT_NODUP;
1678 /* check for missing refs on the remote */
1679 for (ref = *dst; ref; ref = ref->next) {
1680 char *src_name;
1682 if (ref->peer_ref)
1683 /* We're already sending something to this ref. */
1684 continue;
1686 src_name = get_ref_match(rs, ref, send_mirror, FROM_DST, NULL);
1687 if (src_name) {
1688 if (!src_ref_index.nr)
1689 prepare_ref_index(&src_ref_index, src);
1690 if (!string_list_has_string(&src_ref_index,
1691 src_name))
1692 ref->peer_ref = alloc_delete_ref();
1693 free(src_name);
1696 string_list_clear(&src_ref_index, 0);
1699 *dst = apply_negative_refspecs(*dst, rs);
1701 if (errs)
1702 return -1;
1703 return 0;
1706 void set_ref_status_for_push(struct ref *remote_refs, int send_mirror,
1707 int force_update)
1709 struct ref *ref;
1711 for (ref = remote_refs; ref; ref = ref->next) {
1712 int force_ref_update = ref->force || force_update;
1713 int reject_reason = 0;
1715 if (ref->peer_ref)
1716 oidcpy(&ref->new_oid, &ref->peer_ref->new_oid);
1717 else if (!send_mirror)
1718 continue;
1720 ref->deletion = is_null_oid(&ref->new_oid);
1721 if (!ref->deletion &&
1722 oideq(&ref->old_oid, &ref->new_oid)) {
1723 ref->status = REF_STATUS_UPTODATE;
1724 continue;
1728 * If the remote ref has moved and is now different
1729 * from what we expect, reject any push.
1731 * It also is an error if the user told us to check
1732 * with the remote-tracking branch to find the value
1733 * to expect, but we did not have such a tracking
1734 * branch.
1736 * If the tip of the remote-tracking ref is unreachable
1737 * from any reflog entry of its local ref indicating a
1738 * possible update since checkout; reject the push.
1740 if (ref->expect_old_sha1) {
1741 if (!oideq(&ref->old_oid, &ref->old_oid_expect))
1742 reject_reason = REF_STATUS_REJECT_STALE;
1743 else if (ref->check_reachable && ref->unreachable)
1744 reject_reason =
1745 REF_STATUS_REJECT_REMOTE_UPDATED;
1746 else
1748 * If the ref isn't stale, and is reachable
1749 * from one of the reflog entries of
1750 * the local branch, force the update.
1752 force_ref_update = 1;
1756 * If the update isn't already rejected then check
1757 * the usual "must fast-forward" rules.
1759 * Decide whether an individual refspec A:B can be
1760 * pushed. The push will succeed if any of the
1761 * following are true:
1763 * (1) the remote reference B does not exist
1765 * (2) the remote reference B is being removed (i.e.,
1766 * pushing :B where no source is specified)
1768 * (3) the destination is not under refs/tags/, and
1769 * if the old and new value is a commit, the new
1770 * is a descendant of the old.
1772 * (4) it is forced using the +A:B notation, or by
1773 * passing the --force argument
1776 if (!reject_reason && !ref->deletion && !is_null_oid(&ref->old_oid)) {
1777 if (starts_with(ref->name, "refs/tags/"))
1778 reject_reason = REF_STATUS_REJECT_ALREADY_EXISTS;
1779 else if (!repo_has_object_file(the_repository, &ref->old_oid))
1780 reject_reason = REF_STATUS_REJECT_FETCH_FIRST;
1781 else if (!lookup_commit_reference_gently(the_repository, &ref->old_oid, 1) ||
1782 !lookup_commit_reference_gently(the_repository, &ref->new_oid, 1))
1783 reject_reason = REF_STATUS_REJECT_NEEDS_FORCE;
1784 else if (!ref_newer(&ref->new_oid, &ref->old_oid))
1785 reject_reason = REF_STATUS_REJECT_NONFASTFORWARD;
1789 * "--force" will defeat any rejection implemented
1790 * by the rules above.
1792 if (!force_ref_update)
1793 ref->status = reject_reason;
1794 else if (reject_reason)
1795 ref->forced_update = 1;
1799 static void set_merge(struct remote_state *remote_state, struct branch *ret)
1801 struct remote *remote;
1802 char *ref;
1803 struct object_id oid;
1804 int i;
1806 if (!ret)
1807 return; /* no branch */
1808 if (ret->merge)
1809 return; /* already run */
1810 if (!ret->remote_name || !ret->merge_nr) {
1812 * no merge config; let's make sure we don't confuse callers
1813 * with a non-zero merge_nr but a NULL merge
1815 ret->merge_nr = 0;
1816 return;
1819 remote = remotes_remote_get(remote_state, ret->remote_name);
1821 CALLOC_ARRAY(ret->merge, ret->merge_nr);
1822 for (i = 0; i < ret->merge_nr; i++) {
1823 ret->merge[i] = xcalloc(1, sizeof(**ret->merge));
1824 ret->merge[i]->src = xstrdup(ret->merge_name[i]);
1825 if (!remote_find_tracking(remote, ret->merge[i]) ||
1826 strcmp(ret->remote_name, "."))
1827 continue;
1828 if (repo_dwim_ref(the_repository, ret->merge_name[i],
1829 strlen(ret->merge_name[i]), &oid, &ref,
1830 0) == 1)
1831 ret->merge[i]->dst = ref;
1832 else
1833 ret->merge[i]->dst = xstrdup(ret->merge_name[i]);
1837 struct branch *branch_get(const char *name)
1839 struct branch *ret;
1841 read_config(the_repository, 0);
1842 if (!name || !*name || !strcmp(name, "HEAD"))
1843 ret = the_repository->remote_state->current_branch;
1844 else
1845 ret = make_branch(the_repository->remote_state, name,
1846 strlen(name));
1847 set_merge(the_repository->remote_state, ret);
1848 return ret;
1851 int branch_has_merge_config(struct branch *branch)
1853 return branch && !!branch->merge;
1856 int branch_merge_matches(struct branch *branch,
1857 int i,
1858 const char *refname)
1860 if (!branch || i < 0 || i >= branch->merge_nr)
1861 return 0;
1862 return refname_match(branch->merge[i]->src, refname);
1865 __attribute__((format (printf,2,3)))
1866 static const char *error_buf(struct strbuf *err, const char *fmt, ...)
1868 if (err) {
1869 va_list ap;
1870 va_start(ap, fmt);
1871 strbuf_vaddf(err, fmt, ap);
1872 va_end(ap);
1874 return NULL;
1877 const char *branch_get_upstream(struct branch *branch, struct strbuf *err)
1879 if (!branch)
1880 return error_buf(err, _("HEAD does not point to a branch"));
1882 if (!branch->merge || !branch->merge[0]) {
1884 * no merge config; is it because the user didn't define any,
1885 * or because it is not a real branch, and get_branch
1886 * auto-vivified it?
1888 if (!refs_ref_exists(get_main_ref_store(the_repository), branch->refname))
1889 return error_buf(err, _("no such branch: '%s'"),
1890 branch->name);
1891 return error_buf(err,
1892 _("no upstream configured for branch '%s'"),
1893 branch->name);
1896 if (!branch->merge[0]->dst)
1897 return error_buf(err,
1898 _("upstream branch '%s' not stored as a remote-tracking branch"),
1899 branch->merge[0]->src);
1901 return branch->merge[0]->dst;
1904 static const char *tracking_for_push_dest(struct remote *remote,
1905 const char *refname,
1906 struct strbuf *err)
1908 char *ret;
1910 ret = apply_refspecs(&remote->fetch, refname);
1911 if (!ret)
1912 return error_buf(err,
1913 _("push destination '%s' on remote '%s' has no local tracking branch"),
1914 refname, remote->name);
1915 return ret;
1918 static const char *branch_get_push_1(struct remote_state *remote_state,
1919 struct branch *branch, struct strbuf *err)
1921 struct remote *remote;
1923 remote = remotes_remote_get(
1924 remote_state,
1925 remotes_pushremote_for_branch(remote_state, branch, NULL));
1926 if (!remote)
1927 return error_buf(err,
1928 _("branch '%s' has no remote for pushing"),
1929 branch->name);
1931 if (remote->push.nr) {
1932 char *dst;
1933 const char *ret;
1935 dst = apply_refspecs(&remote->push, branch->refname);
1936 if (!dst)
1937 return error_buf(err,
1938 _("push refspecs for '%s' do not include '%s'"),
1939 remote->name, branch->name);
1941 ret = tracking_for_push_dest(remote, dst, err);
1942 free(dst);
1943 return ret;
1946 if (remote->mirror)
1947 return tracking_for_push_dest(remote, branch->refname, err);
1949 switch (push_default) {
1950 case PUSH_DEFAULT_NOTHING:
1951 return error_buf(err, _("push has no destination (push.default is 'nothing')"));
1953 case PUSH_DEFAULT_MATCHING:
1954 case PUSH_DEFAULT_CURRENT:
1955 return tracking_for_push_dest(remote, branch->refname, err);
1957 case PUSH_DEFAULT_UPSTREAM:
1958 return branch_get_upstream(branch, err);
1960 case PUSH_DEFAULT_UNSPECIFIED:
1961 case PUSH_DEFAULT_SIMPLE:
1963 const char *up, *cur;
1965 up = branch_get_upstream(branch, err);
1966 if (!up)
1967 return NULL;
1968 cur = tracking_for_push_dest(remote, branch->refname, err);
1969 if (!cur)
1970 return NULL;
1971 if (strcmp(cur, up))
1972 return error_buf(err,
1973 _("cannot resolve 'simple' push to a single destination"));
1974 return cur;
1978 BUG("unhandled push situation");
1981 const char *branch_get_push(struct branch *branch, struct strbuf *err)
1983 read_config(the_repository, 0);
1984 die_on_missing_branch(the_repository, branch);
1986 if (!branch)
1987 return error_buf(err, _("HEAD does not point to a branch"));
1989 if (!branch->push_tracking_ref)
1990 branch->push_tracking_ref = branch_get_push_1(
1991 the_repository->remote_state, branch, err);
1992 return branch->push_tracking_ref;
1995 static int ignore_symref_update(const char *refname, struct strbuf *scratch)
1997 return !refs_read_symbolic_ref(get_main_ref_store(the_repository), refname, scratch);
2001 * Create and return a list of (struct ref) consisting of copies of
2002 * each remote_ref that matches refspec. refspec must be a pattern.
2003 * Fill in the copies' peer_ref to describe the local tracking refs to
2004 * which they map. Omit any references that would map to an existing
2005 * local symbolic ref.
2007 static struct ref *get_expanded_map(const struct ref *remote_refs,
2008 const struct refspec_item *refspec)
2010 struct strbuf scratch = STRBUF_INIT;
2011 const struct ref *ref;
2012 struct ref *ret = NULL;
2013 struct ref **tail = &ret;
2015 for (ref = remote_refs; ref; ref = ref->next) {
2016 char *expn_name = NULL;
2018 strbuf_reset(&scratch);
2020 if (strchr(ref->name, '^'))
2021 continue; /* a dereference item */
2022 if (match_name_with_pattern(refspec->src, ref->name,
2023 refspec->dst, &expn_name) &&
2024 !ignore_symref_update(expn_name, &scratch)) {
2025 struct ref *cpy = copy_ref(ref);
2027 cpy->peer_ref = alloc_ref(expn_name);
2028 if (refspec->force)
2029 cpy->peer_ref->force = 1;
2030 *tail = cpy;
2031 tail = &cpy->next;
2033 free(expn_name);
2036 strbuf_release(&scratch);
2037 return ret;
2040 static const struct ref *find_ref_by_name_abbrev(const struct ref *refs, const char *name)
2042 const struct ref *ref;
2043 const struct ref *best_match = NULL;
2044 int best_score = 0;
2046 for (ref = refs; ref; ref = ref->next) {
2047 int score = refname_match(name, ref->name);
2049 if (best_score < score) {
2050 best_match = ref;
2051 best_score = score;
2054 return best_match;
2057 struct ref *get_remote_ref(const struct ref *remote_refs, const char *name)
2059 const struct ref *ref = find_ref_by_name_abbrev(remote_refs, name);
2061 if (!ref)
2062 return NULL;
2064 return copy_ref(ref);
2067 static struct ref *get_local_ref(const char *name)
2069 if (!name || name[0] == '\0')
2070 return NULL;
2072 if (starts_with(name, "refs/"))
2073 return alloc_ref(name);
2075 if (starts_with(name, "heads/") ||
2076 starts_with(name, "tags/") ||
2077 starts_with(name, "remotes/"))
2078 return alloc_ref_with_prefix("refs/", 5, name);
2080 return alloc_ref_with_prefix("refs/heads/", 11, name);
2083 int get_fetch_map(const struct ref *remote_refs,
2084 const struct refspec_item *refspec,
2085 struct ref ***tail,
2086 int missing_ok)
2088 struct ref *ref_map, **rmp;
2090 if (refspec->negative)
2091 return 0;
2093 if (refspec->pattern) {
2094 ref_map = get_expanded_map(remote_refs, refspec);
2095 } else {
2096 const char *name = refspec->src[0] ? refspec->src : "HEAD";
2098 if (refspec->exact_sha1) {
2099 ref_map = alloc_ref(name);
2100 get_oid_hex(name, &ref_map->old_oid);
2101 ref_map->exact_oid = 1;
2102 } else {
2103 ref_map = get_remote_ref(remote_refs, name);
2105 if (!missing_ok && !ref_map)
2106 die(_("couldn't find remote ref %s"), name);
2107 if (ref_map) {
2108 ref_map->peer_ref = get_local_ref(refspec->dst);
2109 if (ref_map->peer_ref && refspec->force)
2110 ref_map->peer_ref->force = 1;
2114 for (rmp = &ref_map; *rmp; ) {
2115 if ((*rmp)->peer_ref) {
2116 if (!starts_with((*rmp)->peer_ref->name, "refs/") ||
2117 check_refname_format((*rmp)->peer_ref->name, 0)) {
2118 struct ref *ignore = *rmp;
2119 error(_("* Ignoring funny ref '%s' locally"),
2120 (*rmp)->peer_ref->name);
2121 *rmp = (*rmp)->next;
2122 free(ignore->peer_ref);
2123 free(ignore);
2124 continue;
2127 rmp = &((*rmp)->next);
2130 if (ref_map)
2131 tail_link_ref(ref_map, tail);
2133 return 0;
2136 int resolve_remote_symref(struct ref *ref, struct ref *list)
2138 if (!ref->symref)
2139 return 0;
2140 for (; list; list = list->next)
2141 if (!strcmp(ref->symref, list->name)) {
2142 oidcpy(&ref->old_oid, &list->old_oid);
2143 return 0;
2145 return 1;
2149 * Compute the commit ahead/behind values for the pair branch_name, base.
2151 * If abf is AHEAD_BEHIND_FULL, compute the full ahead/behind and return the
2152 * counts in *num_ours and *num_theirs. If abf is AHEAD_BEHIND_QUICK, skip
2153 * the (potentially expensive) a/b computation (*num_ours and *num_theirs are
2154 * set to zero).
2156 * Returns -1 if num_ours and num_theirs could not be filled in (e.g., ref
2157 * does not exist). Returns 0 if the commits are identical. Returns 1 if
2158 * commits are different.
2161 static int stat_branch_pair(const char *branch_name, const char *base,
2162 int *num_ours, int *num_theirs,
2163 enum ahead_behind_flags abf)
2165 struct object_id oid;
2166 struct commit *ours, *theirs;
2167 struct rev_info revs;
2168 struct setup_revision_opt opt = {
2169 .free_removed_argv_elements = 1,
2171 struct strvec argv = STRVEC_INIT;
2173 /* Cannot stat if what we used to build on no longer exists */
2174 if (refs_read_ref(get_main_ref_store(the_repository), base, &oid))
2175 return -1;
2176 theirs = lookup_commit_reference(the_repository, &oid);
2177 if (!theirs)
2178 return -1;
2180 if (refs_read_ref(get_main_ref_store(the_repository), branch_name, &oid))
2181 return -1;
2182 ours = lookup_commit_reference(the_repository, &oid);
2183 if (!ours)
2184 return -1;
2186 *num_theirs = *num_ours = 0;
2188 /* are we the same? */
2189 if (theirs == ours)
2190 return 0;
2191 if (abf == AHEAD_BEHIND_QUICK)
2192 return 1;
2193 if (abf != AHEAD_BEHIND_FULL)
2194 BUG("stat_branch_pair: invalid abf '%d'", abf);
2196 /* Run "rev-list --left-right ours...theirs" internally... */
2197 strvec_push(&argv, ""); /* ignored */
2198 strvec_push(&argv, "--left-right");
2199 strvec_pushf(&argv, "%s...%s",
2200 oid_to_hex(&ours->object.oid),
2201 oid_to_hex(&theirs->object.oid));
2202 strvec_push(&argv, "--");
2204 repo_init_revisions(the_repository, &revs, NULL);
2205 setup_revisions(argv.nr, argv.v, &revs, &opt);
2206 if (prepare_revision_walk(&revs))
2207 die(_("revision walk setup failed"));
2209 /* ... and count the commits on each side. */
2210 while (1) {
2211 struct commit *c = get_revision(&revs);
2212 if (!c)
2213 break;
2214 if (c->object.flags & SYMMETRIC_LEFT)
2215 (*num_ours)++;
2216 else
2217 (*num_theirs)++;
2220 /* clear object flags smudged by the above traversal */
2221 clear_commit_marks(ours, ALL_REV_FLAGS);
2222 clear_commit_marks(theirs, ALL_REV_FLAGS);
2224 strvec_clear(&argv);
2225 release_revisions(&revs);
2226 return 1;
2230 * Lookup the tracking branch for the given branch and if present, optionally
2231 * compute the commit ahead/behind values for the pair.
2233 * If for_push is true, the tracking branch refers to the push branch,
2234 * otherwise it refers to the upstream branch.
2236 * The name of the tracking branch (or NULL if it is not defined) is
2237 * returned via *tracking_name, if it is not itself NULL.
2239 * If abf is AHEAD_BEHIND_FULL, compute the full ahead/behind and return the
2240 * counts in *num_ours and *num_theirs. If abf is AHEAD_BEHIND_QUICK, skip
2241 * the (potentially expensive) a/b computation (*num_ours and *num_theirs are
2242 * set to zero).
2244 * Returns -1 if num_ours and num_theirs could not be filled in (e.g., no
2245 * upstream defined, or ref does not exist). Returns 0 if the commits are
2246 * identical. Returns 1 if commits are different.
2248 int stat_tracking_info(struct branch *branch, int *num_ours, int *num_theirs,
2249 const char **tracking_name, int for_push,
2250 enum ahead_behind_flags abf)
2252 const char *base;
2254 /* Cannot stat unless we are marked to build on top of somebody else. */
2255 base = for_push ? branch_get_push(branch, NULL) :
2256 branch_get_upstream(branch, NULL);
2257 if (tracking_name)
2258 *tracking_name = base;
2259 if (!base)
2260 return -1;
2262 return stat_branch_pair(branch->refname, base, num_ours, num_theirs, abf);
2266 * Return true when there is anything to report, otherwise false.
2268 int format_tracking_info(struct branch *branch, struct strbuf *sb,
2269 enum ahead_behind_flags abf,
2270 int show_divergence_advice)
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 = refs_shorten_unambiguous_ref(get_main_ref_store(the_repository),
2285 full_base, 0);
2286 if (upstream_is_gone) {
2287 strbuf_addf(sb,
2288 _("Your branch is based on '%s', but the upstream is gone.\n"),
2289 base);
2290 if (advice_enabled(ADVICE_STATUS_HINTS))
2291 strbuf_addstr(sb,
2292 _(" (use \"git branch --unset-upstream\" to fixup)\n"));
2293 } else if (!sti) {
2294 strbuf_addf(sb,
2295 _("Your branch is up to date with '%s'.\n"),
2296 base);
2297 } else if (abf == AHEAD_BEHIND_QUICK) {
2298 strbuf_addf(sb,
2299 _("Your branch and '%s' refer to different commits.\n"),
2300 base);
2301 if (advice_enabled(ADVICE_STATUS_HINTS))
2302 strbuf_addf(sb, _(" (use \"%s\" for details)\n"),
2303 "git status --ahead-behind");
2304 } else if (!theirs) {
2305 strbuf_addf(sb,
2306 Q_("Your branch is ahead of '%s' by %d commit.\n",
2307 "Your branch is ahead of '%s' by %d commits.\n",
2308 ours),
2309 base, ours);
2310 if (advice_enabled(ADVICE_STATUS_HINTS))
2311 strbuf_addstr(sb,
2312 _(" (use \"git push\" to publish your local commits)\n"));
2313 } else if (!ours) {
2314 strbuf_addf(sb,
2315 Q_("Your branch is behind '%s' by %d commit, "
2316 "and can be fast-forwarded.\n",
2317 "Your branch is behind '%s' by %d commits, "
2318 "and can be fast-forwarded.\n",
2319 theirs),
2320 base, theirs);
2321 if (advice_enabled(ADVICE_STATUS_HINTS))
2322 strbuf_addstr(sb,
2323 _(" (use \"git pull\" to update your local branch)\n"));
2324 } else {
2325 strbuf_addf(sb,
2326 Q_("Your branch and '%s' have diverged,\n"
2327 "and have %d and %d different commit each, "
2328 "respectively.\n",
2329 "Your branch and '%s' have diverged,\n"
2330 "and have %d and %d different commits each, "
2331 "respectively.\n",
2332 ours + theirs),
2333 base, ours, theirs);
2334 if (show_divergence_advice &&
2335 advice_enabled(ADVICE_STATUS_HINTS))
2336 strbuf_addstr(sb,
2337 _(" (use \"git pull\" if you want to integrate the remote branch with yours)\n"));
2339 free(base);
2340 return 1;
2343 static int one_local_ref(const char *refname, const struct object_id *oid,
2344 int flag UNUSED,
2345 void *cb_data)
2347 struct ref ***local_tail = cb_data;
2348 struct ref *ref;
2350 /* we already know it starts with refs/ to get here */
2351 if (check_refname_format(refname + 5, 0))
2352 return 0;
2354 ref = alloc_ref(refname);
2355 oidcpy(&ref->new_oid, oid);
2356 **local_tail = ref;
2357 *local_tail = &ref->next;
2358 return 0;
2361 struct ref *get_local_heads(void)
2363 struct ref *local_refs = NULL, **local_tail = &local_refs;
2365 refs_for_each_ref(get_main_ref_store(the_repository), one_local_ref,
2366 &local_tail);
2367 return local_refs;
2370 struct ref *guess_remote_head(const struct ref *head,
2371 const struct ref *refs,
2372 int all)
2374 const struct ref *r;
2375 struct ref *list = NULL;
2376 struct ref **tail = &list;
2378 if (!head)
2379 return NULL;
2382 * Some transports support directly peeking at
2383 * where HEAD points; if that is the case, then
2384 * we don't have to guess.
2386 if (head->symref)
2387 return copy_ref(find_ref_by_name(refs, head->symref));
2389 /* If a remote branch exists with the default branch name, let's use it. */
2390 if (!all) {
2391 char *ref = xstrfmt("refs/heads/%s",
2392 git_default_branch_name(0));
2394 r = find_ref_by_name(refs, ref);
2395 free(ref);
2396 if (r && oideq(&r->old_oid, &head->old_oid))
2397 return copy_ref(r);
2399 /* Fall back to the hard-coded historical default */
2400 r = find_ref_by_name(refs, "refs/heads/master");
2401 if (r && oideq(&r->old_oid, &head->old_oid))
2402 return copy_ref(r);
2405 /* Look for another ref that points there */
2406 for (r = refs; r; r = r->next) {
2407 if (r != head &&
2408 starts_with(r->name, "refs/heads/") &&
2409 oideq(&r->old_oid, &head->old_oid)) {
2410 *tail = copy_ref(r);
2411 tail = &((*tail)->next);
2412 if (!all)
2413 break;
2417 return list;
2420 struct stale_heads_info {
2421 struct string_list *ref_names;
2422 struct ref **stale_refs_tail;
2423 struct refspec *rs;
2426 static int get_stale_heads_cb(const char *refname, const struct object_id *oid,
2427 int flags, void *cb_data)
2429 struct stale_heads_info *info = cb_data;
2430 struct string_list matches = STRING_LIST_INIT_DUP;
2431 struct refspec_item query;
2432 int i, stale = 1;
2433 memset(&query, 0, sizeof(struct refspec_item));
2434 query.dst = (char *)refname;
2436 query_refspecs_multiple(info->rs, &query, &matches);
2437 if (matches.nr == 0)
2438 goto clean_exit; /* No matches */
2441 * If we did find a suitable refspec and it's not a symref and
2442 * it's not in the list of refs that currently exist in that
2443 * remote, we consider it to be stale. In order to deal with
2444 * overlapping refspecs, we need to go over all of the
2445 * matching refs.
2447 if (flags & REF_ISSYMREF)
2448 goto clean_exit;
2450 for (i = 0; stale && i < matches.nr; i++)
2451 if (string_list_has_string(info->ref_names, matches.items[i].string))
2452 stale = 0;
2454 if (stale) {
2455 struct ref *ref = make_linked_ref(refname, &info->stale_refs_tail);
2456 oidcpy(&ref->new_oid, oid);
2459 clean_exit:
2460 string_list_clear(&matches, 0);
2461 return 0;
2464 struct ref *get_stale_heads(struct refspec *rs, struct ref *fetch_map)
2466 struct ref *ref, *stale_refs = NULL;
2467 struct string_list ref_names = STRING_LIST_INIT_NODUP;
2468 struct stale_heads_info info;
2470 info.ref_names = &ref_names;
2471 info.stale_refs_tail = &stale_refs;
2472 info.rs = rs;
2473 for (ref = fetch_map; ref; ref = ref->next)
2474 string_list_append(&ref_names, ref->name);
2475 string_list_sort(&ref_names);
2476 refs_for_each_ref(get_main_ref_store(the_repository),
2477 get_stale_heads_cb, &info);
2478 string_list_clear(&ref_names, 0);
2479 return stale_refs;
2483 * Compare-and-swap
2485 static void clear_cas_option(struct push_cas_option *cas)
2487 int i;
2489 for (i = 0; i < cas->nr; i++)
2490 free(cas->entry[i].refname);
2491 free(cas->entry);
2492 memset(cas, 0, sizeof(*cas));
2495 static struct push_cas *add_cas_entry(struct push_cas_option *cas,
2496 const char *refname,
2497 size_t refnamelen)
2499 struct push_cas *entry;
2500 ALLOC_GROW(cas->entry, cas->nr + 1, cas->alloc);
2501 entry = &cas->entry[cas->nr++];
2502 memset(entry, 0, sizeof(*entry));
2503 entry->refname = xmemdupz(refname, refnamelen);
2504 return entry;
2507 static int parse_push_cas_option(struct push_cas_option *cas, const char *arg, int unset)
2509 const char *colon;
2510 struct push_cas *entry;
2512 if (unset) {
2513 /* "--no-<option>" */
2514 clear_cas_option(cas);
2515 return 0;
2518 if (!arg) {
2519 /* just "--<option>" */
2520 cas->use_tracking_for_rest = 1;
2521 return 0;
2524 /* "--<option>=refname" or "--<option>=refname:value" */
2525 colon = strchrnul(arg, ':');
2526 entry = add_cas_entry(cas, arg, colon - arg);
2527 if (!*colon)
2528 entry->use_tracking = 1;
2529 else if (!colon[1])
2530 oidclr(&entry->expect);
2531 else if (repo_get_oid(the_repository, colon + 1, &entry->expect))
2532 return error(_("cannot parse expected object name '%s'"),
2533 colon + 1);
2534 return 0;
2537 int parseopt_push_cas_option(const struct option *opt, const char *arg, int unset)
2539 return parse_push_cas_option(opt->value, arg, unset);
2542 int is_empty_cas(const struct push_cas_option *cas)
2544 return !cas->use_tracking_for_rest && !cas->nr;
2548 * Look at remote.fetch refspec and see if we have a remote
2549 * tracking branch for the refname there. Fill the name of
2550 * the remote-tracking branch in *dst_refname, and the name
2551 * of the commit object at its tip in oid[].
2552 * If we cannot do so, return negative to signal an error.
2554 static int remote_tracking(struct remote *remote, const char *refname,
2555 struct object_id *oid, char **dst_refname)
2557 char *dst;
2559 dst = apply_refspecs(&remote->fetch, refname);
2560 if (!dst)
2561 return -1; /* no tracking ref for refname at remote */
2562 if (refs_read_ref(get_main_ref_store(the_repository), dst, oid))
2563 return -1; /* we know what the tracking ref is but we cannot read it */
2565 *dst_refname = dst;
2566 return 0;
2570 * The struct "reflog_commit_array" and related helper functions
2571 * are used for collecting commits into an array during reflog
2572 * traversals in "check_and_collect_until()".
2574 struct reflog_commit_array {
2575 struct commit **item;
2576 size_t nr, alloc;
2579 #define REFLOG_COMMIT_ARRAY_INIT { 0 }
2581 /* Append a commit to the array. */
2582 static void append_commit(struct reflog_commit_array *arr,
2583 struct commit *commit)
2585 ALLOC_GROW(arr->item, arr->nr + 1, arr->alloc);
2586 arr->item[arr->nr++] = commit;
2589 /* Free and reset the array. */
2590 static void free_commit_array(struct reflog_commit_array *arr)
2592 FREE_AND_NULL(arr->item);
2593 arr->nr = arr->alloc = 0;
2596 struct check_and_collect_until_cb_data {
2597 struct commit *remote_commit;
2598 struct reflog_commit_array *local_commits;
2599 timestamp_t remote_reflog_timestamp;
2602 /* Get the timestamp of the latest entry. */
2603 static int peek_reflog(struct object_id *o_oid UNUSED,
2604 struct object_id *n_oid UNUSED,
2605 const char *ident UNUSED,
2606 timestamp_t timestamp, int tz UNUSED,
2607 const char *message UNUSED, void *cb_data)
2609 timestamp_t *ts = cb_data;
2610 *ts = timestamp;
2611 return 1;
2614 static int check_and_collect_until(struct object_id *o_oid UNUSED,
2615 struct object_id *n_oid,
2616 const char *ident UNUSED,
2617 timestamp_t timestamp, int tz UNUSED,
2618 const char *message UNUSED, void *cb_data)
2620 struct commit *commit;
2621 struct check_and_collect_until_cb_data *cb = cb_data;
2623 /* An entry was found. */
2624 if (oideq(n_oid, &cb->remote_commit->object.oid))
2625 return 1;
2627 if ((commit = lookup_commit_reference(the_repository, n_oid)))
2628 append_commit(cb->local_commits, commit);
2631 * If the reflog entry timestamp is older than the remote ref's
2632 * latest reflog entry, there is no need to check or collect
2633 * entries older than this one.
2635 if (timestamp < cb->remote_reflog_timestamp)
2636 return -1;
2638 return 0;
2641 #define MERGE_BASES_BATCH_SIZE 8
2644 * Iterate through the reflog of the local ref to check if there is an entry
2645 * for the given remote-tracking ref; runs until the timestamp of an entry is
2646 * older than latest timestamp of remote-tracking ref's reflog. Any commits
2647 * are that seen along the way are collected into an array to check if the
2648 * remote-tracking ref is reachable from any of them.
2650 static int is_reachable_in_reflog(const char *local, const struct ref *remote)
2652 timestamp_t date;
2653 struct commit *commit;
2654 struct commit **chunk;
2655 struct check_and_collect_until_cb_data cb;
2656 struct reflog_commit_array arr = REFLOG_COMMIT_ARRAY_INIT;
2657 size_t size = 0;
2658 int ret = 0;
2660 commit = lookup_commit_reference(the_repository, &remote->old_oid);
2661 if (!commit)
2662 goto cleanup_return;
2665 * Get the timestamp from the latest entry
2666 * of the remote-tracking ref's reflog.
2668 refs_for_each_reflog_ent_reverse(get_main_ref_store(the_repository),
2669 remote->tracking_ref, peek_reflog,
2670 &date);
2672 cb.remote_commit = commit;
2673 cb.local_commits = &arr;
2674 cb.remote_reflog_timestamp = date;
2675 ret = refs_for_each_reflog_ent_reverse(get_main_ref_store(the_repository),
2676 local, check_and_collect_until,
2677 &cb);
2679 /* We found an entry in the reflog. */
2680 if (ret > 0)
2681 goto cleanup_return;
2684 * Check if the remote commit is reachable from any
2685 * of the commits in the collected array, in batches.
2687 for (chunk = arr.item; chunk < arr.item + arr.nr; chunk += size) {
2688 size = arr.item + arr.nr - chunk;
2689 if (MERGE_BASES_BATCH_SIZE < size)
2690 size = MERGE_BASES_BATCH_SIZE;
2692 if ((ret = repo_in_merge_bases_many(the_repository, commit, size, chunk, 0)))
2693 break;
2696 cleanup_return:
2697 free_commit_array(&arr);
2698 return ret;
2702 * Check for reachability of a remote-tracking
2703 * ref in the reflog entries of its local ref.
2705 static void check_if_includes_upstream(struct ref *remote)
2707 struct ref *local = get_local_ref(remote->name);
2708 if (!local)
2709 return;
2711 if (is_reachable_in_reflog(local->name, remote) <= 0)
2712 remote->unreachable = 1;
2715 static void apply_cas(struct push_cas_option *cas,
2716 struct remote *remote,
2717 struct ref *ref)
2719 int i;
2721 /* Find an explicit --<option>=<name>[:<value>] entry */
2722 for (i = 0; i < cas->nr; i++) {
2723 struct push_cas *entry = &cas->entry[i];
2724 if (!refname_match(entry->refname, ref->name))
2725 continue;
2726 ref->expect_old_sha1 = 1;
2727 if (!entry->use_tracking)
2728 oidcpy(&ref->old_oid_expect, &entry->expect);
2729 else if (remote_tracking(remote, ref->name,
2730 &ref->old_oid_expect,
2731 &ref->tracking_ref))
2732 oidclr(&ref->old_oid_expect);
2733 else
2734 ref->check_reachable = cas->use_force_if_includes;
2735 return;
2738 /* Are we using "--<option>" to cover all? */
2739 if (!cas->use_tracking_for_rest)
2740 return;
2742 ref->expect_old_sha1 = 1;
2743 if (remote_tracking(remote, ref->name,
2744 &ref->old_oid_expect,
2745 &ref->tracking_ref))
2746 oidclr(&ref->old_oid_expect);
2747 else
2748 ref->check_reachable = cas->use_force_if_includes;
2751 void apply_push_cas(struct push_cas_option *cas,
2752 struct remote *remote,
2753 struct ref *remote_refs)
2755 struct ref *ref;
2756 for (ref = remote_refs; ref; ref = ref->next) {
2757 apply_cas(cas, remote, ref);
2760 * If "compare-and-swap" is in "use_tracking[_for_rest]"
2761 * mode, and if "--force-if-includes" was specified, run
2762 * the check.
2764 if (ref->check_reachable)
2765 check_if_includes_upstream(ref);
2769 struct remote_state *remote_state_new(void)
2771 struct remote_state *r = xmalloc(sizeof(*r));
2773 memset(r, 0, sizeof(*r));
2775 hashmap_init(&r->remotes_hash, remotes_hash_cmp, NULL, 0);
2776 hashmap_init(&r->branches_hash, branches_hash_cmp, NULL, 0);
2777 return r;
2780 void remote_state_clear(struct remote_state *remote_state)
2782 int i;
2784 for (i = 0; i < remote_state->remotes_nr; i++)
2785 remote_clear(remote_state->remotes[i]);
2786 FREE_AND_NULL(remote_state->remotes);
2787 remote_state->remotes_alloc = 0;
2788 remote_state->remotes_nr = 0;
2790 hashmap_clear_and_free(&remote_state->remotes_hash, struct remote, ent);
2791 hashmap_clear_and_free(&remote_state->branches_hash, struct remote, ent);
2795 * Returns 1 if it was the last chop before ':'.
2797 static int chop_last_dir(char **remoteurl, int is_relative)
2799 char *rfind = find_last_dir_sep(*remoteurl);
2800 if (rfind) {
2801 *rfind = '\0';
2802 return 0;
2805 rfind = strrchr(*remoteurl, ':');
2806 if (rfind) {
2807 *rfind = '\0';
2808 return 1;
2811 if (is_relative || !strcmp(".", *remoteurl))
2812 die(_("cannot strip one component off url '%s'"),
2813 *remoteurl);
2815 free(*remoteurl);
2816 *remoteurl = xstrdup(".");
2817 return 0;
2820 char *relative_url(const char *remote_url, const char *url,
2821 const char *up_path)
2823 int is_relative = 0;
2824 int colonsep = 0;
2825 char *out;
2826 char *remoteurl;
2827 struct strbuf sb = STRBUF_INIT;
2828 size_t len;
2830 if (!url_is_local_not_ssh(url) || is_absolute_path(url))
2831 return xstrdup(url);
2833 len = strlen(remote_url);
2834 if (!len)
2835 BUG("invalid empty remote_url");
2837 remoteurl = xstrdup(remote_url);
2838 if (is_dir_sep(remoteurl[len-1]))
2839 remoteurl[len-1] = '\0';
2841 if (!url_is_local_not_ssh(remoteurl) || is_absolute_path(remoteurl))
2842 is_relative = 0;
2843 else {
2844 is_relative = 1;
2846 * Prepend a './' to ensure all relative
2847 * remoteurls start with './' or '../'
2849 if (!starts_with_dot_slash_native(remoteurl) &&
2850 !starts_with_dot_dot_slash_native(remoteurl)) {
2851 strbuf_reset(&sb);
2852 strbuf_addf(&sb, "./%s", remoteurl);
2853 free(remoteurl);
2854 remoteurl = strbuf_detach(&sb, NULL);
2858 * When the url starts with '../', remove that and the
2859 * last directory in remoteurl.
2861 while (*url) {
2862 if (starts_with_dot_dot_slash_native(url)) {
2863 url += 3;
2864 colonsep |= chop_last_dir(&remoteurl, is_relative);
2865 } else if (starts_with_dot_slash_native(url))
2866 url += 2;
2867 else
2868 break;
2870 strbuf_reset(&sb);
2871 strbuf_addf(&sb, "%s%s%s", remoteurl, colonsep ? ":" : "/", url);
2872 if (ends_with(url, "/"))
2873 strbuf_setlen(&sb, sb.len - 1);
2874 free(remoteurl);
2876 if (starts_with_dot_slash_native(sb.buf))
2877 out = xstrdup(sb.buf + 2);
2878 else
2879 out = xstrdup(sb.buf);
2881 if (!up_path || !is_relative) {
2882 strbuf_release(&sb);
2883 return out;
2886 strbuf_reset(&sb);
2887 strbuf_addf(&sb, "%s%s", up_path, out);
2888 free(out);
2889 return strbuf_detach(&sb, NULL);