Skip to main content

lux_cli/dist/
flat_archive.rs

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