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