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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
use std::collections::HashMap;
use std::fs;
use std::io::{self, BufRead, BufReader};
use std::iter;
use std::path::{Path, PathBuf};
#[macro_use]
extern crate error_chain;
extern crate git2;
extern crate glob;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
extern crate serde;
extern crate home;
error_chain! {
foreign_links {
Git(git2::Error);
}
}
static INDEX_GIT_URL: &str = "https://github.com/rust-lang/crates.io-index";
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Version {
name: String,
vers: String,
deps: Vec<Dependency>,
cksum: String,
features: HashMap<String, Vec<String>>,
yanked: bool,
}
impl Version {
pub fn name(&self) -> &str {
&self.name
}
pub fn version(&self) -> &str {
&self.vers
}
pub fn dependencies(&self) -> &[Dependency] {
&self.deps
}
pub fn checksum(&self) -> &str {
&self.cksum
}
pub fn features(&self) -> &HashMap<String, Vec<String>> {
&self.features
}
pub fn is_yanked(&self) -> bool {
self.yanked
}
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Dependency {
name: String,
req: String,
features: Vec<String>,
optional: bool,
default_features: bool,
target: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
kind: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
package: Option<String>,
}
impl Dependency {
pub fn name(&self) -> &str {
&self.name
}
pub fn requirement(&self) -> &str {
&self.req
}
pub fn features(&self) -> &[String] {
&self.features
}
pub fn is_optional(&self) -> bool {
self.optional
}
pub fn has_default_features(&self) -> bool {
self.default_features
}
pub fn target(&self) -> Option<&str> {
self.target.as_deref()
}
pub fn kind(&self) -> Option<&str> {
self.kind.as_deref()
}
pub fn package(&self) -> Option<&str> {
self.package.as_deref()
}
pub fn crate_name(&self) -> &str {
match self.package {
Some(ref s) => s,
None => self.name(),
}
}
}
pub struct Crates(CrateIndexPaths);
impl Iterator for Crates {
type Item = Crate;
fn next(&mut self) -> Option<Self::Item> {
while let Some(p) = self.0.next() {
if let Ok(c) = Crate::new_checked(&p) {
return Some(c)
}
}
None
}
}
pub struct CrateIndexPaths(iter::Chain<glob::Paths, glob::Paths>);
impl CrateIndexPaths {
fn new<P: AsRef<Path>>(path: P) -> CrateIndexPaths {
let mut match_options = glob::MatchOptions::new();
match_options.require_literal_leading_dot = true;
let path = path.as_ref();
let glob_pattern = format!("{}/*/*/*", path.to_str().unwrap());
let index_paths1 = glob::glob_with(&glob_pattern, match_options).unwrap();
let glob_pattern = format!("{}/[12]/*", path.to_str().unwrap());
let index_paths2 = glob::glob_with(&glob_pattern, match_options).unwrap();
CrateIndexPaths(index_paths1.chain(index_paths2))
}
}
impl Iterator for CrateIndexPaths {
type Item = PathBuf;
fn next(&mut self) -> Option<Self::Item> {
self.0.next().map(|glob_result| glob_result.unwrap())
}
}
fn fetch_opts<'cb>() -> git2::FetchOptions<'cb> {
let mut proxy_opts = git2::ProxyOptions::new();
proxy_opts.auto();
let mut fetch_opts = git2::FetchOptions::new();
fetch_opts.proxy_options(proxy_opts);
fetch_opts
}
#[derive(Debug, Clone, PartialEq)]
pub struct Index {
path: PathBuf,
}
impl Index {
pub fn new<P: Into<PathBuf>>(path: P) -> Index {
Index { path: path.into() }
}
pub fn new_cargo_default() -> Index {
let cargo_home = home::cargo_home().unwrap_or_default();
Self::new(cargo_home.join("registry").join("index").join("github.com-1ecc6299db9ec823"))
}
pub fn exists(&self) -> bool {
git2::Repository::discover(&self.path)
.map(|repository| {
repository
.find_remote("origin").ok()
.map_or(true, |remote| remote.url().map_or(true, |url| url == INDEX_GIT_URL))
})
.unwrap_or(false)
}
pub fn retrieve(&self) -> Result<()> {
git2::build::RepoBuilder::new()
.fetch_options(fetch_opts())
.clone(INDEX_GIT_URL, &self.path)?;
Ok(())
}
pub fn update(&self) -> Result<()> {
debug_assert!(self.exists());
let repo = git2::Repository::discover(&self.path)?;
let mut origin_remote = repo.find_remote("origin")
.or_else(|_| repo.remote_anonymous(INDEX_GIT_URL))?;
origin_remote.fetch(&["master"], Some(&mut fetch_opts()), None)?;
let oid = repo.refname_to_id("FETCH_HEAD")?;
let object = repo.find_object(oid, None).unwrap();
repo.reset(&object, git2::ResetType::Hard, None)?;
Ok(())
}
pub fn retrieve_or_update(&self) -> Result<()> {
if self.exists() {
self.update()
} else {
self.retrieve()
}
}
pub fn crate_(&self, crate_name: &str) -> Option<Crate> {
let name_lower = crate_name.to_ascii_lowercase();
if !name_lower.is_ascii() {
return None;
}
let path = match name_lower.len() {
0 => return None,
1 => self.path.join("1"),
2 => self.path.join("2"),
3 => self.path.join("3").join(&name_lower[0..1]),
_ => self.path.join(&name_lower[0..2]).join(&name_lower[2..4]),
}.join(name_lower);
if path.exists() {
Crate::new_checked(path.as_path()).ok()
} else {
None
}
}
pub fn crates(&self) -> Crates {
Crates(self.crate_index_paths())
}
pub fn crate_index_paths(&self) -> CrateIndexPaths {
CrateIndexPaths::new(self.path.clone())
}
pub fn path(&self) -> &Path {
&self.path
}
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Crate {
versions: Vec<Version>,
}
impl Crate {
#[doc(hidden)]
#[deprecated(note = "this may panic. use new_checked() instead")]
pub fn new<P: AsRef<Path>>(index_path: P) -> Crate {
Self::new_checked(index_path).unwrap()
}
pub fn new_checked<P: AsRef<Path>>(index_path: P) -> io::Result<Crate> {
let index_path = index_path.as_ref();
let mut versions = vec![];
let file = fs::File::open(&index_path)?;
for line in BufReader::new(file).lines() {
let version: Version = serde_json::from_str(&line?).map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
versions.push(version);
}
if versions.is_empty() {
return Err(io::Error::new(io::ErrorKind::Other, "crate must have versions"));
}
Ok(Crate { versions })
}
pub fn versions(&self) -> &[Version] {
&self.versions
}
pub fn earliest_version(&self) -> &Version {
&self.versions[0]
}
pub fn latest_version(&self) -> &Version {
&self.versions[self.versions.len() - 1]
}
pub fn name(&self) -> &str {
self.latest_version().name()
}
}
#[cfg(test)]
mod test {
use super::Index;
extern crate tempdir;
use self::tempdir::TempDir;
#[test]
fn test_dependencies() {
let tmp_dir = TempDir::new("test1").unwrap();
let index = Index::new(tmp_dir.path());
index.retrieve_or_update().expect("could not fetch crates io index");
let crate_ = index.crate_("sval").expect("Could not find the crate libnotify in the index");
let _ = format!("supports debug {:?}", crate_);
let version = crate_.versions().iter().find(|v| v.version() == "0.0.1")
.expect("Version 0.0.1 of sval does not exist?");
let dep_with_package_name = version.dependencies().iter().find(|d| d.name() == "serde_lib")
.expect("sval does not have expected dependency?");
assert_ne!(dep_with_package_name.name(), dep_with_package_name.package().unwrap());
assert_eq!(dep_with_package_name.crate_name(), dep_with_package_name.package().unwrap());
}
#[test]
fn test_retrieve_or_update() {
let tmp_dir = TempDir::new("test2").unwrap();
let index = Index::new(tmp_dir.path());
index.retrieve_or_update().expect("could not fetch crates io index");
assert!(index.exists());
index.retrieve_or_update().expect("could not fetch crates io index");
assert!(index.exists());
}
#[test]
fn test_cargo_default_updates() {
let index = Index::new_cargo_default();
index.update().map_err(|e| format!("could not fetch cargo's index in {}: {}", index.path().display(), e)).unwrap();
assert!(index.crate_("crates-index").is_some());
assert!(index.crate_("toml").is_some());
assert!(index.crate_("gcc").is_some());
assert!(index.crate_("cc").is_some());
assert!(index.crate_("CC").is_some());
assert!(index.crate_("無").is_none());
}
#[test]
fn test_exists() {
let tmp_dir = TempDir::new("test3").unwrap();
let index = Index::new(tmp_dir.path());
assert!(!index.exists());
index.retrieve().unwrap();
assert!(index.exists());
}
}