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