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