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