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