Skip to main content

cargo/core/
workspace.rs

1use std::cell::RefCell;
2use std::collections::hash_map::{Entry, HashMap};
3use std::collections::BTreeMap;
4use std::path::{Path, PathBuf};
5use std::slice;
6
7use glob::glob;
8use log::debug;
9use url::Url;
10
11use crate::core::profiles::Profiles;
12use crate::core::registry::PackageRegistry;
13use crate::core::{Dependency, PackageIdSpec};
14use crate::core::{EitherManifest, Package, SourceId, VirtualManifest};
15use crate::ops;
16use crate::sources::PathSource;
17use crate::util::errors::{CargoResult, CargoResultExt, ManifestError};
18use crate::util::paths;
19use crate::util::toml::read_manifest;
20use crate::util::{Config, Filesystem};
21
22/// The core abstraction in Cargo for working with a workspace of crates.
23///
24/// A workspace is often created very early on and then threaded through all
25/// other functions. It's typically through this object that the current
26/// package is loaded and/or learned about.
27#[derive(Debug)]
28pub struct Workspace<'cfg> {
29    config: &'cfg Config,
30
31    // This path is a path to where the current cargo subcommand was invoked
32    // from. That is the `--manifest-path` argument to Cargo, and
33    // points to the "main crate" that we're going to worry about.
34    current_manifest: PathBuf,
35
36    // A list of packages found in this workspace. Always includes at least the
37    // package mentioned by `current_manifest`.
38    packages: Packages<'cfg>,
39
40    // If this workspace includes more than one crate, this points to the root
41    // of the workspace. This is `None` in the case that `[workspace]` is
42    // missing, `package.workspace` is missing, and no `Cargo.toml` above
43    // `current_manifest` was found on the filesystem with `[workspace]`.
44    root_manifest: Option<PathBuf>,
45
46    // Shared target directory for all the packages of this workspace.
47    // `None` if the default path of `root/target` should be used.
48    target_dir: Option<Filesystem>,
49
50    // List of members in this workspace with a listing of all their manifest
51    // paths. The packages themselves can be looked up through the `packages`
52    // set above.
53    members: Vec<PathBuf>,
54
55    // The subset of `members` that are used by the
56    // `build`, `check`, `test`, and `bench` subcommands
57    // when no package is selected with `--package` / `-p` and `--all`
58    // is not used.
59    //
60    // This is set by the `default-members` config
61    // in the `[workspace]` section.
62    // When unset, this is the same as `members` for virtual workspaces
63    // (`--all` is implied)
64    // or only the root package for non-virtual workspaces.
65    default_members: Vec<PathBuf>,
66
67    // True, if this is a temporary workspace created for the purposes of
68    // cargo install or cargo package.
69    is_ephemeral: bool,
70
71    // True if this workspace should enforce optional dependencies even when
72    // not needed; false if this workspace should only enforce dependencies
73    // needed by the current configuration (such as in cargo install). In some
74    // cases `false` also results in the non-enforcement of dev-dependencies.
75    require_optional_deps: bool,
76
77    // A cache of loaded packages for particular paths which is disjoint from
78    // `packages` up above, used in the `load` method down below.
79    loaded_packages: RefCell<HashMap<PathBuf, Package>>,
80}
81
82// Separate structure for tracking loaded packages (to avoid loading anything
83// twice), and this is separate to help appease the borrow checker.
84#[derive(Debug)]
85struct Packages<'cfg> {
86    config: &'cfg Config,
87    packages: HashMap<PathBuf, MaybePackage>,
88}
89
90#[derive(Debug)]
91enum MaybePackage {
92    Package(Package),
93    Virtual(VirtualManifest),
94}
95
96/// Configuration of a workspace in a manifest.
97#[derive(Debug, Clone)]
98pub enum WorkspaceConfig {
99    /// Indicates that `[workspace]` was present and the members were
100    /// optionally specified as well.
101    Root(WorkspaceRootConfig),
102
103    /// Indicates that `[workspace]` was present and the `root` field is the
104    /// optional value of `package.workspace`, if present.
105    Member { root: Option<String> },
106}
107
108/// Intermediate configuration of a workspace root in a manifest.
109///
110/// Knows the Workspace Root path, as well as `members` and `exclude` lists of path patterns, which
111/// together tell if some path is recognized as a member by this root or not.
112#[derive(Debug, Clone)]
113pub struct WorkspaceRootConfig {
114    root_dir: PathBuf,
115    members: Option<Vec<String>>,
116    default_members: Option<Vec<String>>,
117    exclude: Vec<String>,
118}
119
120/// An iterator over the member packages of a workspace, returned by
121/// `Workspace::members`
122pub struct Members<'a, 'cfg: 'a> {
123    ws: &'a Workspace<'cfg>,
124    iter: slice::Iter<'a, PathBuf>,
125}
126
127impl<'cfg> Workspace<'cfg> {
128    /// Creates a new workspace given the target manifest pointed to by
129    /// `manifest_path`.
130    ///
131    /// This function will construct the entire workspace by determining the
132    /// root and all member packages. It will then validate the workspace
133    /// before returning it, so `Ok` is only returned for valid workspaces.
134    pub fn new(manifest_path: &Path, config: &'cfg Config) -> CargoResult<Workspace<'cfg>> {
135        let target_dir = config.target_dir()?;
136
137        let mut ws = Workspace {
138            config,
139            current_manifest: manifest_path.to_path_buf(),
140            packages: Packages {
141                config,
142                packages: HashMap::new(),
143            },
144            root_manifest: None,
145            target_dir,
146            members: Vec::new(),
147            default_members: Vec::new(),
148            is_ephemeral: false,
149            require_optional_deps: true,
150            loaded_packages: RefCell::new(HashMap::new()),
151        };
152        ws.root_manifest = ws.find_root(manifest_path)?;
153        ws.find_members()?;
154        ws.validate()?;
155        Ok(ws)
156    }
157
158    /// Creates a "temporary workspace" from one package which only contains
159    /// that package.
160    ///
161    /// This constructor will not touch the filesystem and only creates an
162    /// in-memory workspace. That is, all configuration is ignored, it's just
163    /// intended for that one package.
164    ///
165    /// This is currently only used in niche situations like `cargo install` or
166    /// `cargo package`.
167    pub fn ephemeral(
168        package: Package,
169        config: &'cfg Config,
170        target_dir: Option<Filesystem>,
171        require_optional_deps: bool,
172    ) -> CargoResult<Workspace<'cfg>> {
173        let mut ws = Workspace {
174            config,
175            current_manifest: package.manifest_path().to_path_buf(),
176            packages: Packages {
177                config,
178                packages: HashMap::new(),
179            },
180            root_manifest: None,
181            target_dir: None,
182            members: Vec::new(),
183            default_members: Vec::new(),
184            is_ephemeral: true,
185            require_optional_deps,
186            loaded_packages: RefCell::new(HashMap::new()),
187        };
188        {
189            let key = ws.current_manifest.parent().unwrap();
190            let package = MaybePackage::Package(package);
191            ws.packages.packages.insert(key.to_path_buf(), package);
192            ws.target_dir = if let Some(dir) = target_dir {
193                Some(dir)
194            } else {
195                ws.config.target_dir()?
196            };
197            ws.members.push(ws.current_manifest.clone());
198            ws.default_members.push(ws.current_manifest.clone());
199        }
200        Ok(ws)
201    }
202
203    /// Returns the current package of this workspace.
204    ///
205    /// Note that this can return an error if it the current manifest is
206    /// actually a "virtual Cargo.toml", in which case an error is returned
207    /// indicating that something else should be passed.
208    pub fn current(&self) -> CargoResult<&Package> {
209        let pkg = self.current_opt().ok_or_else(|| {
210            failure::format_err!(
211                "manifest path `{}` is a virtual manifest, but this \
212                 command requires running against an actual package in \
213                 this workspace",
214                self.current_manifest.display()
215            )
216        })?;
217        Ok(pkg)
218    }
219
220    pub fn current_opt(&self) -> Option<&Package> {
221        match *self.packages.get(&self.current_manifest) {
222            MaybePackage::Package(ref p) => Some(p),
223            MaybePackage::Virtual(..) => None,
224        }
225    }
226
227    pub fn is_virtual(&self) -> bool {
228        match *self.packages.get(&self.current_manifest) {
229            MaybePackage::Package(..) => false,
230            MaybePackage::Virtual(..) => true,
231        }
232    }
233
234    /// Returns the `Config` this workspace is associated with.
235    pub fn config(&self) -> &'cfg Config {
236        self.config
237    }
238
239    pub fn profiles(&self) -> &Profiles {
240        let root = self
241            .root_manifest
242            .as_ref()
243            .unwrap_or(&self.current_manifest);
244        match *self.packages.get(root) {
245            MaybePackage::Package(ref p) => p.manifest().profiles(),
246            MaybePackage::Virtual(ref vm) => vm.profiles(),
247        }
248    }
249
250    /// Returns the root path of this workspace.
251    ///
252    /// That is, this returns the path of the directory containing the
253    /// `Cargo.toml` which is the root of this workspace.
254    pub fn root(&self) -> &Path {
255        match self.root_manifest {
256            Some(ref p) => p,
257            None => &self.current_manifest,
258        }
259        .parent()
260        .unwrap()
261    }
262
263    pub fn target_dir(&self) -> Filesystem {
264        self.target_dir
265            .clone()
266            .unwrap_or_else(|| Filesystem::new(self.root().join("target")))
267    }
268
269    /// Returns the root [replace] section of this workspace.
270    ///
271    /// This may be from a virtual crate or an actual crate.
272    pub fn root_replace(&self) -> &[(PackageIdSpec, Dependency)] {
273        let path = match self.root_manifest {
274            Some(ref p) => p,
275            None => &self.current_manifest,
276        };
277        match *self.packages.get(path) {
278            MaybePackage::Package(ref p) => p.manifest().replace(),
279            MaybePackage::Virtual(ref vm) => vm.replace(),
280        }
281    }
282
283    /// Returns the root [patch] section of this workspace.
284    ///
285    /// This may be from a virtual crate or an actual crate.
286    pub fn root_patch(&self) -> &HashMap<Url, Vec<Dependency>> {
287        let path = match self.root_manifest {
288            Some(ref p) => p,
289            None => &self.current_manifest,
290        };
291        match *self.packages.get(path) {
292            MaybePackage::Package(ref p) => p.manifest().patch(),
293            MaybePackage::Virtual(ref vm) => vm.patch(),
294        }
295    }
296
297    /// Returns an iterator over all packages in this workspace
298    pub fn members<'a>(&'a self) -> Members<'a, 'cfg> {
299        Members {
300            ws: self,
301            iter: self.members.iter(),
302        }
303    }
304
305    /// Returns an iterator over default packages in this workspace
306    pub fn default_members<'a>(&'a self) -> Members<'a, 'cfg> {
307        Members {
308            ws: self,
309            iter: self.default_members.iter(),
310        }
311    }
312
313    /// Returns true if the package is a member of the workspace.
314    pub fn is_member(&self, pkg: &Package) -> bool {
315        self.members().any(|p| p == pkg)
316    }
317
318    pub fn is_ephemeral(&self) -> bool {
319        self.is_ephemeral
320    }
321
322    pub fn require_optional_deps(&self) -> bool {
323        self.require_optional_deps
324    }
325
326    pub fn set_require_optional_deps<'a>(
327        &'a mut self,
328        require_optional_deps: bool,
329    ) -> &mut Workspace<'cfg> {
330        self.require_optional_deps = require_optional_deps;
331        self
332    }
333
334    /// Finds the root of a workspace for the crate whose manifest is located
335    /// at `manifest_path`.
336    ///
337    /// This will parse the `Cargo.toml` at `manifest_path` and then interpret
338    /// the workspace configuration, optionally walking up the filesystem
339    /// looking for other workspace roots.
340    ///
341    /// Returns an error if `manifest_path` isn't actually a valid manifest or
342    /// if some other transient error happens.
343    fn find_root(&mut self, manifest_path: &Path) -> CargoResult<Option<PathBuf>> {
344        fn read_root_pointer(member_manifest: &Path, root_link: &str) -> CargoResult<PathBuf> {
345            let path = member_manifest
346                .parent()
347                .unwrap()
348                .join(root_link)
349                .join("Cargo.toml");
350            debug!("find_root - pointer {}", path.display());
351            Ok(paths::normalize_path(&path))
352        };
353
354        {
355            let current = self.packages.load(manifest_path)?;
356            match *current.workspace_config() {
357                WorkspaceConfig::Root(_) => {
358                    debug!("find_root - is root {}", manifest_path.display());
359                    return Ok(Some(manifest_path.to_path_buf()));
360                }
361                WorkspaceConfig::Member {
362                    root: Some(ref path_to_root),
363                } => return Ok(Some(read_root_pointer(manifest_path, path_to_root)?)),
364                WorkspaceConfig::Member { root: None } => {}
365            }
366        }
367
368        for path in paths::ancestors(manifest_path).skip(2) {
369            if path.ends_with("target/package") {
370                break;
371            }
372
373            let ances_manifest_path = path.join("Cargo.toml");
374            debug!("find_root - trying {}", ances_manifest_path.display());
375            if ances_manifest_path.exists() {
376                match *self.packages.load(&ances_manifest_path)?.workspace_config() {
377                    WorkspaceConfig::Root(ref ances_root_config) => {
378                        debug!("find_root - found a root checking exclusion");
379                        if !ances_root_config.is_excluded(manifest_path) {
380                            debug!("find_root - found!");
381                            return Ok(Some(ances_manifest_path));
382                        }
383                    }
384                    WorkspaceConfig::Member {
385                        root: Some(ref path_to_root),
386                    } => {
387                        debug!("find_root - found pointer");
388                        return Ok(Some(read_root_pointer(&ances_manifest_path, path_to_root)?));
389                    }
390                    WorkspaceConfig::Member { .. } => {}
391                }
392            }
393
394            // Don't walk across `CARGO_HOME` when we're looking for the
395            // workspace root. Sometimes a package will be organized with
396            // `CARGO_HOME` pointing inside of the workspace root or in the
397            // current package, but we don't want to mistakenly try to put
398            // crates.io crates into the workspace by accident.
399            if self.config.home() == path {
400                break;
401            }
402        }
403
404        Ok(None)
405    }
406
407    /// After the root of a workspace has been located, probes for all members
408    /// of a workspace.
409    ///
410    /// If the `workspace.members` configuration is present, then this just
411    /// verifies that those are all valid packages to point to. Otherwise, this
412    /// will transitively follow all `path` dependencies looking for members of
413    /// the workspace.
414    fn find_members(&mut self) -> CargoResult<()> {
415        let root_manifest_path = match self.root_manifest {
416            Some(ref path) => path.clone(),
417            None => {
418                debug!("find_members - only me as a member");
419                self.members.push(self.current_manifest.clone());
420                self.default_members.push(self.current_manifest.clone());
421                return Ok(());
422            }
423        };
424
425        let members_paths;
426        let default_members_paths;
427        {
428            let root_package = self.packages.load(&root_manifest_path)?;
429            match *root_package.workspace_config() {
430                WorkspaceConfig::Root(ref root_config) => {
431                    members_paths = root_config
432                        .members_paths(root_config.members.as_ref().unwrap_or(&vec![]))?;
433                    default_members_paths = if let Some(ref default) = root_config.default_members {
434                        Some(root_config.members_paths(default)?)
435                    } else {
436                        None
437                    }
438                }
439                _ => failure::bail!(
440                    "root of a workspace inferred but wasn't a root: {}",
441                    root_manifest_path.display()
442                ),
443            }
444        }
445
446        for path in members_paths {
447            self.find_path_deps(&path.join("Cargo.toml"), &root_manifest_path, false)?;
448        }
449
450        if let Some(default) = default_members_paths {
451            for path in default {
452                let manifest_path = paths::normalize_path(&path.join("Cargo.toml"));
453                if !self.members.contains(&manifest_path) {
454                    failure::bail!(
455                        "package `{}` is listed in workspace’s default-members \
456                         but is not a member.",
457                        path.display()
458                    )
459                }
460                self.default_members.push(manifest_path)
461            }
462        } else if self.is_virtual() {
463            self.default_members = self.members.clone()
464        } else {
465            self.default_members.push(self.current_manifest.clone())
466        }
467
468        self.find_path_deps(&root_manifest_path, &root_manifest_path, false)
469    }
470
471    fn find_path_deps(
472        &mut self,
473        manifest_path: &Path,
474        root_manifest: &Path,
475        is_path_dep: bool,
476    ) -> CargoResult<()> {
477        let manifest_path = paths::normalize_path(manifest_path);
478        if self.members.contains(&manifest_path) {
479            return Ok(());
480        }
481        if is_path_dep
482            && !manifest_path.parent().unwrap().starts_with(self.root())
483            && self.find_root(&manifest_path)? != self.root_manifest
484        {
485            // If `manifest_path` is a path dependency outside of the workspace,
486            // don't add it, or any of its dependencies, as a members.
487            return Ok(());
488        }
489
490        if let WorkspaceConfig::Root(ref root_config) =
491            *self.packages.load(root_manifest)?.workspace_config()
492        {
493            if root_config.is_excluded(&manifest_path) {
494                return Ok(());
495            }
496        }
497
498        debug!("find_members - {}", manifest_path.display());
499        self.members.push(manifest_path.clone());
500
501        let candidates = {
502            let pkg = match *self.packages.load(&manifest_path)? {
503                MaybePackage::Package(ref p) => p,
504                MaybePackage::Virtual(_) => return Ok(()),
505            };
506            pkg.dependencies()
507                .iter()
508                .map(|d| d.source_id())
509                .filter(|d| d.is_path())
510                .filter_map(|d| d.url().to_file_path().ok())
511                .map(|p| p.join("Cargo.toml"))
512                .collect::<Vec<_>>()
513        };
514        for candidate in candidates {
515            self.find_path_deps(&candidate, root_manifest, true)
516                .map_err(|err| ManifestError::new(err, manifest_path.clone()))?;
517        }
518        Ok(())
519    }
520
521    /// Validates a workspace, ensuring that a number of invariants are upheld:
522    ///
523    /// 1. A workspace only has one root.
524    /// 2. All workspace members agree on this one root as the root.
525    /// 3. The current crate is a member of this workspace.
526    fn validate(&mut self) -> CargoResult<()> {
527        if self.root_manifest.is_none() {
528            return Ok(());
529        }
530
531        let mut roots = Vec::new();
532        {
533            let mut names = BTreeMap::new();
534            for member in self.members.iter() {
535                let package = self.packages.get(member);
536                match *package.workspace_config() {
537                    WorkspaceConfig::Root(_) => {
538                        roots.push(member.parent().unwrap().to_path_buf());
539                    }
540                    WorkspaceConfig::Member { .. } => {}
541                }
542                let name = match *package {
543                    MaybePackage::Package(ref p) => p.name(),
544                    MaybePackage::Virtual(_) => continue,
545                };
546                if let Some(prev) = names.insert(name, member) {
547                    failure::bail!(
548                        "two packages named `{}` in this workspace:\n\
549                         - {}\n\
550                         - {}",
551                        name,
552                        prev.display(),
553                        member.display()
554                    );
555                }
556            }
557        }
558
559        match roots.len() {
560            0 => failure::bail!(
561                "`package.workspace` configuration points to a crate \
562                 which is not configured with [workspace]: \n\
563                 configuration at: {}\n\
564                 points to: {}",
565                self.current_manifest.display(),
566                self.root_manifest.as_ref().unwrap().display()
567            ),
568            1 => {}
569            _ => {
570                failure::bail!(
571                    "multiple workspace roots found in the same workspace:\n{}",
572                    roots
573                        .iter()
574                        .map(|r| format!("  {}", r.display()))
575                        .collect::<Vec<_>>()
576                        .join("\n")
577                );
578            }
579        }
580
581        for member in self.members.clone() {
582            let root = self.find_root(&member)?;
583            if root == self.root_manifest {
584                continue;
585            }
586
587            match root {
588                Some(root) => {
589                    failure::bail!(
590                        "package `{}` is a member of the wrong workspace\n\
591                         expected: {}\n\
592                         actual:   {}",
593                        member.display(),
594                        self.root_manifest.as_ref().unwrap().display(),
595                        root.display()
596                    );
597                }
598                None => {
599                    failure::bail!(
600                        "workspace member `{}` is not hierarchically below \
601                         the workspace root `{}`",
602                        member.display(),
603                        self.root_manifest.as_ref().unwrap().display()
604                    );
605                }
606            }
607        }
608
609        if !self.members.contains(&self.current_manifest) {
610            let root = self.root_manifest.as_ref().unwrap();
611            let root_dir = root.parent().unwrap();
612            let current_dir = self.current_manifest.parent().unwrap();
613            let root_pkg = self.packages.get(root);
614
615            // FIXME: Make this more generic by using a relative path resolver between member and
616            // root.
617            let members_msg = match current_dir.strip_prefix(root_dir) {
618                Ok(rel) => format!(
619                    "this may be fixable by adding `{}` to the \
620                     `workspace.members` array of the manifest \
621                     located at: {}",
622                    rel.display(),
623                    root.display()
624                ),
625                Err(_) => format!(
626                    "this may be fixable by adding a member to \
627                     the `workspace.members` array of the \
628                     manifest located at: {}",
629                    root.display()
630                ),
631            };
632            let extra = match *root_pkg {
633                MaybePackage::Virtual(_) => members_msg,
634                MaybePackage::Package(ref p) => {
635                    let has_members_list = match *p.manifest().workspace_config() {
636                        WorkspaceConfig::Root(ref root_config) => root_config.has_members_list(),
637                        WorkspaceConfig::Member { .. } => unreachable!(),
638                    };
639                    if !has_members_list {
640                        format!(
641                            "this may be fixable by ensuring that this \
642                             crate is depended on by the workspace \
643                             root: {}",
644                            root.display()
645                        )
646                    } else {
647                        members_msg
648                    }
649                }
650            };
651            failure::bail!(
652                "current package believes it's in a workspace when it's not:\n\
653                 current:   {}\n\
654                 workspace: {}\n\n{}",
655                self.current_manifest.display(),
656                root.display(),
657                extra
658            );
659        }
660
661        if let Some(ref root_manifest) = self.root_manifest {
662            for pkg in self
663                .members()
664                .filter(|p| p.manifest_path() != root_manifest)
665            {
666                let manifest = pkg.manifest();
667                let emit_warning = |what| -> CargoResult<()> {
668                    let msg = format!(
669                        "{} for the non root package will be ignored, \
670                         specify {} at the workspace root:\n\
671                         package:   {}\n\
672                         workspace: {}",
673                        what,
674                        what,
675                        pkg.manifest_path().display(),
676                        root_manifest.display(),
677                    );
678                    self.config.shell().warn(&msg)
679                };
680                if manifest.original().has_profiles() {
681                    emit_warning("profiles")?;
682                }
683                if !manifest.replace().is_empty() {
684                    emit_warning("replace")?;
685                }
686                if !manifest.patch().is_empty() {
687                    emit_warning("patch")?;
688                }
689            }
690        }
691
692        Ok(())
693    }
694
695    pub fn load(&self, manifest_path: &Path) -> CargoResult<Package> {
696        match self.packages.maybe_get(manifest_path) {
697            Some(&MaybePackage::Package(ref p)) => return Ok(p.clone()),
698            Some(&MaybePackage::Virtual(_)) => failure::bail!("cannot load workspace root"),
699            None => {}
700        }
701
702        let mut loaded = self.loaded_packages.borrow_mut();
703        if let Some(p) = loaded.get(manifest_path).cloned() {
704            return Ok(p);
705        }
706        let source_id = SourceId::for_path(manifest_path.parent().unwrap())?;
707        let (package, _nested_paths) = ops::read_package(manifest_path, source_id, self.config)?;
708        loaded.insert(manifest_path.to_path_buf(), package.clone());
709        Ok(package)
710    }
711
712    /// Preload the provided registry with already loaded packages.
713    ///
714    /// A workspace may load packages during construction/parsing/early phases
715    /// for various operations, and this preload step avoids doubly-loading and
716    /// parsing crates on the filesystem by inserting them all into the registry
717    /// with their in-memory formats.
718    pub fn preload(&self, registry: &mut PackageRegistry<'cfg>) {
719        // These can get weird as this generally represents a workspace during
720        // `cargo install`. Things like git repositories will actually have a
721        // `PathSource` with multiple entries in it, so the logic below is
722        // mostly just an optimization for normal `cargo build` in workspaces
723        // during development.
724        if self.is_ephemeral {
725            return;
726        }
727
728        for pkg in self.packages.packages.values() {
729            let pkg = match *pkg {
730                MaybePackage::Package(ref p) => p.clone(),
731                MaybePackage::Virtual(_) => continue,
732            };
733            let mut src = PathSource::new(
734                pkg.manifest_path(),
735                pkg.package_id().source_id(),
736                self.config,
737            );
738            src.preload_with(pkg);
739            registry.add_preloaded(Box::new(src));
740        }
741    }
742
743    pub fn emit_warnings(&self) -> CargoResult<()> {
744        for (path, maybe_pkg) in &self.packages.packages {
745            let warnings = match maybe_pkg {
746                MaybePackage::Package(pkg) => pkg.manifest().warnings().warnings(),
747                MaybePackage::Virtual(vm) => vm.warnings().warnings(),
748            };
749            let path = path.join("Cargo.toml");
750            for warning in warnings {
751                if warning.is_critical {
752                    let err = failure::format_err!("{}", warning.message);
753                    let cx =
754                        failure::format_err!("failed to parse manifest at `{}`", path.display());
755                    return Err(err.context(cx).into());
756                } else {
757                    let msg = if self.root_manifest.is_none() {
758                        warning.message.to_string()
759                    } else {
760                        // In a workspace, it can be confusing where a warning
761                        // originated, so include the path.
762                        format!("{}: {}", path.display(), warning.message)
763                    };
764                    self.config.shell().warn(msg)?
765                }
766            }
767        }
768        Ok(())
769    }
770}
771
772impl<'cfg> Packages<'cfg> {
773    fn get(&self, manifest_path: &Path) -> &MaybePackage {
774        self.maybe_get(manifest_path).unwrap()
775    }
776
777    fn maybe_get(&self, manifest_path: &Path) -> Option<&MaybePackage> {
778        self.packages.get(manifest_path.parent().unwrap())
779    }
780
781    fn load(&mut self, manifest_path: &Path) -> CargoResult<&MaybePackage> {
782        let key = manifest_path.parent().unwrap();
783        match self.packages.entry(key.to_path_buf()) {
784            Entry::Occupied(e) => Ok(e.into_mut()),
785            Entry::Vacant(v) => {
786                let source_id = SourceId::for_path(key)?;
787                let (manifest, _nested_paths) =
788                    read_manifest(manifest_path, source_id, self.config)?;
789                Ok(v.insert(match manifest {
790                    EitherManifest::Real(manifest) => {
791                        MaybePackage::Package(Package::new(manifest, manifest_path))
792                    }
793                    EitherManifest::Virtual(vm) => MaybePackage::Virtual(vm),
794                }))
795            }
796        }
797    }
798}
799
800impl<'a, 'cfg> Iterator for Members<'a, 'cfg> {
801    type Item = &'a Package;
802
803    fn next(&mut self) -> Option<&'a Package> {
804        loop {
805            let next = self.iter.next().map(|path| self.ws.packages.get(path));
806            match next {
807                Some(&MaybePackage::Package(ref p)) => return Some(p),
808                Some(&MaybePackage::Virtual(_)) => {}
809                None => return None,
810            }
811        }
812    }
813
814    fn size_hint(&self) -> (usize, Option<usize>) {
815        let (_, upper) = self.iter.size_hint();
816        (0, upper)
817    }
818}
819
820impl MaybePackage {
821    fn workspace_config(&self) -> &WorkspaceConfig {
822        match *self {
823            MaybePackage::Package(ref p) => p.manifest().workspace_config(),
824            MaybePackage::Virtual(ref vm) => vm.workspace_config(),
825        }
826    }
827}
828
829impl WorkspaceRootConfig {
830    /// Create a new Intermediate Workspace Root configuration.
831    pub fn new(
832        root_dir: &Path,
833        members: &Option<Vec<String>>,
834        default_members: &Option<Vec<String>>,
835        exclude: &Option<Vec<String>>,
836    ) -> WorkspaceRootConfig {
837        WorkspaceRootConfig {
838            root_dir: root_dir.to_path_buf(),
839            members: members.clone(),
840            default_members: default_members.clone(),
841            exclude: exclude.clone().unwrap_or_default(),
842        }
843    }
844
845    /// Checks the path against the `excluded` list.
846    ///
847    /// This method does NOT consider the `members` list.
848    fn is_excluded(&self, manifest_path: &Path) -> bool {
849        let excluded = self
850            .exclude
851            .iter()
852            .any(|ex| manifest_path.starts_with(self.root_dir.join(ex)));
853
854        let explicit_member = match self.members {
855            Some(ref members) => members
856                .iter()
857                .any(|mem| manifest_path.starts_with(self.root_dir.join(mem))),
858            None => false,
859        };
860
861        !explicit_member && excluded
862    }
863
864    fn has_members_list(&self) -> bool {
865        self.members.is_some()
866    }
867
868    fn members_paths(&self, globs: &[String]) -> CargoResult<Vec<PathBuf>> {
869        let mut expanded_list = Vec::new();
870
871        for glob in globs {
872            let pathbuf = self.root_dir.join(glob);
873            let expanded_paths = Self::expand_member_path(&pathbuf)?;
874
875            // If glob does not find any valid paths, then put the original
876            // path in the expanded list to maintain backwards compatibility.
877            if expanded_paths.is_empty() {
878                expanded_list.push(pathbuf);
879            } else {
880                expanded_list.extend(expanded_paths);
881            }
882        }
883
884        Ok(expanded_list)
885    }
886
887    fn expand_member_path(path: &Path) -> CargoResult<Vec<PathBuf>> {
888        let path = match path.to_str() {
889            Some(p) => p,
890            None => return Ok(Vec::new()),
891        };
892        let res =
893            glob(path).chain_err(|| failure::format_err!("could not parse pattern `{}`", &path))?;
894        let res = res
895            .map(|p| {
896                p.chain_err(|| failure::format_err!("unable to match path to pattern `{}`", &path))
897            })
898            .collect::<Result<Vec<_>, _>>()?;
899        Ok(res)
900    }
901}