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