Skip to main content

lux_cli/dist/
flat_archive.rs

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