Skip to main content

lux_cli/dist/
bin.rs

1use std::path::PathBuf;
2
3use clap::Args;
4use lux_lib::{
5    config::{Config, ConfigBuilder},
6    operations::DistProjectBin,
7    package::PackageName,
8    tree::FlatDistTree,
9    workspace::Workspace,
10};
11use 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    package: Option<PackageName>,
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 = ConfigBuilder::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    let tree = FlatDistTree::new(staging_dir.path().to_path_buf(), lua_version, &config)?;
49
50    let out = DistProjectBin::new()
51        .project(project)
52        .config(&config)
53        .tree(&tree)
54        .maybe_output(data.output)
55        .compile()
56        .await
57        .into_diagnostic()?;
58
59    match data.output_format {
60        OutputFormat::Json => println!("{}", serde_json::to_string(&out).into_diagnostic()?),
61        OutputFormat::Text => println!("Binary written to {}", out.display()),
62    }
63
64    Ok(())
65}