Skip to main content

lux_cli/dist/
flat_archive.rs

1use std::{
2    io,
3    path::{Path, PathBuf},
4};
5
6use clap::Args;
7use lux_lib::{
8    build::BuildBehaviour,
9    config::{Config, ConfigBuilder},
10    drivers::install_packages::InstallPackages,
11    lockfile::LockedPackage,
12    lua_installation::LuaInstallation,
13    lua_rockspec::RemoteLuaRockspec,
14    lua_version::LuaVersion,
15    operations::{InstallProject, PackageInstallSpec},
16    package::{PackageName, PackageReq},
17    package_db::PackageDB,
18    pipeline::build_local::Build,
19    tree::{self, FlatDistTree, InstallTree},
20    workspace::Workspace,
21};
22
23use miette::{miette, IntoDiagnostic, Result, WrapErr};
24use path_slash::PathExt;
25use tempfile::{tempdir, TempDir};
26use tokio::fs::{self, File};
27use walkdir::WalkDir;
28use zip::{write::SimpleFileOptions, ZipWriter};
29
30use crate::{
31    args::{OutputFormat, PackageOrRockspec},
32    workspace::exists_matching_workspace_member,
33};
34
35#[derive(Args)]
36pub struct FlatArchive {
37    /// Path to a RockSpec or a package query for a package to distribute.{n}
38    /// Prioritises local projects if in a workspace, then installed rocks.{n}
39    /// If there is no matching workspace member or installed rock,{n}
40    /// a rock will be downloaded and installed to a temporary directory.{n}
41    /// In case of multiple matches, the latest version will be distributed.{n}
42    ///{n}
43    /// Examples:{n}
44    ///     - "pkg"{n}
45    ///     - "pkg@1.0.0"{n}
46    ///     - "pkg>=1.0.0"{n}
47    ///     - "/path/to/foo-1.0.0-1.rockspec"{n}
48    ///{n}
49    /// If not set, lux will attempt to distribute the current project.{n}
50    /// Must be set in multi-project workspaces.
51    #[clap(value_parser)]
52    pub(crate) package_or_rockspec: Option<PackageOrRockspec>,
53
54    /// The destination path. Defaults to '<cwd>/<package>-<version>.zip'.{n}
55    #[arg(short, long, visible_short_alias = 'd')]
56    destination: Option<PathBuf>,
57
58    #[clap(default_value_t=CompressionMethod::default())]
59    #[arg(short, long, value_enum, visible_short_alias = 'c')]
60    compression_method: CompressionMethod,
61
62    #[arg(long, default_value = "text", value_enum, ignore_case = true)]
63    output_format: OutputFormat,
64}
65
66#[derive(Clone, clap::ValueEnum, Default)]
67enum CompressionMethod {
68    /// Store the install tree as is
69    #[default]
70    Stored,
71    /// Compress the install tree using Deflate
72    Deflated,
73    /// Compress the install tree using BZIP2
74    Bzip2,
75    /// Compress the install tree using XZ
76    Xz,
77    /// Compress the install tree using `ZStandard`
78    Zstd,
79    /// Compress the install tree using LZMA
80    Lzma,
81}
82
83pub async fn dist_archive(args: FlatArchive, config: Config) -> Result<()> {
84    let staging_dir = tempdir().into_diagnostic()?;
85    let config = ConfigBuilder::from(config)
86        // Wrapping bin scripts does not make sense for distributed packages.
87        .wrap_bin_scripts(Some(false))
88        .user_tree(Some(staging_dir.path().to_path_buf()))
89        .build()?;
90
91    let (pkg, install_root) = match &args.package_or_rockspec {
92        None => install_project(None, &staging_dir, &config).await,
93        Some(PackageOrRockspec::Package(package_req))
94            if exists_matching_workspace_member(package_req)? =>
95        {
96            install_project(Some(package_req.name()), &staging_dir, &config).await
97        }
98        Some(PackageOrRockspec::Package(package)) => {
99            install_package(package, &staging_dir, &config).await
100        }
101        Some(PackageOrRockspec::RockSpec(rockspec_path)) => {
102            install_rockspec(rockspec_path, &staging_dir, &config).await
103        }
104    }?;
105
106    let destination = args
107        .destination
108        .clone()
109        .map(|dest| {
110            if dest.is_dir() {
111                dest.join(format!("{}-{}.zip", pkg.name(), pkg.version()))
112            } else {
113                dest
114            }
115        })
116        .unwrap_or(PathBuf::from(format!(
117            "{}-{}.zip",
118            pkg.name(),
119            pkg.version()
120        )));
121
122    zip_dir(&install_root, &destination, &args.compression_method).await?;
123
124    match args.output_format {
125        OutputFormat::Json => {
126            println!("{}", serde_json::to_string(&destination).into_diagnostic()?)
127        }
128        OutputFormat::Text => println!("Wrote archive to {}", destination.display()),
129    }
130
131    Ok(())
132}
133
134async fn install_project(
135    package: Option<&PackageName>,
136    staging_dir: &TempDir,
137    config: &Config,
138) -> Result<(LockedPackage, PathBuf)> {
139    let workspace = Workspace::current_or_err()?;
140    let project = match package {
141        Some(package) => workspace.select_member(package)?,
142        None => workspace.single_member()?,
143    };
144    let lua_version = project.lua_version(config)?;
145    let tree = FlatDistTree::new(staging_dir.path().to_path_buf(), lua_version, config)?;
146    Ok((
147        InstallProject::new()
148            .project(project)
149            .config(config)
150            .tree(&tree)
151            .build()
152            .await?,
153        tree.root(),
154    ))
155}
156
157async fn install_package(
158    package: &PackageReq,
159    staging_dir: &TempDir,
160    config: &Config,
161) -> Result<(LockedPackage, PathBuf)> {
162    let lua_version = LuaVersion::from(config)?.clone();
163    let tree = FlatDistTree::new(staging_dir.path().to_path_buf(), lua_version, config)?;
164    let packages = InstallPackages::new(config, &tree)
165        .package(
166            PackageInstallSpec::new(package.clone(), tree::EntryType::Entrypoint)
167                .build_behaviour(BuildBehaviour::Force)
168                .build(),
169        )
170        .package_db(PackageDB::from_config(config).await?)
171        .install()
172        .await?
173        .0;
174    let package = packages
175        .into_iter()
176        .find(|pkg| pkg.name() == package.name())
177        .ok_or_else(|| miette!("package was not installed"))?;
178    Ok((package, tree.root()))
179}
180
181async fn install_rockspec(
182    rockspec_path: &Path,
183    staging_dir: &TempDir,
184    config: &Config,
185) -> Result<(LockedPackage, PathBuf)> {
186    let content = tokio::fs::read_to_string(&rockspec_path)
187        .await
188        .into_diagnostic()?;
189    let lua_version = LuaVersion::from(config)?.clone();
190    let rockspec = match rockspec_path
191        .extension()
192        .map(|ext| ext.to_string_lossy().to_string())
193        .unwrap_or("".into())
194        .as_str()
195    {
196        "rockspec" => Ok(RemoteLuaRockspec::new(&content)?),
197        _ => Err(miette!(
198            help = "for example '/path/to/package-1.0.0-1.rockpec' or package@1.0.0",
199            "expected a path to a .rockspec or a package requirement."
200        )),
201    }?;
202    let lua = LuaInstallation::new(&lua_version, config).await?;
203    let tree = FlatDistTree::new(staging_dir.path().to_path_buf(), lua_version, config)?;
204    let package = Build::new()
205        .rockspec(&rockspec)
206        .lua(&lua)
207        .tree(&tree)
208        .entry_type(tree::EntryType::Entrypoint)
209        .config(config)
210        .behaviour(BuildBehaviour::Force)
211        .build()
212        .await?;
213    Ok((package, tree.root()))
214}
215
216async fn zip_dir(src_dir: &Path, dest_file: &Path, method: &CompressionMethod) -> Result<()> {
217    if dest_file.exists() {
218        return Err(miette!("File {} already exists!", dest_file.display()));
219    }
220    let temp_archive = PathBuf::from(format!("{}.part", dest_file.display()));
221    let archive = File::create(&temp_archive)
222        .await
223        .into_diagnostic()?
224        .into_std()
225        .await;
226    let walkdir = WalkDir::new(src_dir);
227    let mut zip = ZipWriter::new(archive);
228
229    let compression_method = match method {
230        CompressionMethod::Stored => zip::CompressionMethod::Stored,
231        CompressionMethod::Deflated => zip::CompressionMethod::Deflated,
232        CompressionMethod::Bzip2 => zip::CompressionMethod::Bzip2,
233        CompressionMethod::Xz => zip::CompressionMethod::Xz,
234        CompressionMethod::Zstd => zip::CompressionMethod::Zstd,
235        CompressionMethod::Lzma => zip::CompressionMethod::Lzma,
236    };
237
238    #[cfg(target_family = "unix")]
239    let options = SimpleFileOptions::default()
240        .compression_method(compression_method)
241        .unix_permissions(0o755);
242
243    #[cfg(target_family = "windows")]
244    let options = SimpleFileOptions::default().compression_method(compression_method);
245
246    for entry_result in walkdir.into_iter() {
247        let entry = entry_result.map_err(|err| {
248            miette!(
249                help = format!("ensure the path to '{}' is accessible", src_dir.display()),
250                "error while traversing directory '{}': {}.",
251                src_dir.display(),
252                err,
253            )
254        })?;
255        let path = entry.path();
256        let relative_path = path.strip_prefix(src_dir).into_diagnostic()?;
257        let relative_path_str = relative_path.to_slash_lossy().to_string();
258        if path.is_file() {
259            zip.start_file(relative_path_str, options)
260                .into_diagnostic()?;
261            let mut f = File::open(path).await.into_diagnostic()?.into_std().await;
262            io::copy(&mut f, &mut zip).into_diagnostic()?;
263        } else if !relative_path.as_os_str().is_empty() {
264            zip.add_directory(relative_path_str, options)
265                .into_diagnostic()?;
266        }
267    }
268    zip.finish().into_diagnostic()?;
269    fs::rename(&temp_archive, &dest_file)
270        .await
271        .into_diagnostic()
272        .wrap_err(format!(
273            "Error renaming {} to {}",
274            temp_archive.display(),
275            dest_file.display()
276        ))?;
277    Ok(())
278}