1use miette::Diagnostic;
2use std::{
3 collections::HashMap,
4 io,
5 path::Path,
6 process::{ExitStatus, Output, Stdio},
7};
8use thiserror::Error;
9
10use tracing::{info_span, Instrument};
11use which::which;
12
13use crate::{
14 build::{
15 backend::{self, BuildBackend, BuildInfo, RunBuildArgs},
16 dependency,
17 },
18 config::Config,
19 lua,
20 path::{self, Paths},
21 rockspec,
22 tree::{self, InstallTree, RockLayout},
23 variables,
24};
25
26use super::external_dependency::ExternalDependencyInfo;
27
28#[derive(Error, Debug, Diagnostic)]
29pub enum Error {
30 #[error(transparent)]
31 #[diagnostic(transparent)]
32 Tree(#[from] tree::Error),
33 #[error(transparent)]
34 #[diagnostic(transparent)]
35 Paths(#[from] path::Error),
36 #[error("'build_command' and 'install_command' cannot be empty.")]
37 #[diagnostic(
38 help("set a command in the `build.build_command` or `build.install_command` field"),
39 url("https://lux.lumen-labs.org/reference/lux-toml#command")
40 )]
41 EmptyCommand,
42 #[error("error parsing command:\n{command}\n\nerror: {err}")]
43 #[diagnostic(
44 help("put build/install command arguments in quotes if they contain spaces"),
45 url("https://lux.lumen-labs.org/reference/lux-toml/#command")
46 )]
47 ParseError {
48 err: shell_words::ParseError,
49 command: String,
50 },
51 #[error("cannot find a shell to execute the command")]
52 ShellNotFoundError(#[from] which::Error),
53 #[error("error executing command:\n{command}\n\nerror: {err}")]
54 Io { err: io::Error, command: String },
55 #[error(
56 "failed to execute command:\n{command}\n\nstatus: {status}\nstdout: {stdout}\nstderr: {stderr}"
57 )]
58 CommandFailure {
59 command: String,
60 status: ExitStatus,
61 stdout: String,
62 stderr: String,
63 },
64 #[error(transparent)]
65 #[diagnostic(transparent)]
66 VariableSubstitution(#[from] variables::Error),
67}
68pub(crate) fn trace_output(output: &Output) {
69 if !output.stderr.is_empty() {
70 for line in String::from_utf8_lossy(&output.stderr).lines() {
71 tracing::debug!("{}", line);
72 }
73 }
74 if !output.stdout.is_empty() {
75 for line in String::from_utf8_lossy(&output.stdout).lines() {
76 tracing::debug!("{}", line);
77 }
78 }
79}
80
81impl BuildBackend for rockspec::build::backend::Command {
82 type Err = Error;
83
84 #[tracing::instrument(name = "command::run", skip_all, level = "debug")]
85 async fn run<T>(self, args: RunBuildArgs<'_, T>) -> Result<BuildInfo, Self::Err>
86 where
87 T: InstallTree,
88 {
89 let package = args.package;
90 let no_install = args.no_install;
91 let lua = args.lua;
92 let external_dependencies = args.external_dependencies;
93 let config = args.config;
94 let tree = args.tree;
95 let layout = tree.layout_for(package);
96 let build_dir = args.build_dir;
97 let dependency_layouts = args.dependency_layouts;
98
99 let build_tree = tree.build_tree(config)?;
100 let build_paths = Paths::new(&build_tree)?;
101
102 let runner = Runner {
103 output_paths: &layout,
104 lua,
105 external_dependencies,
106 dependency_layouts,
107 config,
108 build_dir,
109 build_paths: &build_paths,
110 };
111
112 if let Some(build_command) = &self.build_command {
113 runner.run(build_command).await?;
114 }
115 if !no_install {
116 if let Some(install_command) = &self.install_command {
117 runner.run(install_command).await?;
118 }
119 }
120 Ok(BuildInfo::default())
121 }
122}
123
124struct Runner<'a> {
125 output_paths: &'a RockLayout,
126 lua: &'a lua::Installation,
127 external_dependencies: &'a HashMap<String, ExternalDependencyInfo>,
128 dependency_layouts: &'a dependency::Layouts,
129 config: &'a Config,
130 build_dir: &'a Path,
131 build_paths: &'a Paths,
132}
133
134impl Runner<'_> {
135 #[tracing::instrument(level = "trace", skip(self))]
136 async fn run(&self, command: &str) -> Result<(), Error> {
137 let lua_path = self.build_paths.package_path_prepended().joined();
138 let lua_cpath = self.build_paths.package_cpath_prepended().joined();
139 let bin_path = self.build_paths.path_prepended().joined();
140 let substituted_cmd = backend::substitute_variables(
141 command,
142 self.output_paths,
143 self.lua,
144 self.external_dependencies,
145 self.dependency_layouts,
146 self.config,
147 )?;
148
149 if substituted_cmd.is_empty() {
150 return Err(Error::EmptyCommand);
151 }
152
153 #[cfg(target_env = "msvc")]
154 let (shell, shell_arg) = (which("cmd.exe")?, "/C");
155 #[cfg(not(target_env = "msvc"))]
156 let (shell, shell_arg) = (which("sh")?, "-c");
157
158 match self
159 .config
160 .wrapped_command(shell, [shell_arg, &substituted_cmd])
161 .current_dir(self.build_dir)
162 .stdout(Stdio::piped())
163 .stderr(Stdio::piped())
164 .env("PATH", &bin_path)
165 .env("LUA_PATH", &lua_path)
166 .env("LUA_CPATH", &lua_cpath)
167 .spawn()
168 {
169 Err(err) => {
170 return Err(Error::Io {
171 err,
172 command: substituted_cmd,
173 });
174 }
175 Ok(child) => match child
176 .wait_with_output()
177 .instrument(info_span!(
178 "Running build command",
179 command = substituted_cmd
180 ))
181 .await
182 {
183 Ok(output) if output.status.success() => trace_output(&output),
184 Ok(output) => {
185 return Err(Error::CommandFailure {
186 command: substituted_cmd,
187 status: output.status,
188 stdout: String::from_utf8_lossy(&output.stdout).into(),
189 stderr: String::from_utf8_lossy(&output.stderr).into(),
190 });
191 }
192 Err(err) => {
193 return Err(Error::Io {
194 err,
195 command: substituted_cmd,
196 });
197 }
198 },
199 }
200 Ok(())
201 }
202}