Skip to main content

lux_cli/dist/
bin.rs

1use lux_lib::package;
2use std::path::PathBuf;
3
4use clap::Args;
5use lux_lib::{
6    config::{Config, ConfigBuilder},
7    lua_version::LuaVersion,
8    operations::DistProjectBin,
9    tree::FlatDistTree,
10    workspace::Workspace,
11};
12use miette::{miette, IntoDiagnostic, Result};
13use tempfile::tempdir;
14
15use crate::args::OutputFormat;
16
17#[derive(Args)]
18pub struct Bin {
19    /// Output path for the compiled binary.{n}
20    /// Defaults to `<package>[.exe]` in the current directory.
21    #[arg(short, long, visible_short_alias = 'o')]
22    pub output: Option<PathBuf>,
23
24    /// Package to compile.{n}
25    /// Prioritises local projects if in a workspace.{n}
26    /// If not set, lux will attempt to compile the current project.{n}
27    /// Must be set in multi-project workspaces.
28    #[arg(short, long, visible_short_alias = 'p')]
29    pub(crate) package: Option<package::Name>,
30
31    #[arg(long, default_value = "text", value_enum, ignore_case = true)]
32    output_format: OutputFormat,
33}
34
35pub async fn bin(data: Bin, config: Config) -> Result<()> {
36    let staging_dir = tempdir().into_diagnostic()?;
37    let config = ConfigBuilder::from(config)
38        .wrap_bin_scripts(Some(false))
39        .user_tree(Some(staging_dir.path().to_path_buf()))
40        .build()?;
41
42    let workspace = Workspace::current_or_err()?;
43    let project = match &data.package {
44        None => workspace.single_member()?,
45        Some(package) => workspace.select_member(package)?,
46    };
47
48    let lua_version = project.lua_version(&config)?;
49    if lua_version == LuaVersion::Luau {
50        return Err(miette!("Lux cannot distribute binaries for Luau projects"));
51    }
52    let tree = FlatDistTree::new(staging_dir.path().to_path_buf(), lua_version, &config)?;
53
54    let out = DistProjectBin::new()
55        .project(project)
56        .config(&config)
57        .tree(&tree)
58        .maybe_output(data.output)
59        .compile()
60        .await
61        .into_diagnostic()?;
62
63    match data.output_format {
64        OutputFormat::Json => println!("{}", serde_json::to_string(&out).into_diagnostic()?),
65        OutputFormat::Text => println!("Binary written to {}", out.display()),
66    }
67
68    Ok(())
69}