Skip to main content

lux_cli/dist/
flat_archive.rs

1use lux_lib::package;
2use lux_lib::rockspec;
3use std::{
4    collections::BTreeMap,
5    io,
6    path::{Path, PathBuf},
7};
8
9use clap::Args;
10use lux_lib::{
11    build,
12    config::{self, Config},
13    drivers::InstallPackages,
14    lockfile::LockedPackage,
15    lua, operations,
16    operations::install,
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 = config::Builder::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, tree) = 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    let install_root = tree.root();
106
107    if tree.version() == &lua::Version::Luau {
108        write_luaurc(&tree).await?;
109    }
110
111    let destination = args
112        .destination
113        .clone()
114        .map(|dest| {
115            if dest.is_dir() {
116                dest.join(format!("{}-{}.zip", pkg.name(), pkg.version()))
117            } else {
118                dest
119            }
120        })
121        .unwrap_or(PathBuf::from(format!(
122            "{}-{}.zip",
123            pkg.name(),
124            pkg.version()
125        )));
126
127    zip_dir(&install_root, &destination, &args.compression_method).await?;
128
129    match args.output_format {
130        OutputFormat::Json => {
131            println!("{}", serde_json::to_string(&destination).into_diagnostic()?)
132        }
133        OutputFormat::Text => println!("Wrote archive to {}", destination.display()),
134    }
135
136    Ok(())
137}
138
139async fn install_project(
140    package: Option<&package::Name>,
141    staging_dir: &TempDir,
142    config: &Config,
143) -> Result<(LockedPackage, FlatDistTree)> {
144    let workspace = Workspace::current_or_err()?;
145    let project = match package {
146        Some(package) => workspace.select_member(package)?,
147        None => workspace.single_member()?,
148    };
149    let lua_version = project.lua_version(config)?;
150    let tree = FlatDistTree::new(staging_dir.path().to_path_buf(), lua_version, config)?;
151    let pkg = operations::InstallProject::new()
152        .project(project)
153        .config(config)
154        .tree(&tree)
155        .build()
156        .await?;
157    Ok((pkg, tree))
158}
159
160async fn install_package(
161    package: &package::Req,
162    staging_dir: &TempDir,
163    config: &Config,
164) -> Result<(LockedPackage, FlatDistTree)> {
165    let lua_version = lua::Version::from(config)?.clone();
166    let tree = FlatDistTree::new(staging_dir.path().to_path_buf(), lua_version, config)?;
167    let packages = InstallPackages::new(config, &tree)
168        .package(
169            install::Spec::new(package.clone(), tree::EntryType::Entrypoint)
170                .build_behaviour(build::Behaviour::Force)
171                .build(),
172        )
173        .package_db(PackageDB::from_config(config).await?)
174        .install()
175        .await?
176        .0;
177    let package = packages
178        .into_iter()
179        .find(|pkg| pkg.name() == package.name())
180        .ok_or_else(|| miette!("package was not installed"))?;
181    Ok((package, tree))
182}
183
184async fn install_rockspec(
185    rockspec_path: &Path,
186    staging_dir: &TempDir,
187    config: &Config,
188) -> Result<(LockedPackage, FlatDistTree)> {
189    let content = tokio::fs::read_to_string(&rockspec_path)
190        .await
191        .into_diagnostic()?;
192    let lua_version = lua::Version::from(config)?.clone();
193    let rockspec = match rockspec_path
194        .extension()
195        .map(|ext| ext.to_string_lossy().to_string())
196        .unwrap_or("".into())
197        .as_str()
198    {
199        "rockspec" => Ok(rockspec::lua::Remote::new(&content)?),
200        _ => Err(miette!(
201            help = "for example '/path/to/package-1.0.0-1.rockpec' or package@1.0.0",
202            "expected a path to a .rockspec or a package requirement."
203        )),
204    }?;
205    let lua = lua::Installation::new(&lua_version, config).await?;
206    let tree = FlatDistTree::new(staging_dir.path().to_path_buf(), lua_version, config)?;
207    let package = Build::new()
208        .rockspec(&rockspec)
209        .lua(&lua)
210        .tree(&tree)
211        .entry_type(tree::EntryType::Entrypoint)
212        .config(config)
213        .behaviour(build::Behaviour::Force)
214        .build()
215        .await?;
216    Ok((package, tree))
217}
218
219async fn write_luaurc(tree: &FlatDistTree) -> Result<()> {
220    let aliases = tree
221        .list()?
222        .keys()
223        .map(|name| (name.to_string(), "./lua".into()))
224        .collect::<BTreeMap<String, String>>();
225    let content = serde_json::to_string_pretty(&serde_json::json!({ "aliases": aliases }))
226        .into_diagnostic()?;
227    fs::write(tree.root().join(".luaurc"), content)
228        .await
229        .into_diagnostic()?;
230    Ok(())
231}
232
233async fn zip_dir(src_dir: &Path, dest_file: &Path, method: &CompressionMethod) -> Result<()> {
234    if dest_file.exists() {
235        return Err(miette!("File {} already exists!", dest_file.display()));
236    }
237    let temp_archive = PathBuf::from(format!("{}.part", dest_file.display()));
238    let archive = File::create(&temp_archive)
239        .await
240        .into_diagnostic()?
241        .into_std()
242        .await;
243    let walkdir = WalkDir::new(src_dir);
244    let mut zip = ZipWriter::new(archive);
245
246    let compression_method = match method {
247        CompressionMethod::Stored => zip::CompressionMethod::Stored,
248        CompressionMethod::Deflated => zip::CompressionMethod::Deflated,
249        CompressionMethod::Bzip2 => zip::CompressionMethod::Bzip2,
250        CompressionMethod::Xz => zip::CompressionMethod::Xz,
251        CompressionMethod::Zstd => zip::CompressionMethod::Zstd,
252        CompressionMethod::Lzma => zip::CompressionMethod::Lzma,
253    };
254
255    #[cfg(target_family = "unix")]
256    let options = SimpleFileOptions::default()
257        .compression_method(compression_method)
258        .unix_permissions(0o755);
259
260    #[cfg(target_family = "windows")]
261    let options = SimpleFileOptions::default().compression_method(compression_method);
262
263    for entry_result in walkdir.into_iter() {
264        let entry = entry_result.map_err(|err| {
265            miette!(
266                help = format!("ensure the path to '{}' is accessible", src_dir.display()),
267                "error while traversing directory '{}': {}.",
268                src_dir.display(),
269                err,
270            )
271        })?;
272        let path = entry.path();
273        let relative_path = path.strip_prefix(src_dir).into_diagnostic()?;
274        let relative_path_str = relative_path.to_slash_lossy().to_string();
275        if path.is_file() {
276            zip.start_file(relative_path_str, options)
277                .into_diagnostic()?;
278            let mut f = File::open(path).await.into_diagnostic()?.into_std().await;
279            io::copy(&mut f, &mut zip).into_diagnostic()?;
280        } else if !relative_path.as_os_str().is_empty() {
281            zip.add_directory(relative_path_str, options)
282                .into_diagnostic()?;
283        }
284    }
285    zip.finish().into_diagnostic()?;
286    fs::rename(&temp_archive, &dest_file)
287        .await
288        .into_diagnostic()
289        .wrap_err(format!(
290            "Error renaming {} to {}",
291            temp_archive.display(),
292            dest_file.display()
293        ))?;
294    Ok(())
295}