1use std::collections::HashMap;
8use std::path::{Path, PathBuf};
9
10use log::debug;
11use url::Url;
12
13use crate::core::{GitReference, Source, SourceId};
14use crate::sources::{ReplacedSource, CRATES_IO_REGISTRY};
15use crate::util::config::ConfigValue;
16use crate::util::errors::{CargoResult, CargoResultExt};
17use crate::util::{Config, ToUrl};
18
19#[derive(Clone)]
20pub struct SourceConfigMap<'cfg> {
21 cfgs: HashMap<String, SourceConfig>,
22 id2name: HashMap<SourceId, String>,
23 config: &'cfg Config,
24}
25
26#[derive(Clone)]
34struct SourceConfig {
35 id: SourceId,
38
39 replace_with: Option<(String, PathBuf)>,
43}
44
45impl<'cfg> SourceConfigMap<'cfg> {
46 pub fn new(config: &'cfg Config) -> CargoResult<SourceConfigMap<'cfg>> {
47 let mut base = SourceConfigMap::empty(config)?;
48 if let Some(table) = config.get_table("source")? {
49 for (key, value) in table.val.iter() {
50 base.add_config(key, value)?;
51 }
52 }
53 Ok(base)
54 }
55
56 pub fn empty(config: &'cfg Config) -> CargoResult<SourceConfigMap<'cfg>> {
57 let mut base = SourceConfigMap {
58 cfgs: HashMap::new(),
59 id2name: HashMap::new(),
60 config,
61 };
62 base.add(
63 CRATES_IO_REGISTRY,
64 SourceConfig {
65 id: SourceId::crates_io(config)?,
66 replace_with: None,
67 },
68 );
69 Ok(base)
70 }
71
72 pub fn config(&self) -> &'cfg Config {
73 self.config
74 }
75
76 pub fn load(&self, id: SourceId) -> CargoResult<Box<dyn Source + 'cfg>> {
77 debug!("loading: {}", id);
78 let mut name = match self.id2name.get(&id) {
79 Some(name) => name,
80 None => return Ok(id.load(self.config)?),
81 };
82 let mut path = Path::new("/");
83 let orig_name = name;
84 let new_id;
85 loop {
86 let cfg = match self.cfgs.get(name) {
87 Some(cfg) => cfg,
88 None => failure::bail!(
89 "could not find a configured source with the \
90 name `{}` when attempting to lookup `{}` \
91 (configuration in `{}`)",
92 name,
93 orig_name,
94 path.display()
95 ),
96 };
97 match cfg.replace_with {
98 Some((ref s, ref p)) => {
99 name = s;
100 path = p;
101 }
102 None if id == cfg.id => return Ok(id.load(self.config)?),
103 None => {
104 new_id = cfg.id.with_precise(id.precise().map(|s| s.to_string()));
105 break;
106 }
107 }
108 debug!("following pointer to {}", name);
109 if name == orig_name {
110 failure::bail!(
111 "detected a cycle of `replace-with` sources, the source \
112 `{}` is eventually replaced with itself \
113 (configuration in `{}`)",
114 name,
115 path.display()
116 )
117 }
118 }
119 let new_src = new_id.load(self.config)?;
120 let old_src = id.load(self.config)?;
121 if !new_src.supports_checksums() && old_src.supports_checksums() {
122 failure::bail!(
123 "\
124cannot replace `{orig}` with `{name}`, the source `{orig}` supports \
125checksums, but `{name}` does not
126
127a lock file compatible with `{orig}` cannot be generated in this situation
128",
129 orig = orig_name,
130 name = name
131 );
132 }
133
134 if old_src.requires_precise() && id.precise().is_none() {
135 failure::bail!(
136 "\
137the source {orig} requires a lock file to be present first before it can be
138used against vendored source code
139
140remove the source replacement configuration, generate a lock file, and then
141restore the source replacement configuration to continue the build
142",
143 orig = orig_name
144 );
145 }
146
147 Ok(Box::new(ReplacedSource::new(id, new_id, new_src)))
148 }
149
150 fn add(&mut self, name: &str, cfg: SourceConfig) {
151 self.id2name.insert(cfg.id, name.to_string());
152 self.cfgs.insert(name.to_string(), cfg);
153 }
154
155 fn add_config(&mut self, name: &str, cfg: &ConfigValue) -> CargoResult<()> {
156 let (table, _path) = cfg.table(&format!("source.{}", name))?;
157 let mut srcs = Vec::new();
158 if let Some(val) = table.get("registry") {
159 let url = url(val, &format!("source.{}.registry", name))?;
160 srcs.push(SourceId::for_registry(&url)?);
161 }
162 if let Some(val) = table.get("local-registry") {
163 let (s, path) = val.string(&format!("source.{}.local-registry", name))?;
164 let mut path = path.to_path_buf();
165 path.pop();
166 path.pop();
167 path.push(s);
168 srcs.push(SourceId::for_local_registry(&path)?);
169 }
170 if let Some(val) = table.get("directory") {
171 let (s, path) = val.string(&format!("source.{}.directory", name))?;
172 let mut path = path.to_path_buf();
173 path.pop();
174 path.pop();
175 path.push(s);
176 srcs.push(SourceId::for_directory(&path)?);
177 }
178 if let Some(val) = table.get("git") {
179 let url = url(val, &format!("source.{}.git", name))?;
180 let r#try = |s: &str| {
181 let val = match table.get(s) {
182 Some(s) => s,
183 None => return Ok(None),
184 };
185 let key = format!("source.{}.{}", name, s);
186 val.string(&key).map(Some)
187 };
188 let reference = match r#try("branch")? {
189 Some(b) => GitReference::Branch(b.0.to_string()),
190 None => match r#try("tag")? {
191 Some(b) => GitReference::Tag(b.0.to_string()),
192 None => match r#try("rev")? {
193 Some(b) => GitReference::Rev(b.0.to_string()),
194 None => GitReference::Branch("master".to_string()),
195 },
196 },
197 };
198 srcs.push(SourceId::for_git(&url, reference)?);
199 }
200 if name == "crates-io" && srcs.is_empty() {
201 srcs.push(SourceId::crates_io(self.config)?);
202 }
203
204 let mut srcs = srcs.into_iter();
205 let src = srcs.next().ok_or_else(|| {
206 failure::format_err!(
207 "no source URL specified for `source.{}`, need \
208 either `registry` or `local-registry` defined",
209 name
210 )
211 })?;
212 if srcs.next().is_some() {
213 failure::bail!("more than one source URL specified for `source.{}`", name)
214 }
215
216 let mut replace_with = None;
217 if let Some(val) = table.get("replace-with") {
218 let (s, path) = val.string(&format!("source.{}.replace-with", name))?;
219 replace_with = Some((s.to_string(), path.to_path_buf()));
220 }
221
222 self.add(
223 name,
224 SourceConfig {
225 id: src,
226 replace_with,
227 },
228 );
229
230 return Ok(());
231
232 fn url(cfg: &ConfigValue, key: &str) -> CargoResult<Url> {
233 let (url, path) = cfg.string(key)?;
234 let url = url.to_url().chain_err(|| {
235 format!(
236 "configuration key `{}` specified an invalid \
237 URL (in {})",
238 key,
239 path.display()
240 )
241 })?;
242 Ok(url)
243 }
244 }
245}