Skip to main content

lux_lib/operations/
run.rs

1use crate::package;
2use crate::rockspec;
3use std::{ops::Deref, path::PathBuf};
4
5use bon::Builder;
6use itertools::Itertools;
7use miette::Diagnostic;
8use serde::Deserialize;
9use thiserror::Error;
10use tokio::process::Command as ProcessCommand;
11
12use crate::{
13    config::Config,
14    lua,
15    operations::run_lua::{self, RunLua},
16    path::{self, LuaEnvironment, Paths},
17    tree::InstallTree,
18    workspace::{self, TreeError, Workspace},
19};
20
21#[derive(Debug, Error, Diagnostic)]
22#[error("'{0}' should not be used as a `command` as it is not cross-platform.
23You should only change the default `command` if it is a different Lua interpreter that behaves identically on all platforms.
24Consider removing the `command` field and letting Lux choose the default Lua interpreter instead.")]
25pub struct CommandError(String);
26
27#[derive(Debug, Clone)]
28#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
29#[cfg_attr(feature = "schema", serde(transparent))]
30pub struct Command(String);
31
32impl Command {
33    pub fn from(command: String) -> Result<Self, CommandError> {
34        match command.as_str() {
35            // Common Lua interpreters that could lead to cross-platform issues
36            // Luajit is also included because it may or may not have lua52 syntax support compiled in.
37            "lua" | "lua5.1" | "lua5.2" | "lua5.3" | "lua5.4" | "luajit" => {
38                Err(CommandError(command))
39            }
40            _ => Ok(Self(command)),
41        }
42    }
43}
44
45impl<'de> Deserialize<'de> for Command {
46    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
47    where
48        D: serde::Deserializer<'de>,
49    {
50        let command = String::deserialize(deserializer)?;
51
52        Command::from(command).map_err(serde::de::Error::custom)
53    }
54}
55
56impl Deref for Command {
57    type Target = String;
58
59    fn deref(&self) -> &Self::Target {
60        &self.0
61    }
62}
63
64#[derive(Debug, Error, Diagnostic)]
65#[error(transparent)]
66#[non_exhaustive]
67pub enum Error {
68    #[diagnostic(transparent)]
69    Toml(#[from] rockspec::toml::Error),
70    #[diagnostic(transparent)]
71    Command(#[from] CommandError),
72    #[diagnostic(transparent)]
73    LuaVersion(#[from] rockspec::Error),
74    #[diagnostic(transparent)]
75    RunLua(#[from] run_lua::Error),
76    #[error("failed to detect or install a luau runtime")]
77    #[diagnostic(forward(0))]
78    LuaInstallation(#[from] lua::installation::Error),
79    #[diagnostic(transparent)]
80    Workspace(#[from] workspace::Error),
81    #[diagnostic(transparent)]
82    WorkspaceTree(#[from] TreeError),
83    Io(#[from] std::io::Error),
84    #[diagnostic(transparent)]
85    Paths(#[from] path::Error),
86    #[error("No `run` field found in `lux.toml`")]
87    NoRunField,
88}
89
90#[derive(Builder)]
91#[builder(start_fn = new, finish_fn(name = _build, vis = ""))]
92pub struct Run<'a> {
93    workspace: &'a Workspace,
94    package: Option<package::Name>,
95    dir: Option<PathBuf>,
96    args: &'a [String],
97    config: &'a Config,
98    disable_loader: Option<bool>,
99    environment: LuaEnvironment,
100}
101
102impl<State> RunBuilder<'_, State>
103where
104    State: run_builder::State + run_builder::IsComplete,
105{
106    pub async fn run(self) -> Result<(), Error> {
107        let run = self._build();
108        let workspace = run.workspace;
109        let config = run.config;
110        let extra_args = run.args;
111        let project = workspace.single_member_or_select(&run.package)?;
112        let toml = project.toml().into_local()?;
113
114        let run_spec = toml
115            .run()
116            .ok_or(Error::NoRunField)?
117            .current_platform()
118            .clone();
119
120        let mut args: Vec<String> = run_spec.args.map(|args| args.into()).unwrap_or_default();
121
122        if !extra_args.is_empty() {
123            args.extend(extra_args.iter().cloned());
124        }
125        let disable_loader = run.disable_loader.unwrap_or(false);
126        let environment = run.environment;
127        match &run_spec.command {
128            Some(command) => {
129                run_with_command(
130                    workspace,
131                    command,
132                    run.dir,
133                    disable_loader,
134                    &args,
135                    config,
136                    environment,
137                )
138                .await
139            }
140            None => {
141                run_with_local_lua(
142                    workspace,
143                    run.dir,
144                    disable_loader,
145                    &args,
146                    config,
147                    environment,
148                )
149                .await
150            }
151        }
152    }
153}
154
155async fn run_with_local_lua(
156    workspace: &Workspace,
157    root_dir: Option<PathBuf>,
158    disable_loader: bool,
159    args: &Vec<String>,
160    config: &Config,
161    environment: LuaEnvironment,
162) -> Result<(), Error> {
163    let version = workspace.lua_version(config)?;
164
165    let tree = workspace.tree(config)?;
166
167    let lua_cmd = lua::Binary::from(run_lua::resolve_runtime(&version, config).await?);
168
169    RunLua::new()
170        .root(&root_dir.unwrap_or(workspace.root().to_path_buf()))
171        .tree(&tree)
172        .config(config)
173        .lua_cmd(lua_cmd)
174        .disable_loader(disable_loader)
175        .args(args)
176        .environment(environment)
177        .run_lua()
178        .await?;
179
180    Ok(())
181}
182
183async fn run_with_command(
184    workspace: &Workspace,
185    command: &Command,
186    root_dir: Option<PathBuf>,
187    disable_loader: bool,
188    args: &[String],
189    config: &Config,
190    environment: LuaEnvironment,
191) -> Result<(), Error> {
192    let tree = workspace.tree(config)?;
193    let paths = Paths::for_environment(&tree, config, environment)?;
194
195    let lua_init = if tree.version().is_luau() || disable_loader {
196        None
197    } else if tree.version().lux_lib_dir().is_none() {
198        tracing::warn!("lux-lua library not found.\n    Cannot use the `lux.loader`.\n    To suppress this warning, set the `--no-loader` option.");
199        None
200    } else {
201        Some(paths.init())
202    };
203
204    let mut cmd = ProcessCommand::new(command.deref());
205    if let Some(dir) = root_dir {
206        cmd.current_dir(dir);
207    } else {
208        cmd.current_dir(workspace.root());
209    }
210    match cmd
211        .args(args.iter().cloned().collect_vec())
212        .env("PATH", paths.path_prepended().joined())
213        .envs(paths.lua_env_vars(environment, &lua_init.unwrap_or_default()))
214        .status()
215        .await?
216        .code()
217    {
218        Some(0) => Ok(()),
219        code => Err(run_lua::Error::LuaCommandNonZeroExitCode {
220            lua_cmd: command.to_string(),
221            exit_code: code,
222        }
223        .into()),
224    }
225}