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