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