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