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