Skip to main content

lux_cli/
uninstall.rs

1use clap::Args;
2use inquire::Confirm;
3use itertools::Itertools;
4use lux_lib::{
5    build::BuildBehaviour,
6    config::Config,
7    drivers::install_packages::InstallPackages,
8    lockfile::LockedPackageId,
9    lua_version::LuaVersion,
10    operations::{self, PackageInstallSpec},
11    package::PackageReq,
12    package_db::PackageDB,
13    tree::{self, InstallTree, RockMatches, TreeError},
14};
15
16use miette::{miette, IntoDiagnostic, Result};
17
18#[derive(Args)]
19pub struct Uninstall {
20    /// The package or packages to uninstall from the system.
21    packages: Vec<PackageReq>,
22}
23
24/// Uninstall one or multiple rocks from the user tree
25pub async fn uninstall(uninstall_args: Uninstall, config: Config) -> Result<()> {
26    let tree = config.user_tree(LuaVersion::from(&config)?.clone())?;
27
28    let package_matches = uninstall_args
29        .packages
30        .iter()
31        .map(|package_req| tree.match_rocks(package_req))
32        .try_collect::<_, Vec<_>, TreeError>()?;
33
34    let (packages, nonexistent_packages, duplicate_packages) = package_matches.into_iter().fold(
35        (Vec::new(), Vec::new(), Vec::new()),
36        |(mut p, mut n, mut d), rock_match| {
37            match rock_match {
38                RockMatches::NotFound(req) => n.push(req),
39                RockMatches::Single(package) => p.push(package),
40                RockMatches::Many(packages) => d.extend(packages),
41            };
42
43            (p, n, d)
44        },
45    );
46
47    if !nonexistent_packages.is_empty() {
48        // TODO(vhyrro): Render this in the form of a tree.
49        return Err(miette!(
50            "The following packages were not found: {:#?}",
51            nonexistent_packages
52        ));
53    }
54
55    if !duplicate_packages.is_empty() {
56        return Err(miette!(
57            help = r#"specify the exact package to uninstall:
58> lux uninstall '<name>@<version>'
59"#,
60            r#"
61multiple packages satisfying your version requirements were found:
62{:#?}
63"#,
64            duplicate_packages,
65        ));
66    }
67
68    let lockfile = tree.lockfile()?;
69    let non_entrypoints = packages
70        .iter()
71        .filter_map(|pkg_id| {
72            if lockfile.is_entrypoint(pkg_id) {
73                None
74            } else {
75                Some(unsafe { lockfile.get_unchecked(pkg_id) }.name().to_string())
76            }
77        })
78        .collect_vec();
79    if !non_entrypoints.is_empty() {
80        return Err(miette!(
81            r#"cannot uninstall dependencies:
82{:#?}
83"#,
84            non_entrypoints,
85        ));
86    }
87
88    let (dependencies, entrypoints): (Vec<LockedPackageId>, Vec<LockedPackageId>) = packages
89        .iter()
90        .cloned()
91        .partition(|pkg_id| lockfile.is_dependency(pkg_id));
92
93    if dependencies.is_empty() {
94        operations::Uninstall::new()
95            .config(&config)
96            .packages(entrypoints)
97            .remove()
98            .await?;
99    } else {
100        let package_names = dependencies
101            .iter()
102            .map(|pkg_id| unsafe { lockfile.get_unchecked(pkg_id) }.name().to_string())
103            .collect_vec();
104        let prompt = if package_names.len() == 1 {
105            format!(
106                "
107            Package {} can be removed from the entrypoints, but it is also a dependency, so it will have to be reinstalled.
108Reinstall?
109            ",
110                package_names[0]
111            )
112        } else {
113            format!(
114                "
115            The following packages can be removed from the entrypoints, but are also dependencies:
116{package_names:#?}
117
118They will have to be reinstalled.
119Reinstall?
120            ",
121            )
122        };
123        if !config.no_prompt()
124            && Confirm::new(&prompt)
125                .with_default(false)
126                .prompt()
127                .into_diagnostic()
128                .map_err(|_| miette!("error prompting for reinstall"))?
129        {
130            operations::Uninstall::new()
131                .config(&config)
132                .packages(entrypoints)
133                .remove()
134                .await?;
135
136            let reinstall_specs = dependencies
137                .iter()
138                .map(|pkg_id| {
139                    let package = unsafe { lockfile.get_unchecked(pkg_id) };
140                    PackageInstallSpec::new(
141                        package.clone().into_package_req(),
142                        tree::EntryType::DependencyOnly,
143                    )
144                    .build_behaviour(BuildBehaviour::Force)
145                    .pin(package.pinned())
146                    .opt(package.opt())
147                    .constraint(package.constraint())
148                    .build()
149                })
150                .collect_vec();
151            operations::Uninstall::new()
152                .config(&config)
153                .packages(dependencies)
154                .remove()
155                .await?;
156            InstallPackages::new(&config, &tree)
157                .package_db(PackageDB::from_config(&config).await?)
158                .packages(reinstall_specs)
159                .install()
160                .await?;
161        } else {
162            return Err(miette!("operation cancelled"));
163        }
164    };
165
166    let mut has_dangling_rocks = true;
167    while has_dangling_rocks {
168        let tree = config.user_tree(LuaVersion::from(&config)?.clone())?;
169        let lockfile = tree.lockfile()?;
170        let dangling_rocks = lockfile
171            .rocks()
172            .keys()
173            .filter(|pkg_id| !lockfile.is_entrypoint(pkg_id) && !lockfile.is_dependency(pkg_id))
174            .cloned()
175            .collect_vec();
176        if dangling_rocks.is_empty() {
177            has_dangling_rocks = false
178        } else {
179            operations::Uninstall::new()
180                .config(&config)
181                .packages(dangling_rocks)
182                .remove()
183                .await?;
184        }
185    }
186
187    Ok(())
188}