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