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