lux-lib 0.75.0

Library for the lux package manager for Lua
Documentation
use miette::Diagnostic;
use std::{
    collections::HashMap,
    io,
    path::Path,
    process::{ExitStatus, Output, Stdio},
};
use thiserror::Error;

use tracing::{info_span, Instrument};
use which::which;

use crate::{
    build::{
        backend::{self, BuildBackend, BuildInfo, RunBuildArgs},
        dependency,
    },
    config::Config,
    lua,
    path::{self, Paths},
    rockspec,
    tree::{self, InstallTree, RockLayout},
    variables,
};

use super::external_dependency::ExternalDependencyInfo;

#[derive(Error, Debug, Diagnostic)]
pub enum Error {
    #[error(transparent)]
    #[diagnostic(transparent)]
    Tree(#[from] tree::Error),
    #[error(transparent)]
    #[diagnostic(transparent)]
    Paths(#[from] path::Error),
    #[error("'build_command' and 'install_command' cannot be empty.")]
    #[diagnostic(
        help("set a command in the `build.build_command` or `build.install_command` field"),
        url("https://lux.lumen-labs.org/reference/lux-toml#command")
    )]
    EmptyCommand,
    #[error("error parsing command:\n{command}\n\nerror: {err}")]
    #[diagnostic(
        help("put build/install command arguments in quotes if they contain spaces"),
        url("https://lux.lumen-labs.org/reference/lux-toml/#command")
    )]
    ParseError {
        err: shell_words::ParseError,
        command: String,
    },
    #[error("cannot find a shell to execute the command")]
    ShellNotFoundError(#[from] which::Error),
    #[error("error executing command:\n{command}\n\nerror: {err}")]
    Io { err: io::Error, command: String },
    #[error(
        "failed to execute command:\n{command}\n\nstatus: {status}\nstdout: {stdout}\nstderr: {stderr}"
    )]
    CommandFailure {
        command: String,
        status: ExitStatus,
        stdout: String,
        stderr: String,
    },
    #[error(transparent)]
    #[diagnostic(transparent)]
    VariableSubstitution(#[from] variables::Error),
}
pub(crate) fn trace_output(output: &Output) {
    if !output.stderr.is_empty() {
        for line in String::from_utf8_lossy(&output.stderr).lines() {
            tracing::debug!("{}", line);
        }
    }
    if !output.stdout.is_empty() {
        for line in String::from_utf8_lossy(&output.stdout).lines() {
            tracing::debug!("{}", line);
        }
    }
}

impl BuildBackend for rockspec::build::backend::Command {
    type Err = Error;

    #[tracing::instrument(name = "command::run", skip_all, level = "debug")]
    async fn run<T>(self, args: RunBuildArgs<'_, T>) -> Result<BuildInfo, Self::Err>
    where
        T: InstallTree,
    {
        let package = args.package;
        let no_install = args.no_install;
        let lua = args.lua;
        let external_dependencies = args.external_dependencies;
        let config = args.config;
        let tree = args.tree;
        let layout = tree.layout_for(package);
        let build_dir = args.build_dir;
        let dependency_layouts = args.dependency_layouts;

        let build_tree = tree.build_tree(config)?;
        let build_paths = Paths::new(&build_tree)?;

        let runner = Runner {
            output_paths: &layout,
            lua,
            external_dependencies,
            dependency_layouts,
            config,
            build_dir,
            build_paths: &build_paths,
        };

        if let Some(build_command) = &self.build_command {
            runner.run(build_command).await?;
        }
        if !no_install {
            if let Some(install_command) = &self.install_command {
                runner.run(install_command).await?;
            }
        }
        Ok(BuildInfo::default())
    }
}

struct Runner<'a> {
    output_paths: &'a RockLayout,
    lua: &'a lua::Installation,
    external_dependencies: &'a HashMap<String, ExternalDependencyInfo>,
    dependency_layouts: &'a dependency::Layouts,
    config: &'a Config,
    build_dir: &'a Path,
    build_paths: &'a Paths,
}

impl Runner<'_> {
    #[tracing::instrument(level = "trace", skip(self))]
    async fn run(&self, command: &str) -> Result<(), Error> {
        let lua_path = self.build_paths.package_path_prepended().joined();
        let lua_cpath = self.build_paths.package_cpath_prepended().joined();
        let bin_path = self.build_paths.path_prepended().joined();
        let substituted_cmd = backend::substitute_variables(
            command,
            self.output_paths,
            self.lua,
            self.external_dependencies,
            self.dependency_layouts,
            self.config,
        )?;

        if substituted_cmd.is_empty() {
            return Err(Error::EmptyCommand);
        }

        #[cfg(target_env = "msvc")]
        let (shell, shell_arg) = (which("cmd.exe")?, "/C");
        #[cfg(not(target_env = "msvc"))]
        let (shell, shell_arg) = (which("sh")?, "-c");

        match self
            .config
            .wrapped_command(shell, [shell_arg, &substituted_cmd])
            .current_dir(self.build_dir)
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .env("PATH", &bin_path)
            .env("LUA_PATH", &lua_path)
            .env("LUA_CPATH", &lua_cpath)
            .spawn()
        {
            Err(err) => {
                return Err(Error::Io {
                    err,
                    command: substituted_cmd,
                });
            }
            Ok(child) => match child
                .wait_with_output()
                .instrument(info_span!(
                    "Running build command",
                    command = substituted_cmd
                ))
                .await
            {
                Ok(output) if output.status.success() => trace_output(&output),
                Ok(output) => {
                    return Err(Error::CommandFailure {
                        command: substituted_cmd,
                        status: output.status,
                        stdout: String::from_utf8_lossy(&output.stdout).into(),
                        stderr: String::from_utf8_lossy(&output.stderr).into(),
                    });
                }
                Err(err) => {
                    return Err(Error::Io {
                        err,
                        command: substituted_cmd,
                    });
                }
            },
        }
        Ok(())
    }
}