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