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
use std::collections::BTreeSet;
use std::path::PathBuf;

use structopt::StructOpt;

use crate::installation::InstallationContext;
use crate::lockfile::{LockPackage, Lockfile};
use crate::manifest::Manifest;
use crate::package_id::PackageId;
use crate::package_source::{PackageSource, PackageSourceMap, Registry, TestRegistry};
use crate::resolution::resolve;

use super::GlobalOptions;

/// Install all of the dependencies of this project.
#[derive(Debug, StructOpt)]
pub struct InstallSubcommand {
    /// Path to the project to install dependencies for.
    #[structopt(long = "project-path", default_value = ".")]
    pub project_path: PathBuf,
}

impl InstallSubcommand {
    pub fn run(self, global: GlobalOptions) -> anyhow::Result<()> {
        let manifest = Manifest::load(&self.project_path)?;

        let lockfile = Lockfile::load(&self.project_path)?
            .unwrap_or_else(|| Lockfile::from_manifest(&manifest));

        let default_registry: Box<dyn PackageSource> = match &global.test_registry {
            Some(test_registry) => Box::new(TestRegistry::new(test_registry)),
            None => Box::new(Registry::from_registry_spec(&manifest.package.registry)?),
        };

        let package_sources = PackageSourceMap::new(default_registry);

        let mut try_to_use = BTreeSet::new();
        for package in lockfile.packages {
            match package {
                LockPackage::Registry(registry_package) => {
                    try_to_use.insert(PackageId::new(
                        registry_package.name,
                        registry_package.version,
                    ));
                }
                LockPackage::Git(_) => {}
            }
        }

        let resolved = resolve(&manifest, &try_to_use, &package_sources)?;

        let lockfile = Lockfile::from_resolve(&resolved);
        lockfile.save(&self.project_path)?;

        let root_package_id = PackageId::new(manifest.package.name, manifest.package.version);
        let installation = InstallationContext::new(&self.project_path);
        installation.clean()?;
        installation.install(&package_sources, root_package_id, &resolved)?;

        Ok(())
    }
}