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