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