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