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