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