Raw
1 #define USE_THE_REPOSITORY_VARIABLE
2 #define DISABLE_SIGN_COMPARE_WARNINGS
3
4 #include "git-compat-util.h"
5 #include "abspath.h"
6 #include "config.h"
7 #include "environment.h"
8 #include "gettext.h"
9 #include "hex.h"
10 #include "remote.h"
11 #include "url.h"
12 #include "urlmatch.h"
13 #include "refs.h"
14 #include "refspec.h"
15 #include "object-name.h"
16 #include "odb.h"
17 #include "path.h"
18 #include "commit.h"
19 #include "diff.h"
20 #include "revision.h"
21 #include "dir.h"
22 #include "setup.h"
23 #include "string-list.h"
24 #include "strvec.h"
25 #include "commit-reach.h"
26 #include "advice.h"
27 #include "connect.h"
28 #include "parse-options.h"
29 #include "transport.h"
30
31 enum map_direction { FROM_SRC, FROM_DST };
32
33 enum {
34 ENABLE_ADVICE_PULL = (1 << 0),
35 ENABLE_ADVICE_PUSH = (1 << 1),
36 ENABLE_ADVICE_DIVERGENCE = (1 << 2),
37 };
38
39 struct counted_string {
40 size_t len;
41 const char *s;
42 };
43
44 static int valid_remote(const struct remote *remote)
45 {
46 return !!remote->url.nr;
47 }
48
49 static char *alias_url(const char *url, struct rewrites *r)
50 {
51 int i, j;
52 struct counted_string *longest;
53 int longest_i;
54
55 longest = NULL;
56 longest_i = -1;
57 for (i = 0; i < r->rewrite_nr; i++) {
58 if (!r->rewrite[i])
59 continue;
60 for (j = 0; j < r->rewrite[i]->instead_of_nr; j++) {
61 if (starts_with(url, r->rewrite[i]->instead_of[j].s) &&
62 (!longest ||
63 longest->len < r->rewrite[i]->instead_of[j].len)) {
64 longest = &(r->rewrite[i]->instead_of[j]);
65 longest_i = i;
66 }
67 }
68 }
69 if (!longest)
70 return NULL;
71
72 return xstrfmt("%s%s", r->rewrite[longest_i]->base, url + longest->len);
73 }
74
75 static void add_url(struct remote *remote, const char *url)
76 {
77 if (*url)
78 strvec_push(&remote->url, url);
79 else
80 strvec_clear(&remote->url);
81 }
82
83 static void add_pushurl(struct remote *remote, const char *pushurl)
84 {
85 if (*pushurl)
86 strvec_push(&remote->pushurl, pushurl);
87 else
88 strvec_clear(&remote->pushurl);
89 }
90
91 static void add_pushurl_alias(struct remote_state *remote_state,
92 struct remote *remote, const char *url)
93 {
94 char *alias = alias_url(url, &remote_state->rewrites_push);
95 if (alias)
96 add_pushurl(remote, alias);
97 free(alias);
98 }
99
100 static void add_url_alias(struct remote_state *remote_state,
101 struct remote *remote, const char *url)
102 {
103 char *alias = alias_url(url, &remote_state->rewrites);
104 add_url(remote, alias ? alias : url);
105 add_pushurl_alias(remote_state, remote, url);
106 free(alias);
107 }
108
109 struct remotes_hash_key {
110 const char *str;
111 int len;
112 };
113
114 static int remotes_hash_cmp(const void *cmp_data UNUSED,
115 const struct hashmap_entry *eptr,
116 const struct hashmap_entry *entry_or_key,
117 const void *keydata)
118 {
119 const struct remote *a, *b;
120 const struct remotes_hash_key *key = keydata;
121
122 a = container_of(eptr, const struct remote, ent);
123 b = container_of(entry_or_key, const struct remote, ent);
124
125 if (key)
126 return !!xstrncmpz(a->name, key->str, key->len);
127 else
128 return strcmp(a->name, b->name);
129 }
130
131 static struct remote *make_remote(struct remote_state *remote_state,
132 const char *name, int len)
133 {
134 struct remote *ret;
135 struct remotes_hash_key lookup;
136 struct hashmap_entry lookup_entry, *e;
137
138 if (!len)
139 len = strlen(name);
140
141 lookup.str = name;
142 lookup.len = len;
143 hashmap_entry_init(&lookup_entry, memhash(name, len));
144
145 e = hashmap_get(&remote_state->remotes_hash, &lookup_entry, &lookup);
146 if (e)
147 return container_of(e, struct remote, ent);
148
149 CALLOC_ARRAY(ret, 1);
150 ret->prune = -1; /* unspecified */
151 ret->prune_tags = -1; /* unspecified */
152 ret->name = xstrndup(name, len);
153 refspec_init_push(&ret->push, the_hash_algo);
154 refspec_init_fetch(&ret->fetch, the_hash_algo);
155 string_list_init_dup(&ret->server_options);
156 string_list_init_dup(&ret->negotiation_restrict);
157 string_list_init_dup(&ret->negotiation_include);
158
159 ALLOC_GROW(remote_state->remotes, remote_state->remotes_nr + 1,
160 remote_state->remotes_alloc);
161 remote_state->remotes[remote_state->remotes_nr++] = ret;
162
163 hashmap_entry_init(&ret->ent, lookup_entry.hash);
164 if (hashmap_put_entry(&remote_state->remotes_hash, ret, ent))
165 BUG("hashmap_put overwrote entry after hashmap_get returned NULL");
166 return ret;
167 }
168
169 static void remote_clear(struct remote *remote)
170 {
171 free((char *)remote->name);
172 free((char *)remote->foreign_vcs);
173
174 strvec_clear(&remote->url);
175 strvec_clear(&remote->pushurl);
176
177 refspec_clear(&remote->push);
178 refspec_clear(&remote->fetch);
179
180 free((char *)remote->receivepack);
181 free((char *)remote->uploadpack);
182 FREE_AND_NULL(remote->http_proxy);
183 FREE_AND_NULL(remote->http_proxy_authmethod);
184 string_list_clear(&remote->server_options, 0);
185 string_list_clear(&remote->negotiation_restrict, 0);
186 string_list_clear(&remote->negotiation_include, 0);
187 }
188
189 static void add_merge(struct branch *branch, const char *name)
190 {
191 struct refspec_item *merge;
192
193 ALLOC_GROW(branch->merge, branch->merge_nr + 1,
194 branch->merge_alloc);
195
196 merge = xcalloc(1, sizeof(*merge));
197 merge->src = xstrdup(name);
198
199 branch->merge[branch->merge_nr++] = merge;
200 }
201
202 struct branches_hash_key {
203 const char *str;
204 int len;
205 };
206
207 static int branches_hash_cmp(const void *cmp_data UNUSED,
208 const struct hashmap_entry *eptr,
209 const struct hashmap_entry *entry_or_key,
210 const void *keydata)
211 {
212 const struct branch *a, *b;
213 const struct branches_hash_key *key = keydata;
214
215 a = container_of(eptr, const struct branch, ent);
216 b = container_of(entry_or_key, const struct branch, ent);
217
218 if (key)
219 return !!xstrncmpz(a->name, key->str, key->len);
220 else
221 return strcmp(a->name, b->name);
222 }
223
224 static struct branch *find_branch(struct remote_state *remote_state,
225 const char *name, size_t len)
226 {
227 struct branches_hash_key lookup;
228 struct hashmap_entry lookup_entry, *e;
229
230 lookup.str = name;
231 lookup.len = len;
232 hashmap_entry_init(&lookup_entry, memhash(name, len));
233
234 e = hashmap_get(&remote_state->branches_hash, &lookup_entry, &lookup);
235 if (e)
236 return container_of(e, struct branch, ent);
237
238 return NULL;
239 }
240
241 static void die_on_missing_branch(struct repository *repo,
242 struct branch *branch)
243 {
244 /* branch == NULL is always valid because it represents detached HEAD. */
245 if (branch &&
246 branch != find_branch(repo->remote_state, branch->name,
247 strlen(branch->name)))
248 die("branch %s was not found in the repository", branch->name);
249 }
250
251 static struct branch *make_branch(struct remote_state *remote_state,
252 const char *name, size_t len)
253 {
254 struct branch *ret;
255
256 ret = find_branch(remote_state, name, len);
257 if (ret)
258 return ret;
259
260 CALLOC_ARRAY(ret, 1);
261 ret->name = xstrndup(name, len);
262 ret->refname = xstrfmt("refs/heads/%s", ret->name);
263
264 hashmap_entry_init(&ret->ent, memhash(name, len));
265 if (hashmap_put_entry(&remote_state->branches_hash, ret, ent))
266 BUG("hashmap_put overwrote entry after hashmap_get returned NULL");
267 return ret;
268 }
269
270 static void merge_clear(struct branch *branch)
271 {
272 for (int i = 0; i < branch->merge_nr; i++) {
273 refspec_item_clear(branch->merge[i]);
274 free(branch->merge[i]);
275 }
276 FREE_AND_NULL(branch->merge);
277 branch->merge_nr = 0;
278 }
279
280 static void branch_release(struct branch *branch)
281 {
282 free((char *)branch->name);
283 free((char *)branch->refname);
284 free(branch->remote_name);
285 free(branch->pushremote_name);
286 free(branch->push_tracking_ref);
287 merge_clear(branch);
288 }
289
290 static struct rewrite *make_rewrite(struct rewrites *r,
291 const char *base, size_t len)
292 {
293 struct rewrite *ret;
294 int i;
295
296 for (i = 0; i < r->rewrite_nr; i++) {
297 if (len == r->rewrite[i]->baselen &&
298 !strncmp(base, r->rewrite[i]->base, len))
299 return r->rewrite[i];
300 }
301
302 ALLOC_GROW(r->rewrite, r->rewrite_nr + 1, r->rewrite_alloc);
303 CALLOC_ARRAY(ret, 1);
304 r->rewrite[r->rewrite_nr++] = ret;
305 ret->base = xstrndup(base, len);
306 ret->baselen = len;
307 return ret;
308 }
309
310 static void rewrites_release(struct rewrites *r)
311 {
312 for (int i = 0; i < r->rewrite_nr; i++)
313 free((char *)r->rewrite[i]->base);
314 free(r->rewrite);
315 memset(r, 0, sizeof(*r));
316 }
317
318 static void add_instead_of(struct rewrite *rewrite, const char *instead_of)
319 {
320 ALLOC_GROW(rewrite->instead_of, rewrite->instead_of_nr + 1, rewrite->instead_of_alloc);
321 rewrite->instead_of[rewrite->instead_of_nr].s = instead_of;
322 rewrite->instead_of[rewrite->instead_of_nr].len = strlen(instead_of);
323 rewrite->instead_of_nr++;
324 }
325
326 #ifndef WITH_BREAKING_CHANGES
327 static const char *skip_spaces(const char *s)
328 {
329 while (isspace(*s))
330 s++;
331 return s;
332 }
333
334 static void warn_about_deprecated_remote_type(const char *type,
335 const struct remote *remote)
336 {
337 warning(_("reading remote from \"%s/%s\", which is nominated for removal.\n"
338 "\n"
339 "If you still use the \"remotes/\" directory it is recommended to\n"
340 "migrate to config-based remotes:\n"
341 "\n"
342 "\tgit remote rename %s %s\n"
343 "\n"
344 "If you cannot, please let us know why you still need to use it by\n"
345 "sending an e-mail to <git@vger.kernel.org>."),
346 type, remote->name, remote->name, remote->name);
347 }
348
349 static void read_remotes_file(struct repository *repo, struct remote *remote)
350 {
351 struct strbuf buf = STRBUF_INIT;
352 FILE *f = fopen_or_warn(repo_git_path_append(repo, &buf,
353 "remotes/%s", remote->name), "r");
354
355 if (!f)
356 goto out;
357
358 warn_about_deprecated_remote_type("remotes", remote);
359
360 remote->configured_in_repo = 1;
361 remote->origin = REMOTE_REMOTES;
362 while (strbuf_getline(&buf, f) != EOF) {
363 const char *v;
364
365 strbuf_rtrim(&buf);
366
367 if (skip_prefix(buf.buf, "URL:", &v))
368 add_url_alias(repo->remote_state, remote,
369 skip_spaces(v));
370 else if (skip_prefix(buf.buf, "Push:", &v))
371 refspec_append(&remote->push, skip_spaces(v));
372 else if (skip_prefix(buf.buf, "Pull:", &v))
373 refspec_append(&remote->fetch, skip_spaces(v));
374 }
375 fclose(f);
376
377 out:
378 strbuf_release(&buf);
379 }
380
381 static void read_branches_file(struct repository *repo, struct remote *remote)
382 {
383 char *frag, *to_free = NULL;
384 struct strbuf buf = STRBUF_INIT;
385 FILE *f = fopen_or_warn(repo_git_path_append(repo, &buf,
386 "branches/%s", remote->name), "r");
387
388 if (!f)
389 goto out;
390
391 warn_about_deprecated_remote_type("branches", remote);
392
393 strbuf_getline_lf(&buf, f);
394 fclose(f);
395 strbuf_trim(&buf);
396 if (!buf.len)
397 goto out;
398
399 remote->configured_in_repo = 1;
400 remote->origin = REMOTE_BRANCHES;
401
402 /*
403 * The branches file would have URL and optionally
404 * #branch specified. The default (or specified) branch is
405 * fetched and stored in the local branch matching the
406 * remote name.
407 */
408 frag = strchr(buf.buf, '#');
409 if (frag)
410 *(frag++) = '\0';
411 else
412 frag = to_free = repo_default_branch_name(repo, 0);
413
414 add_url_alias(repo->remote_state, remote, buf.buf);
415 refspec_appendf(&remote->fetch, "refs/heads/%s:refs/heads/%s",
416 frag, remote->name);
417
418 /*
419 * Cogito compatible push: push current HEAD to remote #branch
420 * (master if missing)
421 */
422 refspec_appendf(&remote->push, "HEAD:refs/heads/%s", frag);
423 remote->fetch_tags = 1; /* always auto-follow */
424
425 out:
426 strbuf_release(&buf);
427 free(to_free);
428 }
429 #endif /* WITH_BREAKING_CHANGES */
430
431 static int handle_config(const char *key, const char *value,
432 const struct config_context *ctx, void *cb)
433 {
434 const char *name;
435 size_t namelen;
436 const char *subkey;
437 struct remote *remote;
438 struct branch *branch;
439 struct remote_state *remote_state = cb;
440 const struct key_value_info *kvi = ctx->kvi;
441
442 if (parse_config_key(key, "branch", &name, &namelen, &subkey) >= 0) {
443 /* There is no subsection. */
444 if (!name)
445 return 0;
446 /* There is a subsection, but it is empty. */
447 if (!namelen)
448 return -1;
449 branch = make_branch(remote_state, name, namelen);
450 if (!strcmp(subkey, "remote")) {
451 FREE_AND_NULL(branch->remote_name);
452 return git_config_string(&branch->remote_name, key, value);
453 } else if (!strcmp(subkey, "pushremote")) {
454 FREE_AND_NULL(branch->pushremote_name);
455 return git_config_string(&branch->pushremote_name, key, value);
456 } else if (!strcmp(subkey, "merge")) {
457 if (!value)
458 return config_error_nonbool(key);
459 add_merge(branch, value);
460 }
461 return 0;
462 }
463 if (parse_config_key(key, "url", &name, &namelen, &subkey) >= 0) {
464 struct rewrite *rewrite;
465 if (!name)
466 return 0;
467 if (!strcmp(subkey, "insteadof")) {
468 if (!value)
469 return config_error_nonbool(key);
470 rewrite = make_rewrite(&remote_state->rewrites, name,
471 namelen);
472 add_instead_of(rewrite, xstrdup(value));
473 } else if (!strcmp(subkey, "pushinsteadof")) {
474 if (!value)
475 return config_error_nonbool(key);
476 rewrite = make_rewrite(&remote_state->rewrites_push,
477 name, namelen);
478 add_instead_of(rewrite, xstrdup(value));
479 }
480 }
481
482 if (parse_config_key(key, "remote", &name, &namelen, &subkey) < 0)
483 return 0;
484
485 /* Handle remote.* variables */
486 if (!name && !strcmp(subkey, "pushdefault")) {
487 FREE_AND_NULL(remote_state->pushremote_name);
488 return git_config_string(&remote_state->pushremote_name, key,
489 value);
490 }
491
492 if (!name)
493 return 0;
494 /* Handle remote.<name>.* variables */
495 if (*name == '/') {
496 warning(_("config remote shorthand cannot begin with '/': %s"),
497 name);
498 return 0;
499 }
500 remote = make_remote(remote_state, name, namelen);
501 remote->origin = REMOTE_CONFIG;
502 if (kvi->scope == CONFIG_SCOPE_LOCAL ||
503 kvi->scope == CONFIG_SCOPE_WORKTREE)
504 remote->configured_in_repo = 1;
505 if (!strcmp(subkey, "mirror"))
506 remote->mirror = git_config_bool(key, value);
507 else if (!strcmp(subkey, "skipdefaultupdate"))
508 remote->skip_default_update = git_config_bool(key, value);
509 else if (!strcmp(subkey, "skipfetchall"))
510 remote->skip_default_update = git_config_bool(key, value);
511 else if (!strcmp(subkey, "prune"))
512 remote->prune = git_config_bool(key, value);
513 else if (!strcmp(subkey, "prunetags"))
514 remote->prune_tags = git_config_bool(key, value);
515 else if (!strcmp(subkey, "url")) {
516 if (!value)
517 return config_error_nonbool(key);
518 add_url(remote, value);
519 } else if (!strcmp(subkey, "pushurl")) {
520 if (!value)
521 return config_error_nonbool(key);
522 add_pushurl(remote, value);
523 } else if (!strcmp(subkey, "push")) {
524 char *v;
525 if (git_config_string(&v, key, value))
526 return -1;
527 refspec_append(&remote->push, v);
528 free(v);
529 } else if (!strcmp(subkey, "fetch")) {
530 char *v;
531 if (git_config_string(&v, key, value))
532 return -1;
533 refspec_append(&remote->fetch, v);
534 free(v);
535 } else if (!strcmp(subkey, "receivepack")) {
536 char *v;
537 if (git_config_string(&v, key, value))
538 return -1;
539 if (!remote->receivepack)
540 remote->receivepack = v;
541 else
542 error(_("more than one receivepack given, using the first"));
543 } else if (!strcmp(subkey, "uploadpack")) {
544 char *v;
545 if (git_config_string(&v, key, value))
546 return -1;
547 if (!remote->uploadpack)
548 remote->uploadpack = v;
549 else
550 error(_("more than one uploadpack given, using the first"));
551 } else if (!strcmp(subkey, "tagopt")) {
552 if (!strcmp(value, "--no-tags"))
553 remote->fetch_tags = -1;
554 else if (!strcmp(value, "--tags"))
555 remote->fetch_tags = 2;
556 } else if (!strcmp(subkey, "proxy")) {
557 FREE_AND_NULL(remote->http_proxy);
558 return git_config_string(&remote->http_proxy,
559 key, value);
560 } else if (!strcmp(subkey, "proxyauthmethod")) {
561 FREE_AND_NULL(remote->http_proxy_authmethod);
562 return git_config_string(&remote->http_proxy_authmethod,
563 key, value);
564 } else if (!strcmp(subkey, "vcs")) {
565 FREE_AND_NULL(remote->foreign_vcs);
566 return git_config_string(&remote->foreign_vcs, key, value);
567 } else if (!strcmp(subkey, "serveroption")) {
568 return parse_transport_option(key, value,
569 &remote->server_options);
570 } else if (!strcmp(subkey, "negotiationrestrict")) {
571 return parse_transport_option(key, value,
572 &remote->negotiation_restrict);
573 } else if (!strcmp(subkey, "negotiationinclude")) {
574 return parse_transport_option(key, value,
575 &remote->negotiation_include);
576 } else if (!strcmp(subkey, "followremotehead")) {
577 const char *no_warn_branch;
578 if (!strcmp(value, "never"))
579 remote->follow_remote_head = FOLLOW_REMOTE_NEVER;
580 else if (!strcmp(value, "create"))
581 remote->follow_remote_head = FOLLOW_REMOTE_CREATE;
582 else if (!strcmp(value, "warn")) {
583 remote->follow_remote_head = FOLLOW_REMOTE_WARN;
584 remote->no_warn_branch = NULL;
585 } else if (skip_prefix(value, "warn-if-not-", &no_warn_branch)) {
586 remote->follow_remote_head = FOLLOW_REMOTE_WARN;
587 remote->no_warn_branch = no_warn_branch;
588 } else if (!strcmp(value, "always")) {
589 remote->follow_remote_head = FOLLOW_REMOTE_ALWAYS;
590 } else {
591 warning(_("unrecognized followRemoteHEAD value '%s' ignored"),
592 value);
593 }
594 }
595 return 0;
596 }
597
598 static void alias_all_urls(struct remote_state *remote_state)
599 {
600 int i, j;
601 for (i = 0; i < remote_state->remotes_nr; i++) {
602 int add_pushurl_aliases;
603 if (!remote_state->remotes[i])
604 continue;
605 for (j = 0; j < remote_state->remotes[i]->pushurl.nr; j++) {
606 char *alias = alias_url(remote_state->remotes[i]->pushurl.v[j],
607 &remote_state->rewrites);
608 if (alias)
609 strvec_replace(&remote_state->remotes[i]->pushurl,
610 j, alias);
611 free(alias);
612 }
613 add_pushurl_aliases = remote_state->remotes[i]->pushurl.nr == 0;
614 for (j = 0; j < remote_state->remotes[i]->url.nr; j++) {
615 char *alias;
616 if (add_pushurl_aliases)
617 add_pushurl_alias(
618 remote_state, remote_state->remotes[i],
619 remote_state->remotes[i]->url.v[j]);
620 alias = alias_url(remote_state->remotes[i]->url.v[j],
621 &remote_state->rewrites);
622 if (alias)
623 strvec_replace(&remote_state->remotes[i]->url,
624 j, alias);
625 free(alias);
626 }
627 }
628 }
629
630 static void read_config(struct repository *repo, int early)
631 {
632 int flag;
633
634 if (repo->remote_state->initialized)
635 return;
636 repo->remote_state->initialized = 1;
637
638 repo->remote_state->current_branch = NULL;
639 if (startup_info->have_repository && !early) {
640 const char *head_ref = refs_resolve_ref_unsafe(
641 get_main_ref_store(repo), "HEAD", 0, NULL, &flag);
642 if (head_ref && (flag & REF_ISSYMREF) &&
643 skip_prefix(head_ref, "refs/heads/", &head_ref)) {
644 repo->remote_state->current_branch = make_branch(
645 repo->remote_state, head_ref, strlen(head_ref));
646 }
647 }
648 repo_config(repo, handle_config, repo->remote_state);
649 alias_all_urls(repo->remote_state);
650 }
651
652 #ifndef WITH_BREAKING_CHANGES
653 static int valid_remote_nick(const char *name)
654 {
655 if (!name[0] || is_dot_or_dotdot(name))
656 return 0;
657
658 /* remote nicknames cannot contain slashes */
659 while (*name)
660 if (is_dir_sep(*name++))
661 return 0;
662 return 1;
663 }
664 #endif /* WITH_BREAKING_CHANGES */
665
666 static const char *remotes_remote_for_branch(struct remote_state *remote_state,
667 struct branch *branch,
668 int *explicit)
669 {
670 if (branch && branch->remote_name) {
671 if (explicit)
672 *explicit = 1;
673 return branch->remote_name;
674 }
675 if (explicit)
676 *explicit = 0;
677 if (remote_state->remotes_nr == 1)
678 return remote_state->remotes[0]->name;
679 return "origin";
680 }
681
682 const char *remote_for_branch(struct branch *branch, int *explicit)
683 {
684 read_config(the_repository, 0);
685 die_on_missing_branch(the_repository, branch);
686
687 return remotes_remote_for_branch(the_repository->remote_state, branch,
688 explicit);
689 }
690
691 static const char *
692 remotes_pushremote_for_branch(struct remote_state *remote_state,
693 struct branch *branch, int *explicit)
694 {
695 if (branch && branch->pushremote_name) {
696 if (explicit)
697 *explicit = 1;
698 return branch->pushremote_name;
699 }
700 if (remote_state->pushremote_name) {
701 if (explicit)
702 *explicit = 1;
703 return remote_state->pushremote_name;
704 }
705 return remotes_remote_for_branch(remote_state, branch, explicit);
706 }
707
708 const char *pushremote_for_branch(struct branch *branch, int *explicit)
709 {
710 read_config(the_repository, 0);
711 die_on_missing_branch(the_repository, branch);
712
713 return remotes_pushremote_for_branch(the_repository->remote_state,
714 branch, explicit);
715 }
716
717 static struct remote *remotes_remote_get(struct repository *repo,
718 const char *name);
719
720 char *remote_ref_for_branch(struct branch *branch, int for_push)
721 {
722 read_config(the_repository, 0);
723 die_on_missing_branch(the_repository, branch);
724
725 if (branch) {
726 if (!for_push) {
727 if (branch->merge_nr) {
728 return xstrdup(branch->merge[0]->src);
729 }
730 } else {
731 char *dst;
732 const char *remote_name = remotes_pushremote_for_branch(
733 the_repository->remote_state, branch,
734 NULL);
735 struct remote *remote = remotes_remote_get(
736 the_repository, remote_name);
737
738 if (remote && remote->push.nr &&
739 (dst = apply_refspecs(&remote->push,
740 branch->refname))) {
741 return dst;
742 }
743 }
744 }
745 return NULL;
746 }
747
748 static void validate_remote_url(struct remote *remote)
749 {
750 int i;
751 const char *value;
752 struct strbuf redacted = STRBUF_INIT;
753 int warn_not_die;
754
755 if (repo_config_get_string_tmp(the_repository, "transfer.credentialsinurl", &value))
756 return;
757
758 if (!strcmp("warn", value))
759 warn_not_die = 1;
760 else if (!strcmp("die", value))
761 warn_not_die = 0;
762 else if (!strcmp("allow", value))
763 return;
764 else
765 die(_("unrecognized value transfer.credentialsInUrl: '%s'"), value);
766
767 for (i = 0; i < remote->url.nr; i++) {
768 struct url_info url_info = { 0 };
769
770 if (!url_normalize(remote->url.v[i], &url_info) ||
771 !url_info.passwd_off)
772 goto loop_cleanup;
773
774 strbuf_reset(&redacted);
775 strbuf_add(&redacted, url_info.url, url_info.passwd_off);
776 strbuf_addstr(&redacted, "<redacted>");
777 strbuf_addstr(&redacted,
778 url_info.url + url_info.passwd_off + url_info.passwd_len);
779
780 if (warn_not_die)
781 warning(_("URL '%s' uses plaintext credentials"), redacted.buf);
782 else
783 die(_("URL '%s' uses plaintext credentials"), redacted.buf);
784
785 loop_cleanup:
786 free(url_info.url);
787 }
788
789 strbuf_release(&redacted);
790 }
791
792 static struct remote *
793 remotes_remote_get_1(struct repository *repo, const char *name,
794 const char *(*get_default)(struct remote_state *,
795 struct branch *, int *))
796 {
797 struct remote_state *remote_state = repo->remote_state;
798 struct remote *ret;
799 int name_given = 0;
800
801 if (name)
802 name_given = 1;
803 else
804 name = get_default(remote_state, remote_state->current_branch,
805 &name_given);
806
807 ret = make_remote(remote_state, name, 0);
808 #ifndef WITH_BREAKING_CHANGES
809 if (valid_remote_nick(name) && have_git_dir()) {
810 if (!valid_remote(ret))
811 read_remotes_file(repo, ret);
812 if (!valid_remote(ret))
813 read_branches_file(repo, ret);
814 }
815 #endif /* WITH_BREAKING_CHANGES */
816 if (name_given && !valid_remote(ret))
817 add_url_alias(remote_state, ret, name);
818 if (!valid_remote(ret))
819 return NULL;
820
821 validate_remote_url(ret);
822
823 return ret;
824 }
825
826 static inline struct remote *
827 remotes_remote_get(struct repository *repo, const char *name)
828 {
829 return remotes_remote_get_1(repo, name, remotes_remote_for_branch);
830 }
831
832 struct remote *remote_get(const char *name)
833 {
834 read_config(the_repository, 0);
835 return remotes_remote_get(the_repository, name);
836 }
837
838 struct remote *remote_get_early(const char *name)
839 {
840 read_config(the_repository, 1);
841 return remotes_remote_get(the_repository, name);
842 }
843
844 static inline struct remote *
845 remotes_pushremote_get(struct repository *repo, const char *name)
846 {
847 return remotes_remote_get_1(repo, name, remotes_pushremote_for_branch);
848 }
849
850 struct remote *pushremote_get(const char *name)
851 {
852 read_config(the_repository, 0);
853 return remotes_pushremote_get(the_repository, name);
854 }
855
856 int remote_is_configured(struct remote *remote, int in_repo)
857 {
858 if (!remote)
859 return 0;
860 if (in_repo)
861 return remote->configured_in_repo;
862 return !!remote->origin;
863 }
864
865 int for_each_remote(each_remote_fn fn, void *priv)
866 {
867 int i, result = 0;
868 read_config(the_repository, 0);
869 for (i = 0; i < the_repository->remote_state->remotes_nr && !result;
870 i++) {
871 struct remote *remote =
872 the_repository->remote_state->remotes[i];
873 if (!remote)
874 continue;
875 result = fn(remote, priv);
876 }
877 return result;
878 }
879
880 static void handle_duplicate(struct ref *ref1, struct ref *ref2)
881 {
882 if (strcmp(ref1->name, ref2->name)) {
883 if (ref1->fetch_head_status != FETCH_HEAD_IGNORE &&
884 ref2->fetch_head_status != FETCH_HEAD_IGNORE) {
885 die(_("Cannot fetch both %s and %s to %s"),
886 ref1->name, ref2->name, ref2->peer_ref->name);
887 } else if (ref1->fetch_head_status != FETCH_HEAD_IGNORE &&
888 ref2->fetch_head_status == FETCH_HEAD_IGNORE) {
889 warning(_("%s usually tracks %s, not %s"),
890 ref2->peer_ref->name, ref2->name, ref1->name);
891 } else if (ref1->fetch_head_status == FETCH_HEAD_IGNORE &&
892 ref2->fetch_head_status == FETCH_HEAD_IGNORE) {
893 die(_("%s tracks both %s and %s"),
894 ref2->peer_ref->name, ref1->name, ref2->name);
895 } else {
896 /*
897 * This last possibility doesn't occur because
898 * FETCH_HEAD_IGNORE entries always appear at
899 * the end of the list.
900 */
901 BUG("Internal error");
902 }
903 }
904 free(ref2->peer_ref);
905 free(ref2);
906 }
907
908 struct ref *ref_remove_duplicates(struct ref *ref_map)
909 {
910 struct string_list refs = STRING_LIST_INIT_NODUP;
911 struct ref *retval = NULL;
912 struct ref **p = &retval;
913
914 while (ref_map) {
915 struct ref *ref = ref_map;
916
917 ref_map = ref_map->next;
918 ref->next = NULL;
919
920 if (!ref->peer_ref) {
921 *p = ref;
922 p = &ref->next;
923 } else {
924 struct string_list_item *item =
925 string_list_insert(&refs, ref->peer_ref->name);
926
927 if (item->util) {
928 /* Entry already existed */
929 handle_duplicate((struct ref *)item->util, ref);
930 } else {
931 *p = ref;
932 p = &ref->next;
933 item->util = ref;
934 }
935 }
936 }
937
938 string_list_clear(&refs, 0);
939 return retval;
940 }
941
942 int remote_has_url(struct remote *remote, const char *url)
943 {
944 int i;
945 for (i = 0; i < remote->url.nr; i++) {
946 if (!strcmp(remote->url.v[i], url))
947 return 1;
948 }
949 return 0;
950 }
951
952 struct strvec *push_url_of_remote(struct remote *remote)
953 {
954 return remote->pushurl.nr ? &remote->pushurl : &remote->url;
955 }
956
957 static bool remote_has_push_url(struct remote *remote, const char *url)
958 {
959 const struct strvec *push_urls = push_url_of_remote(remote);
960
961 for (size_t i = 0; i < push_urls->nr; i++) {
962 if (!strcmp(push_urls->v[i], url))
963 return true;
964 }
965 return false;
966 }
967
968 void ref_push_report_free(struct ref_push_report *report)
969 {
970 while (report) {
971 struct ref_push_report *next = report->next;
972
973 free(report->ref_name);
974 free(report->old_oid);
975 free(report->new_oid);
976 free(report);
977
978 report = next;
979 }
980 }
981
982 int remote_find_tracking(struct remote *remote, struct refspec_item *refspec)
983 {
984 return refspec_find_match(&remote->fetch, refspec);
985 }
986
987 static struct ref *alloc_ref_with_prefix(const char *prefix, size_t prefixlen,
988 const char *name)
989 {
990 size_t len = strlen(name);
991 struct ref *ref = xcalloc(1, st_add4(sizeof(*ref), prefixlen, len, 1));
992 memcpy(ref->name, prefix, prefixlen);
993 memcpy(ref->name + prefixlen, name, len);
994 return ref;
995 }
996
997 struct ref *alloc_ref(const char *name)
998 {
999 return alloc_ref_with_prefix("", 0, name);
1000 }
1001
1002 struct ref *copy_ref(const struct ref *ref)
1003 {
1004 struct ref *cpy;
1005 size_t len;
1006 if (!ref)
1007 return NULL;
1008 len = st_add3(sizeof(struct ref), strlen(ref->name), 1);
1009 cpy = xmalloc(len);
1010 memcpy(cpy, ref, len);
1011 cpy->next = NULL;
1012 cpy->symref = xstrdup_or_null(ref->symref);
1013 cpy->remote_status = xstrdup_or_null(ref->remote_status);
1014 cpy->peer_ref = copy_ref(ref->peer_ref);
1015 return cpy;
1016 }
1017
1018 struct ref *copy_ref_list(const struct ref *ref)
1019 {
1020 struct ref *ret = NULL;
1021 struct ref **tail = &ret;
1022 while (ref) {
1023 *tail = copy_ref(ref);
1024 ref = ref->next;
1025 tail = &((*tail)->next);
1026 }
1027 return ret;
1028 }
1029
1030 void free_one_ref(struct ref *ref)
1031 {
1032 if (!ref)
1033 return;
1034 free_one_ref(ref->peer_ref);
1035 ref_push_report_free(ref->report);
1036 free(ref->remote_status);
1037 free(ref->tracking_ref);
1038 free(ref->symref);
1039 free(ref);
1040 }
1041
1042 void free_refs(struct ref *ref)
1043 {
1044 struct ref *next;
1045 while (ref) {
1046 next = ref->next;
1047 free_one_ref(ref);
1048 ref = next;
1049 }
1050 }
1051
1052 int count_refspec_match(const char *pattern,
1053 struct ref *refs,
1054 struct ref **matched_ref)
1055 {
1056 int patlen = strlen(pattern);
1057 struct ref *matched_weak = NULL;
1058 struct ref *matched = NULL;
1059 int weak_match = 0;
1060 int match = 0;
1061
1062 for (weak_match = match = 0; refs; refs = refs->next) {
1063 char *name = refs->name;
1064 int namelen = strlen(name);
1065
1066 if (!refname_match(pattern, name))
1067 continue;
1068
1069 /* A match is "weak" if it is with refs outside
1070 * heads or tags, and did not specify the pattern
1071 * in full (e.g. "refs/remotes/origin/master") or at
1072 * least from the toplevel (e.g. "remotes/origin/master");
1073 * otherwise "git push $URL master" would result in
1074 * ambiguity between remotes/origin/master and heads/master
1075 * at the remote site.
1076 */
1077 if (namelen != patlen &&
1078 patlen != namelen - 5 &&
1079 !starts_with(name, "refs/heads/") &&
1080 !starts_with(name, "refs/tags/")) {
1081 /* We want to catch the case where only weak
1082 * matches are found and there are multiple
1083 * matches, and where more than one strong
1084 * matches are found, as ambiguous. One
1085 * strong match with zero or more weak matches
1086 * are acceptable as a unique match.
1087 */
1088 matched_weak = refs;
1089 weak_match++;
1090 }
1091 else {
1092 matched = refs;
1093 match++;
1094 }
1095 }
1096 if (!matched) {
1097 if (matched_ref)
1098 *matched_ref = matched_weak;
1099 return weak_match;
1100 }
1101 else {
1102 if (matched_ref)
1103 *matched_ref = matched;
1104 return match;
1105 }
1106 }
1107
1108 void tail_link_ref(struct ref *ref, struct ref ***tail)
1109 {
1110 **tail = ref;
1111 while (ref->next)
1112 ref = ref->next;
1113 *tail = &ref->next;
1114 }
1115
1116 static struct ref *alloc_delete_ref(void)
1117 {
1118 struct ref *ref = alloc_ref("(delete)");
1119 oidclr(&ref->new_oid, the_repository->hash_algo);
1120 return ref;
1121 }
1122
1123 static int try_explicit_object_name(const char *name,
1124 struct ref **match)
1125 {
1126 struct object_id oid;
1127
1128 if (!*name) {
1129 if (match)
1130 *match = alloc_delete_ref();
1131 return 0;
1132 }
1133
1134 if (repo_get_oid(the_repository, name, &oid))
1135 return -1;
1136
1137 if (match) {
1138 *match = alloc_ref(name);
1139 oidcpy(&(*match)->new_oid, &oid);
1140 }
1141 return 0;
1142 }
1143
1144 static struct ref *make_linked_ref(const char *name, struct ref ***tail)
1145 {
1146 struct ref *ret = alloc_ref(name);
1147 tail_link_ref(ret, tail);
1148 return ret;
1149 }
1150
1151 static char *guess_ref(const char *name, struct ref *peer)
1152 {
1153 struct strbuf buf = STRBUF_INIT;
1154
1155 const char *r = refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
1156 peer->name,
1157 RESOLVE_REF_READING,
1158 NULL, NULL);
1159 if (!r)
1160 return NULL;
1161
1162 if (starts_with(r, "refs/heads/")) {
1163 strbuf_addstr(&buf, "refs/heads/");
1164 } else if (starts_with(r, "refs/tags/")) {
1165 strbuf_addstr(&buf, "refs/tags/");
1166 } else {
1167 return NULL;
1168 }
1169
1170 strbuf_addstr(&buf, name);
1171 return strbuf_detach(&buf, NULL);
1172 }
1173
1174 static int match_explicit_lhs(struct ref *src,
1175 struct refspec_item *rs,
1176 struct ref **match,
1177 int *allocated_match)
1178 {
1179 switch (count_refspec_match(rs->src, src, match)) {
1180 case 1:
1181 if (allocated_match)
1182 *allocated_match = 0;
1183 return 0;
1184 case 0:
1185 /* The source could be in the get_sha1() format
1186 * not a reference name. :refs/other is a
1187 * way to delete 'other' ref at the remote end.
1188 */
1189 if (try_explicit_object_name(rs->src, match) < 0)
1190 return error(_("src refspec %s does not match any"), rs->src);
1191 if (allocated_match)
1192 *allocated_match = 1;
1193 return 0;
1194 default:
1195 return error(_("src refspec %s matches more than one"), rs->src);
1196 }
1197 }
1198
1199 static void show_push_unqualified_ref_name_error(const char *dst_value,
1200 const char *matched_src_name)
1201 {
1202 struct object_id oid;
1203
1204 /*
1205 * TRANSLATORS: "matches '%s'%" is the <dst> part of "git push
1206 * <remote> <src>:<dst>" push, and "being pushed ('%s')" is
1207 * the <src>.
1208 */
1209 error(_("The destination you provided is not a full refname (i.e.,\n"
1210 "starting with \"refs/\"). We tried to guess what you meant by:\n"
1211 "\n"
1212 "- Looking for a ref that matches '%s' on the remote side.\n"
1213 "- Checking if the <src> being pushed ('%s')\n"
1214 " is a ref in \"refs/{heads,tags}/\". If so we add a corresponding\n"
1215 " refs/{heads,tags}/ prefix on the remote side.\n"
1216 "\n"
1217 "Neither worked, so we gave up. You must fully qualify the ref."),
1218 dst_value, matched_src_name);
1219
1220 if (!advice_enabled(ADVICE_PUSH_UNQUALIFIED_REF_NAME))
1221 return;
1222
1223 if (repo_get_oid(the_repository, matched_src_name, &oid))
1224 BUG("'%s' is not a valid object, "
1225 "match_explicit_lhs() should catch this!",
1226 matched_src_name);
1227
1228 switch (odb_read_object_info(the_repository->objects, &oid, NULL)) {
1229 case OBJ_COMMIT:
1230 advise(_("The <src> part of the refspec is a commit object.\n"
1231 "Did you mean to create a new branch by pushing to\n"
1232 "'%s:refs/heads/%s'?"),
1233 matched_src_name, dst_value);
1234 break;
1235 case OBJ_TAG:
1236 advise(_("The <src> part of the refspec is a tag object.\n"
1237 "Did you mean to create a new tag by pushing to\n"
1238 "'%s:refs/tags/%s'?"),
1239 matched_src_name, dst_value);
1240 break;
1241 case OBJ_TREE:
1242 advise(_("The <src> part of the refspec is a tree object.\n"
1243 "Did you mean to tag a new tree by pushing to\n"
1244 "'%s:refs/tags/%s'?"),
1245 matched_src_name, dst_value);
1246 break;
1247 case OBJ_BLOB:
1248 advise(_("The <src> part of the refspec is a blob object.\n"
1249 "Did you mean to tag a new blob by pushing to\n"
1250 "'%s:refs/tags/%s'?"),
1251 matched_src_name, dst_value);
1252 break;
1253 default:
1254 advise(_("The <src> part of the refspec ('%s') "
1255 "is an object ID that doesn't exist.\n"),
1256 matched_src_name);
1257 break;
1258 }
1259 }
1260
1261 static int match_explicit(struct ref *src, struct ref *dst,
1262 struct ref ***dst_tail,
1263 struct refspec_item *rs)
1264 {
1265 struct ref *matched_src = NULL, *matched_dst = NULL;
1266 int allocated_src = 0, ret;
1267
1268 const char *dst_value = rs->dst;
1269 char *dst_guess;
1270
1271 if (rs->pattern || rs->matching || rs->negative) {
1272 ret = 0;
1273 goto out;
1274 }
1275
1276 if (match_explicit_lhs(src, rs, &matched_src, &allocated_src) < 0) {
1277 ret = -1;
1278 goto out;
1279 }
1280
1281 if (!dst_value) {
1282 int flag;
1283
1284 dst_value = refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
1285 matched_src->name,
1286 RESOLVE_REF_READING,
1287 NULL, &flag);
1288 if (!dst_value ||
1289 ((flag & REF_ISSYMREF) &&
1290 !starts_with(dst_value, "refs/heads/")))
1291 die(_("%s cannot be resolved to branch"),
1292 matched_src->name);
1293 }
1294
1295 switch (count_refspec_match(dst_value, dst, &matched_dst)) {
1296 case 1:
1297 break;
1298 case 0:
1299 if (starts_with(dst_value, "refs/")) {
1300 matched_dst = make_linked_ref(dst_value, dst_tail);
1301 } else if (is_null_oid(&matched_src->new_oid)) {
1302 error(_("unable to delete '%s': remote ref does not exist"),
1303 dst_value);
1304 } else if ((dst_guess = guess_ref(dst_value, matched_src))) {
1305 matched_dst = make_linked_ref(dst_guess, dst_tail);
1306 free(dst_guess);
1307 } else {
1308 show_push_unqualified_ref_name_error(dst_value,
1309 matched_src->name);
1310 }
1311 break;
1312 default:
1313 matched_dst = NULL;
1314 error(_("dst refspec %s matches more than one"),
1315 dst_value);
1316 break;
1317 }
1318
1319 if (!matched_dst) {
1320 ret = -1;
1321 goto out;
1322 }
1323
1324 if (matched_dst->peer_ref) {
1325 ret = error(_("dst ref %s receives from more than one src"),
1326 matched_dst->name);
1327 goto out;
1328 } else {
1329 matched_dst->peer_ref = allocated_src ?
1330 matched_src :
1331 copy_ref(matched_src);
1332 matched_dst->force = rs->force;
1333 matched_src = NULL;
1334 }
1335
1336 ret = 0;
1337
1338 out:
1339 if (allocated_src)
1340 free_one_ref(matched_src);
1341 return ret;
1342 }
1343
1344 static int match_explicit_refs(struct ref *src, struct ref *dst,
1345 struct ref ***dst_tail, struct refspec *rs)
1346 {
1347 int i, errs;
1348 for (i = errs = 0; i < rs->nr; i++)
1349 errs += match_explicit(src, dst, dst_tail, &rs->items[i]);
1350 return errs;
1351 }
1352
1353 static char *get_ref_match(const struct refspec *rs, const struct ref *ref,
1354 int send_mirror, int direction,
1355 const struct refspec_item **ret_pat)
1356 {
1357 const struct refspec_item *pat;
1358 char *name;
1359 int i;
1360 int matching_refs = -1;
1361 for (i = 0; i < rs->nr; i++) {
1362 const struct refspec_item *item = &rs->items[i];
1363
1364 if (item->negative)
1365 continue;
1366
1367 if (item->matching &&
1368 (matching_refs == -1 || item->force)) {
1369 matching_refs = i;
1370 continue;
1371 }
1372
1373 if (item->pattern) {
1374 const char *dst_side = item->dst ? item->dst : item->src;
1375 int match;
1376 if (direction == FROM_SRC)
1377 match = match_refname_with_pattern(item->src, ref->name, dst_side, &name);
1378 else
1379 match = match_refname_with_pattern(dst_side, ref->name, item->src, &name);
1380 if (match) {
1381 matching_refs = i;
1382 break;
1383 }
1384 }
1385 }
1386 if (matching_refs == -1)
1387 return NULL;
1388
1389 pat = &rs->items[matching_refs];
1390 if (pat->matching) {
1391 /*
1392 * "matching refs"; traditionally we pushed everything
1393 * including refs outside refs/heads/ hierarchy, but
1394 * that does not make much sense these days.
1395 */
1396 if (!send_mirror && !starts_with(ref->name, "refs/heads/"))
1397 return NULL;
1398 name = xstrdup(ref->name);
1399 }
1400 if (ret_pat)
1401 *ret_pat = pat;
1402 return name;
1403 }
1404
1405 static struct ref **tail_ref(struct ref **head)
1406 {
1407 struct ref **tail = head;
1408 while (*tail)
1409 tail = &((*tail)->next);
1410 return tail;
1411 }
1412
1413 static void add_to_tips(struct commit_stack *tips, const struct object_id *oid)
1414 {
1415 struct commit *commit;
1416
1417 if (is_null_oid(oid))
1418 return;
1419 commit = lookup_commit_reference_gently(the_repository, oid, 1);
1420 if (!commit || (commit->object.flags & TMP_MARK))
1421 return;
1422 commit->object.flags |= TMP_MARK;
1423 commit_stack_push(tips, commit);
1424 }
1425
1426 static void add_missing_tags(struct ref *src, struct ref **dst, struct ref ***dst_tail)
1427 {
1428 struct string_list dst_tag = STRING_LIST_INIT_NODUP;
1429 struct string_list src_tag = STRING_LIST_INIT_NODUP;
1430 struct string_list_item *item;
1431 struct ref *ref;
1432 struct commit_stack sent_tips = COMMIT_STACK_INIT;
1433
1434 /*
1435 * Collect everything we know they would have at the end of
1436 * this push, and collect all tags they have.
1437 */
1438 for (ref = *dst; ref; ref = ref->next) {
1439 if (ref->peer_ref &&
1440 !is_null_oid(&ref->peer_ref->new_oid))
1441 add_to_tips(&sent_tips, &ref->peer_ref->new_oid);
1442 else
1443 add_to_tips(&sent_tips, &ref->old_oid);
1444 if (starts_with(ref->name, "refs/tags/"))
1445 string_list_append(&dst_tag, ref->name);
1446 }
1447 clear_commit_marks_many(sent_tips.nr, sent_tips.items, TMP_MARK);
1448
1449 string_list_sort(&dst_tag);
1450
1451 /* Collect tags they do not have. */
1452 for (ref = src; ref; ref = ref->next) {
1453 if (!starts_with(ref->name, "refs/tags/"))
1454 continue; /* not a tag */
1455 if (string_list_has_string(&dst_tag, ref->name))
1456 continue; /* they already have it */
1457 if (odb_read_object_info(the_repository->objects,
1458 &ref->new_oid, NULL) != OBJ_TAG)
1459 continue; /* be conservative */
1460 item = string_list_append(&src_tag, ref->name);
1461 item->util = ref;
1462 }
1463 string_list_clear(&dst_tag, 0);
1464
1465 /*
1466 * At this point, src_tag lists tags that are missing from
1467 * dst, and sent_tips lists the tips we are pushing or those
1468 * that we know they already have. An element in the src_tag
1469 * that is an ancestor of any of the sent_tips needs to be
1470 * sent to the other side.
1471 */
1472 if (sent_tips.nr) {
1473 const int reachable_flag = 1;
1474 struct commit_list *found_commits;
1475 struct commit_stack src_commits = COMMIT_STACK_INIT;
1476
1477 for_each_string_list_item(item, &src_tag) {
1478 struct ref *ref = item->util;
1479 struct commit *commit;
1480
1481 if (is_null_oid(&ref->new_oid))
1482 continue;
1483 commit = lookup_commit_reference_gently(the_repository,
1484 &ref->new_oid,
1485 1);
1486 if (!commit)
1487 /* not pushing a commit, which is not an error */
1488 continue;
1489
1490 commit_stack_push(&src_commits, commit);
1491 }
1492
1493 found_commits = get_reachable_subset(sent_tips.items,
1494 sent_tips.nr,
1495 src_commits.items,
1496 src_commits.nr,
1497 reachable_flag);
1498
1499 for_each_string_list_item(item, &src_tag) {
1500 struct ref *dst_ref;
1501 struct ref *ref = item->util;
1502 struct commit *commit;
1503
1504 if (is_null_oid(&ref->new_oid))
1505 continue;
1506 commit = lookup_commit_reference_gently(the_repository,
1507 &ref->new_oid,
1508 1);
1509 if (!commit)
1510 /* not pushing a commit, which is not an error */
1511 continue;
1512
1513 /*
1514 * Is this tag, which they do not have, reachable from
1515 * any of the commits we are sending?
1516 */
1517 if (!(commit->object.flags & reachable_flag))
1518 continue;
1519
1520 /* Add it in */
1521 dst_ref = make_linked_ref(ref->name, dst_tail);
1522 oidcpy(&dst_ref->new_oid, &ref->new_oid);
1523 dst_ref->peer_ref = copy_ref(ref);
1524 }
1525
1526 clear_commit_marks_many(src_commits.nr, src_commits.items,
1527 reachable_flag);
1528 commit_stack_clear(&src_commits);
1529 commit_list_free(found_commits);
1530 }
1531
1532 string_list_clear(&src_tag, 0);
1533 commit_stack_clear(&sent_tips);
1534 }
1535
1536 struct ref *find_ref_by_name(const struct ref *list, const char *name)
1537 {
1538 for ( ; list; list = list->next)
1539 if (!strcmp(list->name, name))
1540 return (struct ref *)list;
1541 return NULL;
1542 }
1543
1544 static void prepare_ref_index(struct string_list *ref_index, struct ref *ref)
1545 {
1546 for ( ; ref; ref = ref->next)
1547 string_list_append_nodup(ref_index, ref->name)->util = ref;
1548
1549 string_list_sort(ref_index);
1550 }
1551
1552 /*
1553 * Given only the set of local refs, sanity-check the set of push
1554 * refspecs. We can't catch all errors that match_push_refs would,
1555 * but we can catch some errors early before even talking to the
1556 * remote side.
1557 */
1558 int check_push_refs(struct ref *src, struct refspec *rs)
1559 {
1560 int ret = 0;
1561 int i;
1562
1563 for (i = 0; i < rs->nr; i++) {
1564 struct refspec_item *item = &rs->items[i];
1565
1566 if (item->pattern || item->matching || item->negative)
1567 continue;
1568
1569 ret |= match_explicit_lhs(src, item, NULL, NULL);
1570 }
1571
1572 return ret;
1573 }
1574
1575 /*
1576 * Given the set of refs the local repository has, the set of refs the
1577 * remote repository has, and the refspec used for push, determine
1578 * what remote refs we will update and with what value by setting
1579 * peer_ref (which object is being pushed) and force (if the push is
1580 * forced) in elements of "dst". The function may add new elements to
1581 * dst (e.g. pushing to a new branch, done in match_explicit_refs).
1582 */
1583 int match_push_refs(struct ref *src, struct ref **dst,
1584 struct refspec *rs, int flags)
1585 {
1586 int send_all = flags & MATCH_REFS_ALL;
1587 int send_mirror = flags & MATCH_REFS_MIRROR;
1588 int send_prune = flags & MATCH_REFS_PRUNE;
1589 int errs;
1590 struct ref *ref, **dst_tail = tail_ref(dst);
1591 struct string_list dst_ref_index = STRING_LIST_INIT_NODUP;
1592
1593 /* If no refspec is provided, use the default ":" */
1594 if (!rs->nr)
1595 refspec_append(rs, ":");
1596
1597 errs = match_explicit_refs(src, *dst, &dst_tail, rs);
1598
1599 /* pick the remainder */
1600 for (ref = src; ref; ref = ref->next) {
1601 struct string_list_item *dst_item;
1602 struct ref *dst_peer;
1603 const struct refspec_item *pat = NULL;
1604 char *dst_name;
1605
1606 dst_name = get_ref_match(rs, ref, send_mirror, FROM_SRC, &pat);
1607 if (!dst_name)
1608 continue;
1609
1610 if (!dst_ref_index.nr)
1611 prepare_ref_index(&dst_ref_index, *dst);
1612
1613 dst_item = string_list_lookup(&dst_ref_index, dst_name);
1614 dst_peer = dst_item ? dst_item->util : NULL;
1615 if (dst_peer) {
1616 if (dst_peer->peer_ref)
1617 /* We're already sending something to this ref. */
1618 goto free_name;
1619 } else {
1620 if (pat->matching && !(send_all || send_mirror))
1621 /*
1622 * Remote doesn't have it, and we have no
1623 * explicit pattern, and we don't have
1624 * --all or --mirror.
1625 */
1626 goto free_name;
1627
1628 /* Create a new one and link it */
1629 dst_peer = make_linked_ref(dst_name, &dst_tail);
1630 oidcpy(&dst_peer->new_oid, &ref->new_oid);
1631 string_list_insert(&dst_ref_index,
1632 dst_peer->name)->util = dst_peer;
1633 }
1634 dst_peer->peer_ref = copy_ref(ref);
1635 dst_peer->force = pat->force;
1636 free_name:
1637 free(dst_name);
1638 }
1639
1640 string_list_clear(&dst_ref_index, 0);
1641
1642 if (flags & MATCH_REFS_FOLLOW_TAGS)
1643 add_missing_tags(src, dst, &dst_tail);
1644
1645 if (send_prune) {
1646 struct string_list src_ref_index = STRING_LIST_INIT_NODUP;
1647 /* check for missing refs on the remote */
1648 for (ref = *dst; ref; ref = ref->next) {
1649 char *src_name;
1650
1651 if (ref->peer_ref)
1652 /* We're already sending something to this ref. */
1653 continue;
1654
1655 src_name = get_ref_match(rs, ref, send_mirror, FROM_DST, NULL);
1656 if (src_name) {
1657 if (!src_ref_index.nr)
1658 prepare_ref_index(&src_ref_index, src);
1659 if (!string_list_has_string(&src_ref_index,
1660 src_name))
1661 ref->peer_ref = alloc_delete_ref();
1662 free(src_name);
1663 }
1664 }
1665 string_list_clear(&src_ref_index, 0);
1666 }
1667
1668 *dst = apply_negative_refspecs(*dst, rs);
1669
1670 if (errs)
1671 return -1;
1672 return 0;
1673 }
1674
1675 void set_ref_status_for_push(struct ref *remote_refs, int send_mirror,
1676 int force_update)
1677 {
1678 struct ref *ref;
1679
1680 for (ref = remote_refs; ref; ref = ref->next) {
1681 int force_ref_update = ref->force || force_update;
1682 int reject_reason = 0;
1683
1684 if (ref->peer_ref)
1685 oidcpy(&ref->new_oid, &ref->peer_ref->new_oid);
1686 else if (!send_mirror)
1687 continue;
1688
1689 ref->deletion = is_null_oid(&ref->new_oid);
1690 if (!ref->deletion &&
1691 oideq(&ref->old_oid, &ref->new_oid)) {
1692 ref->status = REF_STATUS_UPTODATE;
1693 continue;
1694 }
1695
1696 /*
1697 * If the remote ref has moved and is now different
1698 * from what we expect, reject any push.
1699 *
1700 * It also is an error if the user told us to check
1701 * with the remote-tracking branch to find the value
1702 * to expect, but we did not have such a tracking
1703 * branch.
1704 *
1705 * If the tip of the remote-tracking ref is unreachable
1706 * from any reflog entry of its local ref indicating a
1707 * possible update since checkout; reject the push.
1708 */
1709 if (ref->expect_old_sha1) {
1710 if (!oideq(&ref->old_oid, &ref->old_oid_expect))
1711 reject_reason = REF_STATUS_REJECT_STALE;
1712 else if (ref->check_reachable && ref->unreachable)
1713 reject_reason =
1714 REF_STATUS_REJECT_REMOTE_UPDATED;
1715 else
1716 /*
1717 * If the ref isn't stale, and is reachable
1718 * from one of the reflog entries of
1719 * the local branch, force the update.
1720 */
1721 force_ref_update = 1;
1722 }
1723
1724 /*
1725 * If the update isn't already rejected then check
1726 * the usual "must fast-forward" rules.
1727 *
1728 * Decide whether an individual refspec A:B can be
1729 * pushed. The push will succeed if any of the
1730 * following are true:
1731 *
1732 * (1) the remote reference B does not exist
1733 *
1734 * (2) the remote reference B is being removed (i.e.,
1735 * pushing :B where no source is specified)
1736 *
1737 * (3) the destination is not under refs/tags/, and
1738 * if the old and new value is a commit, the new
1739 * is a descendant of the old.
1740 *
1741 * (4) it is forced using the +A:B notation, or by
1742 * passing the --force argument
1743 */
1744
1745 if (!reject_reason && !ref->deletion && !is_null_oid(&ref->old_oid)) {
1746 if (starts_with(ref->name, "refs/tags/"))
1747 reject_reason = REF_STATUS_REJECT_ALREADY_EXISTS;
1748 else if (!odb_has_object(the_repository->objects, &ref->old_oid, ODB_HAS_OBJECT_RECHECK_PACKED))
1749 reject_reason = REF_STATUS_REJECT_FETCH_FIRST;
1750 else if (!lookup_commit_reference_gently(the_repository, &ref->old_oid, 1) ||
1751 !lookup_commit_reference_gently(the_repository, &ref->new_oid, 1))
1752 reject_reason = REF_STATUS_REJECT_NEEDS_FORCE;
1753 else if (!ref_newer(&ref->new_oid, &ref->old_oid))
1754 reject_reason = REF_STATUS_REJECT_NONFASTFORWARD;
1755 }
1756
1757 /*
1758 * "--force" will defeat any rejection implemented
1759 * by the rules above.
1760 */
1761 if (!force_ref_update)
1762 ref->status = reject_reason;
1763 else if (reject_reason)
1764 ref->forced_update = 1;
1765 }
1766 }
1767
1768 static void set_merge(struct repository *repo, struct branch *ret)
1769 {
1770 struct remote *remote;
1771 char *ref;
1772 struct object_id oid;
1773 int i;
1774
1775 if (!ret)
1776 return; /* no branch */
1777 if (ret->set_merge)
1778 return; /* already run */
1779 if (!ret->remote_name || !ret->merge_nr) {
1780 /*
1781 * no merge config; let's make sure we don't confuse callers
1782 * with a non-zero merge_nr but a NULL merge
1783 */
1784 merge_clear(ret);
1785 return;
1786 }
1787 ret->set_merge = 1;
1788
1789 remote = remotes_remote_get(repo, ret->remote_name);
1790
1791 for (i = 0; i < ret->merge_nr; i++) {
1792 if (!remote_find_tracking(remote, ret->merge[i]) ||
1793 strcmp(ret->remote_name, "."))
1794 continue;
1795 if (repo_dwim_ref(repo, ret->merge[i]->src,
1796 strlen(ret->merge[i]->src), &oid, &ref,
1797 0) == 1)
1798 ret->merge[i]->dst = ref;
1799 else
1800 ret->merge[i]->dst = xstrdup(ret->merge[i]->src);
1801 }
1802 }
1803
1804 static struct branch *repo_branch_get(struct repository *repo, const char *name)
1805 {
1806 struct branch *ret;
1807
1808 read_config(repo, 0);
1809 if (!name || !*name || !strcmp(name, "HEAD"))
1810 ret = repo->remote_state->current_branch;
1811 else
1812 ret = make_branch(repo->remote_state, name,
1813 strlen(name));
1814 set_merge(repo, ret);
1815 return ret;
1816 }
1817
1818 struct branch *branch_get(const char *name)
1819 {
1820 return repo_branch_get(the_repository, name);
1821 }
1822
1823 const char *repo_default_remote(struct repository *repo)
1824 {
1825 struct branch *branch;
1826
1827 read_config(repo, 0);
1828 branch = repo_branch_get(repo, "HEAD");
1829
1830 return remotes_remote_for_branch(repo->remote_state, branch, NULL);
1831 }
1832
1833 const char *repo_remote_from_url(struct repository *repo, const char *url)
1834 {
1835 char *rewritten_url;
1836 const char *remote_name = NULL;
1837
1838 read_config(repo, 0);
1839 if ((rewritten_url = alias_url(url, &repo->remote_state->rewrites)))
1840 url = rewritten_url;
1841
1842 for (int i = 0; i < repo->remote_state->remotes_nr; i++) {
1843 struct remote *remote = repo->remote_state->remotes[i];
1844 if (!remote)
1845 continue;
1846
1847 if (remote_has_url(remote, url)) {
1848 remote_name = remote->name;
1849 break;
1850 }
1851 }
1852 free(rewritten_url);
1853 return remote_name;
1854 }
1855
1856 int branch_has_merge_config(struct branch *branch)
1857 {
1858 return branch && branch->set_merge;
1859 }
1860
1861 int branch_merge_matches(struct branch *branch,
1862 int i,
1863 const char *refname)
1864 {
1865 if (!branch || i < 0 || i >= branch->merge_nr)
1866 return 0;
1867 return refname_match(branch->merge[i]->src, refname);
1868 }
1869
1870 __attribute__((format (printf,2,3)))
1871 static char *error_buf(struct strbuf *err, const char *fmt, ...)
1872 {
1873 if (err) {
1874 va_list ap;
1875 va_start(ap, fmt);
1876 strbuf_vaddf(err, fmt, ap);
1877 va_end(ap);
1878 }
1879 return NULL;
1880 }
1881
1882 const char *branch_get_upstream(struct branch *branch, struct strbuf *err)
1883 {
1884 if (!branch)
1885 return error_buf(err, _("HEAD does not point to a branch"));
1886
1887 if (!branch->merge || !branch->merge[0]) {
1888 /*
1889 * no merge config; is it because the user didn't define any,
1890 * or because it is not a real branch, and get_branch
1891 * auto-vivified it?
1892 */
1893 if (!refs_ref_exists(get_main_ref_store(the_repository), branch->refname))
1894 return error_buf(err, _("no such branch: '%s'"),
1895 branch->name);
1896 return error_buf(err,
1897 _("no upstream configured for branch '%s'"),
1898 branch->name);
1899 }
1900
1901 if (!branch->merge[0]->dst)
1902 return error_buf(err,
1903 _("upstream branch '%s' not stored as a remote-tracking branch"),
1904 branch->merge[0]->src);
1905
1906 return branch->merge[0]->dst;
1907 }
1908
1909 struct remote *repo_remote_for_push_tracking(struct repository *repo,
1910 struct remote *remote)
1911 {
1912 const struct strvec *push_urls;
1913 struct remote *first_match = NULL;
1914 struct remote_state *remote_state = repo->remote_state;
1915 const char *check_url;
1916
1917 if (remote->origin != REMOTE_UNCONFIGURED)
1918 return remote;
1919
1920 push_urls = push_url_of_remote(remote);
1921 if (push_urls->nr != 1)
1922 return remote;
1923 check_url = push_urls->v[0];
1924
1925 for (int i = 0; i < remote_state->remotes_nr; i++) {
1926 struct remote *candidate = remote_state->remotes[i];
1927
1928 if (!candidate || candidate == remote ||
1929 !remote_is_configured(candidate, 0) ||
1930 !remote_has_push_url(candidate, check_url))
1931 continue;
1932 if (first_match)
1933 return remote;
1934 first_match = candidate;
1935 }
1936
1937 return first_match ? first_match : remote;
1938 }
1939
1940 static char *tracking_for_push_dest(struct repository *repo,
1941 struct remote *remote,
1942 const char *refname,
1943 struct strbuf *err)
1944 {
1945 char *ret;
1946
1947 remote = repo_remote_for_push_tracking(repo, remote);
1948 ret = apply_refspecs(&remote->fetch, refname);
1949 if (!ret)
1950 return error_buf(err,
1951 _("push destination '%s' on remote '%s' has no local tracking branch"),
1952 refname, remote->name);
1953 return ret;
1954 }
1955
1956 static char *branch_get_push_1(struct repository *repo,
1957 struct branch *branch, struct strbuf *err)
1958 {
1959 struct remote_state *remote_state = repo->remote_state;
1960 struct remote *remote;
1961
1962 remote = remotes_remote_get(
1963 repo,
1964 remotes_pushremote_for_branch(remote_state, branch, NULL));
1965 if (!remote)
1966 return error_buf(err,
1967 _("branch '%s' has no remote for pushing"),
1968 branch->name);
1969
1970 if (remote->push.nr) {
1971 char *dst;
1972 char *ret;
1973
1974 dst = apply_refspecs(&remote->push, branch->refname);
1975 if (!dst)
1976 return error_buf(err,
1977 _("push refspecs for '%s' do not include '%s'"),
1978 remote->name, branch->name);
1979
1980 ret = tracking_for_push_dest(repo, remote, dst, err);
1981 free(dst);
1982 return ret;
1983 }
1984
1985 if (remote->mirror)
1986 return tracking_for_push_dest(repo, remote, branch->refname, err);
1987
1988 switch (repo_config_values(repo)->push_default) {
1989 case PUSH_DEFAULT_NOTHING:
1990 return error_buf(err, _("push has no destination (push.default is 'nothing')"));
1991
1992 case PUSH_DEFAULT_MATCHING:
1993 case PUSH_DEFAULT_CURRENT:
1994 return tracking_for_push_dest(repo, remote, branch->refname, err);
1995
1996 case PUSH_DEFAULT_UPSTREAM:
1997 return xstrdup_or_null(branch_get_upstream(branch, err));
1998
1999 case PUSH_DEFAULT_UNSPECIFIED:
2000 case PUSH_DEFAULT_SIMPLE:
2001 {
2002 const char *up;
2003 char *cur;
2004
2005 up = branch_get_upstream(branch, err);
2006 if (!up)
2007 return NULL;
2008 cur = tracking_for_push_dest(repo, remote, branch->refname, err);
2009 if (!cur)
2010 return NULL;
2011 if (strcmp(cur, up)) {
2012 free(cur);
2013 return error_buf(err,
2014 _("cannot resolve 'simple' push to a single destination"));
2015 }
2016 return cur;
2017 }
2018 }
2019
2020 BUG("unhandled push situation");
2021 }
2022
2023 const char *branch_get_push(struct branch *branch, struct strbuf *err)
2024 {
2025 read_config(the_repository, 0);
2026 die_on_missing_branch(the_repository, branch);
2027
2028 if (!branch)
2029 return error_buf(err, _("HEAD does not point to a branch"));
2030
2031 if (!branch->push_tracking_ref)
2032 branch->push_tracking_ref = branch_get_push_1(
2033 the_repository, branch, err);
2034 return branch->push_tracking_ref;
2035 }
2036
2037 static int ignore_symref_update(const char *refname, struct strbuf *scratch)
2038 {
2039 return !refs_read_symbolic_ref(get_main_ref_store(the_repository), refname, scratch);
2040 }
2041
2042 /*
2043 * Create and return a list of (struct ref) consisting of copies of
2044 * each remote_ref that matches refspec. refspec must be a pattern.
2045 * Fill in the copies' peer_ref to describe the local tracking refs to
2046 * which they map. Omit any references that would map to an existing
2047 * local symbolic ref.
2048 */
2049 static struct ref *get_expanded_map(const struct ref *remote_refs,
2050 const struct refspec_item *refspec)
2051 {
2052 struct strbuf scratch = STRBUF_INIT;
2053 const struct ref *ref;
2054 struct ref *ret = NULL;
2055 struct ref **tail = &ret;
2056
2057 for (ref = remote_refs; ref; ref = ref->next) {
2058 char *expn_name = NULL;
2059
2060 strbuf_reset(&scratch);
2061
2062 if (strchr(ref->name, '^'))
2063 continue; /* a dereference item */
2064 if (match_refname_with_pattern(refspec->src, ref->name,
2065 refspec->dst, &expn_name) &&
2066 !ignore_symref_update(expn_name, &scratch)) {
2067 struct ref *cpy = copy_ref(ref);
2068
2069 if (cpy->peer_ref)
2070 free_one_ref(cpy->peer_ref);
2071 cpy->peer_ref = alloc_ref(expn_name);
2072 if (refspec->force)
2073 cpy->peer_ref->force = 1;
2074 *tail = cpy;
2075 tail = &cpy->next;
2076 }
2077 free(expn_name);
2078 }
2079
2080 strbuf_release(&scratch);
2081 return ret;
2082 }
2083
2084 static const struct ref *find_ref_by_name_abbrev(const struct ref *refs, const char *name)
2085 {
2086 const struct ref *ref;
2087 const struct ref *best_match = NULL;
2088 int best_score = 0;
2089
2090 for (ref = refs; ref; ref = ref->next) {
2091 int score = refname_match(name, ref->name);
2092
2093 if (best_score < score) {
2094 best_match = ref;
2095 best_score = score;
2096 }
2097 }
2098 return best_match;
2099 }
2100
2101 struct ref *get_remote_ref(const struct ref *remote_refs, const char *name)
2102 {
2103 const struct ref *ref = find_ref_by_name_abbrev(remote_refs, name);
2104
2105 if (!ref)
2106 return NULL;
2107
2108 return copy_ref(ref);
2109 }
2110
2111 static struct ref *get_local_ref(const char *name)
2112 {
2113 if (!name || name[0] == '\0')
2114 return NULL;
2115
2116 if (starts_with(name, "refs/"))
2117 return alloc_ref(name);
2118
2119 if (starts_with(name, "heads/") ||
2120 starts_with(name, "tags/") ||
2121 starts_with(name, "remotes/"))
2122 return alloc_ref_with_prefix("refs/", 5, name);
2123
2124 return alloc_ref_with_prefix("refs/heads/", 11, name);
2125 }
2126
2127 int get_fetch_map(const struct ref *remote_refs,
2128 const struct refspec_item *refspec,
2129 struct ref ***tail,
2130 int missing_ok)
2131 {
2132 struct ref *ref_map, **rmp;
2133
2134 if (refspec->negative)
2135 return 0;
2136
2137 if (refspec->pattern) {
2138 ref_map = get_expanded_map(remote_refs, refspec);
2139 } else {
2140 const char *name = refspec->src[0] ? refspec->src : "HEAD";
2141
2142 if (refspec->exact_sha1) {
2143 ref_map = alloc_ref(name);
2144 get_oid_hex(name, &ref_map->old_oid);
2145 ref_map->exact_oid = 1;
2146 } else {
2147 ref_map = get_remote_ref(remote_refs, name);
2148 }
2149 if (!missing_ok && !ref_map)
2150 die(_("couldn't find remote ref %s"), name);
2151 if (ref_map) {
2152 ref_map->peer_ref = get_local_ref(refspec->dst);
2153 if (ref_map->peer_ref && refspec->force)
2154 ref_map->peer_ref->force = 1;
2155 }
2156 }
2157
2158 for (rmp = &ref_map; *rmp; ) {
2159 if ((*rmp)->peer_ref) {
2160 if (!starts_with((*rmp)->peer_ref->name, "refs/") ||
2161 check_refname_format((*rmp)->peer_ref->name, 0)) {
2162 struct ref *ignore = *rmp;
2163 error(_("* Ignoring funny ref '%s' locally"),
2164 (*rmp)->peer_ref->name);
2165 *rmp = (*rmp)->next;
2166 free(ignore->peer_ref);
2167 free(ignore);
2168 continue;
2169 }
2170 }
2171 rmp = &((*rmp)->next);
2172 }
2173
2174 if (ref_map)
2175 tail_link_ref(ref_map, tail);
2176
2177 return 0;
2178 }
2179
2180 int get_remote_group(const char *key, const char *value,
2181 const struct config_context *ctx UNUSED,
2182 void *priv)
2183 {
2184 struct remote_group_data *g = priv;
2185
2186 if (skip_prefix(key, "remotes.", &key) && !strcmp(key, g->name)) {
2187 /* split list by white space */
2188 while (*value) {
2189 size_t wordlen = strcspn(value, " \t\n");
2190
2191 if (wordlen >= 1)
2192 string_list_append_nodup(g->list,
2193 xstrndup(value, wordlen));
2194 value += wordlen + (value[wordlen] != '\0');
2195 }
2196 }
2197
2198 return 0;
2199 }
2200
2201 int add_remote_or_group(const char *name, struct string_list *list)
2202 {
2203 int prev_nr = list->nr;
2204 struct remote_group_data g;
2205 g.name = name; g.list = list;
2206
2207 repo_config(the_repository, get_remote_group, &g);
2208 if (list->nr == prev_nr) {
2209 struct remote *remote = remote_get(name);
2210 if (!remote_is_configured(remote, 0))
2211 return 0;
2212 string_list_append(list, remote->name);
2213 }
2214 return 1;
2215 }
2216
2217 int resolve_remote_symref(struct ref *ref, struct ref *list)
2218 {
2219 if (!ref->symref)
2220 return 0;
2221 for (; list; list = list->next)
2222 if (!strcmp(ref->symref, list->name)) {
2223 oidcpy(&ref->old_oid, &list->old_oid);
2224 return 0;
2225 }
2226 return 1;
2227 }
2228
2229 /*
2230 * Compute the commit ahead/behind values for the pair branch_name, base.
2231 *
2232 * If abf is AHEAD_BEHIND_FULL, compute the full ahead/behind and return the
2233 * counts in *num_ours and *num_theirs. If abf is AHEAD_BEHIND_QUICK, skip
2234 * the (potentially expensive) a/b computation (*num_ours and *num_theirs are
2235 * set to zero).
2236 *
2237 * Returns -1 if num_ours and num_theirs could not be filled in (e.g., ref
2238 * does not exist). Returns 0 if the commits are identical. Returns 1 if
2239 * commits are different.
2240 */
2241
2242 static int stat_branch_pair(const char *branch_name, const char *base,
2243 int *num_ours, int *num_theirs,
2244 enum ahead_behind_flags abf)
2245 {
2246 struct object_id oid;
2247 struct commit *ours, *theirs;
2248 struct rev_info revs;
2249 struct strvec argv = STRVEC_INIT;
2250
2251 /* Cannot stat if what we used to build on no longer exists */
2252 if (refs_read_ref(get_main_ref_store(the_repository), base, &oid))
2253 return -1;
2254 theirs = lookup_commit_reference(the_repository, &oid);
2255 if (!theirs)
2256 return -1;
2257
2258 if (refs_read_ref(get_main_ref_store(the_repository), branch_name, &oid))
2259 return -1;
2260 ours = lookup_commit_reference(the_repository, &oid);
2261 if (!ours)
2262 return -1;
2263
2264 *num_theirs = *num_ours = 0;
2265
2266 /* are we the same? */
2267 if (theirs == ours)
2268 return 0;
2269 if (abf == AHEAD_BEHIND_QUICK)
2270 return 1;
2271 if (abf != AHEAD_BEHIND_FULL)
2272 BUG("stat_branch_pair: invalid abf '%d'", abf);
2273
2274 /* Run "rev-list --left-right ours...theirs" internally... */
2275 strvec_push(&argv, ""); /* ignored */
2276 strvec_push(&argv, "--left-right");
2277 strvec_pushf(&argv, "%s...%s",
2278 oid_to_hex(&ours->object.oid),
2279 oid_to_hex(&theirs->object.oid));
2280 strvec_push(&argv, "--");
2281
2282 repo_init_revisions(the_repository, &revs, NULL);
2283 setup_revisions_from_strvec(&argv, &revs, NULL);
2284 if (prepare_revision_walk(&revs))
2285 die(_("revision walk setup failed"));
2286
2287 /* ... and count the commits on each side. */
2288 while (1) {
2289 struct commit *c = get_revision(&revs);
2290 if (!c)
2291 break;
2292 if (c->object.flags & SYMMETRIC_LEFT)
2293 (*num_ours)++;
2294 else
2295 (*num_theirs)++;
2296 }
2297
2298 /* clear object flags smudged by the above traversal */
2299 clear_commit_marks(ours, ALL_REV_FLAGS);
2300 clear_commit_marks(theirs, ALL_REV_FLAGS);
2301
2302 strvec_clear(&argv);
2303 release_revisions(&revs);
2304 return 1;
2305 }
2306
2307 /*
2308 * Lookup the tracking branch for the given branch and if present, optionally
2309 * compute the commit ahead/behind values for the pair.
2310 *
2311 * If for_push is true, the tracking branch refers to the push branch,
2312 * otherwise it refers to the upstream branch.
2313 *
2314 * The name of the tracking branch (or NULL if it is not defined) is
2315 * returned via *tracking_name, if it is not itself NULL.
2316 *
2317 * If abf is AHEAD_BEHIND_FULL, compute the full ahead/behind and return the
2318 * counts in *num_ours and *num_theirs. If abf is AHEAD_BEHIND_QUICK, skip
2319 * the (potentially expensive) a/b computation (*num_ours and *num_theirs are
2320 * set to zero).
2321 *
2322 * Returns -1 if num_ours and num_theirs could not be filled in (e.g., no
2323 * upstream defined, or ref does not exist). Returns 0 if the commits are
2324 * identical. Returns 1 if commits are different.
2325 */
2326 int stat_tracking_info(struct branch *branch, int *num_ours, int *num_theirs,
2327 const char **tracking_name, int for_push,
2328 enum ahead_behind_flags abf)
2329 {
2330 const char *base;
2331
2332 /* Cannot stat unless we are marked to build on top of somebody else. */
2333 base = for_push ? branch_get_push(branch, NULL) :
2334 branch_get_upstream(branch, NULL);
2335 if (tracking_name)
2336 *tracking_name = base;
2337 if (!base)
2338 return -1;
2339
2340 return stat_branch_pair(branch->refname, base, num_ours, num_theirs, abf);
2341 }
2342
2343 static char *resolve_compare_branch(struct branch *branch, const char *name)
2344 {
2345 const char *resolved = NULL;
2346
2347 if (!branch || !name)
2348 return NULL;
2349
2350 if (!strcasecmp(name, "@{upstream}")) {
2351 resolved = branch_get_upstream(branch, NULL);
2352 } else if (!strcasecmp(name, "@{push}")) {
2353 resolved = branch_get_push(branch, NULL);
2354 } else {
2355 warning(_("ignoring value '%s' for status.compareBranches, "
2356 "only @{upstream} and @{push} are supported"),
2357 name);
2358 return NULL;
2359 }
2360
2361 if (resolved)
2362 return xstrdup(resolved);
2363 return NULL;
2364 }
2365
2366 static void format_branch_comparison(struct strbuf *sb,
2367 bool up_to_date,
2368 int ours, int theirs,
2369 const char *branch_name,
2370 const char *push_remote_name,
2371 const char *push_branch_name,
2372 enum ahead_behind_flags abf,
2373 unsigned flags)
2374 {
2375 bool use_push_advice = (flags & ENABLE_ADVICE_PUSH);
2376 bool use_pull_advice = (flags & ENABLE_ADVICE_PULL);
2377 bool use_divergence_advice = (flags & ENABLE_ADVICE_DIVERGENCE);
2378
2379 if (up_to_date) {
2380 strbuf_addf(sb,
2381 _("Your branch is up to date with '%s'.\n"),
2382 branch_name);
2383 } else if (abf == AHEAD_BEHIND_QUICK) {
2384 strbuf_addf(sb,
2385 _("Your branch and '%s' refer to different commits.\n"),
2386 branch_name);
2387 if (use_push_advice && advice_enabled(ADVICE_STATUS_HINTS))
2388 strbuf_addf(sb, _(" (use \"%s\" for details)\n"),
2389 "git status --ahead-behind");
2390 } else if (!theirs) {
2391 strbuf_addf(sb,
2392 Q_("Your branch is ahead of '%s' by %d commit.\n",
2393 "Your branch is ahead of '%s' by %d commits.\n",
2394 ours),
2395 branch_name, ours);
2396 if (use_push_advice && advice_enabled(ADVICE_STATUS_HINTS))
2397 strbuf_addstr(sb,
2398 _(" (use \"git push\" to publish your local commits)\n"));
2399 } else if (!ours) {
2400 strbuf_addf(sb,
2401 Q_("Your branch is behind '%s' by %d commit, "
2402 "and can be fast-forwarded.\n",
2403 "Your branch is behind '%s' by %d commits, "
2404 "and can be fast-forwarded.\n",
2405 theirs),
2406 branch_name, theirs);
2407 if (use_pull_advice && advice_enabled(ADVICE_STATUS_HINTS)) {
2408 if (push_remote_name && push_branch_name)
2409 strbuf_addf(sb,
2410 _(" (use \"git pull %s %s\" to update your local branch)\n"),
2411 push_remote_name, push_branch_name);
2412 else
2413 strbuf_addstr(sb,
2414 _(" (use \"git pull\" to update your local branch)\n"));
2415 }
2416 } else {
2417 strbuf_addf(sb,
2418 Q_("Your branch and '%s' have diverged,\n"
2419 "and have %d and %d different commit each, "
2420 "respectively.\n",
2421 "Your branch and '%s' have diverged,\n"
2422 "and have %d and %d different commits each, "
2423 "respectively.\n",
2424 ours + theirs),
2425 branch_name, ours, theirs);
2426 if (use_divergence_advice && advice_enabled(ADVICE_STATUS_HINTS)) {
2427 if (push_remote_name && push_branch_name)
2428 strbuf_addf(sb,
2429 _(" (use \"git pull %s %s\" if you want to integrate the remote branch with yours)\n"),
2430 push_remote_name, push_branch_name);
2431 else
2432 strbuf_addstr(sb,
2433 _(" (use \"git pull\" if you want to integrate the remote branch with yours)\n"));
2434 }
2435 }
2436 }
2437
2438 /*
2439 * Return true when there is anything to report, otherwise false.
2440 */
2441 int format_tracking_info(struct branch *branch, struct strbuf *sb,
2442 enum ahead_behind_flags abf,
2443 int show_divergence_advice)
2444 {
2445 char *compare_branches = NULL;
2446 struct string_list branches = STRING_LIST_INIT_DUP;
2447 struct strset processed_refs = STRSET_INIT;
2448 int reported = 0;
2449 size_t i;
2450 const char *upstream_ref;
2451 const char *push_ref;
2452
2453 repo_config_get_string(the_repository, "status.comparebranches",
2454 &compare_branches);
2455
2456 if (compare_branches) {
2457 string_list_split(&branches, compare_branches, " ", -1);
2458 string_list_remove_empty_items(&branches, 0);
2459 } else {
2460 string_list_append(&branches, "@{upstream}");
2461 }
2462
2463 upstream_ref = branch_get_upstream(branch, NULL);
2464 push_ref = branch_get_push(branch, NULL);
2465
2466 for (i = 0; i < branches.nr; i++) {
2467 char *full_ref;
2468 char *short_ref;
2469 int ours, theirs, cmp;
2470 int is_upstream, is_push;
2471 unsigned flags = 0;
2472 const char *push_remote_name = NULL;
2473 const char *push_branch_name = NULL;
2474
2475 full_ref = resolve_compare_branch(branch,
2476 branches.items[i].string);
2477 if (!full_ref)
2478 continue;
2479
2480 if (!strset_add(&processed_refs, full_ref)) {
2481 free(full_ref);
2482 continue;
2483 }
2484
2485 short_ref = refs_shorten_unambiguous_ref(
2486 get_main_ref_store(the_repository), full_ref, 0);
2487
2488 is_upstream = upstream_ref && !strcmp(full_ref, upstream_ref);
2489 is_push = push_ref && !strcmp(full_ref, push_ref);
2490
2491 if (is_upstream && (!push_ref || !strcmp(upstream_ref, push_ref)))
2492 is_push = 1;
2493
2494 cmp = stat_branch_pair(branch->refname, full_ref,
2495 &ours, &theirs, abf);
2496
2497 if (cmp < 0) {
2498 if (is_upstream) {
2499 strbuf_addf(sb,
2500 _("Your branch is based on '%s', but the upstream is gone.\n"),
2501 short_ref);
2502 if (advice_enabled(ADVICE_STATUS_HINTS))
2503 strbuf_addstr(sb,
2504 _(" (use \"git branch --unset-upstream\" to fixup)\n"));
2505 reported = 1;
2506 }
2507 free(full_ref);
2508 free(short_ref);
2509 continue;
2510 }
2511
2512 if (reported)
2513 strbuf_addstr(sb, "\n");
2514
2515 if (is_upstream)
2516 flags |= ENABLE_ADVICE_PULL;
2517 if (show_divergence_advice && is_upstream)
2518 flags |= ENABLE_ADVICE_DIVERGENCE;
2519 if (is_push) {
2520 flags |= ENABLE_ADVICE_PUSH;
2521 if (!upstream_ref || strcmp(upstream_ref, full_ref)) {
2522 push_remote_name = pushremote_for_branch(branch, NULL);
2523 if (push_remote_name &&
2524 skip_prefix(full_ref, "refs/remotes/", &push_branch_name) &&
2525 skip_prefix(push_branch_name, push_remote_name, &push_branch_name) &&
2526 *push_branch_name == '/') {
2527 push_branch_name++;
2528 flags |= ENABLE_ADVICE_PULL;
2529 } else {
2530 push_remote_name = NULL;
2531 }
2532 } else {
2533 flags |= ENABLE_ADVICE_PULL;
2534 }
2535 }
2536 format_branch_comparison(sb, !cmp, ours, theirs, short_ref,
2537 push_remote_name, push_branch_name,
2538 abf, flags);
2539 reported = 1;
2540
2541 free(full_ref);
2542 free(short_ref);
2543 }
2544
2545 string_list_clear(&branches, 0);
2546 strset_clear(&processed_refs);
2547 free(compare_branches);
2548 return reported;
2549 }
2550
2551 static int one_local_ref(const struct reference *ref, void *cb_data)
2552 {
2553 struct ref ***local_tail = cb_data;
2554 struct ref *local_ref;
2555
2556 /* we already know it starts with refs/ to get here */
2557 if (check_refname_format(ref->name + 5, 0))
2558 return 0;
2559
2560 local_ref = alloc_ref(ref->name);
2561 oidcpy(&local_ref->new_oid, ref->oid);
2562 **local_tail = local_ref;
2563 *local_tail = &local_ref->next;
2564 return 0;
2565 }
2566
2567 struct ref *get_local_heads(void)
2568 {
2569 struct ref *local_refs = NULL, **local_tail = &local_refs;
2570
2571 refs_for_each_ref(get_main_ref_store(the_repository), one_local_ref,
2572 &local_tail);
2573 return local_refs;
2574 }
2575
2576 struct ref *guess_remote_head(const struct ref *head,
2577 const struct ref *refs,
2578 unsigned flags)
2579 {
2580 const struct ref *r;
2581 struct ref *list = NULL;
2582 struct ref **tail = &list;
2583
2584 if (!head)
2585 return NULL;
2586
2587 /*
2588 * Some transports support directly peeking at
2589 * where HEAD points; if that is the case, then
2590 * we don't have to guess.
2591 */
2592 if (head->symref)
2593 return copy_ref(find_ref_by_name(refs, head->symref));
2594
2595 /* If a remote branch exists with the default branch name, let's use it. */
2596 if (!(flags & REMOTE_GUESS_HEAD_ALL)) {
2597 char *default_branch =
2598 repo_default_branch_name(the_repository,
2599 flags & REMOTE_GUESS_HEAD_QUIET);
2600 char *ref = xstrfmt("refs/heads/%s", default_branch);
2601
2602 r = find_ref_by_name(refs, ref);
2603 free(ref);
2604 free(default_branch);
2605
2606 if (r && oideq(&r->old_oid, &head->old_oid))
2607 return copy_ref(r);
2608
2609 /* Fall back to the hard-coded historical default */
2610 r = find_ref_by_name(refs, "refs/heads/master");
2611 if (r && oideq(&r->old_oid, &head->old_oid))
2612 return copy_ref(r);
2613 }
2614
2615 /* Look for another ref that points there */
2616 for (r = refs; r; r = r->next) {
2617 if (r != head &&
2618 starts_with(r->name, "refs/heads/") &&
2619 oideq(&r->old_oid, &head->old_oid)) {
2620 *tail = copy_ref(r);
2621 tail = &((*tail)->next);
2622 if (!(flags & REMOTE_GUESS_HEAD_ALL))
2623 break;
2624 }
2625 }
2626
2627 return list;
2628 }
2629
2630 struct stale_heads_info {
2631 struct string_list *ref_names;
2632 struct ref **stale_refs_tail;
2633 struct refspec *rs;
2634 };
2635
2636 static int get_stale_heads_cb(const struct reference *ref, void *cb_data)
2637 {
2638 struct stale_heads_info *info = cb_data;
2639 struct string_list matches = STRING_LIST_INIT_DUP;
2640 struct refspec_item query;
2641 int i, stale = 1;
2642 memset(&query, 0, sizeof(struct refspec_item));
2643 query.dst = (char *)ref->name;
2644
2645 refspec_find_all_matches(info->rs, &query, &matches);
2646 if (matches.nr == 0)
2647 goto clean_exit; /* No matches */
2648
2649 /*
2650 * If we did find a suitable refspec and it's not a symref and
2651 * it's not in the list of refs that currently exist in that
2652 * remote, we consider it to be stale. In order to deal with
2653 * overlapping refspecs, we need to go over all of the
2654 * matching refs.
2655 */
2656 if (ref->flags & REF_ISSYMREF)
2657 goto clean_exit;
2658
2659 for (i = 0; stale && i < matches.nr; i++)
2660 if (string_list_has_string(info->ref_names, matches.items[i].string))
2661 stale = 0;
2662
2663 if (stale) {
2664 struct ref *linked_ref = make_linked_ref(ref->name, &info->stale_refs_tail);
2665 oidcpy(&linked_ref->new_oid, ref->oid);
2666 }
2667
2668 clean_exit:
2669 string_list_clear(&matches, 0);
2670 return 0;
2671 }
2672
2673 struct ref *get_stale_heads(struct refspec *rs, struct ref *fetch_map)
2674 {
2675 struct ref *ref, *stale_refs = NULL;
2676 struct string_list ref_names = STRING_LIST_INIT_NODUP;
2677 struct stale_heads_info info;
2678
2679 info.ref_names = &ref_names;
2680 info.stale_refs_tail = &stale_refs;
2681 info.rs = rs;
2682 for (ref = fetch_map; ref; ref = ref->next)
2683 string_list_append(&ref_names, ref->name);
2684 string_list_sort(&ref_names);
2685 refs_for_each_ref(get_main_ref_store(the_repository),
2686 get_stale_heads_cb, &info);
2687 string_list_clear(&ref_names, 0);
2688 return stale_refs;
2689 }
2690
2691 /*
2692 * Compare-and-swap
2693 */
2694 void clear_cas_option(struct push_cas_option *cas)
2695 {
2696 int i;
2697
2698 for (i = 0; i < cas->nr; i++)
2699 free(cas->entry[i].refname);
2700 free(cas->entry);
2701 memset(cas, 0, sizeof(*cas));
2702 }
2703
2704 static struct push_cas *add_cas_entry(struct push_cas_option *cas,
2705 const char *refname,
2706 size_t refnamelen)
2707 {
2708 struct push_cas *entry;
2709 ALLOC_GROW(cas->entry, cas->nr + 1, cas->alloc);
2710 entry = &cas->entry[cas->nr++];
2711 memset(entry, 0, sizeof(*entry));
2712 entry->refname = xmemdupz(refname, refnamelen);
2713 return entry;
2714 }
2715
2716 static int parse_push_cas_option(struct push_cas_option *cas, const char *arg, int unset)
2717 {
2718 const char *colon;
2719 struct push_cas *entry;
2720
2721 if (unset) {
2722 /* "--no-<option>" */
2723 clear_cas_option(cas);
2724 return 0;
2725 }
2726
2727 if (!arg) {
2728 /* just "--<option>" */
2729 cas->use_tracking_for_rest = 1;
2730 return 0;
2731 }
2732
2733 /* "--<option>=refname" or "--<option>=refname:value" */
2734 colon = strchrnul(arg, ':');
2735 entry = add_cas_entry(cas, arg, colon - arg);
2736 if (!*colon)
2737 entry->use_tracking = 1;
2738 else if (!colon[1])
2739 oidclr(&entry->expect, the_repository->hash_algo);
2740 else if (repo_get_oid(the_repository, colon + 1, &entry->expect))
2741 return error(_("cannot parse expected object name '%s'"),
2742 colon + 1);
2743 return 0;
2744 }
2745
2746 int parseopt_push_cas_option(const struct option *opt, const char *arg, int unset)
2747 {
2748 return parse_push_cas_option(opt->value, arg, unset);
2749 }
2750
2751 int is_empty_cas(const struct push_cas_option *cas)
2752 {
2753 return !cas->use_tracking_for_rest && !cas->nr;
2754 }
2755
2756 /*
2757 * Look at remote.fetch refspec and see if we have a remote
2758 * tracking branch for the refname there. Fill the name of
2759 * the remote-tracking branch in *dst_refname, and the name
2760 * of the commit object at its tip in oid[].
2761 * If we cannot do so, return negative to signal an error.
2762 */
2763 static int remote_tracking(struct remote *remote, const char *refname,
2764 struct object_id *oid, char **dst_refname)
2765 {
2766 char *dst;
2767
2768 if (!remote)
2769 BUG("remote_tracking() called with NULL remote");
2770 dst = apply_refspecs(&remote->fetch, refname);
2771 if (!dst)
2772 return -1; /* no tracking ref for refname at remote */
2773 if (refs_read_ref(get_main_ref_store(the_repository), dst, oid)) {
2774 free(dst);
2775 return -1; /* we know what the tracking ref is but we cannot read it */
2776 }
2777
2778 *dst_refname = dst;
2779 return 0;
2780 }
2781
2782 struct check_and_collect_until_cb_data {
2783 struct commit *remote_commit;
2784 struct commit_stack *local_commits;
2785 timestamp_t remote_reflog_timestamp;
2786 };
2787
2788 /* Get the timestamp of the latest entry. */
2789 static int peek_reflog(const char *refname UNUSED,
2790 struct object_id *o_oid UNUSED,
2791 struct object_id *n_oid UNUSED,
2792 const char *ident UNUSED,
2793 timestamp_t timestamp, int tz UNUSED,
2794 const char *message UNUSED, void *cb_data)
2795 {
2796 timestamp_t *ts = cb_data;
2797 *ts = timestamp;
2798 return 1;
2799 }
2800
2801 static int check_and_collect_until(const char *refname UNUSED,
2802 struct object_id *o_oid UNUSED,
2803 struct object_id *n_oid,
2804 const char *ident UNUSED,
2805 timestamp_t timestamp, int tz UNUSED,
2806 const char *message UNUSED, void *cb_data)
2807 {
2808 struct commit *commit;
2809 struct check_and_collect_until_cb_data *cb = cb_data;
2810
2811 /* An entry was found. */
2812 if (oideq(n_oid, &cb->remote_commit->object.oid))
2813 return 1;
2814
2815 if ((commit = lookup_commit_reference(the_repository, n_oid)))
2816 commit_stack_push(cb->local_commits, commit);
2817
2818 /*
2819 * If the reflog entry timestamp is older than the remote ref's
2820 * latest reflog entry, there is no need to check or collect
2821 * entries older than this one.
2822 */
2823 if (timestamp < cb->remote_reflog_timestamp)
2824 return -1;
2825
2826 return 0;
2827 }
2828
2829 #define MERGE_BASES_BATCH_SIZE 8
2830
2831 /*
2832 * Iterate through the reflog of the local ref to check if there is an entry
2833 * for the given remote-tracking ref; runs until the timestamp of an entry is
2834 * older than latest timestamp of remote-tracking ref's reflog. Any commits
2835 * are that seen along the way are collected into an array to check if the
2836 * remote-tracking ref is reachable from any of them.
2837 */
2838 static int is_reachable_in_reflog(const char *local, const struct ref *remote)
2839 {
2840 timestamp_t date;
2841 struct commit *commit;
2842 struct commit **chunk;
2843 struct check_and_collect_until_cb_data cb;
2844 struct commit_stack arr = COMMIT_STACK_INIT;
2845 size_t size = 0;
2846 int ret = 0;
2847
2848 commit = lookup_commit_reference(the_repository, &remote->old_oid);
2849 if (!commit)
2850 goto cleanup_return;
2851
2852 /*
2853 * Get the timestamp from the latest entry
2854 * of the remote-tracking ref's reflog.
2855 */
2856 refs_for_each_reflog_ent_reverse(get_main_ref_store(the_repository),
2857 remote->tracking_ref, peek_reflog,
2858 &date);
2859
2860 cb.remote_commit = commit;
2861 cb.local_commits = &arr;
2862 cb.remote_reflog_timestamp = date;
2863 ret = refs_for_each_reflog_ent_reverse(get_main_ref_store(the_repository),
2864 local, check_and_collect_until,
2865 &cb);
2866
2867 /* We found an entry in the reflog. */
2868 if (ret > 0)
2869 goto cleanup_return;
2870
2871 /*
2872 * Check if the remote commit is reachable from any
2873 * of the commits in the collected array, in batches.
2874 */
2875 for (chunk = arr.items; chunk < arr.items + arr.nr; chunk += size) {
2876 size = arr.items + arr.nr - chunk;
2877 if (MERGE_BASES_BATCH_SIZE < size)
2878 size = MERGE_BASES_BATCH_SIZE;
2879
2880 if ((ret = repo_in_merge_bases_many(the_repository, commit, size, chunk, 0)))
2881 break;
2882 }
2883
2884 cleanup_return:
2885 commit_stack_clear(&arr);
2886 return ret;
2887 }
2888
2889 /*
2890 * Check for reachability of a remote-tracking
2891 * ref in the reflog entries of its local ref.
2892 */
2893 static void check_if_includes_upstream(struct ref *remote)
2894 {
2895 struct ref *local = get_local_ref(remote->name);
2896 if (!local)
2897 return;
2898
2899 if (is_reachable_in_reflog(local->name, remote) <= 0)
2900 remote->unreachable = 1;
2901 free_one_ref(local);
2902 }
2903
2904 static void apply_cas(struct push_cas_option *cas,
2905 struct remote *remote,
2906 struct ref *ref)
2907 {
2908 int i;
2909
2910 /* Find an explicit --<option>=<name>[:<value>] entry */
2911 for (i = 0; i < cas->nr; i++) {
2912 struct push_cas *entry = &cas->entry[i];
2913 if (!refname_match(entry->refname, ref->name))
2914 continue;
2915 ref->expect_old_sha1 = 1;
2916 if (!entry->use_tracking)
2917 oidcpy(&ref->old_oid_expect, &entry->expect);
2918 else if (remote_tracking(remote, ref->name,
2919 &ref->old_oid_expect,
2920 &ref->tracking_ref))
2921 oidclr(&ref->old_oid_expect, the_repository->hash_algo);
2922 else
2923 ref->check_reachable = cas->use_force_if_includes;
2924 return;
2925 }
2926
2927 /* Are we using "--<option>" to cover all? */
2928 if (!cas->use_tracking_for_rest)
2929 return;
2930
2931 ref->expect_old_sha1 = 1;
2932 if (remote_tracking(remote, ref->name,
2933 &ref->old_oid_expect,
2934 &ref->tracking_ref))
2935 oidclr(&ref->old_oid_expect, the_repository->hash_algo);
2936 else
2937 ref->check_reachable = cas->use_force_if_includes;
2938 }
2939
2940 void apply_push_cas(struct push_cas_option *cas,
2941 struct remote *remote,
2942 struct ref *remote_refs)
2943 {
2944 struct ref *ref;
2945 for (ref = remote_refs; ref; ref = ref->next) {
2946 apply_cas(cas, remote, ref);
2947
2948 /*
2949 * If "compare-and-swap" is in "use_tracking[_for_rest]"
2950 * mode, and if "--force-if-includes" was specified, run
2951 * the check.
2952 */
2953 if (ref->check_reachable)
2954 check_if_includes_upstream(ref);
2955 }
2956 }
2957
2958 struct remote_state *remote_state_new(void)
2959 {
2960 struct remote_state *r;
2961
2962 CALLOC_ARRAY(r, 1);
2963
2964 hashmap_init(&r->remotes_hash, remotes_hash_cmp, NULL, 0);
2965 hashmap_init(&r->branches_hash, branches_hash_cmp, NULL, 0);
2966 return r;
2967 }
2968
2969 void remote_state_clear(struct remote_state *remote_state)
2970 {
2971 struct hashmap_iter iter;
2972 struct branch *b;
2973 int i;
2974
2975 for (i = 0; i < remote_state->remotes_nr; i++)
2976 remote_clear(remote_state->remotes[i]);
2977 FREE_AND_NULL(remote_state->remotes);
2978 FREE_AND_NULL(remote_state->pushremote_name);
2979 remote_state->remotes_alloc = 0;
2980 remote_state->remotes_nr = 0;
2981
2982 rewrites_release(&remote_state->rewrites);
2983 rewrites_release(&remote_state->rewrites_push);
2984
2985 hashmap_clear_and_free(&remote_state->remotes_hash, struct remote, ent);
2986 hashmap_for_each_entry(&remote_state->branches_hash, &iter, b, ent) {
2987 branch_release(b);
2988 free(b);
2989 }
2990 hashmap_clear(&remote_state->branches_hash);
2991 }
2992
2993 /*
2994 * Returns 1 if it was the last chop before ':'.
2995 */
2996 static int chop_last_dir(char **remoteurl, int is_relative)
2997 {
2998 char *rfind = find_last_dir_sep(*remoteurl);
2999 if (rfind) {
3000 *rfind = '\0';
3001 return 0;
3002 }
3003
3004 rfind = strrchr(*remoteurl, ':');
3005 if (rfind) {
3006 *rfind = '\0';
3007 return 1;
3008 }
3009
3010 if (is_relative || !strcmp(".", *remoteurl))
3011 die(_("cannot strip one component off url '%s'"),
3012 *remoteurl);
3013
3014 free(*remoteurl);
3015 *remoteurl = xstrdup(".");
3016 return 0;
3017 }
3018
3019 char *relative_url(const char *remote_url, const char *url,
3020 const char *up_path)
3021 {
3022 int is_relative = 0;
3023 int colonsep = 0;
3024 char *out;
3025 char *remoteurl;
3026 struct strbuf sb = STRBUF_INIT;
3027 size_t len;
3028
3029 if (!url_is_local_not_ssh(url) || is_absolute_path(url))
3030 return xstrdup(url);
3031
3032 len = strlen(remote_url);
3033 if (!len)
3034 BUG("invalid empty remote_url");
3035
3036 remoteurl = xstrdup(remote_url);
3037 if (is_dir_sep(remoteurl[len-1]))
3038 remoteurl[len-1] = '\0';
3039
3040 if (!url_is_local_not_ssh(remoteurl) || is_absolute_path(remoteurl))
3041 is_relative = 0;
3042 else {
3043 is_relative = 1;
3044 /*
3045 * Prepend a './' to ensure all relative
3046 * remoteurls start with './' or '../'
3047 */
3048 if (!starts_with_dot_slash_native(remoteurl) &&
3049 !starts_with_dot_dot_slash_native(remoteurl)) {
3050 strbuf_reset(&sb);
3051 strbuf_addf(&sb, "./%s", remoteurl);
3052 free(remoteurl);
3053 remoteurl = strbuf_detach(&sb, NULL);
3054 }
3055 }
3056 /*
3057 * When the url starts with '../', remove that and the
3058 * last directory in remoteurl.
3059 */
3060 while (*url) {
3061 if (starts_with_dot_dot_slash_native(url)) {
3062 url += 3;
3063 colonsep |= chop_last_dir(&remoteurl, is_relative);
3064 } else if (starts_with_dot_slash_native(url))
3065 url += 2;
3066 else
3067 break;
3068 }
3069 strbuf_reset(&sb);
3070 strbuf_addf(&sb, "%s%s%s", remoteurl, colonsep ? ":" : "/", url);
3071 if (ends_with(url, "/"))
3072 strbuf_setlen(&sb, sb.len - 1);
3073 free(remoteurl);
3074
3075 if (starts_with_dot_slash_native(sb.buf))
3076 out = xstrdup(sb.buf + 2);
3077 else
3078 out = xstrdup(sb.buf);
3079
3080 if (!up_path || !is_relative) {
3081 strbuf_release(&sb);
3082 return out;
3083 }
3084
3085 strbuf_reset(&sb);
3086 strbuf_addf(&sb, "%s%s", up_path, out);
3087 free(out);
3088 return strbuf_detach(&sb, NULL);
3089 }
3090
3091 int valid_remote_name(const char *name)
3092 {
3093 int result;
3094 struct strbuf refspec = STRBUF_INIT;
3095 strbuf_addf(&refspec, "refs/heads/test:refs/remotes/%s/test", name);
3096 result = valid_fetch_refspec(refspec.buf, the_hash_algo);
3097 strbuf_release(&refspec);
3098 return result;
3099 }