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