1use std::borrow::Borrow;
2use std::collections::{HashMap, HashSet};
3use std::fmt;
4use std::hash::Hash;
5use std::iter::FromIterator;
6
7use url::Url;
8
9use crate::core::{Dependency, PackageId, PackageIdSpec, Summary, Target};
10use crate::util::errors::CargoResult;
11use crate::util::Graph;
12
13use super::encode::Metadata;
14
15#[derive(PartialEq)]
21pub struct Resolve {
22 graph: Graph<PackageId, Vec<Dependency>>,
26 replacements: HashMap<PackageId, PackageId>,
27 reverse_replacements: HashMap<PackageId, PackageId>,
28 empty_features: HashSet<String>,
29 features: HashMap<PackageId, HashSet<String>>,
30 checksums: HashMap<PackageId, Option<String>>,
31 metadata: Metadata,
32 unused_patches: Vec<PackageId>,
33}
34
35impl Resolve {
36 pub fn new(
37 graph: Graph<PackageId, Vec<Dependency>>,
38 replacements: HashMap<PackageId, PackageId>,
39 features: HashMap<PackageId, HashSet<String>>,
40 checksums: HashMap<PackageId, Option<String>>,
41 metadata: Metadata,
42 unused_patches: Vec<PackageId>,
43 ) -> Resolve {
44 let reverse_replacements = replacements.iter().map(|(&p, &r)| (r, p)).collect();
45 Resolve {
46 graph,
47 replacements,
48 features,
49 checksums,
50 metadata,
51 unused_patches,
52 empty_features: HashSet::new(),
53 reverse_replacements,
54 }
55 }
56
57 pub fn path_to_top<'a>(&'a self, pkg: &'a PackageId) -> Vec<&'a PackageId> {
60 self.graph.path_to_top(pkg)
61 }
62
63 pub fn register_used_patches(&mut self, patches: &HashMap<Url, Vec<Summary>>) {
64 for summary in patches.values().flat_map(|v| v) {
65 if self.iter().any(|id| id == summary.package_id()) {
66 continue;
67 }
68 self.unused_patches.push(summary.package_id());
69 }
70 }
71
72 pub fn merge_from(&mut self, previous: &Resolve) -> CargoResult<()> {
73 for (id, cksum) in previous.checksums.iter() {
86 if let Some(mine) = self.checksums.get(id) {
87 if mine == cksum {
88 continue;
89 }
90
91 if cksum.is_none() {
97 failure::bail!(
98 "\
99checksum for `{}` was not previously calculated, but a checksum could now \
100be calculated
101
102this could be indicative of a few possible situations:
103
104 * the source `{}` did not previously support checksums,
105 but was replaced with one that does
106 * newer Cargo implementations know how to checksum this source, but this
107 older implementation does not
108 * the lock file is corrupt
109",
110 id,
111 id.source_id()
112 )
113
114 } else if mine.is_none() {
119 failure::bail!(
120 "\
121checksum for `{}` could not be calculated, but a checksum is listed in \
122the existing lock file
123
124this could be indicative of a few possible situations:
125
126 * the source `{}` supports checksums,
127 but was replaced with one that doesn't
128 * the lock file is corrupt
129
130unable to verify that `{0}` is the same as when the lockfile was generated
131",
132 id,
133 id.source_id()
134 )
135
136 } else {
140 failure::bail!(
141 "\
142checksum for `{}` changed between lock files
143
144this could be indicative of a few possible errors:
145
146 * the lock file is corrupt
147 * a replacement source in use (e.g. a mirror) returned a different checksum
148 * the source itself may be corrupt in one way or another
149
150unable to verify that `{0}` is the same as when the lockfile was generated
151",
152 id
153 );
154 }
155 }
156 }
157
158 self.metadata = previous.metadata.clone();
160 Ok(())
161 }
162
163 pub fn contains<Q: ?Sized>(&self, k: &Q) -> bool
164 where
165 PackageId: Borrow<Q>,
166 Q: Hash + Eq,
167 {
168 self.graph.contains(k)
169 }
170
171 pub fn sort(&self) -> Vec<PackageId> {
172 self.graph.sort()
173 }
174
175 pub fn iter<'a>(&'a self) -> impl Iterator<Item = PackageId> + 'a {
176 self.graph.iter().cloned()
177 }
178
179 pub fn deps(&self, pkg: PackageId) -> impl Iterator<Item = (PackageId, &[Dependency])> {
180 self.graph
181 .edges(&pkg)
182 .map(move |(&id, deps)| (self.replacement(id).unwrap_or(id), deps.as_slice()))
183 }
184
185 pub fn deps_not_replaced<'a>(&'a self, pkg: PackageId) -> impl Iterator<Item = PackageId> + 'a {
186 self.graph.edges(&pkg).map(|(&id, _)| id)
187 }
188
189 pub fn replacement(&self, pkg: PackageId) -> Option<PackageId> {
190 self.replacements.get(&pkg).cloned()
191 }
192
193 pub fn replacements(&self) -> &HashMap<PackageId, PackageId> {
194 &self.replacements
195 }
196
197 pub fn features(&self, pkg: PackageId) -> &HashSet<String> {
198 self.features.get(&pkg).unwrap_or(&self.empty_features)
199 }
200
201 pub fn features_sorted(&self, pkg: PackageId) -> Vec<&str> {
202 let mut v = Vec::from_iter(self.features(pkg).iter().map(|s| s.as_ref()));
203 v.sort_unstable();
204 v
205 }
206
207 pub fn query(&self, spec: &str) -> CargoResult<PackageId> {
208 PackageIdSpec::query_str(spec, self.iter())
209 }
210
211 pub fn unused_patches(&self) -> &[PackageId] {
212 &self.unused_patches
213 }
214
215 pub fn checksums(&self) -> &HashMap<PackageId, Option<String>> {
216 &self.checksums
217 }
218
219 pub fn metadata(&self) -> &Metadata {
220 &self.metadata
221 }
222
223 pub fn extern_crate_name(
224 &self,
225 from: PackageId,
226 to: PackageId,
227 to_target: &Target,
228 ) -> CargoResult<String> {
229 let deps = if from == to {
230 &[]
231 } else {
232 self.dependencies_listed(from, to)
233 };
234
235 let crate_name = to_target.crate_name();
236 let mut names = deps.iter().map(|d| {
237 d.explicit_name_in_toml()
238 .map(|s| s.as_str().replace("-", "_"))
239 .unwrap_or_else(|| crate_name.clone())
240 });
241 let name = names.next().unwrap_or_else(|| crate_name.clone());
242 for n in names {
243 if n == name {
244 continue;
245 }
246 failure::bail!(
247 "multiple dependencies listed for the same crate must \
248 all have the same name, but the dependency on `{}` \
249 is listed as having different names",
250 to
251 );
252 }
253 Ok(name)
254 }
255
256 fn dependencies_listed(&self, from: PackageId, to: PackageId) -> &[Dependency] {
257 if let Some(replace) = self.reverse_replacements.get(&to) {
267 if let Some(deps) = self.graph.edge(&from, replace) {
268 return deps;
269 }
270 }
271 match self.graph.edge(&from, &to) {
272 Some(ret) => ret,
273 None => panic!("no Dependency listed for `{}` => `{}`", from, to),
274 }
275 }
276}
277
278impl fmt::Debug for Resolve {
279 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
280 writeln!(fmt, "graph: {:?}", self.graph)?;
281 writeln!(fmt, "\nfeatures: {{")?;
282 for (pkg, features) in &self.features {
283 writeln!(fmt, " {}: {:?}", pkg, features)?;
284 }
285 write!(fmt, "}}")
286 }
287}