lux_lib/operations/exec/
mod.rs1use crate::rockspec;
2use std::io;
3use tokio::process::Command;
4
5use super::BuildWorkspace;
6use crate::{
7 config::Config,
8 lua,
9 operations::build_workspace,
10 path::{self, Paths},
11 tree::{self, InstallTree},
12 workspace::{TreeError, Workspace},
13};
14use bon::Builder;
15use itertools::Itertools;
16use miette::Diagnostic;
17use thiserror::Error;
18use which::which;
19
20mod command;
21
22#[derive(Builder)]
25#[builder(start_fn = new, finish_fn(name = _exec, vis = ""))]
26pub struct Exec<'a> {
27 #[builder(start_fn)]
28 command: &'a str,
29 #[builder(start_fn)]
30 workspace: Option<&'a Workspace>,
31 #[builder(start_fn)]
32 config: &'a Config,
33
34 #[builder(field)]
35 args: Vec<String>,
36
37 disable_loader: Option<bool>,
38}
39
40impl<State: exec_builder::State> ExecBuilder<'_, State> {
41 pub fn arg(mut self, arg: impl Into<String>) -> Self {
42 self.args.push(arg.into());
43 self
44 }
45
46 pub fn args(mut self, args: impl IntoIterator<Item: Into<String>>) -> Self {
47 self.args.extend(args.into_iter().map_into());
48 self
49 }
50}
51
52impl<State> ExecBuilder<'_, State>
53where
54 State: exec_builder::State + exec_builder::IsComplete,
55{
56 pub async fn exec(self) -> Result<(), Error>
57 where
58 State: exec_builder::IsComplete,
59 {
60 exec(self._exec()).await
61 }
62}
63
64#[derive(Error, Debug, Diagnostic)]
65pub enum Error {
66 #[error("failed to run {cmd}: {source}")]
67 RunCommandFailed {
68 cmd: String,
69 source: io::Error,
70 #[help]
71 help: Option<String>,
72 },
73 #[error(
74 "{cmd} exited with non-zero exit code: {}",
75 exit_code.map(|code| code.to_string()).unwrap_or("unknown".into())
76 )]
77 #[diagnostic(help("check the command's output for errors."))]
78 RunCommandNonZeroExitCode { cmd: String, exit_code: Option<i32> },
79 #[error(transparent)]
80 #[diagnostic(transparent)]
81 LuaVersion(#[from] lua::version::Error),
82 #[error(transparent)]
83 #[diagnostic(transparent)]
84 Tree(#[from] tree::Error),
85 #[error(transparent)]
86 #[diagnostic(transparent)]
87 Paths(#[from] path::Error),
88 #[error(transparent)]
89 #[diagnostic(transparent)]
90 LuaVersionError(#[from] rockspec::Error),
91 #[error(transparent)]
92 #[diagnostic(transparent)]
93 BuildWorkspace(#[from] Box<build_workspace::Error>),
94 #[error(transparent)]
95 #[diagnostic(transparent)]
96 Command(#[from] Box<command::Error>),
97 #[error(transparent)]
98 #[diagnostic(transparent)]
99 WorkspaceTree(#[from] TreeError),
100 #[error("failed to execute '{0}':\n{1}")]
101 Io(String, io::Error),
102}
103
104impl From<build_workspace::Error> for Error {
105 fn from(source: build_workspace::Error) -> Self {
106 Self::BuildWorkspace(Box::new(source))
107 }
108}
109
110impl From<command::Error> for Error {
111 fn from(source: command::Error) -> Self {
112 Self::Command(Box::new(source))
113 }
114}
115
116async fn exec(run: Exec<'_>) -> Result<(), Error> {
117 let lua_version = run
118 .workspace
119 .map(|project| project.lua_version(run.config))
120 .transpose()?
121 .unwrap_or(lua::Version::from(run.config)?.clone());
122
123 if let Some(project) = run.workspace {
124 BuildWorkspace::new(project, run.config)
125 .no_lock(false)
126 .only_deps(false)
127 .build()
128 .await?;
129 } else if which(run.command).is_err() {
130 command::install(run.command, run.config).await?
131 };
132
133 let user_tree = run.config.user_tree(lua_version.clone())?;
134
135 let paths = if let Some(project) = run.workspace {
136 let workspace_paths = Paths::new(&project.tree(run.config)?)?;
137 match Paths::new(&user_tree) {
138 Ok(mut user_paths) => {
139 user_paths.prepend(&workspace_paths);
140 user_paths
141 }
142 Err(err) => {
143 tracing::warn!(
144 "failed to load the user tree at '{}': {err}",
145 user_tree.root().display()
146 );
147 workspace_paths
148 }
149 }
150 } else {
151 Paths::new(&user_tree)?
152 };
153
154 let lua_init = if user_tree.version().is_luau() || run.disable_loader.unwrap_or(false) {
155 None
156 } else if lua_version.lux_lib_dir().is_none() {
157 tracing::warn!(
158 r#"lux-lua library not found.
159Cannot use the `lux.loader`.
160To suppress this warning, set the `--no-loader` option."#
161 );
162 None
163 } else {
164 Some(paths.init())
165 };
166
167 let status = match Command::new(run.command)
168 .args(run.args)
169 .env("PATH", paths.path_prepended().joined())
170 .env("LUA_INIT", lua_init.unwrap_or_default())
171 .env("LUA_PATH", paths.package_path().joined())
172 .env("LUA_CPATH", paths.package_cpath().joined())
173 .status()
174 .await
175 {
176 Ok(status) => Ok(status),
177 Err(err) => {
178 let help = if err.to_string().starts_with("No such file") {
179 Some(format!(
180 "make sure '{}' is available on your PATH",
181 run.command
182 ))
183 } else {
184 None
185 };
186 Err(Error::RunCommandFailed {
187 cmd: run.command.to_string(),
188 source: err,
189 help,
190 })
191 }
192 }?;
193 if status.success() {
194 Ok(())
195 } else {
196 Err(Error::RunCommandNonZeroExitCode {
197 cmd: run.command.to_string(),
198 exit_code: status.code(),
199 })
200 }
201}