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