Skip to main content

cargo/sources/
path.rs

1use std::fmt::{self, Debug, Formatter};
2use std::fs;
3use std::path::{Path, PathBuf};
4
5use filetime::FileTime;
6use glob::Pattern;
7use ignore::gitignore::GitignoreBuilder;
8use ignore::Match;
9use log::{trace, warn};
10
11use crate::core::source::MaybePackage;
12use crate::core::{Dependency, Package, PackageId, Source, SourceId, Summary};
13use crate::ops;
14use crate::util::paths;
15use crate::util::Config;
16use crate::util::{self, internal, CargoResult};
17
18pub struct PathSource<'cfg> {
19    source_id: SourceId,
20    path: PathBuf,
21    updated: bool,
22    packages: Vec<Package>,
23    config: &'cfg Config,
24    recursive: bool,
25}
26
27impl<'cfg> PathSource<'cfg> {
28    /// Invoked with an absolute path to a directory that contains a Cargo.toml.
29    ///
30    /// This source will only return the package at precisely the `path`
31    /// specified, and it will be an error if there's not a package at `path`.
32    pub fn new(path: &Path, source_id: SourceId, config: &'cfg Config) -> PathSource<'cfg> {
33        PathSource {
34            source_id,
35            path: path.to_path_buf(),
36            updated: false,
37            packages: Vec::new(),
38            config,
39            recursive: false,
40        }
41    }
42
43    /// Creates a new source which is walked recursively to discover packages.
44    ///
45    /// This is similar to the `new` method except that instead of requiring a
46    /// valid package to be present at `root` the folder is walked entirely to
47    /// crawl for packages.
48    ///
49    /// Note that this should be used with care and likely shouldn't be chosen
50    /// by default!
51    pub fn new_recursive(root: &Path, id: SourceId, config: &'cfg Config) -> PathSource<'cfg> {
52        PathSource {
53            recursive: true,
54            ..PathSource::new(root, id, config)
55        }
56    }
57
58    pub fn preload_with(&mut self, pkg: Package) {
59        assert!(!self.updated);
60        assert!(!self.recursive);
61        assert!(self.packages.is_empty());
62        self.updated = true;
63        self.packages.push(pkg);
64    }
65
66    pub fn root_package(&mut self) -> CargoResult<Package> {
67        trace!("root_package; source={:?}", self);
68
69        self.update()?;
70
71        match self.packages.iter().find(|p| p.root() == &*self.path) {
72            Some(pkg) => Ok(pkg.clone()),
73            None => Err(internal("no package found in source")),
74        }
75    }
76
77    pub fn read_packages(&self) -> CargoResult<Vec<Package>> {
78        if self.updated {
79            Ok(self.packages.clone())
80        } else if self.recursive {
81            ops::read_packages(&self.path, self.source_id, self.config)
82        } else {
83            let path = self.path.join("Cargo.toml");
84            let (pkg, _) = ops::read_package(&path, self.source_id, self.config)?;
85            Ok(vec![pkg])
86        }
87    }
88
89    /// List all files relevant to building this package inside this source.
90    ///
91    /// This function will use the appropriate methods to determine the
92    /// set of files underneath this source's directory which are relevant for
93    /// building `pkg`.
94    ///
95    /// The basic assumption of this method is that all files in the directory
96    /// are relevant for building this package, but it also contains logic to
97    /// use other methods like .gitignore to filter the list of files.
98    ///
99    /// ## Pattern matching strategy
100    ///
101    /// Migrating from a glob-like pattern matching (using `glob` crate) to a
102    /// gitignore-like pattern matching (using `ignore` crate). The migration
103    /// stages are:
104    ///
105    /// 1) Only warn users about the future change iff their matching rules are
106    ///    affected.  (CURRENT STAGE)
107    ///
108    /// 2) Switch to the new strategy and update documents. Still keep warning
109    ///    affected users.
110    ///
111    /// 3) Drop the old strategy and no more warnings.
112    ///
113    /// See <https://github.com/rust-lang/cargo/issues/4268> for more info.
114    pub fn list_files(&self, pkg: &Package) -> CargoResult<Vec<PathBuf>> {
115        let root = pkg.root();
116        let no_include_option = pkg.manifest().include().is_empty();
117
118        // glob-like matching rules
119
120        let glob_parse = |p: &String| {
121            let pattern: &str = if p.starts_with('/') {
122                &p[1..p.len()]
123            } else {
124                p
125            };
126            Pattern::new(pattern)
127                .map_err(|e| failure::format_err!("could not parse glob pattern `{}`: {}", p, e))
128        };
129
130        let glob_exclude = pkg
131            .manifest()
132            .exclude()
133            .iter()
134            .map(|p| glob_parse(p))
135            .collect::<Result<Vec<_>, _>>()?;
136
137        let glob_include = pkg
138            .manifest()
139            .include()
140            .iter()
141            .map(|p| glob_parse(p))
142            .collect::<Result<Vec<_>, _>>()?;
143
144        let glob_should_package = |relative_path: &Path| -> bool {
145            fn glob_match(patterns: &[Pattern], relative_path: &Path) -> bool {
146                patterns
147                    .iter()
148                    .any(|pattern| pattern.matches_path(relative_path))
149            }
150
151            // include and exclude options are mutually exclusive.
152            if no_include_option {
153                !glob_match(&glob_exclude, relative_path)
154            } else {
155                glob_match(&glob_include, relative_path)
156            }
157        };
158
159        // ignore-like matching rules
160
161        let mut exclude_builder = GitignoreBuilder::new(root);
162        for rule in pkg.manifest().exclude() {
163            exclude_builder.add_line(None, rule)?;
164        }
165        let ignore_exclude = exclude_builder.build()?;
166
167        let mut include_builder = GitignoreBuilder::new(root);
168        for rule in pkg.manifest().include() {
169            include_builder.add_line(None, rule)?;
170        }
171        let ignore_include = include_builder.build()?;
172
173        let ignore_should_package = |relative_path: &Path| -> CargoResult<bool> {
174            // include and exclude options are mutually exclusive.
175            if no_include_option {
176                match ignore_exclude
177                    .matched_path_or_any_parents(relative_path, /* is_dir */ false)
178                {
179                    Match::None => Ok(true),
180                    Match::Ignore(_) => Ok(false),
181                    Match::Whitelist(pattern) => Err(failure::format_err!(
182                        "exclude rules cannot start with `!`: {}",
183                        pattern.original()
184                    )),
185                }
186            } else {
187                match ignore_include
188                    .matched_path_or_any_parents(relative_path, /* is_dir */ false)
189                {
190                    Match::None => Ok(false),
191                    Match::Ignore(_) => Ok(true),
192                    Match::Whitelist(pattern) => Err(failure::format_err!(
193                        "include rules cannot start with `!`: {}",
194                        pattern.original()
195                    )),
196                }
197            }
198        };
199
200        // matching to paths
201
202        let mut filter = |path: &Path| -> CargoResult<bool> {
203            let relative_path = util::without_prefix(path, root).unwrap();
204            let glob_should_package = glob_should_package(relative_path);
205            let ignore_should_package = ignore_should_package(relative_path)?;
206
207            if glob_should_package != ignore_should_package {
208                if glob_should_package {
209                    if no_include_option {
210                        self.config.shell().warn(format!(
211                            "Pattern matching for Cargo's include/exclude fields is changing and \
212                             file `{}` WILL be excluded in a future Cargo version.\n\
213                             See https://github.com/rust-lang/cargo/issues/4268 for more info",
214                            relative_path.display()
215                        ))?;
216                    } else {
217                        self.config.shell().warn(format!(
218                            "Pattern matching for Cargo's include/exclude fields is changing and \
219                             file `{}` WILL NOT be included in a future Cargo version.\n\
220                             See https://github.com/rust-lang/cargo/issues/4268 for more info",
221                            relative_path.display()
222                        ))?;
223                    }
224                } else if no_include_option {
225                    self.config.shell().warn(format!(
226                        "Pattern matching for Cargo's include/exclude fields is changing and \
227                         file `{}` WILL NOT be excluded in a future Cargo version.\n\
228                         See https://github.com/rust-lang/cargo/issues/4268 for more info",
229                        relative_path.display()
230                    ))?;
231                } else {
232                    self.config.shell().warn(format!(
233                        "Pattern matching for Cargo's include/exclude fields is changing and \
234                         file `{}` WILL be included in a future Cargo version.\n\
235                         See https://github.com/rust-lang/cargo/issues/4268 for more info",
236                        relative_path.display()
237                    ))?;
238                }
239            }
240
241            // Update to ignore_should_package for Stage 2
242            Ok(glob_should_package)
243        };
244
245        // attempt git-prepopulate only if no `include` (rust-lang/cargo#4135)
246        if no_include_option {
247            if let Some(result) = self.discover_git_and_list_files(pkg, root, &mut filter) {
248                return result;
249            }
250        }
251        self.list_files_walk(pkg, &mut filter)
252    }
253
254    // Returns Some(_) if found sibling Cargo.toml and .git folder;
255    // otherwise caller should fall back on full file list.
256    fn discover_git_and_list_files(
257        &self,
258        pkg: &Package,
259        root: &Path,
260        filter: &mut dyn FnMut(&Path) -> CargoResult<bool>,
261    ) -> Option<CargoResult<Vec<PathBuf>>> {
262        // If this package is in a git repository, then we really do want to
263        // query the git repository as it takes into account items such as
264        // .gitignore. We're not quite sure where the git repository is,
265        // however, so we do a bit of a probe.
266        //
267        // We walk this package's path upwards and look for a sibling
268        // Cargo.toml and .git folder. If we find one then we assume that we're
269        // part of that repository.
270        let mut cur = root;
271        loop {
272            if cur.join("Cargo.toml").is_file() {
273                // If we find a git repository next to this Cargo.toml, we still
274                // check to see if we are indeed part of the index. If not, then
275                // this is likely an unrelated git repo, so keep going.
276                if let Ok(repo) = git2::Repository::open(cur) {
277                    let index = match repo.index() {
278                        Ok(index) => index,
279                        Err(err) => return Some(Err(err.into())),
280                    };
281                    let path = util::without_prefix(root, cur).unwrap().join("Cargo.toml");
282                    if index.get_path(&path, 0).is_some() {
283                        return Some(self.list_files_git(pkg, &repo, filter));
284                    }
285                }
286            }
287            // don't cross submodule boundaries
288            if cur.join(".git").is_dir() {
289                break;
290            }
291            match cur.parent() {
292                Some(parent) => cur = parent,
293                None => break,
294            }
295        }
296        None
297    }
298
299    fn list_files_git(
300        &self,
301        pkg: &Package,
302        repo: &git2::Repository,
303        filter: &mut dyn FnMut(&Path) -> CargoResult<bool>,
304    ) -> CargoResult<Vec<PathBuf>> {
305        warn!("list_files_git {}", pkg.package_id());
306        let index = repo.index()?;
307        let root = repo
308            .workdir()
309            .ok_or_else(|| internal("Can't list files on a bare repository."))?;
310        let pkg_path = pkg.root();
311
312        let mut ret = Vec::<PathBuf>::new();
313
314        // We use information from the git repository to guide us in traversing
315        // its tree. The primary purpose of this is to take advantage of the
316        // .gitignore and auto-ignore files that don't matter.
317        //
318        // Here we're also careful to look at both tracked and untracked files as
319        // the untracked files are often part of a build and may become relevant
320        // as part of a future commit.
321        let index_files = index.iter().map(|entry| {
322            use libgit2_sys::GIT_FILEMODE_COMMIT;
323            let is_dir = entry.mode == GIT_FILEMODE_COMMIT as u32;
324            (join(root, &entry.path), Some(is_dir))
325        });
326        let mut opts = git2::StatusOptions::new();
327        opts.include_untracked(true);
328        if let Some(suffix) = util::without_prefix(pkg_path, root) {
329            opts.pathspec(suffix);
330        }
331        let statuses = repo.statuses(Some(&mut opts))?;
332        let untracked = statuses.iter().filter_map(|entry| match entry.status() {
333            git2::Status::WT_NEW => Some((join(root, entry.path_bytes()), None)),
334            _ => None,
335        });
336
337        let mut subpackages_found = Vec::new();
338
339        for (file_path, is_dir) in index_files.chain(untracked) {
340            let file_path = file_path?;
341
342            // Filter out files blatantly outside this package. This is helped a
343            // bit obove via the `pathspec` function call, but we need to filter
344            // the entries in the index as well.
345            if !file_path.starts_with(pkg_path) {
346                continue;
347            }
348
349            match file_path.file_name().and_then(|s| s.to_str()) {
350                // Filter out Cargo.lock and target always, we don't want to
351                // package a lock file no one will ever read and we also avoid
352                // build artifacts
353                Some("Cargo.lock") | Some("target") => continue,
354
355                // Keep track of all sub-packages found and also strip out all
356                // matches we've found so far. Note, though, that if we find
357                // our own `Cargo.toml` we keep going.
358                Some("Cargo.toml") => {
359                    let path = file_path.parent().unwrap();
360                    if path != pkg_path {
361                        warn!("subpackage found: {}", path.display());
362                        ret.retain(|p| !p.starts_with(path));
363                        subpackages_found.push(path.to_path_buf());
364                        continue;
365                    }
366                }
367
368                _ => {}
369            }
370
371            // If this file is part of any other sub-package we've found so far,
372            // skip it.
373            if subpackages_found.iter().any(|p| file_path.starts_with(p)) {
374                continue;
375            }
376
377            if is_dir.unwrap_or_else(|| file_path.is_dir()) {
378                warn!("  found submodule {}", file_path.display());
379                let rel = util::without_prefix(&file_path, root).unwrap();
380                let rel = rel.to_str().ok_or_else(|| {
381                    failure::format_err!("invalid utf-8 filename: {}", rel.display())
382                })?;
383                // Git submodules are currently only named through `/` path
384                // separators, explicitly not `\` which windows uses. Who knew?
385                let rel = rel.replace(r"\", "/");
386                match repo.find_submodule(&rel).and_then(|s| s.open()) {
387                    Ok(repo) => {
388                        let files = self.list_files_git(pkg, &repo, filter)?;
389                        ret.extend(files.into_iter());
390                    }
391                    Err(..) => {
392                        PathSource::walk(&file_path, &mut ret, false, filter)?;
393                    }
394                }
395            } else if (*filter)(&file_path)? {
396                // We found a file!
397                warn!("  found {}", file_path.display());
398                ret.push(file_path);
399            }
400        }
401        return Ok(ret);
402
403        #[cfg(unix)]
404        fn join(path: &Path, data: &[u8]) -> CargoResult<PathBuf> {
405            use std::ffi::OsStr;
406            use std::os::unix::prelude::*;
407            Ok(path.join(<OsStr as OsStrExt>::from_bytes(data)))
408        }
409        #[cfg(windows)]
410        fn join(path: &Path, data: &[u8]) -> CargoResult<PathBuf> {
411            use std::str;
412            match str::from_utf8(data) {
413                Ok(s) => Ok(path.join(s)),
414                Err(..) => Err(internal(
415                    "cannot process path in git with a non \
416                     unicode filename",
417                )),
418            }
419        }
420    }
421
422    fn list_files_walk(
423        &self,
424        pkg: &Package,
425        filter: &mut dyn FnMut(&Path) -> CargoResult<bool>,
426    ) -> CargoResult<Vec<PathBuf>> {
427        let mut ret = Vec::new();
428        PathSource::walk(pkg.root(), &mut ret, true, filter)?;
429        Ok(ret)
430    }
431
432    fn walk(
433        path: &Path,
434        ret: &mut Vec<PathBuf>,
435        is_root: bool,
436        filter: &mut dyn FnMut(&Path) -> CargoResult<bool>,
437    ) -> CargoResult<()> {
438        if !fs::metadata(&path).map(|m| m.is_dir()).unwrap_or(false) {
439            if (*filter)(path)? {
440                ret.push(path.to_path_buf());
441            }
442            return Ok(());
443        }
444        // Don't recurse into any sub-packages that we have
445        if !is_root && fs::metadata(&path.join("Cargo.toml")).is_ok() {
446            return Ok(());
447        }
448
449        // For package integration tests, we need to sort the paths in a deterministic order to
450        // be able to match stdout warnings in the same order.
451        //
452        // TODO: Drop collect and sort after transition period and dropping warning tests.
453        // See <https://github.com/rust-lang/cargo/issues/4268>
454        // and <https://github.com/rust-lang/cargo/pull/4270>
455        let mut entries: Vec<PathBuf> = fs::read_dir(path)?.map(|e| e.unwrap().path()).collect();
456        entries.sort_unstable_by(|a, b| a.as_os_str().cmp(b.as_os_str()));
457        for path in entries {
458            let name = path.file_name().and_then(|s| s.to_str());
459            // Skip dotfile directories
460            if name.map(|s| s.starts_with('.')) == Some(true) {
461                continue;
462            }
463            if is_root {
464                // Skip cargo artifacts
465                match name {
466                    Some("target") | Some("Cargo.lock") => continue,
467                    _ => {}
468                }
469            }
470            PathSource::walk(&path, ret, false, filter)?;
471        }
472        Ok(())
473    }
474
475    pub fn last_modified_file(&self, pkg: &Package) -> CargoResult<(FileTime, PathBuf)> {
476        if !self.updated {
477            return Err(internal("BUG: source was not updated"));
478        }
479
480        let mut max = FileTime::zero();
481        let mut max_path = PathBuf::new();
482        for file in self.list_files(pkg)? {
483            // An fs::stat error here is either because path is a
484            // broken symlink, a permissions error, or a race
485            // condition where this path was rm'ed - either way,
486            // we can ignore the error and treat the path's mtime
487            // as 0.
488            let mtime = paths::mtime(&file).unwrap_or_else(|_| FileTime::zero());
489            if mtime > max {
490                max = mtime;
491                max_path = file;
492            }
493        }
494        trace!("last modified file {}: {}", self.path.display(), max);
495        Ok((max, max_path))
496    }
497
498    pub fn path(&self) -> &Path {
499        &self.path
500    }
501}
502
503impl<'cfg> Debug for PathSource<'cfg> {
504    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
505        write!(f, "the paths source")
506    }
507}
508
509impl<'cfg> Source for PathSource<'cfg> {
510    fn query(&mut self, dep: &Dependency, f: &mut dyn FnMut(Summary)) -> CargoResult<()> {
511        for s in self.packages.iter().map(|p| p.summary()) {
512            if dep.matches(s) {
513                f(s.clone())
514            }
515        }
516        Ok(())
517    }
518
519    fn fuzzy_query(&mut self, _dep: &Dependency, f: &mut dyn FnMut(Summary)) -> CargoResult<()> {
520        for s in self.packages.iter().map(|p| p.summary()) {
521            f(s.clone())
522        }
523        Ok(())
524    }
525
526    fn supports_checksums(&self) -> bool {
527        false
528    }
529
530    fn requires_precise(&self) -> bool {
531        false
532    }
533
534    fn source_id(&self) -> SourceId {
535        self.source_id
536    }
537
538    fn update(&mut self) -> CargoResult<()> {
539        if !self.updated {
540            let packages = self.read_packages()?;
541            self.packages.extend(packages.into_iter());
542            self.updated = true;
543        }
544
545        Ok(())
546    }
547
548    fn download(&mut self, id: PackageId) -> CargoResult<MaybePackage> {
549        trace!("getting packages; id={}", id);
550
551        let pkg = self.packages.iter().find(|pkg| pkg.package_id() == id);
552        pkg.cloned()
553            .map(MaybePackage::Ready)
554            .ok_or_else(|| internal(format!("failed to find {} in path source", id)))
555    }
556
557    fn finish_download(&mut self, _id: PackageId, _data: Vec<u8>) -> CargoResult<Package> {
558        panic!("no download should have started")
559    }
560
561    fn fingerprint(&self, pkg: &Package) -> CargoResult<String> {
562        let (max, max_path) = self.last_modified_file(pkg)?;
563        Ok(format!("{} ({})", max, max_path.display()))
564    }
565
566    fn describe(&self) -> String {
567        match self.source_id.url().to_file_path() {
568            Ok(path) => path.display().to_string(),
569            Err(_) => self.source_id.to_string(),
570        }
571    }
572}