Skip to main content

lux_cli/
pack.rs

1use lux_lib::package;
2use std::path::{Path, PathBuf};
3
4use crate::{args::PackageOrRockspec, build, workspace::exists_matching_workspace_member};
5use clap::Args;
6use itertools::Itertools;
7use lux_lib::{
8    build::BuildBehaviour,
9    config::Config,
10    drivers::install_packages::InstallPackages,
11    lua_installation::LuaInstallation,
12    lua_rockspec::RemoteLuaRockspec,
13    lua_version::LuaVersion,
14    operations::{self, PackageInstallSpec},
15    package_db::PackageDB,
16    pipeline::build_local::Build,
17    rockspec::Rockspec as _,
18    tree::{self, InstallTree},
19    workspace::Workspace,
20};
21use miette::{miette, IntoDiagnostic, Result};
22use path_slash::PathBufExt;
23use tempfile::tempdir;
24
25#[derive(Args)]
26pub struct Pack {
27    /// Path to a RockSpec or a package query for a package to pack.{n}
28    /// Prioritises local projects if in a workspace, then installed rocks.{n}
29    /// If there is no matching workspace member or installed rock,{n}
30    /// a rock will be downloaded and installed to a temporary directory.{n}
31    /// In case of multiple matches, the latest version will be packed.{n}
32    ///{n}
33    /// Examples:{n}
34    ///     - "pkg"{n}
35    ///     - "pkg@1.0.0"{n}
36    ///     - "pkg>=1.0.0"{n}
37    ///     - "/path/to/foo-1.0.0-1.rockspec"{n}
38    ///{n}
39    /// If not set, lux will attempt to pack either all workspace members{n}
40    /// or the current project.{n}
41    /// To pack a project, lux must be able to generate a release or dev RockSpec.{n}
42    #[clap(value_parser)]
43    pub(crate) package_or_rockspec: Option<PackageOrRockspec>,
44}
45
46async fn pack_workspace(
47    member: Option<&package::Name>,
48    dest_dir: &Path,
49    config: &Config,
50) -> Result<Vec<PathBuf>> {
51    let workspace = Workspace::current_or_err()?;
52
53    // luarocks expects a `<package>-<version>.rockspec` in the package root,
54    // so we add a guard that it can be created here.
55    let packages = match member {
56        // Pack only the provided workspace member
57        Some(package_name) => {
58            let project = workspace.select_member(package_name)?;
59            project
60                .toml()
61                .into_remote(None)?
62                .to_lua_remote_rockspec_string()?;
63
64            let mut build = build::Build::default();
65            build.package = Some(package_name.clone());
66            build::build(build, config.clone())
67                .await?
68                .into_iter()
69                .filter(|package| package.name() == package_name)
70                .collect_vec()
71        }
72        // Pack all workspace members
73        None => {
74            for project in workspace.members() {
75                project
76                    .toml()
77                    .into_remote(None)?
78                    .to_lua_remote_rockspec_string()?;
79            }
80            build::build(build::Build::default(), config.clone())
81                .await?
82                .into_iter()
83                .filter(|package| {
84                    workspace
85                        .members()
86                        .iter()
87                        .any(|member| member.toml().package() == package.name())
88                })
89                .collect_vec()
90        }
91    };
92
93    if packages.is_empty() {
94        return Err(miette!("build did not produce a package"));
95    }
96
97    let mut rock_paths = Vec::new();
98    for package in packages {
99        let tree = workspace.tree(config)?;
100        let rock_path = operations::Pack::new(dest_dir.to_path_buf(), tree, package)
101            .pack()
102            .await?;
103        rock_paths.push(rock_path);
104    }
105
106    Ok(rock_paths)
107}
108
109pub async fn pack(args: Pack, config: Config) -> Result<()> {
110    let lua_version = LuaVersion::from(&config)?.clone();
111    let dest_dir = std::env::current_dir().into_diagnostic()?;
112    let rock_paths: Vec<PathBuf> = match args.package_or_rockspec {
113        Some(PackageOrRockspec::Package(package_req))
114            if exists_matching_workspace_member(&package_req)? =>
115        {
116            pack_workspace(Some(package_req.name()), &dest_dir, &config).await
117        }
118        Some(PackageOrRockspec::Package(package_req)) => {
119            let user_tree = config.user_tree(lua_version.clone())?;
120            match user_tree.match_rocks(&package_req)? {
121                lux_lib::tree::RockMatches::NotFound(_) => {
122                    let temp_dir = tempdir().into_diagnostic()?;
123                    let temp_config = config.with_tree(temp_dir.path().to_path_buf());
124                    let tree = temp_config.user_tree(lua_version.clone())?;
125                    let packages = InstallPackages::new(&temp_config, &tree)
126                        .package(
127                            PackageInstallSpec::new(package_req, tree::EntryType::Entrypoint)
128                                .build_behaviour(BuildBehaviour::Force)
129                                .build(),
130                        )
131                        .package_db(PackageDB::from_config(&temp_config).await?)
132                        .install()
133                        .await?
134                        .0;
135                    let package = packages
136                        .first()
137                        .ok_or_else(|| miette!("no packages installed"))?;
138                    let rock_path = operations::Pack::new(dest_dir, tree, package.clone())
139                        .pack()
140                        .await?;
141                    Ok(vec![rock_path])
142                }
143                lux_lib::tree::RockMatches::Single(local_package_id) => {
144                    let lockfile = user_tree.lockfile()?;
145                    let package = lockfile.get(&local_package_id).ok_or_else(|| {
146                        miette!("package is installed, but was not found in the lockfile")
147                    })?;
148                    let rock_path = operations::Pack::new(dest_dir, user_tree, package.clone())
149                        .pack()
150                        .await?;
151                    Ok(vec![rock_path])
152                }
153                lux_lib::tree::RockMatches::Many(vec) => {
154                    let local_package_id = vec.first();
155                    let lockfile = user_tree.lockfile()?;
156                    let package = lockfile.get(local_package_id).ok_or_else(|| {
157                        miette!(
158                            "multiple package installations found, but not found in the lockfile"
159                        )
160                    })?;
161                    let rock_path = operations::Pack::new(dest_dir, user_tree, package.clone())
162                        .pack()
163                        .await?;
164                    Ok(vec![rock_path])
165                }
166            }
167        }
168        Some(PackageOrRockspec::RockSpec(rockspec_path)) => {
169            let content = tokio::fs::read_to_string(&rockspec_path)
170                .await
171                .into_diagnostic()?;
172            let rockspec = match rockspec_path
173                .extension()
174                .map(|ext| ext.to_string_lossy().to_string())
175                .unwrap_or("".into())
176                .as_str()
177            {
178                "rockspec" => Ok(RemoteLuaRockspec::new(&content)?),
179                _ => Err(miette!(
180                    "expected a path to a .rockspec or a package requirement."
181                )),
182            }?;
183            let temp_dir = tempdir().into_diagnostic()?;
184            let config = config.with_tree(temp_dir.path().to_path_buf());
185            let lua = LuaInstallation::new(&lua_version, &config).await?;
186            let tree = config.user_tree(lua_version)?;
187            let package = Build::new()
188                .rockspec(&rockspec)
189                .lua(&lua)
190                .tree(&tree)
191                .entry_type(tree::EntryType::Entrypoint)
192                .config(&config)
193                .behaviour(BuildBehaviour::Force)
194                .build()
195                .await?;
196            let rock_path = operations::Pack::new(dest_dir, tree, package)
197                .pack()
198                .await?;
199            Ok(vec![rock_path])
200        }
201        None => pack_workspace(None, &dest_dir, &config).await,
202    }?;
203
204    if rock_paths.len() > 1 {
205        let rock_paths = rock_paths
206            .iter()
207            .map(|path| path.to_slash_lossy().to_string())
208            .join("\n");
209        print!("packed rocks created at\n{}", rock_paths)
210    } else {
211        rock_paths
212            .first()
213            .iter()
214            .for_each(|path| print!("packed rock created at {}", path.display()));
215    }
216    Ok(())
217}