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