Skip to main content

lux_cli/
add.rs

1use itertools::{Either, Itertools};
2use lux_lib::{
3    config::Config,
4    package::PackageName,
5    remote_package_db::RemotePackageDB,
6    rockspec::lua_dependency::{self},
7    workspace::Workspace,
8};
9
10use miette::Result;
11
12use crate::workspace::{sync_dependencies_if_locked, PackageReqOrGitShorthand};
13
14#[derive(clap::Args)]
15pub struct Add {
16    /// Package or list of packages to install and add to the project's dependencies. {n}
17    /// Examples: "pkg", "pkg@1.0.0", "pkg>=1.0.0" {n}
18    /// If you do not specify a version requirement, lux will fetch the latest version. {n}
19    /// {n}
20    /// You can also specify git packages by providing a git URL shorthand. {n}
21    /// Example: "github:owner/repo" {n}
22    /// Supported git host prefixes are: "github:", "gitlab:", "sourcehut:" and "codeberg:". {n}
23    /// Lux will automatically fetch the latest SemVer tag or commit SHA if no SemVer tag is found. {n}
24    /// Note that projects with git dependencies cannot be published to luarocks.org.
25    package_req: Vec<PackageReqOrGitShorthand>,
26
27    /// Reinstall without prompt if a package is already installed.
28    #[arg(long, visible_short_alias = 'f')]
29    force: bool,
30
31    /// Install the package as a development dependency. {n}
32    /// Also called `dev`.
33    #[arg(short, long, alias = "dev", visible_short_aliases = ['d', 'b'])]
34    build: Option<Vec<PackageReqOrGitShorthand>>,
35
36    /// Install the package as a test dependency.
37    #[arg(short, long, visible_short_alias = 't')]
38    test: Option<Vec<PackageReqOrGitShorthand>>,
39
40    /// Project to modify.
41    #[arg(short, long, visible_short_alias = 'p')]
42    pub(crate) package: Option<PackageName>,
43}
44
45pub async fn add(data: Add, config: Config) -> Result<()> {
46    let mut workspace = Workspace::current_or_err()?;
47    let project = workspace.single_member_or_select_mut(&data.package)?;
48    let db = RemotePackageDB::from_config(&config).await?;
49
50    let (dependencies, git_dependencies): (Vec<_>, Vec<_>) =
51        data.package_req.iter().partition_map(|req| match req {
52            PackageReqOrGitShorthand::PackageReq(req) => Either::Left(req.clone()),
53            PackageReqOrGitShorthand::GitShorthand(url) => Either::Right(url.clone()),
54        });
55
56    if !data.package_req.is_empty() {
57        project
58            .add(
59                lua_dependency::DependencyType::Regular(dependencies.iter().collect()),
60                &db,
61            )
62            .await?;
63        project
64            .add_git(
65                lua_dependency::LuaDependencyType::Regular(git_dependencies.iter().collect()),
66                &config,
67            )
68            .await?;
69    }
70
71    let build_packages = data.build.unwrap_or_default();
72    if !build_packages.is_empty() {
73        let (dependencies, git_dependencies): (Vec<_>, Vec<_>) =
74            build_packages.iter().partition_map(|req| match req {
75                PackageReqOrGitShorthand::PackageReq(req) => Either::Left(req.clone()),
76                PackageReqOrGitShorthand::GitShorthand(url) => Either::Right(url.clone()),
77            });
78        project
79            .add(
80                lua_dependency::DependencyType::Build(dependencies.iter().collect()),
81                &db,
82            )
83            .await?;
84        project
85            .add_git(
86                lua_dependency::LuaDependencyType::Build(git_dependencies.iter().collect()),
87                &config,
88            )
89            .await?;
90    }
91
92    let test_packages = data.test.unwrap_or_default();
93    if !test_packages.is_empty() {
94        let (dependencies, git_dependencies): (Vec<_>, Vec<_>) =
95            test_packages.iter().partition_map(|req| match req {
96                PackageReqOrGitShorthand::PackageReq(req) => Either::Left(req.clone()),
97                PackageReqOrGitShorthand::GitShorthand(url) => Either::Right(url.clone()),
98            });
99        project
100            .add(
101                lua_dependency::DependencyType::Test(dependencies.iter().collect()),
102                &db,
103            )
104            .await?;
105        project
106            .add_git(
107                lua_dependency::LuaDependencyType::Test(git_dependencies.iter().collect()),
108                &config,
109            )
110            .await?;
111    }
112
113    sync_dependencies_if_locked(&workspace, &config).await?;
114
115    Ok(())
116}
117
118#[cfg(test)]
119mod tests {
120    use assert_fs::{prelude::PathCopy, TempDir};
121    use lux_lib::config::ConfigBuilder;
122    use serial_test::serial;
123
124    use super::*;
125    use std::path::PathBuf;
126
127    #[serial]
128    #[tokio::test]
129    async fn test_add_regular_dependencies() {
130        if std::env::var("LUX_SKIP_IMPURE_TESTS").unwrap_or("0".into()) == "1" {
131            println!("Skipping impure test");
132            return;
133        }
134        let sample_project =
135            PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("resources/test/sample-projects/init/");
136        let project_root = TempDir::new().unwrap();
137        project_root.copy_from(&sample_project, &["**"]).unwrap();
138        let cwd = std::env::current_dir().unwrap();
139        std::env::set_current_dir(&project_root).unwrap();
140        let config = ConfigBuilder::new().unwrap().build().unwrap();
141        let args = Add {
142            package: None,
143            package_req: vec!["penlight@1.5".parse().unwrap()],
144            force: false,
145            build: Option::None,
146            test: Option::None,
147        };
148        add(args, config.clone()).await.unwrap();
149        let lockfile_path = project_root.join("lux.lock");
150        let lockfile_content =
151            String::from_utf8(tokio::fs::read(&lockfile_path).await.unwrap()).unwrap();
152        assert!(lockfile_content.contains("penlight"));
153        assert!(lockfile_content.contains("luafilesystem")); // dependency
154
155        let args = Add {
156            package: None,
157            package_req: vec!["md5".parse().unwrap()],
158            force: false,
159            build: Option::None,
160            test: Option::None,
161        };
162        add(args, config.clone()).await.unwrap();
163        let lockfile_path = project_root.join("lux.lock");
164        let lockfile_content =
165            String::from_utf8(tokio::fs::read(&lockfile_path).await.unwrap()).unwrap();
166        assert!(lockfile_content.contains("penlight"));
167        assert!(lockfile_content.contains("luafilesystem"));
168        assert!(lockfile_content.contains("md5"));
169
170        std::env::set_current_dir(&cwd).unwrap();
171    }
172
173    #[serial]
174    #[tokio::test]
175    async fn test_add_build_dependencies() {
176        if std::env::var("LUX_SKIP_IMPURE_TESTS").unwrap_or("0".into()) == "1" {
177            println!("Skipping impure test");
178            return;
179        }
180        let sample_project =
181            PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("resources/test/sample-projects/init/");
182        let project_root = TempDir::new().unwrap();
183        project_root.copy_from(&sample_project, &["**"]).unwrap();
184        let cwd = std::env::current_dir().unwrap();
185        std::env::set_current_dir(&project_root).unwrap();
186        let config = ConfigBuilder::new().unwrap().build().unwrap();
187        let args = Add {
188            package: None,
189            package_req: Vec::new(),
190            force: false,
191            build: Option::Some(vec!["penlight@1.5".parse().unwrap()]),
192            test: Option::None,
193        };
194        add(args, config.clone()).await.unwrap();
195        let lockfile_path = project_root.join("lux.lock");
196        let lockfile_content =
197            String::from_utf8(tokio::fs::read(&lockfile_path).await.unwrap()).unwrap();
198        assert!(lockfile_content.contains("penlight"));
199        assert!(lockfile_content.contains("luafilesystem")); // dependency
200
201        let args = Add {
202            package: None,
203            package_req: Vec::new(),
204            force: false,
205            build: Option::Some(vec!["md5".parse().unwrap()]),
206            test: Option::None,
207        };
208        add(args, config.clone()).await.unwrap();
209        let lockfile_path = project_root.join("lux.lock");
210        let lockfile_content =
211            String::from_utf8(tokio::fs::read(&lockfile_path).await.unwrap()).unwrap();
212        assert!(lockfile_content.contains("penlight"));
213        assert!(lockfile_content.contains("luafilesystem"));
214        assert!(lockfile_content.contains("md5"));
215
216        std::env::set_current_dir(&cwd).unwrap();
217    }
218
219    #[serial]
220    #[tokio::test]
221    async fn test_add_test_dependencies() {
222        if std::env::var("LUX_SKIP_IMPURE_TESTS").unwrap_or("0".into()) == "1" {
223            println!("Skipping impure test");
224            return;
225        }
226        let sample_project =
227            PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("resources/test/sample-projects/init/");
228        let project_root = TempDir::new().unwrap();
229        project_root.copy_from(&sample_project, &["**"]).unwrap();
230        let cwd = std::env::current_dir().unwrap();
231        std::env::set_current_dir(&project_root).unwrap();
232        let config = ConfigBuilder::new().unwrap().build().unwrap();
233        let args = Add {
234            package: None,
235            package_req: Vec::new(),
236            force: false,
237            build: Option::None,
238            test: Option::Some(vec!["penlight@1.5".parse().unwrap()]),
239        };
240        add(args, config.clone()).await.unwrap();
241        let lockfile_path = project_root.join("lux.lock");
242        let lockfile_content =
243            String::from_utf8(tokio::fs::read(&lockfile_path).await.unwrap()).unwrap();
244        assert!(lockfile_content.contains("penlight"));
245        assert!(lockfile_content.contains("luafilesystem")); // dependency
246
247        let args = Add {
248            package: None,
249            package_req: Vec::new(),
250            force: false,
251            build: Option::None,
252            test: Option::Some(vec!["md5".parse().unwrap()]),
253        };
254        add(args, config.clone()).await.unwrap();
255        let lockfile_path = project_root.join("lux.lock");
256        let lockfile_content =
257            String::from_utf8(tokio::fs::read(&lockfile_path).await.unwrap()).unwrap();
258        assert!(lockfile_content.contains("penlight"));
259        assert!(lockfile_content.contains("luafilesystem"));
260        assert!(lockfile_content.contains("md5"));
261
262        std::env::set_current_dir(&cwd).unwrap();
263    }
264}