-
Notifications
You must be signed in to change notification settings - Fork 92
/
Copy pathlock.rs
247 lines (223 loc) · 7.59 KB
/
lock.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
//! Code for extracting hashes and more from Cargo.lock
use anyhow::{format_err, Error};
use cargo_metadata::PackageId;
use serde::{de, ser, Deserialize, Serialize};
use std::collections::{BTreeMap, HashMap};
use std::fmt;
use std::path::Path;
use std::str::FromStr;
impl EncodableResolve {
pub fn load_lock_file(path: &Path) -> Result<EncodableResolve, Error> {
let config = &std::fs::read_to_string(path)
.map_err(|e| format_err!("while reading lock file {}: {}", path.display(), e))?;
Self::load_lock_string(path, config)
}
pub fn load_lock_string(path: &Path, config: &str) -> Result<EncodableResolve, Error> {
let resolve: toml::Value = toml::from_str(config)
.map_err(|e| format_err!("while parsing toml from {}: {}", path.display(), e))?;
let v: EncodableResolve = resolve
.try_into()
.map_err(|e| format_err!("unexpected format in {}: {}", path.display(), e))?;
Ok(v)
}
pub fn get_hashes_by_package_id(
&self,
hashes: &mut HashMap<PackageId, String>,
) -> Result<(), Error> {
for EncodableDependency {
name,
version,
source,
checksum,
..
} in self.package.iter()
{
if let (Some(source), Some(checksum)) = (source, checksum) {
let package_id = PackageId {
repr: format!("{} {} ({})", name, version, source),
};
if checksum != "<none>" {
hashes.insert(package_id, checksum.clone());
}
}
}
// Retrieve legacy checksums.
const CHECKSUM_PREFIX: &str = "checksum ";
if let Some(metadata) = &self.metadata {
for (key, value) in metadata {
if key.starts_with(CHECKSUM_PREFIX) {
let package_id = PackageId {
repr: key.trim_start_matches(CHECKSUM_PREFIX).to_string(),
};
if value != "<none>" {
hashes.insert(package_id, value.clone());
}
}
}
}
Ok(())
}
}
#[test]
fn test_no_legacy_checksums() {
let config = r#"
[[package]]
name = "aho-corasick"
version = "0.7.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"memchr 2.3.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
"#;
let resolve = EncodableResolve::load_lock_string(Path::new("dummy"), config).unwrap();
let mut hashes = HashMap::new();
resolve.get_hashes_by_package_id(&mut hashes).unwrap();
assert_eq!(hashes, HashMap::new());
}
#[test]
fn test_some_legacy_checksums() {
let config = r#"
[[package]]
name = "aho-corasick"
version = "0.7.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"memchr 2.3.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
[metadata]
"checksum structopt 0.2.18 (registry+https://github.com/rust-lang/crates.io-index)" = "16c2cdbf9cc375f15d1b4141bc48aeef444806655cd0e904207edc8d68d86ed7"
"checksum structopt-derive 0.2.18 (registry+https://github.com/rust-lang/crates.io-index)" = "53010261a84b37689f9ed7d395165029f9cc7abb9f56bbfe86bee2597ed25107"
"#;
let resolve = EncodableResolve::load_lock_string(Path::new("dummy"), config).unwrap();
let mut hashes = HashMap::new();
resolve.get_hashes_by_package_id(&mut hashes).unwrap();
assert_eq!(
hashes,
[(
PackageId { repr: "structopt 0.2.18 (registry+https://github.com/rust-lang/crates.io-index)".to_string() },
"16c2cdbf9cc375f15d1b4141bc48aeef444806655cd0e904207edc8d68d86ed7"
),
(
PackageId { repr: "structopt-derive 0.2.18 (registry+https://github.com/rust-lang/crates.io-index)".to_string()},
"53010261a84b37689f9ed7d395165029f9cc7abb9f56bbfe86bee2597ed25107"
)]
.iter()
.map(|(package_id, hash)| (package_id.clone(), hash.to_string()))
.collect::<HashMap<_, _>>()
);
}
#[test]
fn test_some_inline_checksums() {
let config = r#"
[[package]]
name = "aho-corasick"
version = "0.7.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"memchr 2.3.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
checksum = "16c2cdbf9cc375f15d1b4141bc48aeef444806655cd0e904207edc8d68d86ed7"
"#;
let resolve = EncodableResolve::load_lock_string(Path::new("dummy"), config).unwrap();
let mut hashes = HashMap::new();
resolve.get_hashes_by_package_id(&mut hashes).unwrap();
assert_eq!(
hashes,
[(
PackageId {
repr: "aho-corasick 0.7.6 (registry+https://github.com/rust-lang/crates.io-index)"
.to_string()
},
"16c2cdbf9cc375f15d1b4141bc48aeef444806655cd0e904207edc8d68d86ed7"
)]
.iter()
.map(|(package_id, hash)| (package_id.clone(), hash.to_string()))
.collect::<HashMap<_, _>>()
);
}
//
// The code below was copied/adjusted from Cargo.
//
/// The `Cargo.lock` structure.
#[derive(Serialize, Deserialize, Debug)]
pub struct EncodableResolve {
package: Vec<EncodableDependency>,
/// `root` is optional to allow backward compatibility.
root: Option<EncodableDependency>,
metadata: Option<Metadata>,
}
#[derive(Serialize, Deserialize, Debug, Default)]
struct Patch {
unused: Vec<EncodableDependency>,
}
pub type Metadata = BTreeMap<String, String>;
#[derive(Serialize, Deserialize, Debug, PartialOrd, Ord, PartialEq, Eq)]
pub struct EncodableDependency {
name: String,
version: String,
source: Option<String>,
checksum: Option<String>,
dependencies: Option<Vec<EncodablePackageId>>,
replace: Option<EncodablePackageId>,
}
#[derive(Debug, PartialOrd, Ord, PartialEq, Eq, Hash, Clone)]
pub struct EncodablePackageId {
name: String,
version: Option<String>,
source: Option<String>,
}
impl fmt::Display for EncodablePackageId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.name)?;
if let Some(s) = &self.version {
write!(f, " {}", s)?;
}
if let Some(s) = &self.source {
write!(f, " ({})", s)?;
}
Ok(())
}
}
impl FromStr for EncodablePackageId {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<EncodablePackageId, Error> {
let mut s = s.splitn(3, ' ');
let name = s.next().unwrap();
let version = s.next();
let source_id = match s.next() {
Some(s) => {
if s.starts_with('(') && s.ends_with(')') {
Some(String::from(&s[1..s.len() - 1]))
} else {
anyhow::bail!("invalid serialized PackageId")
}
}
None => None,
};
Ok(EncodablePackageId {
name: name.to_string(),
version: version.map(|v| v.to_string()),
source: source_id,
})
}
}
impl ser::Serialize for EncodablePackageId {
fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
where
S: ser::Serializer,
{
s.collect_str(self)
}
}
impl<'de> de::Deserialize<'de> for EncodablePackageId {
fn deserialize<D>(d: D) -> Result<EncodablePackageId, D::Error>
where
D: de::Deserializer<'de>,
{
String::deserialize(d).and_then(|string| {
string
.parse::<EncodablePackageId>()
.map_err(de::Error::custom)
})
}
}