Skip to main content

lux_lib/build/
make.rs

1use itertools::Itertools;
2use miette::Diagnostic;
3use path_slash::PathBufExt;
4use std::{
5    io,
6    path::PathBuf,
7    process::{ExitStatus, Stdio},
8};
9use thiserror::Error;
10
11use tracing::{info_span, Instrument};
12
13use crate::{
14    build::{
15        backend::{self, BuildBackend, BuildInfo, RunBuildArgs},
16        command,
17    },
18    path::{self, Paths},
19    rockspec,
20    tree::{self, InstallTree},
21    variables,
22};
23
24#[derive(Error, Debug, Diagnostic)]
25#[non_exhaustive]
26pub enum Error {
27    #[error(transparent)]
28    #[diagnostic(transparent)]
29    Tree(#[from] tree::Error),
30    #[error(transparent)]
31    #[diagnostic(transparent)]
32    Paths(#[from] path::Error),
33    #[error("{name} step failed.\n\n{status}\n\nstdout:\n{stdout}\n\nstderr:\n{stderr}")]
34    CommandFailure {
35        name: String,
36        status: ExitStatus,
37        stdout: String,
38        stderr: String,
39    },
40    #[error("failed to run `make` step")]
41    Io(#[source] io::Error),
42    #[error("failed to run `make` step: '{0}' command not found!")]
43    #[diagnostic(help("run `lx debug toolchains` to check available build tools."))]
44    CommandNotFound(String),
45    #[error(transparent)]
46    #[diagnostic(transparent)]
47    VariableSubstitution(#[from] variables::Error),
48    #[error("{0} not found")]
49    #[diagnostic(help(
50        "ensure the Makefile exists in the build directory or check the rockspec source layout."
51    ))]
52    MakefileNotFound(PathBuf),
53}
54
55impl BuildBackend for rockspec::build::backend::Make {
56    type Err = Error;
57
58    #[tracing::instrument(name = "make::run", skip_all, level = "debug")]
59    async fn run<T>(self, args: RunBuildArgs<'_, T>) -> Result<BuildInfo, Self::Err>
60    where
61        T: InstallTree,
62    {
63        let no_install = args.no_install;
64        let lua = args.lua;
65        let external_dependencies = args.external_dependencies;
66        let config = args.config;
67        let tree = args.tree;
68        let layout = tree.layout_for(args.package);
69        let build_dir = args.build_dir;
70        let dependency_layouts = args.dependency_layouts;
71
72        let build_tree = tree.build_tree(config)?;
73        let build_paths = Paths::new(&build_tree)?;
74        let lua_path = build_paths.package_path_prepended().joined();
75        let lua_cpath = build_paths.package_cpath_prepended().joined();
76        let bin_path = build_paths.path_prepended().joined();
77
78        // Build step
79        if self.build_pass {
80            let build_args = self
81                .variables
82                .iter()
83                .chain(&self.build_variables)
84                .filter(|(_, value)| !value.is_empty())
85                .map(|(key, value)| {
86                    let substituted_value = backend::substitute_variables(
87                        value,
88                        &layout,
89                        lua,
90                        external_dependencies,
91                        dependency_layouts,
92                        config,
93                    )?;
94                    Ok(format!("{key}={substituted_value}").trim().to_string())
95                })
96                .try_collect::<_, Vec<_>, Self::Err>()?;
97            let mut make_args: Vec<String> = Vec::new();
98            if let Some(build_target) = &self.build_target {
99                make_args.push(build_target.clone());
100            }
101            make_args.push("-f".into());
102            make_args.push(self.makefile.to_slash_lossy().into());
103            make_args.extend(build_args);
104            let mut cmd = config.wrapped_command(config.make_cmd(), make_args);
105            cmd.current_dir(build_dir)
106                .stdout(Stdio::piped())
107                .stderr(Stdio::piped())
108                .env("PATH", &bin_path)
109                .env("LUA_PATH", &lua_path)
110                .env("LUA_CPATH", &lua_cpath);
111            match cmd.spawn() {
112                Ok(child) => match child
113                    .wait_with_output()
114                    .instrument(info_span!("Make build pass"))
115                    .await
116                {
117                    Ok(output) if output.status.success() => command::trace_output(&output),
118                    Ok(output) => {
119                        return Err(Error::CommandFailure {
120                            name: match self.build_target {
121                                Some(build_target) => {
122                                    format!("{} {}", config.make_cmd(), build_target)
123                                }
124                                None => config.make_cmd(),
125                            },
126
127                            status: output.status,
128                            stdout: String::from_utf8_lossy(&output.stdout).into(),
129                            stderr: String::from_utf8_lossy(&output.stderr).into(),
130                        });
131                    }
132                    Err(err) => return Err(Error::Io(err)),
133                },
134                Err(_) => return Err(Error::CommandNotFound(config.make_cmd().clone())),
135            }
136        };
137
138        // Install step
139        if self.install_pass && !no_install {
140            let install_args = self
141                .variables
142                .iter()
143                .chain(&self.install_variables)
144                .filter(|(_, value)| !value.is_empty())
145                .map(|(key, value)| {
146                    let substituted_value = backend::substitute_variables(
147                        value,
148                        &layout,
149                        lua,
150                        external_dependencies,
151                        dependency_layouts,
152                        config,
153                    )?;
154                    Ok(format!("{key}={substituted_value}").trim().to_string())
155                })
156                .try_collect::<_, Vec<_>, Self::Err>()?;
157            let mut install_cmd_args: Vec<String> = Vec::with_capacity(install_args.len() + 3);
158            install_cmd_args.push(self.install_target.clone());
159            install_cmd_args.push("-f".into());
160            install_cmd_args.push(self.makefile.to_slash_lossy().into());
161            install_cmd_args.extend(install_args);
162            match config
163                .wrapped_command(config.make_cmd(), install_cmd_args)
164                .current_dir(build_dir)
165                .env("PATH", &bin_path)
166                .env("LUA_PATH", &lua_path)
167                .env("LUA_CPATH", &lua_cpath)
168                .output()
169                .instrument(info_span!("Make install pass"))
170                .await
171            {
172                Ok(output) if output.status.success() => command::trace_output(&output),
173                Ok(output) => {
174                    return Err(Error::CommandFailure {
175                        name: format!("{} {}", config.make_cmd(), self.install_target),
176                        status: output.status,
177                        stdout: String::from_utf8_lossy(&output.stdout).into(),
178                        stderr: String::from_utf8_lossy(&output.stderr).into(),
179                    });
180                }
181                Err(err) => return Err(Error::Io(err)),
182            }
183        };
184
185        Ok(BuildInfo::default())
186    }
187}