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