Skip to main content

cargo/sources/
directory.rs

1use std::collections::HashMap;
2use std::fmt::{self, Debug, Formatter};
3use std::fs::File;
4use std::io::Read;
5use std::path::{Path, PathBuf};
6
7use serde::Deserialize;
8
9use crate::core::source::MaybePackage;
10use crate::core::{Dependency, Package, PackageId, Source, SourceId, Summary};
11use crate::sources::PathSource;
12use crate::util::errors::{CargoResult, CargoResultExt};
13use crate::util::paths;
14use crate::util::{Config, Sha256};
15
16pub struct DirectorySource<'cfg> {
17    source_id: SourceId,
18    root: PathBuf,
19    packages: HashMap<PackageId, (Package, Checksum)>,
20    config: &'cfg Config,
21}
22
23#[derive(Deserialize)]
24struct Checksum {
25    package: Option<String>,
26    files: HashMap<String, String>,
27}
28
29impl<'cfg> DirectorySource<'cfg> {
30    pub fn new(path: &Path, id: SourceId, config: &'cfg Config) -> DirectorySource<'cfg> {
31        DirectorySource {
32            source_id: id,
33            root: path.to_path_buf(),
34            config,
35            packages: HashMap::new(),
36        }
37    }
38}
39
40impl<'cfg> Debug for DirectorySource<'cfg> {
41    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
42        write!(f, "DirectorySource {{ root: {:?} }}", self.root)
43    }
44}
45
46impl<'cfg> Source for DirectorySource<'cfg> {
47    fn query(&mut self, dep: &Dependency, f: &mut dyn FnMut(Summary)) -> CargoResult<()> {
48        let packages = self.packages.values().map(|p| &p.0);
49        let matches = packages.filter(|pkg| dep.matches(pkg.summary()));
50        for summary in matches.map(|pkg| pkg.summary().clone()) {
51            f(summary);
52        }
53        Ok(())
54    }
55
56    fn fuzzy_query(&mut self, _dep: &Dependency, f: &mut dyn FnMut(Summary)) -> CargoResult<()> {
57        let packages = self.packages.values().map(|p| &p.0);
58        for summary in packages.map(|pkg| pkg.summary().clone()) {
59            f(summary);
60        }
61        Ok(())
62    }
63
64    fn supports_checksums(&self) -> bool {
65        true
66    }
67
68    fn requires_precise(&self) -> bool {
69        true
70    }
71
72    fn source_id(&self) -> SourceId {
73        self.source_id
74    }
75
76    fn update(&mut self) -> CargoResult<()> {
77        self.packages.clear();
78        let entries = self.root.read_dir().chain_err(|| {
79            format!(
80                "failed to read root of directory source: {}",
81                self.root.display()
82            )
83        })?;
84
85        for entry in entries {
86            let entry = entry?;
87            let path = entry.path();
88
89            // Ignore hidden/dot directories as they typically don't contain
90            // crates and otherwise may conflict with a VCS
91            // (rust-lang/cargo#3414).
92            if let Some(s) = path.file_name().and_then(|s| s.to_str()) {
93                if s.starts_with('.') {
94                    continue;
95                }
96            }
97
98            // Vendor directories are often checked into a VCS, but throughout
99            // the lifetime of a vendor dir crates are often added and deleted.
100            // Some VCS implementations don't always fully delete the directory
101            // when a dir is removed from a different checkout. Sometimes a
102            // mostly-empty dir is left behind.
103            //
104            // Additionally vendor directories are sometimes accompanied with
105            // readme files and other auxiliary information not too interesting
106            // to Cargo.
107            //
108            // To help handle all this we only try processing folders with a
109            // `Cargo.toml` in them. This has the upside of being pretty
110            // flexible with the contents of vendor directories but has the
111            // downside of accidentally misconfigured vendor directories
112            // silently returning less crates.
113            if !path.join("Cargo.toml").exists() {
114                continue;
115            }
116
117            let mut src = PathSource::new(&path, self.source_id, self.config);
118            src.update()?;
119            let pkg = src.root_package()?;
120
121            let cksum_file = path.join(".cargo-checksum.json");
122            let cksum = paths::read(&path.join(cksum_file)).chain_err(|| {
123                format!(
124                    "failed to load checksum `.cargo-checksum.json` \
125                     of {} v{}",
126                    pkg.package_id().name(),
127                    pkg.package_id().version()
128                )
129            })?;
130            let cksum: Checksum = serde_json::from_str(&cksum).chain_err(|| {
131                format!(
132                    "failed to decode `.cargo-checksum.json` of \
133                     {} v{}",
134                    pkg.package_id().name(),
135                    pkg.package_id().version()
136                )
137            })?;
138
139            let mut manifest = pkg.manifest().clone();
140            let mut summary = manifest.summary().clone();
141            if let Some(ref package) = cksum.package {
142                summary = summary.set_checksum(package.clone());
143            }
144            manifest.set_summary(summary);
145            let pkg = Package::new(manifest, pkg.manifest_path());
146            self.packages.insert(pkg.package_id(), (pkg, cksum));
147        }
148
149        Ok(())
150    }
151
152    fn download(&mut self, id: PackageId) -> CargoResult<MaybePackage> {
153        self.packages
154            .get(&id)
155            .map(|p| &p.0)
156            .cloned()
157            .map(MaybePackage::Ready)
158            .ok_or_else(|| failure::format_err!("failed to find package with id: {}", id))
159    }
160
161    fn finish_download(&mut self, _id: PackageId, _data: Vec<u8>) -> CargoResult<Package> {
162        panic!("no downloads to do")
163    }
164
165    fn fingerprint(&self, pkg: &Package) -> CargoResult<String> {
166        Ok(pkg.package_id().version().to_string())
167    }
168
169    fn verify(&self, id: PackageId) -> CargoResult<()> {
170        let (pkg, cksum) = match self.packages.get(&id) {
171            Some(&(ref pkg, ref cksum)) => (pkg, cksum),
172            None => failure::bail!("failed to find entry for `{}` in directory source", id),
173        };
174
175        let mut buf = [0; 16 * 1024];
176        for (file, cksum) in cksum.files.iter() {
177            let mut h = Sha256::new();
178            let file = pkg.root().join(file);
179
180            (|| -> CargoResult<()> {
181                let mut f = File::open(&file)?;
182                loop {
183                    match f.read(&mut buf)? {
184                        0 => return Ok(()),
185                        n => h.update(&buf[..n]),
186                    }
187                }
188            })()
189            .chain_err(|| format!("failed to calculate checksum of: {}", file.display()))?;
190
191            let actual = hex::encode(h.finish());
192            if &*actual != cksum {
193                failure::bail!(
194                    "\
195                     the listed checksum of `{}` has changed:\n\
196                     expected: {}\n\
197                     actual:   {}\n\
198                     \n\
199                     directory sources are not intended to be edited, if \
200                     modifications are required then it is recommended \
201                     that [replace] is used with a forked copy of the \
202                     source\
203                     ",
204                    file.display(),
205                    cksum,
206                    actual
207                );
208            }
209        }
210
211        Ok(())
212    }
213
214    fn describe(&self) -> String {
215        format!("directory source `{}`", self.root.display())
216    }
217}