t5000: use check_mtime()
[git.git] / remote.c
blob60869beebe7364a594cd45938d4ed97dcdd28840
1 #include "cache.h"
2 #include "config.h"
3 #include "remote.h"
4 #include "urlmatch.h"
5 #include "refs.h"
6 #include "refspec.h"
7 #include "object-store.h"
8 #include "commit.h"
9 #include "diff.h"
10 #include "revision.h"
11 #include "dir.h"
12 #include "tag.h"
13 #include "string-list.h"
14 #include "strvec.h"
15 #include "commit-reach.h"
16 #include "advice.h"
17 #include "connect.h"
19 enum map_direction { FROM_SRC, FROM_DST };
21 struct counted_string {
22 size_t len;
23 const char *s;
26 static int valid_remote(const struct remote *remote)
28 return (!!remote->url) || (!!remote->foreign_vcs);
31 static const char *alias_url(const char *url, struct rewrites *r)
33 int i, j;
34 struct counted_string *longest;
35 int longest_i;
37 longest = NULL;
38 longest_i = -1;
39 for (i = 0; i < r->rewrite_nr; i++) {
40 if (!r->rewrite[i])
41 continue;
42 for (j = 0; j < r->rewrite[i]->instead_of_nr; j++) {
43 if (starts_with(url, r->rewrite[i]->instead_of[j].s) &&
44 (!longest ||
45 longest->len < r->rewrite[i]->instead_of[j].len)) {
46 longest = &(r->rewrite[i]->instead_of[j]);
47 longest_i = i;
51 if (!longest)
52 return url;
54 return xstrfmt("%s%s", r->rewrite[longest_i]->base, url + longest->len);
57 static void add_url(struct remote *remote, const char *url)
59 ALLOC_GROW(remote->url, remote->url_nr + 1, remote->url_alloc);
60 remote->url[remote->url_nr++] = url;
63 static void add_pushurl(struct remote *remote, const char *pushurl)
65 ALLOC_GROW(remote->pushurl, remote->pushurl_nr + 1, remote->pushurl_alloc);
66 remote->pushurl[remote->pushurl_nr++] = pushurl;
69 static void add_pushurl_alias(struct remote_state *remote_state,
70 struct remote *remote, const char *url)
72 const char *pushurl = alias_url(url, &remote_state->rewrites_push);
73 if (pushurl != url)
74 add_pushurl(remote, pushurl);
77 static void add_url_alias(struct remote_state *remote_state,
78 struct remote *remote, const char *url)
80 add_url(remote, alias_url(url, &remote_state->rewrites));
81 add_pushurl_alias(remote_state, remote, url);
84 struct remotes_hash_key {
85 const char *str;
86 int len;
89 static int remotes_hash_cmp(const void *cmp_data UNUSED,
90 const struct hashmap_entry *eptr,
91 const struct hashmap_entry *entry_or_key,
92 const void *keydata)
94 const struct remote *a, *b;
95 const struct remotes_hash_key *key = keydata;
97 a = container_of(eptr, const struct remote, ent);
98 b = container_of(entry_or_key, const struct remote, ent);
100 if (key)
101 return strncmp(a->name, key->str, key->len) || a->name[key->len];
102 else
103 return strcmp(a->name, b->name);
106 static struct remote *make_remote(struct remote_state *remote_state,
107 const char *name, int len)
109 struct remote *ret;
110 struct remotes_hash_key lookup;
111 struct hashmap_entry lookup_entry, *e;
113 if (!len)
114 len = strlen(name);
116 lookup.str = name;
117 lookup.len = len;
118 hashmap_entry_init(&lookup_entry, memhash(name, len));
120 e = hashmap_get(&remote_state->remotes_hash, &lookup_entry, &lookup);
121 if (e)
122 return container_of(e, struct remote, ent);
124 CALLOC_ARRAY(ret, 1);
125 ret->prune = -1; /* unspecified */
126 ret->prune_tags = -1; /* unspecified */
127 ret->name = xstrndup(name, len);
128 refspec_init(&ret->push, REFSPEC_PUSH);
129 refspec_init(&ret->fetch, REFSPEC_FETCH);
131 ALLOC_GROW(remote_state->remotes, remote_state->remotes_nr + 1,
132 remote_state->remotes_alloc);
133 remote_state->remotes[remote_state->remotes_nr++] = ret;
135 hashmap_entry_init(&ret->ent, lookup_entry.hash);
136 if (hashmap_put_entry(&remote_state->remotes_hash, ret, ent))
137 BUG("hashmap_put overwrote entry after hashmap_get returned NULL");
138 return ret;
141 static void remote_clear(struct remote *remote)
143 int i;
145 free((char *)remote->name);
146 free((char *)remote->foreign_vcs);
148 for (i = 0; i < remote->url_nr; i++)
149 free((char *)remote->url[i]);
150 FREE_AND_NULL(remote->url);
152 for (i = 0; i < remote->pushurl_nr; i++)
153 free((char *)remote->pushurl[i]);
154 FREE_AND_NULL(remote->pushurl);
155 free((char *)remote->receivepack);
156 free((char *)remote->uploadpack);
157 FREE_AND_NULL(remote->http_proxy);
158 FREE_AND_NULL(remote->http_proxy_authmethod);
161 static void add_merge(struct branch *branch, const char *name)
163 ALLOC_GROW(branch->merge_name, branch->merge_nr + 1,
164 branch->merge_alloc);
165 branch->merge_name[branch->merge_nr++] = name;
168 struct branches_hash_key {
169 const char *str;
170 int len;
173 static int branches_hash_cmp(const void *cmp_data UNUSED,
174 const struct hashmap_entry *eptr,
175 const struct hashmap_entry *entry_or_key,
176 const void *keydata)
178 const struct branch *a, *b;
179 const struct branches_hash_key *key = keydata;
181 a = container_of(eptr, const struct branch, ent);
182 b = container_of(entry_or_key, const struct branch, ent);
184 if (key)
185 return strncmp(a->name, key->str, key->len) ||
186 a->name[key->len];
187 else
188 return strcmp(a->name, b->name);
191 static struct branch *find_branch(struct remote_state *remote_state,
192 const char *name, size_t len)
194 struct branches_hash_key lookup;
195 struct hashmap_entry lookup_entry, *e;
197 lookup.str = name;
198 lookup.len = len;
199 hashmap_entry_init(&lookup_entry, memhash(name, len));
201 e = hashmap_get(&remote_state->branches_hash, &lookup_entry, &lookup);
202 if (e)
203 return container_of(e, struct branch, ent);
205 return NULL;
208 static void die_on_missing_branch(struct repository *repo,
209 struct branch *branch)
211 /* branch == NULL is always valid because it represents detached HEAD. */
212 if (branch &&
213 branch != find_branch(repo->remote_state, branch->name,
214 strlen(branch->name)))
215 die("branch %s was not found in the repository", branch->name);
218 static struct branch *make_branch(struct remote_state *remote_state,
219 const char *name, size_t len)
221 struct branch *ret;
223 ret = find_branch(remote_state, name, len);
224 if (ret)
225 return ret;
227 CALLOC_ARRAY(ret, 1);
228 ret->name = xstrndup(name, len);
229 ret->refname = xstrfmt("refs/heads/%s", ret->name);
231 hashmap_entry_init(&ret->ent, memhash(name, len));
232 if (hashmap_put_entry(&remote_state->branches_hash, ret, ent))
233 BUG("hashmap_put overwrote entry after hashmap_get returned NULL");
234 return ret;
237 static struct rewrite *make_rewrite(struct rewrites *r,
238 const char *base, size_t len)
240 struct rewrite *ret;
241 int i;
243 for (i = 0; i < r->rewrite_nr; i++) {
244 if (len == r->rewrite[i]->baselen &&
245 !strncmp(base, r->rewrite[i]->base, len))
246 return r->rewrite[i];
249 ALLOC_GROW(r->rewrite, r->rewrite_nr + 1, r->rewrite_alloc);
250 CALLOC_ARRAY(ret, 1);
251 r->rewrite[r->rewrite_nr++] = ret;
252 ret->base = xstrndup(base, len);
253 ret->baselen = len;
254 return ret;
257 static void add_instead_of(struct rewrite *rewrite, const char *instead_of)
259 ALLOC_GROW(rewrite->instead_of, rewrite->instead_of_nr + 1, rewrite->instead_of_alloc);
260 rewrite->instead_of[rewrite->instead_of_nr].s = instead_of;
261 rewrite->instead_of[rewrite->instead_of_nr].len = strlen(instead_of);
262 rewrite->instead_of_nr++;
265 static const char *skip_spaces(const char *s)
267 while (isspace(*s))
268 s++;
269 return s;
272 static void read_remotes_file(struct remote_state *remote_state,
273 struct remote *remote)
275 struct strbuf buf = STRBUF_INIT;
276 FILE *f = fopen_or_warn(git_path("remotes/%s", remote->name), "r");
278 if (!f)
279 return;
280 remote->configured_in_repo = 1;
281 remote->origin = REMOTE_REMOTES;
282 while (strbuf_getline(&buf, f) != EOF) {
283 const char *v;
285 strbuf_rtrim(&buf);
287 if (skip_prefix(buf.buf, "URL:", &v))
288 add_url_alias(remote_state, remote,
289 xstrdup(skip_spaces(v)));
290 else if (skip_prefix(buf.buf, "Push:", &v))
291 refspec_append(&remote->push, skip_spaces(v));
292 else if (skip_prefix(buf.buf, "Pull:", &v))
293 refspec_append(&remote->fetch, skip_spaces(v));
295 strbuf_release(&buf);
296 fclose(f);
299 static void read_branches_file(struct remote_state *remote_state,
300 struct remote *remote)
302 char *frag;
303 struct strbuf buf = STRBUF_INIT;
304 FILE *f = fopen_or_warn(git_path("branches/%s", remote->name), "r");
306 if (!f)
307 return;
309 strbuf_getline_lf(&buf, f);
310 fclose(f);
311 strbuf_trim(&buf);
312 if (!buf.len) {
313 strbuf_release(&buf);
314 return;
317 remote->configured_in_repo = 1;
318 remote->origin = REMOTE_BRANCHES;
321 * The branches file would have URL and optionally
322 * #branch specified. The default (or specified) branch is
323 * fetched and stored in the local branch matching the
324 * remote name.
326 frag = strchr(buf.buf, '#');
327 if (frag)
328 *(frag++) = '\0';
329 else
330 frag = (char *)git_default_branch_name(0);
332 add_url_alias(remote_state, remote, strbuf_detach(&buf, NULL));
333 refspec_appendf(&remote->fetch, "refs/heads/%s:refs/heads/%s",
334 frag, remote->name);
337 * Cogito compatible push: push current HEAD to remote #branch
338 * (master if missing)
340 refspec_appendf(&remote->push, "HEAD:refs/heads/%s", frag);
341 remote->fetch_tags = 1; /* always auto-follow */
344 static int handle_config(const char *key, const char *value, void *cb)
346 const char *name;
347 size_t namelen;
348 const char *subkey;
349 struct remote *remote;
350 struct branch *branch;
351 struct remote_state *remote_state = cb;
353 if (parse_config_key(key, "branch", &name, &namelen, &subkey) >= 0) {
354 /* There is no subsection. */
355 if (!name)
356 return 0;
357 /* There is a subsection, but it is empty. */
358 if (!namelen)
359 return -1;
360 branch = make_branch(remote_state, name, namelen);
361 if (!strcmp(subkey, "remote")) {
362 return git_config_string(&branch->remote_name, key, value);
363 } else if (!strcmp(subkey, "pushremote")) {
364 return git_config_string(&branch->pushremote_name, key, value);
365 } else if (!strcmp(subkey, "merge")) {
366 if (!value)
367 return config_error_nonbool(key);
368 add_merge(branch, xstrdup(value));
370 return 0;
372 if (parse_config_key(key, "url", &name, &namelen, &subkey) >= 0) {
373 struct rewrite *rewrite;
374 if (!name)
375 return 0;
376 if (!strcmp(subkey, "insteadof")) {
377 if (!value)
378 return config_error_nonbool(key);
379 rewrite = make_rewrite(&remote_state->rewrites, name,
380 namelen);
381 add_instead_of(rewrite, xstrdup(value));
382 } else if (!strcmp(subkey, "pushinsteadof")) {
383 if (!value)
384 return config_error_nonbool(key);
385 rewrite = make_rewrite(&remote_state->rewrites_push,
386 name, namelen);
387 add_instead_of(rewrite, xstrdup(value));
391 if (parse_config_key(key, "remote", &name, &namelen, &subkey) < 0)
392 return 0;
394 /* Handle remote.* variables */
395 if (!name && !strcmp(subkey, "pushdefault"))
396 return git_config_string(&remote_state->pushremote_name, key,
397 value);
399 if (!name)
400 return 0;
401 /* Handle remote.<name>.* variables */
402 if (*name == '/') {
403 warning(_("config remote shorthand cannot begin with '/': %s"),
404 name);
405 return 0;
407 remote = make_remote(remote_state, name, namelen);
408 remote->origin = REMOTE_CONFIG;
409 if (current_config_scope() == CONFIG_SCOPE_LOCAL ||
410 current_config_scope() == CONFIG_SCOPE_WORKTREE)
411 remote->configured_in_repo = 1;
412 if (!strcmp(subkey, "mirror"))
413 remote->mirror = git_config_bool(key, value);
414 else if (!strcmp(subkey, "skipdefaultupdate"))
415 remote->skip_default_update = git_config_bool(key, value);
416 else if (!strcmp(subkey, "skipfetchall"))
417 remote->skip_default_update = git_config_bool(key, value);
418 else if (!strcmp(subkey, "prune"))
419 remote->prune = git_config_bool(key, value);
420 else if (!strcmp(subkey, "prunetags"))
421 remote->prune_tags = git_config_bool(key, value);
422 else if (!strcmp(subkey, "url")) {
423 const char *v;
424 if (git_config_string(&v, key, value))
425 return -1;
426 add_url(remote, v);
427 } else if (!strcmp(subkey, "pushurl")) {
428 const char *v;
429 if (git_config_string(&v, key, value))
430 return -1;
431 add_pushurl(remote, v);
432 } else if (!strcmp(subkey, "push")) {
433 const char *v;
434 if (git_config_string(&v, key, value))
435 return -1;
436 refspec_append(&remote->push, v);
437 free((char *)v);
438 } else if (!strcmp(subkey, "fetch")) {
439 const char *v;
440 if (git_config_string(&v, key, value))
441 return -1;
442 refspec_append(&remote->fetch, v);
443 free((char *)v);
444 } else if (!strcmp(subkey, "receivepack")) {
445 const char *v;
446 if (git_config_string(&v, key, value))
447 return -1;
448 if (!remote->receivepack)
449 remote->receivepack = v;
450 else
451 error(_("more than one receivepack given, using the first"));
452 } else if (!strcmp(subkey, "uploadpack")) {
453 const char *v;
454 if (git_config_string(&v, key, value))
455 return -1;
456 if (!remote->uploadpack)
457 remote->uploadpack = v;
458 else
459 error(_("more than one uploadpack given, using the first"));
460 } else if (!strcmp(subkey, "tagopt")) {
461 if (!strcmp(value, "--no-tags"))
462 remote->fetch_tags = -1;
463 else if (!strcmp(value, "--tags"))
464 remote->fetch_tags = 2;
465 } else if (!strcmp(subkey, "proxy")) {
466 return git_config_string((const char **)&remote->http_proxy,
467 key, value);
468 } else if (!strcmp(subkey, "proxyauthmethod")) {
469 return git_config_string((const char **)&remote->http_proxy_authmethod,
470 key, value);
471 } else if (!strcmp(subkey, "vcs")) {
472 return git_config_string(&remote->foreign_vcs, key, value);
474 return 0;
477 static void alias_all_urls(struct remote_state *remote_state)
479 int i, j;
480 for (i = 0; i < remote_state->remotes_nr; i++) {
481 int add_pushurl_aliases;
482 if (!remote_state->remotes[i])
483 continue;
484 for (j = 0; j < remote_state->remotes[i]->pushurl_nr; j++) {
485 remote_state->remotes[i]->pushurl[j] =
486 alias_url(remote_state->remotes[i]->pushurl[j],
487 &remote_state->rewrites);
489 add_pushurl_aliases = remote_state->remotes[i]->pushurl_nr == 0;
490 for (j = 0; j < remote_state->remotes[i]->url_nr; j++) {
491 if (add_pushurl_aliases)
492 add_pushurl_alias(
493 remote_state, remote_state->remotes[i],
494 remote_state->remotes[i]->url[j]);
495 remote_state->remotes[i]->url[j] =
496 alias_url(remote_state->remotes[i]->url[j],
497 &remote_state->rewrites);
502 static void read_config(struct repository *repo)
504 int flag;
506 if (repo->remote_state->initialized)
507 return;
508 repo->remote_state->initialized = 1;
510 repo->remote_state->current_branch = NULL;
511 if (startup_info->have_repository) {
512 const char *head_ref = refs_resolve_ref_unsafe(
513 get_main_ref_store(repo), "HEAD", 0, NULL, &flag);
514 if (head_ref && (flag & REF_ISSYMREF) &&
515 skip_prefix(head_ref, "refs/heads/", &head_ref)) {
516 repo->remote_state->current_branch = make_branch(
517 repo->remote_state, head_ref, strlen(head_ref));
520 repo_config(repo, handle_config, repo->remote_state);
521 alias_all_urls(repo->remote_state);
524 static int valid_remote_nick(const char *name)
526 if (!name[0] || is_dot_or_dotdot(name))
527 return 0;
529 /* remote nicknames cannot contain slashes */
530 while (*name)
531 if (is_dir_sep(*name++))
532 return 0;
533 return 1;
536 static const char *remotes_remote_for_branch(struct remote_state *remote_state,
537 struct branch *branch,
538 int *explicit)
540 if (branch && branch->remote_name) {
541 if (explicit)
542 *explicit = 1;
543 return branch->remote_name;
545 if (explicit)
546 *explicit = 0;
547 if (remote_state->remotes_nr == 1)
548 return remote_state->remotes[0]->name;
549 return "origin";
552 const char *remote_for_branch(struct branch *branch, int *explicit)
554 read_config(the_repository);
555 die_on_missing_branch(the_repository, branch);
557 return remotes_remote_for_branch(the_repository->remote_state, branch,
558 explicit);
561 static const char *
562 remotes_pushremote_for_branch(struct remote_state *remote_state,
563 struct branch *branch, int *explicit)
565 if (branch && branch->pushremote_name) {
566 if (explicit)
567 *explicit = 1;
568 return branch->pushremote_name;
570 if (remote_state->pushremote_name) {
571 if (explicit)
572 *explicit = 1;
573 return remote_state->pushremote_name;
575 return remotes_remote_for_branch(remote_state, branch, explicit);
578 const char *pushremote_for_branch(struct branch *branch, int *explicit)
580 read_config(the_repository);
581 die_on_missing_branch(the_repository, branch);
583 return remotes_pushremote_for_branch(the_repository->remote_state,
584 branch, explicit);
587 static struct remote *remotes_remote_get(struct remote_state *remote_state,
588 const char *name);
590 const char *remote_ref_for_branch(struct branch *branch, int for_push)
592 read_config(the_repository);
593 die_on_missing_branch(the_repository, branch);
595 if (branch) {
596 if (!for_push) {
597 if (branch->merge_nr) {
598 return branch->merge_name[0];
600 } else {
601 const char *dst,
602 *remote_name = remotes_pushremote_for_branch(
603 the_repository->remote_state, branch,
604 NULL);
605 struct remote *remote = remotes_remote_get(
606 the_repository->remote_state, remote_name);
608 if (remote && remote->push.nr &&
609 (dst = apply_refspecs(&remote->push,
610 branch->refname))) {
611 return dst;
615 return NULL;
618 static void validate_remote_url(struct remote *remote)
620 int i;
621 const char *value;
622 struct strbuf redacted = STRBUF_INIT;
623 int warn_not_die;
625 if (git_config_get_string_tmp("transfer.credentialsinurl", &value))
626 return;
628 if (!strcmp("warn", value))
629 warn_not_die = 1;
630 else if (!strcmp("die", value))
631 warn_not_die = 0;
632 else if (!strcmp("allow", value))
633 return;
634 else
635 die(_("unrecognized value transfer.credentialsInUrl: '%s'"), value);
637 for (i = 0; i < remote->url_nr; i++) {
638 struct url_info url_info = { 0 };
640 if (!url_normalize(remote->url[i], &url_info) ||
641 !url_info.passwd_off)
642 goto loop_cleanup;
644 strbuf_reset(&redacted);
645 strbuf_add(&redacted, url_info.url, url_info.passwd_off);
646 strbuf_addstr(&redacted, "<redacted>");
647 strbuf_addstr(&redacted,
648 url_info.url + url_info.passwd_off + url_info.passwd_len);
650 if (warn_not_die)
651 warning(_("URL '%s' uses plaintext credentials"), redacted.buf);
652 else
653 die(_("URL '%s' uses plaintext credentials"), redacted.buf);
655 loop_cleanup:
656 free(url_info.url);
659 strbuf_release(&redacted);
662 static struct remote *
663 remotes_remote_get_1(struct remote_state *remote_state, const char *name,
664 const char *(*get_default)(struct remote_state *,
665 struct branch *, int *))
667 struct remote *ret;
668 int name_given = 0;
670 if (name)
671 name_given = 1;
672 else
673 name = get_default(remote_state, remote_state->current_branch,
674 &name_given);
676 ret = make_remote(remote_state, name, 0);
677 if (valid_remote_nick(name) && have_git_dir()) {
678 if (!valid_remote(ret))
679 read_remotes_file(remote_state, ret);
680 if (!valid_remote(ret))
681 read_branches_file(remote_state, ret);
683 if (name_given && !valid_remote(ret))
684 add_url_alias(remote_state, ret, name);
685 if (!valid_remote(ret))
686 return NULL;
688 validate_remote_url(ret);
690 return ret;
693 static inline struct remote *
694 remotes_remote_get(struct remote_state *remote_state, const char *name)
696 return remotes_remote_get_1(remote_state, name,
697 remotes_remote_for_branch);
700 struct remote *remote_get(const char *name)
702 read_config(the_repository);
703 return remotes_remote_get(the_repository->remote_state, name);
706 static inline struct remote *
707 remotes_pushremote_get(struct remote_state *remote_state, const char *name)
709 return remotes_remote_get_1(remote_state, name,
710 remotes_pushremote_for_branch);
713 struct remote *pushremote_get(const char *name)
715 read_config(the_repository);
716 return remotes_pushremote_get(the_repository->remote_state, name);
719 int remote_is_configured(struct remote *remote, int in_repo)
721 if (!remote)
722 return 0;
723 if (in_repo)
724 return remote->configured_in_repo;
725 return !!remote->origin;
728 int for_each_remote(each_remote_fn fn, void *priv)
730 int i, result = 0;
731 read_config(the_repository);
732 for (i = 0; i < the_repository->remote_state->remotes_nr && !result;
733 i++) {
734 struct remote *remote =
735 the_repository->remote_state->remotes[i];
736 if (!remote)
737 continue;
738 result = fn(remote, priv);
740 return result;
743 static void handle_duplicate(struct ref *ref1, struct ref *ref2)
745 if (strcmp(ref1->name, ref2->name)) {
746 if (ref1->fetch_head_status != FETCH_HEAD_IGNORE &&
747 ref2->fetch_head_status != FETCH_HEAD_IGNORE) {
748 die(_("Cannot fetch both %s and %s to %s"),
749 ref1->name, ref2->name, ref2->peer_ref->name);
750 } else if (ref1->fetch_head_status != FETCH_HEAD_IGNORE &&
751 ref2->fetch_head_status == FETCH_HEAD_IGNORE) {
752 warning(_("%s usually tracks %s, not %s"),
753 ref2->peer_ref->name, ref2->name, ref1->name);
754 } else if (ref1->fetch_head_status == FETCH_HEAD_IGNORE &&
755 ref2->fetch_head_status == FETCH_HEAD_IGNORE) {
756 die(_("%s tracks both %s and %s"),
757 ref2->peer_ref->name, ref1->name, ref2->name);
758 } else {
760 * This last possibility doesn't occur because
761 * FETCH_HEAD_IGNORE entries always appear at
762 * the end of the list.
764 BUG("Internal error");
767 free(ref2->peer_ref);
768 free(ref2);
771 struct ref *ref_remove_duplicates(struct ref *ref_map)
773 struct string_list refs = STRING_LIST_INIT_NODUP;
774 struct ref *retval = NULL;
775 struct ref **p = &retval;
777 while (ref_map) {
778 struct ref *ref = ref_map;
780 ref_map = ref_map->next;
781 ref->next = NULL;
783 if (!ref->peer_ref) {
784 *p = ref;
785 p = &ref->next;
786 } else {
787 struct string_list_item *item =
788 string_list_insert(&refs, ref->peer_ref->name);
790 if (item->util) {
791 /* Entry already existed */
792 handle_duplicate((struct ref *)item->util, ref);
793 } else {
794 *p = ref;
795 p = &ref->next;
796 item->util = ref;
801 string_list_clear(&refs, 0);
802 return retval;
805 int remote_has_url(struct remote *remote, const char *url)
807 int i;
808 for (i = 0; i < remote->url_nr; i++) {
809 if (!strcmp(remote->url[i], url))
810 return 1;
812 return 0;
815 static int match_name_with_pattern(const char *key, const char *name,
816 const char *value, char **result)
818 const char *kstar = strchr(key, '*');
819 size_t klen;
820 size_t ksuffixlen;
821 size_t namelen;
822 int ret;
823 if (!kstar)
824 die(_("key '%s' of pattern had no '*'"), key);
825 klen = kstar - key;
826 ksuffixlen = strlen(kstar + 1);
827 namelen = strlen(name);
828 ret = !strncmp(name, key, klen) && namelen >= klen + ksuffixlen &&
829 !memcmp(name + namelen - ksuffixlen, kstar + 1, ksuffixlen);
830 if (ret && value) {
831 struct strbuf sb = STRBUF_INIT;
832 const char *vstar = strchr(value, '*');
833 if (!vstar)
834 die(_("value '%s' of pattern has no '*'"), value);
835 strbuf_add(&sb, value, vstar - value);
836 strbuf_add(&sb, name + klen, namelen - klen - ksuffixlen);
837 strbuf_addstr(&sb, vstar + 1);
838 *result = strbuf_detach(&sb, NULL);
840 return ret;
843 static int refspec_match(const struct refspec_item *refspec,
844 const char *name)
846 if (refspec->pattern)
847 return match_name_with_pattern(refspec->src, name, NULL, NULL);
849 return !strcmp(refspec->src, name);
852 int omit_name_by_refspec(const char *name, struct refspec *rs)
854 int i;
856 for (i = 0; i < rs->nr; i++) {
857 if (rs->items[i].negative && refspec_match(&rs->items[i], name))
858 return 1;
860 return 0;
863 struct ref *apply_negative_refspecs(struct ref *ref_map, struct refspec *rs)
865 struct ref **tail;
867 for (tail = &ref_map; *tail; ) {
868 struct ref *ref = *tail;
870 if (omit_name_by_refspec(ref->name, rs)) {
871 *tail = ref->next;
872 free(ref->peer_ref);
873 free(ref);
874 } else
875 tail = &ref->next;
878 return ref_map;
881 static int query_matches_negative_refspec(struct refspec *rs, struct refspec_item *query)
883 int i, matched_negative = 0;
884 int find_src = !query->src;
885 struct string_list reversed = STRING_LIST_INIT_NODUP;
886 const char *needle = find_src ? query->dst : query->src;
889 * Check whether the queried ref matches any negative refpsec. If so,
890 * then we should ultimately treat this as not matching the query at
891 * all.
893 * Note that negative refspecs always match the source, but the query
894 * item uses the destination. To handle this, we apply pattern
895 * refspecs in reverse to figure out if the query source matches any
896 * of the negative refspecs.
898 * The first loop finds and expands all positive refspecs
899 * matched by the queried ref.
901 * The second loop checks if any of the results of the first loop
902 * match any negative refspec.
904 for (i = 0; i < rs->nr; i++) {
905 struct refspec_item *refspec = &rs->items[i];
906 char *expn_name;
908 if (refspec->negative)
909 continue;
911 /* Note the reversal of src and dst */
912 if (refspec->pattern) {
913 const char *key = refspec->dst ? refspec->dst : refspec->src;
914 const char *value = refspec->src;
916 if (match_name_with_pattern(key, needle, value, &expn_name))
917 string_list_append_nodup(&reversed, expn_name);
918 } else if (refspec->matching) {
919 /* For the special matching refspec, any query should match */
920 string_list_append(&reversed, needle);
921 } else if (!refspec->src) {
922 BUG("refspec->src should not be null here");
923 } else if (!strcmp(needle, refspec->src)) {
924 string_list_append(&reversed, refspec->src);
928 for (i = 0; !matched_negative && i < reversed.nr; i++) {
929 if (omit_name_by_refspec(reversed.items[i].string, rs))
930 matched_negative = 1;
933 string_list_clear(&reversed, 0);
935 return matched_negative;
938 static void query_refspecs_multiple(struct refspec *rs,
939 struct refspec_item *query,
940 struct string_list *results)
942 int i;
943 int find_src = !query->src;
945 if (find_src && !query->dst)
946 BUG("query_refspecs_multiple: need either src or dst");
948 if (query_matches_negative_refspec(rs, query))
949 return;
951 for (i = 0; i < rs->nr; i++) {
952 struct refspec_item *refspec = &rs->items[i];
953 const char *key = find_src ? refspec->dst : refspec->src;
954 const char *value = find_src ? refspec->src : refspec->dst;
955 const char *needle = find_src ? query->dst : query->src;
956 char **result = find_src ? &query->src : &query->dst;
958 if (!refspec->dst || refspec->negative)
959 continue;
960 if (refspec->pattern) {
961 if (match_name_with_pattern(key, needle, value, result))
962 string_list_append_nodup(results, *result);
963 } else if (!strcmp(needle, key)) {
964 string_list_append(results, value);
969 int query_refspecs(struct refspec *rs, struct refspec_item *query)
971 int i;
972 int find_src = !query->src;
973 const char *needle = find_src ? query->dst : query->src;
974 char **result = find_src ? &query->src : &query->dst;
976 if (find_src && !query->dst)
977 BUG("query_refspecs: need either src or dst");
979 if (query_matches_negative_refspec(rs, query))
980 return -1;
982 for (i = 0; i < rs->nr; i++) {
983 struct refspec_item *refspec = &rs->items[i];
984 const char *key = find_src ? refspec->dst : refspec->src;
985 const char *value = find_src ? refspec->src : refspec->dst;
987 if (!refspec->dst || refspec->negative)
988 continue;
989 if (refspec->pattern) {
990 if (match_name_with_pattern(key, needle, value, result)) {
991 query->force = refspec->force;
992 return 0;
994 } else if (!strcmp(needle, key)) {
995 *result = xstrdup(value);
996 query->force = refspec->force;
997 return 0;
1000 return -1;
1003 char *apply_refspecs(struct refspec *rs, const char *name)
1005 struct refspec_item query;
1007 memset(&query, 0, sizeof(struct refspec_item));
1008 query.src = (char *)name;
1010 if (query_refspecs(rs, &query))
1011 return NULL;
1013 return query.dst;
1016 int remote_find_tracking(struct remote *remote, struct refspec_item *refspec)
1018 return query_refspecs(&remote->fetch, refspec);
1021 static struct ref *alloc_ref_with_prefix(const char *prefix, size_t prefixlen,
1022 const char *name)
1024 size_t len = strlen(name);
1025 struct ref *ref = xcalloc(1, st_add4(sizeof(*ref), prefixlen, len, 1));
1026 memcpy(ref->name, prefix, prefixlen);
1027 memcpy(ref->name + prefixlen, name, len);
1028 return ref;
1031 struct ref *alloc_ref(const char *name)
1033 return alloc_ref_with_prefix("", 0, name);
1036 struct ref *copy_ref(const struct ref *ref)
1038 struct ref *cpy;
1039 size_t len;
1040 if (!ref)
1041 return NULL;
1042 len = st_add3(sizeof(struct ref), strlen(ref->name), 1);
1043 cpy = xmalloc(len);
1044 memcpy(cpy, ref, len);
1045 cpy->next = NULL;
1046 cpy->symref = xstrdup_or_null(ref->symref);
1047 cpy->remote_status = xstrdup_or_null(ref->remote_status);
1048 cpy->peer_ref = copy_ref(ref->peer_ref);
1049 return cpy;
1052 struct ref *copy_ref_list(const struct ref *ref)
1054 struct ref *ret = NULL;
1055 struct ref **tail = &ret;
1056 while (ref) {
1057 *tail = copy_ref(ref);
1058 ref = ref->next;
1059 tail = &((*tail)->next);
1061 return ret;
1064 void free_one_ref(struct ref *ref)
1066 if (!ref)
1067 return;
1068 free_one_ref(ref->peer_ref);
1069 free(ref->remote_status);
1070 free(ref->symref);
1071 free(ref);
1074 void free_refs(struct ref *ref)
1076 struct ref *next;
1077 while (ref) {
1078 next = ref->next;
1079 free_one_ref(ref);
1080 ref = next;
1084 int count_refspec_match(const char *pattern,
1085 struct ref *refs,
1086 struct ref **matched_ref)
1088 int patlen = strlen(pattern);
1089 struct ref *matched_weak = NULL;
1090 struct ref *matched = NULL;
1091 int weak_match = 0;
1092 int match = 0;
1094 for (weak_match = match = 0; refs; refs = refs->next) {
1095 char *name = refs->name;
1096 int namelen = strlen(name);
1098 if (!refname_match(pattern, name))
1099 continue;
1101 /* A match is "weak" if it is with refs outside
1102 * heads or tags, and did not specify the pattern
1103 * in full (e.g. "refs/remotes/origin/master") or at
1104 * least from the toplevel (e.g. "remotes/origin/master");
1105 * otherwise "git push $URL master" would result in
1106 * ambiguity between remotes/origin/master and heads/master
1107 * at the remote site.
1109 if (namelen != patlen &&
1110 patlen != namelen - 5 &&
1111 !starts_with(name, "refs/heads/") &&
1112 !starts_with(name, "refs/tags/")) {
1113 /* We want to catch the case where only weak
1114 * matches are found and there are multiple
1115 * matches, and where more than one strong
1116 * matches are found, as ambiguous. One
1117 * strong match with zero or more weak matches
1118 * are acceptable as a unique match.
1120 matched_weak = refs;
1121 weak_match++;
1123 else {
1124 matched = refs;
1125 match++;
1128 if (!matched) {
1129 if (matched_ref)
1130 *matched_ref = matched_weak;
1131 return weak_match;
1133 else {
1134 if (matched_ref)
1135 *matched_ref = matched;
1136 return match;
1140 static void tail_link_ref(struct ref *ref, struct ref ***tail)
1142 **tail = ref;
1143 while (ref->next)
1144 ref = ref->next;
1145 *tail = &ref->next;
1148 static struct ref *alloc_delete_ref(void)
1150 struct ref *ref = alloc_ref("(delete)");
1151 oidclr(&ref->new_oid);
1152 return ref;
1155 static int try_explicit_object_name(const char *name,
1156 struct ref **match)
1158 struct object_id oid;
1160 if (!*name) {
1161 if (match)
1162 *match = alloc_delete_ref();
1163 return 0;
1166 if (get_oid(name, &oid))
1167 return -1;
1169 if (match) {
1170 *match = alloc_ref(name);
1171 oidcpy(&(*match)->new_oid, &oid);
1173 return 0;
1176 static struct ref *make_linked_ref(const char *name, struct ref ***tail)
1178 struct ref *ret = alloc_ref(name);
1179 tail_link_ref(ret, tail);
1180 return ret;
1183 static char *guess_ref(const char *name, struct ref *peer)
1185 struct strbuf buf = STRBUF_INIT;
1187 const char *r = resolve_ref_unsafe(peer->name, RESOLVE_REF_READING,
1188 NULL, NULL);
1189 if (!r)
1190 return NULL;
1192 if (starts_with(r, "refs/heads/")) {
1193 strbuf_addstr(&buf, "refs/heads/");
1194 } else if (starts_with(r, "refs/tags/")) {
1195 strbuf_addstr(&buf, "refs/tags/");
1196 } else {
1197 return NULL;
1200 strbuf_addstr(&buf, name);
1201 return strbuf_detach(&buf, NULL);
1204 static int match_explicit_lhs(struct ref *src,
1205 struct refspec_item *rs,
1206 struct ref **match,
1207 int *allocated_match)
1209 switch (count_refspec_match(rs->src, src, match)) {
1210 case 1:
1211 if (allocated_match)
1212 *allocated_match = 0;
1213 return 0;
1214 case 0:
1215 /* The source could be in the get_sha1() format
1216 * not a reference name. :refs/other is a
1217 * way to delete 'other' ref at the remote end.
1219 if (try_explicit_object_name(rs->src, match) < 0)
1220 return error(_("src refspec %s does not match any"), rs->src);
1221 if (allocated_match)
1222 *allocated_match = 1;
1223 return 0;
1224 default:
1225 return error(_("src refspec %s matches more than one"), rs->src);
1229 static void show_push_unqualified_ref_name_error(const char *dst_value,
1230 const char *matched_src_name)
1232 struct object_id oid;
1233 enum object_type type;
1236 * TRANSLATORS: "matches '%s'%" is the <dst> part of "git push
1237 * <remote> <src>:<dst>" push, and "being pushed ('%s')" is
1238 * the <src>.
1240 error(_("The destination you provided is not a full refname (i.e.,\n"
1241 "starting with \"refs/\"). We tried to guess what you meant by:\n"
1242 "\n"
1243 "- Looking for a ref that matches '%s' on the remote side.\n"
1244 "- Checking if the <src> being pushed ('%s')\n"
1245 " is a ref in \"refs/{heads,tags}/\". If so we add a corresponding\n"
1246 " refs/{heads,tags}/ prefix on the remote side.\n"
1247 "\n"
1248 "Neither worked, so we gave up. You must fully qualify the ref."),
1249 dst_value, matched_src_name);
1251 if (!advice_enabled(ADVICE_PUSH_UNQUALIFIED_REF_NAME))
1252 return;
1254 if (get_oid(matched_src_name, &oid))
1255 BUG("'%s' is not a valid object, "
1256 "match_explicit_lhs() should catch this!",
1257 matched_src_name);
1258 type = oid_object_info(the_repository, &oid, NULL);
1259 if (type == OBJ_COMMIT) {
1260 advise(_("The <src> part of the refspec is a commit object.\n"
1261 "Did you mean to create a new branch by pushing to\n"
1262 "'%s:refs/heads/%s'?"),
1263 matched_src_name, dst_value);
1264 } else if (type == OBJ_TAG) {
1265 advise(_("The <src> part of the refspec is a tag object.\n"
1266 "Did you mean to create a new tag by pushing to\n"
1267 "'%s:refs/tags/%s'?"),
1268 matched_src_name, dst_value);
1269 } else if (type == OBJ_TREE) {
1270 advise(_("The <src> part of the refspec is a tree object.\n"
1271 "Did you mean to tag a new tree by pushing to\n"
1272 "'%s:refs/tags/%s'?"),
1273 matched_src_name, dst_value);
1274 } else if (type == OBJ_BLOB) {
1275 advise(_("The <src> part of the refspec is a blob object.\n"
1276 "Did you mean to tag a new blob by pushing to\n"
1277 "'%s:refs/tags/%s'?"),
1278 matched_src_name, dst_value);
1279 } else {
1280 BUG("'%s' should be commit/tag/tree/blob, is '%d'",
1281 matched_src_name, type);
1285 static int match_explicit(struct ref *src, struct ref *dst,
1286 struct ref ***dst_tail,
1287 struct refspec_item *rs)
1289 struct ref *matched_src, *matched_dst;
1290 int allocated_src;
1292 const char *dst_value = rs->dst;
1293 char *dst_guess;
1295 if (rs->pattern || rs->matching || rs->negative)
1296 return 0;
1298 matched_src = matched_dst = NULL;
1299 if (match_explicit_lhs(src, rs, &matched_src, &allocated_src) < 0)
1300 return -1;
1302 if (!dst_value) {
1303 int flag;
1305 dst_value = resolve_ref_unsafe(matched_src->name,
1306 RESOLVE_REF_READING,
1307 NULL, &flag);
1308 if (!dst_value ||
1309 ((flag & REF_ISSYMREF) &&
1310 !starts_with(dst_value, "refs/heads/")))
1311 die(_("%s cannot be resolved to branch"),
1312 matched_src->name);
1315 switch (count_refspec_match(dst_value, dst, &matched_dst)) {
1316 case 1:
1317 break;
1318 case 0:
1319 if (starts_with(dst_value, "refs/")) {
1320 matched_dst = make_linked_ref(dst_value, dst_tail);
1321 } else if (is_null_oid(&matched_src->new_oid)) {
1322 error(_("unable to delete '%s': remote ref does not exist"),
1323 dst_value);
1324 } else if ((dst_guess = guess_ref(dst_value, matched_src))) {
1325 matched_dst = make_linked_ref(dst_guess, dst_tail);
1326 free(dst_guess);
1327 } else {
1328 show_push_unqualified_ref_name_error(dst_value,
1329 matched_src->name);
1331 break;
1332 default:
1333 matched_dst = NULL;
1334 error(_("dst refspec %s matches more than one"),
1335 dst_value);
1336 break;
1338 if (!matched_dst)
1339 return -1;
1340 if (matched_dst->peer_ref)
1341 return error(_("dst ref %s receives from more than one src"),
1342 matched_dst->name);
1343 else {
1344 matched_dst->peer_ref = allocated_src ?
1345 matched_src :
1346 copy_ref(matched_src);
1347 matched_dst->force = rs->force;
1349 return 0;
1352 static int match_explicit_refs(struct ref *src, struct ref *dst,
1353 struct ref ***dst_tail, struct refspec *rs)
1355 int i, errs;
1356 for (i = errs = 0; i < rs->nr; i++)
1357 errs += match_explicit(src, dst, dst_tail, &rs->items[i]);
1358 return errs;
1361 static char *get_ref_match(const struct refspec *rs, const struct ref *ref,
1362 int send_mirror, int direction,
1363 const struct refspec_item **ret_pat)
1365 const struct refspec_item *pat;
1366 char *name;
1367 int i;
1368 int matching_refs = -1;
1369 for (i = 0; i < rs->nr; i++) {
1370 const struct refspec_item *item = &rs->items[i];
1372 if (item->negative)
1373 continue;
1375 if (item->matching &&
1376 (matching_refs == -1 || item->force)) {
1377 matching_refs = i;
1378 continue;
1381 if (item->pattern) {
1382 const char *dst_side = item->dst ? item->dst : item->src;
1383 int match;
1384 if (direction == FROM_SRC)
1385 match = match_name_with_pattern(item->src, ref->name, dst_side, &name);
1386 else
1387 match = match_name_with_pattern(dst_side, ref->name, item->src, &name);
1388 if (match) {
1389 matching_refs = i;
1390 break;
1394 if (matching_refs == -1)
1395 return NULL;
1397 pat = &rs->items[matching_refs];
1398 if (pat->matching) {
1400 * "matching refs"; traditionally we pushed everything
1401 * including refs outside refs/heads/ hierarchy, but
1402 * that does not make much sense these days.
1404 if (!send_mirror && !starts_with(ref->name, "refs/heads/"))
1405 return NULL;
1406 name = xstrdup(ref->name);
1408 if (ret_pat)
1409 *ret_pat = pat;
1410 return name;
1413 static struct ref **tail_ref(struct ref **head)
1415 struct ref **tail = head;
1416 while (*tail)
1417 tail = &((*tail)->next);
1418 return tail;
1421 struct tips {
1422 struct commit **tip;
1423 int nr, alloc;
1426 static void add_to_tips(struct tips *tips, const struct object_id *oid)
1428 struct commit *commit;
1430 if (is_null_oid(oid))
1431 return;
1432 commit = lookup_commit_reference_gently(the_repository, oid, 1);
1433 if (!commit || (commit->object.flags & TMP_MARK))
1434 return;
1435 commit->object.flags |= TMP_MARK;
1436 ALLOC_GROW(tips->tip, tips->nr + 1, tips->alloc);
1437 tips->tip[tips->nr++] = commit;
1440 static void add_missing_tags(struct ref *src, struct ref **dst, struct ref ***dst_tail)
1442 struct string_list dst_tag = STRING_LIST_INIT_NODUP;
1443 struct string_list src_tag = STRING_LIST_INIT_NODUP;
1444 struct string_list_item *item;
1445 struct ref *ref;
1446 struct tips sent_tips;
1449 * Collect everything we know they would have at the end of
1450 * this push, and collect all tags they have.
1452 memset(&sent_tips, 0, sizeof(sent_tips));
1453 for (ref = *dst; ref; ref = ref->next) {
1454 if (ref->peer_ref &&
1455 !is_null_oid(&ref->peer_ref->new_oid))
1456 add_to_tips(&sent_tips, &ref->peer_ref->new_oid);
1457 else
1458 add_to_tips(&sent_tips, &ref->old_oid);
1459 if (starts_with(ref->name, "refs/tags/"))
1460 string_list_append(&dst_tag, ref->name);
1462 clear_commit_marks_many(sent_tips.nr, sent_tips.tip, TMP_MARK);
1464 string_list_sort(&dst_tag);
1466 /* Collect tags they do not have. */
1467 for (ref = src; ref; ref = ref->next) {
1468 if (!starts_with(ref->name, "refs/tags/"))
1469 continue; /* not a tag */
1470 if (string_list_has_string(&dst_tag, ref->name))
1471 continue; /* they already have it */
1472 if (oid_object_info(the_repository, &ref->new_oid, NULL) != OBJ_TAG)
1473 continue; /* be conservative */
1474 item = string_list_append(&src_tag, ref->name);
1475 item->util = ref;
1477 string_list_clear(&dst_tag, 0);
1480 * At this point, src_tag lists tags that are missing from
1481 * dst, and sent_tips lists the tips we are pushing or those
1482 * that we know they already have. An element in the src_tag
1483 * that is an ancestor of any of the sent_tips needs to be
1484 * sent to the other side.
1486 if (sent_tips.nr) {
1487 const int reachable_flag = 1;
1488 struct commit_list *found_commits;
1489 struct commit **src_commits;
1490 int nr_src_commits = 0, alloc_src_commits = 16;
1491 ALLOC_ARRAY(src_commits, alloc_src_commits);
1493 for_each_string_list_item(item, &src_tag) {
1494 struct ref *ref = item->util;
1495 struct commit *commit;
1497 if (is_null_oid(&ref->new_oid))
1498 continue;
1499 commit = lookup_commit_reference_gently(the_repository,
1500 &ref->new_oid,
1502 if (!commit)
1503 /* not pushing a commit, which is not an error */
1504 continue;
1506 ALLOC_GROW(src_commits, nr_src_commits + 1, alloc_src_commits);
1507 src_commits[nr_src_commits++] = commit;
1510 found_commits = get_reachable_subset(sent_tips.tip, sent_tips.nr,
1511 src_commits, nr_src_commits,
1512 reachable_flag);
1514 for_each_string_list_item(item, &src_tag) {
1515 struct ref *dst_ref;
1516 struct ref *ref = item->util;
1517 struct commit *commit;
1519 if (is_null_oid(&ref->new_oid))
1520 continue;
1521 commit = lookup_commit_reference_gently(the_repository,
1522 &ref->new_oid,
1524 if (!commit)
1525 /* not pushing a commit, which is not an error */
1526 continue;
1529 * Is this tag, which they do not have, reachable from
1530 * any of the commits we are sending?
1532 if (!(commit->object.flags & reachable_flag))
1533 continue;
1535 /* Add it in */
1536 dst_ref = make_linked_ref(ref->name, dst_tail);
1537 oidcpy(&dst_ref->new_oid, &ref->new_oid);
1538 dst_ref->peer_ref = copy_ref(ref);
1541 clear_commit_marks_many(nr_src_commits, src_commits, reachable_flag);
1542 free(src_commits);
1543 free_commit_list(found_commits);
1546 string_list_clear(&src_tag, 0);
1547 free(sent_tips.tip);
1550 struct ref *find_ref_by_name(const struct ref *list, const char *name)
1552 for ( ; list; list = list->next)
1553 if (!strcmp(list->name, name))
1554 return (struct ref *)list;
1555 return NULL;
1558 static void prepare_ref_index(struct string_list *ref_index, struct ref *ref)
1560 for ( ; ref; ref = ref->next)
1561 string_list_append_nodup(ref_index, ref->name)->util = ref;
1563 string_list_sort(ref_index);
1567 * Given only the set of local refs, sanity-check the set of push
1568 * refspecs. We can't catch all errors that match_push_refs would,
1569 * but we can catch some errors early before even talking to the
1570 * remote side.
1572 int check_push_refs(struct ref *src, struct refspec *rs)
1574 int ret = 0;
1575 int i;
1577 for (i = 0; i < rs->nr; i++) {
1578 struct refspec_item *item = &rs->items[i];
1580 if (item->pattern || item->matching || item->negative)
1581 continue;
1583 ret |= match_explicit_lhs(src, item, NULL, NULL);
1586 return ret;
1590 * Given the set of refs the local repository has, the set of refs the
1591 * remote repository has, and the refspec used for push, determine
1592 * what remote refs we will update and with what value by setting
1593 * peer_ref (which object is being pushed) and force (if the push is
1594 * forced) in elements of "dst". The function may add new elements to
1595 * dst (e.g. pushing to a new branch, done in match_explicit_refs).
1597 int match_push_refs(struct ref *src, struct ref **dst,
1598 struct refspec *rs, int flags)
1600 int send_all = flags & MATCH_REFS_ALL;
1601 int send_mirror = flags & MATCH_REFS_MIRROR;
1602 int send_prune = flags & MATCH_REFS_PRUNE;
1603 int errs;
1604 struct ref *ref, **dst_tail = tail_ref(dst);
1605 struct string_list dst_ref_index = STRING_LIST_INIT_NODUP;
1607 /* If no refspec is provided, use the default ":" */
1608 if (!rs->nr)
1609 refspec_append(rs, ":");
1611 errs = match_explicit_refs(src, *dst, &dst_tail, rs);
1613 /* pick the remainder */
1614 for (ref = src; ref; ref = ref->next) {
1615 struct string_list_item *dst_item;
1616 struct ref *dst_peer;
1617 const struct refspec_item *pat = NULL;
1618 char *dst_name;
1620 dst_name = get_ref_match(rs, ref, send_mirror, FROM_SRC, &pat);
1621 if (!dst_name)
1622 continue;
1624 if (!dst_ref_index.nr)
1625 prepare_ref_index(&dst_ref_index, *dst);
1627 dst_item = string_list_lookup(&dst_ref_index, dst_name);
1628 dst_peer = dst_item ? dst_item->util : NULL;
1629 if (dst_peer) {
1630 if (dst_peer->peer_ref)
1631 /* We're already sending something to this ref. */
1632 goto free_name;
1633 } else {
1634 if (pat->matching && !(send_all || send_mirror))
1636 * Remote doesn't have it, and we have no
1637 * explicit pattern, and we don't have
1638 * --all or --mirror.
1640 goto free_name;
1642 /* Create a new one and link it */
1643 dst_peer = make_linked_ref(dst_name, &dst_tail);
1644 oidcpy(&dst_peer->new_oid, &ref->new_oid);
1645 string_list_insert(&dst_ref_index,
1646 dst_peer->name)->util = dst_peer;
1648 dst_peer->peer_ref = copy_ref(ref);
1649 dst_peer->force = pat->force;
1650 free_name:
1651 free(dst_name);
1654 string_list_clear(&dst_ref_index, 0);
1656 if (flags & MATCH_REFS_FOLLOW_TAGS)
1657 add_missing_tags(src, dst, &dst_tail);
1659 if (send_prune) {
1660 struct string_list src_ref_index = STRING_LIST_INIT_NODUP;
1661 /* check for missing refs on the remote */
1662 for (ref = *dst; ref; ref = ref->next) {
1663 char *src_name;
1665 if (ref->peer_ref)
1666 /* We're already sending something to this ref. */
1667 continue;
1669 src_name = get_ref_match(rs, ref, send_mirror, FROM_DST, NULL);
1670 if (src_name) {
1671 if (!src_ref_index.nr)
1672 prepare_ref_index(&src_ref_index, src);
1673 if (!string_list_has_string(&src_ref_index,
1674 src_name))
1675 ref->peer_ref = alloc_delete_ref();
1676 free(src_name);
1679 string_list_clear(&src_ref_index, 0);
1682 *dst = apply_negative_refspecs(*dst, rs);
1684 if (errs)
1685 return -1;
1686 return 0;
1689 void set_ref_status_for_push(struct ref *remote_refs, int send_mirror,
1690 int force_update)
1692 struct ref *ref;
1694 for (ref = remote_refs; ref; ref = ref->next) {
1695 int force_ref_update = ref->force || force_update;
1696 int reject_reason = 0;
1698 if (ref->peer_ref)
1699 oidcpy(&ref->new_oid, &ref->peer_ref->new_oid);
1700 else if (!send_mirror)
1701 continue;
1703 ref->deletion = is_null_oid(&ref->new_oid);
1704 if (!ref->deletion &&
1705 oideq(&ref->old_oid, &ref->new_oid)) {
1706 ref->status = REF_STATUS_UPTODATE;
1707 continue;
1711 * If the remote ref has moved and is now different
1712 * from what we expect, reject any push.
1714 * It also is an error if the user told us to check
1715 * with the remote-tracking branch to find the value
1716 * to expect, but we did not have such a tracking
1717 * branch.
1719 * If the tip of the remote-tracking ref is unreachable
1720 * from any reflog entry of its local ref indicating a
1721 * possible update since checkout; reject the push.
1723 if (ref->expect_old_sha1) {
1724 if (!oideq(&ref->old_oid, &ref->old_oid_expect))
1725 reject_reason = REF_STATUS_REJECT_STALE;
1726 else if (ref->check_reachable && ref->unreachable)
1727 reject_reason =
1728 REF_STATUS_REJECT_REMOTE_UPDATED;
1729 else
1731 * If the ref isn't stale, and is reachable
1732 * from one of the reflog entries of
1733 * the local branch, force the update.
1735 force_ref_update = 1;
1739 * If the update isn't already rejected then check
1740 * the usual "must fast-forward" rules.
1742 * Decide whether an individual refspec A:B can be
1743 * pushed. The push will succeed if any of the
1744 * following are true:
1746 * (1) the remote reference B does not exist
1748 * (2) the remote reference B is being removed (i.e.,
1749 * pushing :B where no source is specified)
1751 * (3) the destination is not under refs/tags/, and
1752 * if the old and new value is a commit, the new
1753 * is a descendant of the old.
1755 * (4) it is forced using the +A:B notation, or by
1756 * passing the --force argument
1759 if (!reject_reason && !ref->deletion && !is_null_oid(&ref->old_oid)) {
1760 if (starts_with(ref->name, "refs/tags/"))
1761 reject_reason = REF_STATUS_REJECT_ALREADY_EXISTS;
1762 else if (!has_object_file(&ref->old_oid))
1763 reject_reason = REF_STATUS_REJECT_FETCH_FIRST;
1764 else if (!lookup_commit_reference_gently(the_repository, &ref->old_oid, 1) ||
1765 !lookup_commit_reference_gently(the_repository, &ref->new_oid, 1))
1766 reject_reason = REF_STATUS_REJECT_NEEDS_FORCE;
1767 else if (!ref_newer(&ref->new_oid, &ref->old_oid))
1768 reject_reason = REF_STATUS_REJECT_NONFASTFORWARD;
1772 * "--force" will defeat any rejection implemented
1773 * by the rules above.
1775 if (!force_ref_update)
1776 ref->status = reject_reason;
1777 else if (reject_reason)
1778 ref->forced_update = 1;
1782 static void set_merge(struct remote_state *remote_state, struct branch *ret)
1784 struct remote *remote;
1785 char *ref;
1786 struct object_id oid;
1787 int i;
1789 if (!ret)
1790 return; /* no branch */
1791 if (ret->merge)
1792 return; /* already run */
1793 if (!ret->remote_name || !ret->merge_nr) {
1795 * no merge config; let's make sure we don't confuse callers
1796 * with a non-zero merge_nr but a NULL merge
1798 ret->merge_nr = 0;
1799 return;
1802 remote = remotes_remote_get(remote_state, ret->remote_name);
1804 CALLOC_ARRAY(ret->merge, ret->merge_nr);
1805 for (i = 0; i < ret->merge_nr; i++) {
1806 ret->merge[i] = xcalloc(1, sizeof(**ret->merge));
1807 ret->merge[i]->src = xstrdup(ret->merge_name[i]);
1808 if (!remote_find_tracking(remote, ret->merge[i]) ||
1809 strcmp(ret->remote_name, "."))
1810 continue;
1811 if (dwim_ref(ret->merge_name[i], strlen(ret->merge_name[i]),
1812 &oid, &ref, 0) == 1)
1813 ret->merge[i]->dst = ref;
1814 else
1815 ret->merge[i]->dst = xstrdup(ret->merge_name[i]);
1819 struct branch *branch_get(const char *name)
1821 struct branch *ret;
1823 read_config(the_repository);
1824 if (!name || !*name || !strcmp(name, "HEAD"))
1825 ret = the_repository->remote_state->current_branch;
1826 else
1827 ret = make_branch(the_repository->remote_state, name,
1828 strlen(name));
1829 set_merge(the_repository->remote_state, ret);
1830 return ret;
1833 int branch_has_merge_config(struct branch *branch)
1835 return branch && !!branch->merge;
1838 int branch_merge_matches(struct branch *branch,
1839 int i,
1840 const char *refname)
1842 if (!branch || i < 0 || i >= branch->merge_nr)
1843 return 0;
1844 return refname_match(branch->merge[i]->src, refname);
1847 __attribute__((format (printf,2,3)))
1848 static const char *error_buf(struct strbuf *err, const char *fmt, ...)
1850 if (err) {
1851 va_list ap;
1852 va_start(ap, fmt);
1853 strbuf_vaddf(err, fmt, ap);
1854 va_end(ap);
1856 return NULL;
1859 const char *branch_get_upstream(struct branch *branch, struct strbuf *err)
1861 if (!branch)
1862 return error_buf(err, _("HEAD does not point to a branch"));
1864 if (!branch->merge || !branch->merge[0]) {
1866 * no merge config; is it because the user didn't define any,
1867 * or because it is not a real branch, and get_branch
1868 * auto-vivified it?
1870 if (!ref_exists(branch->refname))
1871 return error_buf(err, _("no such branch: '%s'"),
1872 branch->name);
1873 return error_buf(err,
1874 _("no upstream configured for branch '%s'"),
1875 branch->name);
1878 if (!branch->merge[0]->dst)
1879 return error_buf(err,
1880 _("upstream branch '%s' not stored as a remote-tracking branch"),
1881 branch->merge[0]->src);
1883 return branch->merge[0]->dst;
1886 static const char *tracking_for_push_dest(struct remote *remote,
1887 const char *refname,
1888 struct strbuf *err)
1890 char *ret;
1892 ret = apply_refspecs(&remote->fetch, refname);
1893 if (!ret)
1894 return error_buf(err,
1895 _("push destination '%s' on remote '%s' has no local tracking branch"),
1896 refname, remote->name);
1897 return ret;
1900 static const char *branch_get_push_1(struct remote_state *remote_state,
1901 struct branch *branch, struct strbuf *err)
1903 struct remote *remote;
1905 remote = remotes_remote_get(
1906 remote_state,
1907 remotes_pushremote_for_branch(remote_state, branch, NULL));
1908 if (!remote)
1909 return error_buf(err,
1910 _("branch '%s' has no remote for pushing"),
1911 branch->name);
1913 if (remote->push.nr) {
1914 char *dst;
1915 const char *ret;
1917 dst = apply_refspecs(&remote->push, branch->refname);
1918 if (!dst)
1919 return error_buf(err,
1920 _("push refspecs for '%s' do not include '%s'"),
1921 remote->name, branch->name);
1923 ret = tracking_for_push_dest(remote, dst, err);
1924 free(dst);
1925 return ret;
1928 if (remote->mirror)
1929 return tracking_for_push_dest(remote, branch->refname, err);
1931 switch (push_default) {
1932 case PUSH_DEFAULT_NOTHING:
1933 return error_buf(err, _("push has no destination (push.default is 'nothing')"));
1935 case PUSH_DEFAULT_MATCHING:
1936 case PUSH_DEFAULT_CURRENT:
1937 return tracking_for_push_dest(remote, branch->refname, err);
1939 case PUSH_DEFAULT_UPSTREAM:
1940 return branch_get_upstream(branch, err);
1942 case PUSH_DEFAULT_UNSPECIFIED:
1943 case PUSH_DEFAULT_SIMPLE:
1945 const char *up, *cur;
1947 up = branch_get_upstream(branch, err);
1948 if (!up)
1949 return NULL;
1950 cur = tracking_for_push_dest(remote, branch->refname, err);
1951 if (!cur)
1952 return NULL;
1953 if (strcmp(cur, up))
1954 return error_buf(err,
1955 _("cannot resolve 'simple' push to a single destination"));
1956 return cur;
1960 BUG("unhandled push situation");
1963 const char *branch_get_push(struct branch *branch, struct strbuf *err)
1965 read_config(the_repository);
1966 die_on_missing_branch(the_repository, branch);
1968 if (!branch)
1969 return error_buf(err, _("HEAD does not point to a branch"));
1971 if (!branch->push_tracking_ref)
1972 branch->push_tracking_ref = branch_get_push_1(
1973 the_repository->remote_state, branch, err);
1974 return branch->push_tracking_ref;
1977 static int ignore_symref_update(const char *refname, struct strbuf *scratch)
1979 return !refs_read_symbolic_ref(get_main_ref_store(the_repository), refname, scratch);
1983 * Create and return a list of (struct ref) consisting of copies of
1984 * each remote_ref that matches refspec. refspec must be a pattern.
1985 * Fill in the copies' peer_ref to describe the local tracking refs to
1986 * which they map. Omit any references that would map to an existing
1987 * local symbolic ref.
1989 static struct ref *get_expanded_map(const struct ref *remote_refs,
1990 const struct refspec_item *refspec)
1992 struct strbuf scratch = STRBUF_INIT;
1993 const struct ref *ref;
1994 struct ref *ret = NULL;
1995 struct ref **tail = &ret;
1997 for (ref = remote_refs; ref; ref = ref->next) {
1998 char *expn_name = NULL;
2000 strbuf_reset(&scratch);
2002 if (strchr(ref->name, '^'))
2003 continue; /* a dereference item */
2004 if (match_name_with_pattern(refspec->src, ref->name,
2005 refspec->dst, &expn_name) &&
2006 !ignore_symref_update(expn_name, &scratch)) {
2007 struct ref *cpy = copy_ref(ref);
2009 cpy->peer_ref = alloc_ref(expn_name);
2010 if (refspec->force)
2011 cpy->peer_ref->force = 1;
2012 *tail = cpy;
2013 tail = &cpy->next;
2015 free(expn_name);
2018 strbuf_release(&scratch);
2019 return ret;
2022 static const struct ref *find_ref_by_name_abbrev(const struct ref *refs, const char *name)
2024 const struct ref *ref;
2025 const struct ref *best_match = NULL;
2026 int best_score = 0;
2028 for (ref = refs; ref; ref = ref->next) {
2029 int score = refname_match(name, ref->name);
2031 if (best_score < score) {
2032 best_match = ref;
2033 best_score = score;
2036 return best_match;
2039 struct ref *get_remote_ref(const struct ref *remote_refs, const char *name)
2041 const struct ref *ref = find_ref_by_name_abbrev(remote_refs, name);
2043 if (!ref)
2044 return NULL;
2046 return copy_ref(ref);
2049 static struct ref *get_local_ref(const char *name)
2051 if (!name || name[0] == '\0')
2052 return NULL;
2054 if (starts_with(name, "refs/"))
2055 return alloc_ref(name);
2057 if (starts_with(name, "heads/") ||
2058 starts_with(name, "tags/") ||
2059 starts_with(name, "remotes/"))
2060 return alloc_ref_with_prefix("refs/", 5, name);
2062 return alloc_ref_with_prefix("refs/heads/", 11, name);
2065 int get_fetch_map(const struct ref *remote_refs,
2066 const struct refspec_item *refspec,
2067 struct ref ***tail,
2068 int missing_ok)
2070 struct ref *ref_map, **rmp;
2072 if (refspec->negative)
2073 return 0;
2075 if (refspec->pattern) {
2076 ref_map = get_expanded_map(remote_refs, refspec);
2077 } else {
2078 const char *name = refspec->src[0] ? refspec->src : "HEAD";
2080 if (refspec->exact_sha1) {
2081 ref_map = alloc_ref(name);
2082 get_oid_hex(name, &ref_map->old_oid);
2083 ref_map->exact_oid = 1;
2084 } else {
2085 ref_map = get_remote_ref(remote_refs, name);
2087 if (!missing_ok && !ref_map)
2088 die(_("couldn't find remote ref %s"), name);
2089 if (ref_map) {
2090 ref_map->peer_ref = get_local_ref(refspec->dst);
2091 if (ref_map->peer_ref && refspec->force)
2092 ref_map->peer_ref->force = 1;
2096 for (rmp = &ref_map; *rmp; ) {
2097 if ((*rmp)->peer_ref) {
2098 if (!starts_with((*rmp)->peer_ref->name, "refs/") ||
2099 check_refname_format((*rmp)->peer_ref->name, 0)) {
2100 struct ref *ignore = *rmp;
2101 error(_("* Ignoring funny ref '%s' locally"),
2102 (*rmp)->peer_ref->name);
2103 *rmp = (*rmp)->next;
2104 free(ignore->peer_ref);
2105 free(ignore);
2106 continue;
2109 rmp = &((*rmp)->next);
2112 if (ref_map)
2113 tail_link_ref(ref_map, tail);
2115 return 0;
2118 int resolve_remote_symref(struct ref *ref, struct ref *list)
2120 if (!ref->symref)
2121 return 0;
2122 for (; list; list = list->next)
2123 if (!strcmp(ref->symref, list->name)) {
2124 oidcpy(&ref->old_oid, &list->old_oid);
2125 return 0;
2127 return 1;
2131 * Compute the commit ahead/behind values for the pair branch_name, base.
2133 * If abf is AHEAD_BEHIND_FULL, compute the full ahead/behind and return the
2134 * counts in *num_ours and *num_theirs. If abf is AHEAD_BEHIND_QUICK, skip
2135 * the (potentially expensive) a/b computation (*num_ours and *num_theirs are
2136 * set to zero).
2138 * Returns -1 if num_ours and num_theirs could not be filled in (e.g., ref
2139 * does not exist). Returns 0 if the commits are identical. Returns 1 if
2140 * commits are different.
2143 static int stat_branch_pair(const char *branch_name, const char *base,
2144 int *num_ours, int *num_theirs,
2145 enum ahead_behind_flags abf)
2147 struct object_id oid;
2148 struct commit *ours, *theirs;
2149 struct rev_info revs;
2150 struct setup_revision_opt opt = {
2151 .free_removed_argv_elements = 1,
2153 struct strvec argv = STRVEC_INIT;
2155 /* Cannot stat if what we used to build on no longer exists */
2156 if (read_ref(base, &oid))
2157 return -1;
2158 theirs = lookup_commit_reference(the_repository, &oid);
2159 if (!theirs)
2160 return -1;
2162 if (read_ref(branch_name, &oid))
2163 return -1;
2164 ours = lookup_commit_reference(the_repository, &oid);
2165 if (!ours)
2166 return -1;
2168 *num_theirs = *num_ours = 0;
2170 /* are we the same? */
2171 if (theirs == ours)
2172 return 0;
2173 if (abf == AHEAD_BEHIND_QUICK)
2174 return 1;
2175 if (abf != AHEAD_BEHIND_FULL)
2176 BUG("stat_branch_pair: invalid abf '%d'", abf);
2178 /* Run "rev-list --left-right ours...theirs" internally... */
2179 strvec_push(&argv, ""); /* ignored */
2180 strvec_push(&argv, "--left-right");
2181 strvec_pushf(&argv, "%s...%s",
2182 oid_to_hex(&ours->object.oid),
2183 oid_to_hex(&theirs->object.oid));
2184 strvec_push(&argv, "--");
2186 repo_init_revisions(the_repository, &revs, NULL);
2187 setup_revisions(argv.nr, argv.v, &revs, &opt);
2188 if (prepare_revision_walk(&revs))
2189 die(_("revision walk setup failed"));
2191 /* ... and count the commits on each side. */
2192 while (1) {
2193 struct commit *c = get_revision(&revs);
2194 if (!c)
2195 break;
2196 if (c->object.flags & SYMMETRIC_LEFT)
2197 (*num_ours)++;
2198 else
2199 (*num_theirs)++;
2202 /* clear object flags smudged by the above traversal */
2203 clear_commit_marks(ours, ALL_REV_FLAGS);
2204 clear_commit_marks(theirs, ALL_REV_FLAGS);
2206 strvec_clear(&argv);
2207 release_revisions(&revs);
2208 return 1;
2212 * Lookup the tracking branch for the given branch and if present, optionally
2213 * compute the commit ahead/behind values for the pair.
2215 * If for_push is true, the tracking branch refers to the push branch,
2216 * otherwise it refers to the upstream branch.
2218 * The name of the tracking branch (or NULL if it is not defined) is
2219 * returned via *tracking_name, if it is not itself NULL.
2221 * If abf is AHEAD_BEHIND_FULL, compute the full ahead/behind and return the
2222 * counts in *num_ours and *num_theirs. If abf is AHEAD_BEHIND_QUICK, skip
2223 * the (potentially expensive) a/b computation (*num_ours and *num_theirs are
2224 * set to zero).
2226 * Returns -1 if num_ours and num_theirs could not be filled in (e.g., no
2227 * upstream defined, or ref does not exist). Returns 0 if the commits are
2228 * identical. Returns 1 if commits are different.
2230 int stat_tracking_info(struct branch *branch, int *num_ours, int *num_theirs,
2231 const char **tracking_name, int for_push,
2232 enum ahead_behind_flags abf)
2234 const char *base;
2236 /* Cannot stat unless we are marked to build on top of somebody else. */
2237 base = for_push ? branch_get_push(branch, NULL) :
2238 branch_get_upstream(branch, NULL);
2239 if (tracking_name)
2240 *tracking_name = base;
2241 if (!base)
2242 return -1;
2244 return stat_branch_pair(branch->refname, base, num_ours, num_theirs, abf);
2248 * Return true when there is anything to report, otherwise false.
2250 int format_tracking_info(struct branch *branch, struct strbuf *sb,
2251 enum ahead_behind_flags abf)
2253 int ours, theirs, sti;
2254 const char *full_base;
2255 char *base;
2256 int upstream_is_gone = 0;
2258 sti = stat_tracking_info(branch, &ours, &theirs, &full_base, 0, abf);
2259 if (sti < 0) {
2260 if (!full_base)
2261 return 0;
2262 upstream_is_gone = 1;
2265 base = shorten_unambiguous_ref(full_base, 0);
2266 if (upstream_is_gone) {
2267 strbuf_addf(sb,
2268 _("Your branch is based on '%s', but the upstream is gone.\n"),
2269 base);
2270 if (advice_enabled(ADVICE_STATUS_HINTS))
2271 strbuf_addstr(sb,
2272 _(" (use \"git branch --unset-upstream\" to fixup)\n"));
2273 } else if (!sti) {
2274 strbuf_addf(sb,
2275 _("Your branch is up to date with '%s'.\n"),
2276 base);
2277 } else if (abf == AHEAD_BEHIND_QUICK) {
2278 strbuf_addf(sb,
2279 _("Your branch and '%s' refer to different commits.\n"),
2280 base);
2281 if (advice_enabled(ADVICE_STATUS_HINTS))
2282 strbuf_addf(sb, _(" (use \"%s\" for details)\n"),
2283 "git status --ahead-behind");
2284 } else if (!theirs) {
2285 strbuf_addf(sb,
2286 Q_("Your branch is ahead of '%s' by %d commit.\n",
2287 "Your branch is ahead of '%s' by %d commits.\n",
2288 ours),
2289 base, ours);
2290 if (advice_enabled(ADVICE_STATUS_HINTS))
2291 strbuf_addstr(sb,
2292 _(" (use \"git push\" to publish your local commits)\n"));
2293 } else if (!ours) {
2294 strbuf_addf(sb,
2295 Q_("Your branch is behind '%s' by %d commit, "
2296 "and can be fast-forwarded.\n",
2297 "Your branch is behind '%s' by %d commits, "
2298 "and can be fast-forwarded.\n",
2299 theirs),
2300 base, theirs);
2301 if (advice_enabled(ADVICE_STATUS_HINTS))
2302 strbuf_addstr(sb,
2303 _(" (use \"git pull\" to update your local branch)\n"));
2304 } else {
2305 strbuf_addf(sb,
2306 Q_("Your branch and '%s' have diverged,\n"
2307 "and have %d and %d different commit each, "
2308 "respectively.\n",
2309 "Your branch and '%s' have diverged,\n"
2310 "and have %d and %d different commits each, "
2311 "respectively.\n",
2312 ours + theirs),
2313 base, ours, theirs);
2314 if (advice_enabled(ADVICE_STATUS_HINTS))
2315 strbuf_addstr(sb,
2316 _(" (use \"git pull\" to merge the remote branch into yours)\n"));
2318 free(base);
2319 return 1;
2322 static int one_local_ref(const char *refname, const struct object_id *oid,
2323 int flag UNUSED,
2324 void *cb_data)
2326 struct ref ***local_tail = cb_data;
2327 struct ref *ref;
2329 /* we already know it starts with refs/ to get here */
2330 if (check_refname_format(refname + 5, 0))
2331 return 0;
2333 ref = alloc_ref(refname);
2334 oidcpy(&ref->new_oid, oid);
2335 **local_tail = ref;
2336 *local_tail = &ref->next;
2337 return 0;
2340 struct ref *get_local_heads(void)
2342 struct ref *local_refs = NULL, **local_tail = &local_refs;
2344 for_each_ref(one_local_ref, &local_tail);
2345 return local_refs;
2348 struct ref *guess_remote_head(const struct ref *head,
2349 const struct ref *refs,
2350 int all)
2352 const struct ref *r;
2353 struct ref *list = NULL;
2354 struct ref **tail = &list;
2356 if (!head)
2357 return NULL;
2360 * Some transports support directly peeking at
2361 * where HEAD points; if that is the case, then
2362 * we don't have to guess.
2364 if (head->symref)
2365 return copy_ref(find_ref_by_name(refs, head->symref));
2367 /* If a remote branch exists with the default branch name, let's use it. */
2368 if (!all) {
2369 char *ref = xstrfmt("refs/heads/%s",
2370 git_default_branch_name(0));
2372 r = find_ref_by_name(refs, ref);
2373 free(ref);
2374 if (r && oideq(&r->old_oid, &head->old_oid))
2375 return copy_ref(r);
2377 /* Fall back to the hard-coded historical default */
2378 r = find_ref_by_name(refs, "refs/heads/master");
2379 if (r && oideq(&r->old_oid, &head->old_oid))
2380 return copy_ref(r);
2383 /* Look for another ref that points there */
2384 for (r = refs; r; r = r->next) {
2385 if (r != head &&
2386 starts_with(r->name, "refs/heads/") &&
2387 oideq(&r->old_oid, &head->old_oid)) {
2388 *tail = copy_ref(r);
2389 tail = &((*tail)->next);
2390 if (!all)
2391 break;
2395 return list;
2398 struct stale_heads_info {
2399 struct string_list *ref_names;
2400 struct ref **stale_refs_tail;
2401 struct refspec *rs;
2404 static int get_stale_heads_cb(const char *refname, const struct object_id *oid,
2405 int flags, void *cb_data)
2407 struct stale_heads_info *info = cb_data;
2408 struct string_list matches = STRING_LIST_INIT_DUP;
2409 struct refspec_item query;
2410 int i, stale = 1;
2411 memset(&query, 0, sizeof(struct refspec_item));
2412 query.dst = (char *)refname;
2414 query_refspecs_multiple(info->rs, &query, &matches);
2415 if (matches.nr == 0)
2416 goto clean_exit; /* No matches */
2419 * If we did find a suitable refspec and it's not a symref and
2420 * it's not in the list of refs that currently exist in that
2421 * remote, we consider it to be stale. In order to deal with
2422 * overlapping refspecs, we need to go over all of the
2423 * matching refs.
2425 if (flags & REF_ISSYMREF)
2426 goto clean_exit;
2428 for (i = 0; stale && i < matches.nr; i++)
2429 if (string_list_has_string(info->ref_names, matches.items[i].string))
2430 stale = 0;
2432 if (stale) {
2433 struct ref *ref = make_linked_ref(refname, &info->stale_refs_tail);
2434 oidcpy(&ref->new_oid, oid);
2437 clean_exit:
2438 string_list_clear(&matches, 0);
2439 return 0;
2442 struct ref *get_stale_heads(struct refspec *rs, struct ref *fetch_map)
2444 struct ref *ref, *stale_refs = NULL;
2445 struct string_list ref_names = STRING_LIST_INIT_NODUP;
2446 struct stale_heads_info info;
2448 info.ref_names = &ref_names;
2449 info.stale_refs_tail = &stale_refs;
2450 info.rs = rs;
2451 for (ref = fetch_map; ref; ref = ref->next)
2452 string_list_append(&ref_names, ref->name);
2453 string_list_sort(&ref_names);
2454 for_each_ref(get_stale_heads_cb, &info);
2455 string_list_clear(&ref_names, 0);
2456 return stale_refs;
2460 * Compare-and-swap
2462 static void clear_cas_option(struct push_cas_option *cas)
2464 int i;
2466 for (i = 0; i < cas->nr; i++)
2467 free(cas->entry[i].refname);
2468 free(cas->entry);
2469 memset(cas, 0, sizeof(*cas));
2472 static struct push_cas *add_cas_entry(struct push_cas_option *cas,
2473 const char *refname,
2474 size_t refnamelen)
2476 struct push_cas *entry;
2477 ALLOC_GROW(cas->entry, cas->nr + 1, cas->alloc);
2478 entry = &cas->entry[cas->nr++];
2479 memset(entry, 0, sizeof(*entry));
2480 entry->refname = xmemdupz(refname, refnamelen);
2481 return entry;
2484 static int parse_push_cas_option(struct push_cas_option *cas, const char *arg, int unset)
2486 const char *colon;
2487 struct push_cas *entry;
2489 if (unset) {
2490 /* "--no-<option>" */
2491 clear_cas_option(cas);
2492 return 0;
2495 if (!arg) {
2496 /* just "--<option>" */
2497 cas->use_tracking_for_rest = 1;
2498 return 0;
2501 /* "--<option>=refname" or "--<option>=refname:value" */
2502 colon = strchrnul(arg, ':');
2503 entry = add_cas_entry(cas, arg, colon - arg);
2504 if (!*colon)
2505 entry->use_tracking = 1;
2506 else if (!colon[1])
2507 oidclr(&entry->expect);
2508 else if (get_oid(colon + 1, &entry->expect))
2509 return error(_("cannot parse expected object name '%s'"),
2510 colon + 1);
2511 return 0;
2514 int parseopt_push_cas_option(const struct option *opt, const char *arg, int unset)
2516 return parse_push_cas_option(opt->value, arg, unset);
2519 int is_empty_cas(const struct push_cas_option *cas)
2521 return !cas->use_tracking_for_rest && !cas->nr;
2525 * Look at remote.fetch refspec and see if we have a remote
2526 * tracking branch for the refname there. Fill the name of
2527 * the remote-tracking branch in *dst_refname, and the name
2528 * of the commit object at its tip in oid[].
2529 * If we cannot do so, return negative to signal an error.
2531 static int remote_tracking(struct remote *remote, const char *refname,
2532 struct object_id *oid, char **dst_refname)
2534 char *dst;
2536 dst = apply_refspecs(&remote->fetch, refname);
2537 if (!dst)
2538 return -1; /* no tracking ref for refname at remote */
2539 if (read_ref(dst, oid))
2540 return -1; /* we know what the tracking ref is but we cannot read it */
2542 *dst_refname = dst;
2543 return 0;
2547 * The struct "reflog_commit_array" and related helper functions
2548 * are used for collecting commits into an array during reflog
2549 * traversals in "check_and_collect_until()".
2551 struct reflog_commit_array {
2552 struct commit **item;
2553 size_t nr, alloc;
2556 #define REFLOG_COMMIT_ARRAY_INIT { 0 }
2558 /* Append a commit to the array. */
2559 static void append_commit(struct reflog_commit_array *arr,
2560 struct commit *commit)
2562 ALLOC_GROW(arr->item, arr->nr + 1, arr->alloc);
2563 arr->item[arr->nr++] = commit;
2566 /* Free and reset the array. */
2567 static void free_commit_array(struct reflog_commit_array *arr)
2569 FREE_AND_NULL(arr->item);
2570 arr->nr = arr->alloc = 0;
2573 struct check_and_collect_until_cb_data {
2574 struct commit *remote_commit;
2575 struct reflog_commit_array *local_commits;
2576 timestamp_t remote_reflog_timestamp;
2579 /* Get the timestamp of the latest entry. */
2580 static int peek_reflog(struct object_id *o_oid UNUSED,
2581 struct object_id *n_oid UNUSED,
2582 const char *ident UNUSED,
2583 timestamp_t timestamp, int tz UNUSED,
2584 const char *message UNUSED, void *cb_data)
2586 timestamp_t *ts = cb_data;
2587 *ts = timestamp;
2588 return 1;
2591 static int check_and_collect_until(struct object_id *o_oid UNUSED,
2592 struct object_id *n_oid,
2593 const char *ident UNUSED,
2594 timestamp_t timestamp, int tz UNUSED,
2595 const char *message UNUSED, void *cb_data)
2597 struct commit *commit;
2598 struct check_and_collect_until_cb_data *cb = cb_data;
2600 /* An entry was found. */
2601 if (oideq(n_oid, &cb->remote_commit->object.oid))
2602 return 1;
2604 if ((commit = lookup_commit_reference(the_repository, n_oid)))
2605 append_commit(cb->local_commits, commit);
2608 * If the reflog entry timestamp is older than the remote ref's
2609 * latest reflog entry, there is no need to check or collect
2610 * entries older than this one.
2612 if (timestamp < cb->remote_reflog_timestamp)
2613 return -1;
2615 return 0;
2618 #define MERGE_BASES_BATCH_SIZE 8
2621 * Iterate through the reflog of the local ref to check if there is an entry
2622 * for the given remote-tracking ref; runs until the timestamp of an entry is
2623 * older than latest timestamp of remote-tracking ref's reflog. Any commits
2624 * are that seen along the way are collected into an array to check if the
2625 * remote-tracking ref is reachable from any of them.
2627 static int is_reachable_in_reflog(const char *local, const struct ref *remote)
2629 timestamp_t date;
2630 struct commit *commit;
2631 struct commit **chunk;
2632 struct check_and_collect_until_cb_data cb;
2633 struct reflog_commit_array arr = REFLOG_COMMIT_ARRAY_INIT;
2634 size_t size = 0;
2635 int ret = 0;
2637 commit = lookup_commit_reference(the_repository, &remote->old_oid);
2638 if (!commit)
2639 goto cleanup_return;
2642 * Get the timestamp from the latest entry
2643 * of the remote-tracking ref's reflog.
2645 for_each_reflog_ent_reverse(remote->tracking_ref, peek_reflog, &date);
2647 cb.remote_commit = commit;
2648 cb.local_commits = &arr;
2649 cb.remote_reflog_timestamp = date;
2650 ret = for_each_reflog_ent_reverse(local, check_and_collect_until, &cb);
2652 /* We found an entry in the reflog. */
2653 if (ret > 0)
2654 goto cleanup_return;
2657 * Check if the remote commit is reachable from any
2658 * of the commits in the collected array, in batches.
2660 for (chunk = arr.item; chunk < arr.item + arr.nr; chunk += size) {
2661 size = arr.item + arr.nr - chunk;
2662 if (MERGE_BASES_BATCH_SIZE < size)
2663 size = MERGE_BASES_BATCH_SIZE;
2665 if ((ret = in_merge_bases_many(commit, size, chunk)))
2666 break;
2669 cleanup_return:
2670 free_commit_array(&arr);
2671 return ret;
2675 * Check for reachability of a remote-tracking
2676 * ref in the reflog entries of its local ref.
2678 static void check_if_includes_upstream(struct ref *remote)
2680 struct ref *local = get_local_ref(remote->name);
2681 if (!local)
2682 return;
2684 if (is_reachable_in_reflog(local->name, remote) <= 0)
2685 remote->unreachable = 1;
2688 static void apply_cas(struct push_cas_option *cas,
2689 struct remote *remote,
2690 struct ref *ref)
2692 int i;
2694 /* Find an explicit --<option>=<name>[:<value>] entry */
2695 for (i = 0; i < cas->nr; i++) {
2696 struct push_cas *entry = &cas->entry[i];
2697 if (!refname_match(entry->refname, ref->name))
2698 continue;
2699 ref->expect_old_sha1 = 1;
2700 if (!entry->use_tracking)
2701 oidcpy(&ref->old_oid_expect, &entry->expect);
2702 else if (remote_tracking(remote, ref->name,
2703 &ref->old_oid_expect,
2704 &ref->tracking_ref))
2705 oidclr(&ref->old_oid_expect);
2706 else
2707 ref->check_reachable = cas->use_force_if_includes;
2708 return;
2711 /* Are we using "--<option>" to cover all? */
2712 if (!cas->use_tracking_for_rest)
2713 return;
2715 ref->expect_old_sha1 = 1;
2716 if (remote_tracking(remote, ref->name,
2717 &ref->old_oid_expect,
2718 &ref->tracking_ref))
2719 oidclr(&ref->old_oid_expect);
2720 else
2721 ref->check_reachable = cas->use_force_if_includes;
2724 void apply_push_cas(struct push_cas_option *cas,
2725 struct remote *remote,
2726 struct ref *remote_refs)
2728 struct ref *ref;
2729 for (ref = remote_refs; ref; ref = ref->next) {
2730 apply_cas(cas, remote, ref);
2733 * If "compare-and-swap" is in "use_tracking[_for_rest]"
2734 * mode, and if "--force-if-includes" was specified, run
2735 * the check.
2737 if (ref->check_reachable)
2738 check_if_includes_upstream(ref);
2742 struct remote_state *remote_state_new(void)
2744 struct remote_state *r = xmalloc(sizeof(*r));
2746 memset(r, 0, sizeof(*r));
2748 hashmap_init(&r->remotes_hash, remotes_hash_cmp, NULL, 0);
2749 hashmap_init(&r->branches_hash, branches_hash_cmp, NULL, 0);
2750 return r;
2753 void remote_state_clear(struct remote_state *remote_state)
2755 int i;
2757 for (i = 0; i < remote_state->remotes_nr; i++)
2758 remote_clear(remote_state->remotes[i]);
2759 FREE_AND_NULL(remote_state->remotes);
2760 remote_state->remotes_alloc = 0;
2761 remote_state->remotes_nr = 0;
2763 hashmap_clear_and_free(&remote_state->remotes_hash, struct remote, ent);
2764 hashmap_clear_and_free(&remote_state->branches_hash, struct remote, ent);
2768 * Returns 1 if it was the last chop before ':'.
2770 static int chop_last_dir(char **remoteurl, int is_relative)
2772 char *rfind = find_last_dir_sep(*remoteurl);
2773 if (rfind) {
2774 *rfind = '\0';
2775 return 0;
2778 rfind = strrchr(*remoteurl, ':');
2779 if (rfind) {
2780 *rfind = '\0';
2781 return 1;
2784 if (is_relative || !strcmp(".", *remoteurl))
2785 die(_("cannot strip one component off url '%s'"),
2786 *remoteurl);
2788 free(*remoteurl);
2789 *remoteurl = xstrdup(".");
2790 return 0;
2793 char *relative_url(const char *remote_url, const char *url,
2794 const char *up_path)
2796 int is_relative = 0;
2797 int colonsep = 0;
2798 char *out;
2799 char *remoteurl;
2800 struct strbuf sb = STRBUF_INIT;
2801 size_t len;
2803 if (!url_is_local_not_ssh(url) || is_absolute_path(url))
2804 return xstrdup(url);
2806 len = strlen(remote_url);
2807 if (!len)
2808 BUG("invalid empty remote_url");
2810 remoteurl = xstrdup(remote_url);
2811 if (is_dir_sep(remoteurl[len-1]))
2812 remoteurl[len-1] = '\0';
2814 if (!url_is_local_not_ssh(remoteurl) || is_absolute_path(remoteurl))
2815 is_relative = 0;
2816 else {
2817 is_relative = 1;
2819 * Prepend a './' to ensure all relative
2820 * remoteurls start with './' or '../'
2822 if (!starts_with_dot_slash_native(remoteurl) &&
2823 !starts_with_dot_dot_slash_native(remoteurl)) {
2824 strbuf_reset(&sb);
2825 strbuf_addf(&sb, "./%s", remoteurl);
2826 free(remoteurl);
2827 remoteurl = strbuf_detach(&sb, NULL);
2831 * When the url starts with '../', remove that and the
2832 * last directory in remoteurl.
2834 while (*url) {
2835 if (starts_with_dot_dot_slash_native(url)) {
2836 url += 3;
2837 colonsep |= chop_last_dir(&remoteurl, is_relative);
2838 } else if (starts_with_dot_slash_native(url))
2839 url += 2;
2840 else
2841 break;
2843 strbuf_reset(&sb);
2844 strbuf_addf(&sb, "%s%s%s", remoteurl, colonsep ? ":" : "/", url);
2845 if (ends_with(url, "/"))
2846 strbuf_setlen(&sb, sb.len - 1);
2847 free(remoteurl);
2849 if (starts_with_dot_slash_native(sb.buf))
2850 out = xstrdup(sb.buf + 2);
2851 else
2852 out = xstrdup(sb.buf);
2854 if (!up_path || !is_relative) {
2855 strbuf_release(&sb);
2856 return out;
2859 strbuf_reset(&sb);
2860 strbuf_addf(&sb, "%s%s", up_path, out);
2861 free(out);
2862 return strbuf_detach(&sb, NULL);