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