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