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