Skip to main content

lux_lib/config/
mod.rs

1use build::BuildConfig;
2use directories::ProjectDirs;
3use external_deps::ExternalDependencySearchConfig;
4use itertools::Itertools;
5
6use miette::Diagnostic;
7use reqwest::Client;
8use serde::{Deserialize, Serialize, Serializer};
9use std::ffi::OsStr;
10use std::path::Path;
11use std::{
12    collections::HashMap,
13    env,
14    path::PathBuf,
15    sync::{Arc, OnceLock},
16    time::Duration,
17};
18use thiserror::Error;
19use tokio::process::Command;
20use url::Url;
21
22use crate::config::access_tokens::AccessToken;
23use crate::fs;
24use crate::lua;
25use crate::project::TomlDeError;
26use crate::remote;
27use crate::tree::{self, CustomRockLayout, Tree};
28use crate::variables::GetVariableError;
29use crate::{target, variables::HasVariables};
30
31pub mod access_tokens;
32pub mod build;
33pub mod external_deps;
34
35const DEV_PATH: &str = "dev/";
36const DEFAULT_LUA_MIRRORS: [&str; 2] = [
37    "https://www.lua.org/ftp",
38    "https://www.tecgraf.puc-rio.br/lua/ftp",
39];
40const DEFAULT_USER_AGENT: &str = concat!("lux-lib/", env!("CARGO_PKG_VERSION"));
41
42#[derive(Error, Debug, Diagnostic)]
43#[error("could not find a valid home directory")]
44#[diagnostic(
45    code(lux_lib::no_home_directory),
46    help("this usually means you're running Lux in a managed environment like LDAP or a live session.")
47)]
48pub struct NoValidHomeDirectory;
49
50/// The resolved configuration for a Lux session.
51/// Can be constructed via [`Builder`], which supports layering multiple
52/// configuration sources (config file, CLI flags, environment variables).
53#[derive(Debug, Clone)]
54pub struct Config {
55    enable_development_packages: bool,
56    server: Url,
57    extra_servers: Vec<Url>,
58    extra_wally_registries: Vec<Url>,
59    namespace: Option<String>,
60    lua_dir: Option<PathBuf>,
61    lua_mirrors: Vec<Url>,
62    lua_version: Option<lua::Version>,
63    user_tree: PathBuf,
64    workspace_tree: Option<PathBuf>,
65    verbose: bool,
66    /// Don't display progress bars
67    no_progress: bool,
68    /// Skip prompts (choosing the default choice)
69    no_prompt: bool,
70    timeout: Duration,
71    max_jobs: usize,
72    variables: HashMap<String, String>,
73    access_tokens: HashMap<String, AccessToken>,
74    external_deps: ExternalDependencySearchConfig,
75
76    build: BuildConfig,
77    entrypoint_layout: Option<Arc<dyn CustomRockLayout>>,
78
79    cache_dir: PathBuf,
80    data_dir: PathBuf,
81    vendor_dir: Option<PathBuf>,
82
83    user_agent: String,
84
85    generate_luarc: bool,
86    luarc_file_name: String,
87    wrap_bin_scripts: bool,
88    package_types: remote::package::kind::FilterSpec,
89    no_tfa: bool,
90
91    https_client_cache: OnceLock<Client>,
92    http_client_cache: OnceLock<Client>,
93}
94
95impl Config {
96    /// Lux application directories
97    pub(crate) fn project_dirs() -> Result<ProjectDirs, NoValidHomeDirectory> {
98        directories::ProjectDirs::from("org", "lumenlabs", "lux")
99            .filter(|_| Self::home_dir_exists())
100            .ok_or(NoValidHomeDirectory)
101    }
102
103    fn home_dir_exists() -> bool {
104        directories::BaseDirs::new().is_some_and(|base| base.home_dir().is_dir())
105    }
106
107    /// Lux cache directory
108    fn default_cache_path() -> PathBuf {
109        match Config::project_dirs() {
110            Ok(project_dirs) => project_dirs.cache_dir().to_path_buf(),
111            Err(_) => Self::fallback_data_dir("cache"),
112        }
113    }
114
115    /// Lux data directory
116    fn default_data_path() -> PathBuf {
117        match Config::project_dirs() {
118            Ok(project_dirs) => project_dirs.data_local_dir().to_path_buf(),
119            Err(_) => Self::fallback_data_dir("data"),
120        }
121    }
122
123    /// Fallback data directory used when no valid home directory can be determined.
124    fn fallback_data_dir(subdir: &str) -> PathBuf {
125        let path = std::env::temp_dir().join("lux").join(subdir);
126        tracing::warn!(
127            "no valid home directory found; falling back to `{}`",
128            path.display()
129        );
130        path
131    }
132
133    /// Create a copy of this config for the specified Lua version
134    pub fn with_lua_version(self, lua_version: lua::Version) -> Self {
135        Self {
136            lua_version: Some(lua_version),
137            ..self
138        }
139    }
140
141    /// Create a copy of this config with the specified install tree
142    pub fn with_tree(self, tree: PathBuf) -> Self {
143        Self {
144            user_tree: tree,
145            ..self
146        }
147    }
148
149    /// Create a copy of this config with the specified workspace tree root
150    pub fn with_workspace_tree(self, tree: Option<PathBuf>) -> Self {
151        Self {
152            workspace_tree: tree,
153            ..self
154        }
155    }
156
157    /// The luarocks repository server
158    pub fn server(&self) -> &Url {
159        &self.server
160    }
161
162    /// Additional luarocks repository servers
163    pub fn extra_servers(&self) -> &Vec<Url> {
164        self.extra_servers.as_ref()
165    }
166
167    /// Additional wally package registries (git-index URLs), in addition to the
168    /// official wally index.
169    pub fn extra_wally_registries(&self) -> &Vec<Url> {
170        self.extra_wally_registries.as_ref()
171    }
172
173    /// Enabled luarocks repository servers that provide dev/scm rocks
174    pub fn enabled_dev_servers(&self) -> Result<Vec<Url>, Error> {
175        let mut enabled_dev_servers = Vec::new();
176        if self.enable_development_packages {
177            let config_file = Builder::config_file()
178                .map(|p| p.to_string_lossy().to_string())
179                .unwrap_or_default();
180            enabled_dev_servers.push(self.server().join(DEV_PATH).map_err(|source| {
181                Error::UrlParseError {
182                    source,
183                    help: Some(format!("check the `server` URL in {config_file}")),
184                }
185            })?);
186            for server in self.extra_servers() {
187                enabled_dev_servers.push(server.join(DEV_PATH).map_err(|source| {
188                    Error::UrlParseError {
189                        source,
190                        help: Some(format!("check the `extra_servers` URLs in {config_file}")),
191                    }
192                })?);
193            }
194        }
195        Ok(enabled_dev_servers)
196    }
197
198    /// The luarocks server namespace to use
199    pub fn namespace(&self) -> Option<&String> {
200        self.namespace.as_ref()
201    }
202
203    /// The directory in which to install Lua{n} if not found
204    pub fn lua_dir(&self) -> Option<&PathBuf> {
205        self.lua_dir.as_ref()
206    }
207
208    /// The URLs from which to download Lua sources, in order of preference.
209    pub fn lua_mirrors(&self) -> &[Url] {
210        &self.lua_mirrors
211    }
212
213    // TODO(vhyrro): Remove `Version::from(&config)` and keep this only.
214    pub fn lua_version(&self) -> Option<&lua::Version> {
215        self.lua_version.as_ref()
216    }
217
218    /// The tree in which to install rocks.
219    /// If installing packages for a project, use `Project::tree` instead.
220    pub fn user_tree(&self, version: lua::Version) -> Result<Tree, tree::Error> {
221        Tree::new(self.user_tree.clone(), version, self)
222    }
223
224    /// The detached workspace tree root, if set.
225    pub fn workspace_tree(&self) -> Option<&PathBuf> {
226        self.workspace_tree.as_ref()
227    }
228
229    /// Whether to display verbose output of commands executed
230    pub fn verbose(&self) -> bool {
231        self.verbose
232    }
233
234    /// Whether to disable printing progress bars and spinners
235    pub fn no_progress(&self) -> bool {
236        self.no_progress
237    }
238
239    /// Whether to skip prompts, selecting the default option
240    pub fn no_prompt(&self) -> bool {
241        self.no_prompt
242    }
243
244    /// Timeout on network operations, in seconds.
245    /// 0 means no timeout (wait forever).
246    pub fn timeout(&self) -> &Duration {
247        &self.timeout
248    }
249
250    /// Maximum buffer size for parallel jobs, such as downloading rockspecs and installing rocks.
251    /// 0 means no limit.
252    pub fn max_jobs(&self) -> usize {
253        self.max_jobs
254    }
255
256    /// Command to use for running `make` builds
257    pub fn make_cmd(&self) -> String {
258        match self.variables.get("MAKE") {
259            Some(make) => make.clone(),
260            None => "make".into(),
261        }
262    }
263
264    /// Command to use for running `cmake` builds
265    pub fn cmake_cmd(&self) -> String {
266        match self.variables.get("CMAKE") {
267            Some(cmake) => cmake.clone(),
268            None => "cmake".into(),
269        }
270    }
271
272    /// Construct a [`Command`] for the given program and arguments,
273    /// wrapped in the configured [`BuildConfig::runner`], if any.
274    ///
275    /// If no runner is configured, this is equivalent to
276    /// `Command::new(program).args(args)`.
277    pub(crate) fn wrapped_command<P, A>(&self, program: P, args: A) -> Command
278    where
279        P: AsRef<OsStr>,
280        A: IntoIterator,
281        A::Item: AsRef<OsStr>,
282    {
283        if self.build.runner.is_empty() {
284            let mut cmd = Command::new(program);
285            cmd.args(args);
286            cmd
287        } else {
288            let runner = &self.build.runner;
289            let mut cmd = Command::new(&runner[0]);
290            cmd.args(&runner[1..]).arg(program).args(args);
291            cmd
292        }
293    }
294
295    /// The build profile to use when compiling packages.
296    pub(crate) fn build_profile(&self) -> build::Profile {
297        self.build
298            .profile
299            .as_ref()
300            .cloned()
301            .unwrap_or(build::Profile::Release)
302    }
303
304    /// Variable names, mapped to their values.
305    /// Lux populates variables in the `lux.toml` and in RockSpecs
306    /// with these before building.
307    pub fn variables(&self) -> &HashMap<String, String> {
308        &self.variables
309    }
310
311    /// The access token configured for the given host, if any.
312    /// Precedence: the `LUX_ACCESS_TOKENS` environment variable, then the
313    /// `[access_tokens]` section of the config file, then the `GITHUB_TOKEN`
314    /// environment variable for `github.com`.
315    pub fn access_token(&self, host: &str) -> Option<AccessToken> {
316        access_tokens::env_access_tokens()
317            .get(host)
318            .cloned()
319            .or_else(|| self.access_tokens.get(host).cloned())
320            .or_else(|| {
321                (host == "github.com")
322                    .then(|| env::var("GITHUB_TOKEN").ok())
323                    .flatten()
324                    .map(|raw| AccessToken::from(raw.as_str()))
325            })
326    }
327
328    pub fn external_deps(&self) -> &ExternalDependencySearchConfig {
329        &self.external_deps
330    }
331
332    /// The custom layout applied to entrypoint packages, if any.
333    pub fn entrypoint_layout(&self) -> Option<&Arc<dyn CustomRockLayout>> {
334        self.entrypoint_layout.as_ref()
335    }
336
337    /// The Lux cache directory
338    pub fn cache_dir(&self) -> &PathBuf {
339        &self.cache_dir
340    }
341
342    /// The Lux data directory
343    pub fn data_dir(&self) -> &PathBuf {
344        &self.data_dir
345    }
346
347    /// Specifies a directory with locally vendored sources and RockSpecs.
348    /// When building or installing a package with this flag,
349    /// Lux will fetch sources from the <vendor-dir> instead of from a remote server.
350    pub fn vendor_dir(&self) -> Option<&PathBuf> {
351        self.vendor_dir.as_ref()
352    }
353
354    /// The user agent to use when making web requests.
355    pub fn user_agent(&self) -> &str {
356        &self.user_agent
357    }
358
359    /// Returns a pre-configured HTTPS-only client.
360    pub fn https_client(&self) -> Result<&Client, reqwest::Error> {
361        self.cached_client(true)
362    }
363
364    /// Returns a pre-configured HTTP client.
365    /// Used in tests and to fetch sources, which may have HTTP URLs.
366    pub(crate) fn http_client(&self) -> Result<&Client, reqwest::Error> {
367        self.cached_client(false)
368    }
369
370    fn cached_client(&self, https_only: bool) -> Result<&Client, reqwest::Error> {
371        let cache = if https_only {
372            &self.https_client_cache
373        } else {
374            &self.http_client_cache
375        };
376        if let Some(client) = cache.get() {
377            return Ok(client);
378        }
379        let client = self.build_client(https_only)?;
380        Ok(cache.get_or_init(|| client))
381    }
382
383    fn build_client(&self, https_only: bool) -> Result<Client, reqwest::Error> {
384        let mut builder = Client::builder();
385        // Allow HTTP requests in tests to support mock HTTP servers
386        if https_only && !cfg!(test) {
387            builder = builder.https_only(true);
388        }
389        if !self.timeout().is_zero() {
390            let timeout = *self.timeout();
391            builder = builder.connect_timeout(timeout).read_timeout(timeout);
392        }
393        builder.user_agent(self.user_agent()).build()
394    }
395
396    /// Whether to generate a `.luarc.json` on build.
397    pub fn generate_luarc(&self) -> bool {
398        self.generate_luarc
399    }
400
401    // Lua runtime configuration file name
402    pub fn luarc_file_name(&self) -> &str {
403        &self.luarc_file_name
404    }
405
406    /// Whether to wrap installed Lua bin scripts to be executed with
407    /// the detected or configured Lua installation.
408    /// If `true`, individual rocks can still disable wrapping of their own bin scripts.
409    pub fn wrap_bin_scripts(&self) -> bool {
410        self.wrap_bin_scripts
411    }
412
413    /// Filter specification for package types to include in searches.
414    pub fn package_types(&self) -> &remote::package::kind::FilterSpec {
415        &self.package_types
416    }
417    /// Whether to disable prompts for two-factor authentication (2FA) codes.
418    pub fn no_tfa(&self) -> bool {
419        self.no_tfa
420    }
421}
422
423impl HasVariables for Config {
424    #[tracing::instrument(level = "trace")]
425    fn get_variable(&self, input: &str) -> Result<Option<String>, GetVariableError> {
426        Ok(self.variables.get(input).cloned())
427    }
428}
429
430#[derive(Error, Debug, Diagnostic)]
431pub enum Error {
432    #[error(transparent)]
433    #[diagnostic(transparent)]
434    Fs(#[from] fs::Error),
435    #[error(transparent)]
436    #[diagnostic(transparent)]
437    NoValidHomeDirectory(#[from] NoValidHomeDirectory),
438    #[error("error parsing {config_file}")]
439    Deserialize {
440        config_file: String,
441        #[diagnostic_source]
442        source: TomlDeError,
443    },
444    #[error("error parsing URL: {source}")]
445    UrlParseError {
446        source: url::ParseError,
447        #[help]
448        help: Option<String>,
449    },
450}
451
452/// Incrementally builds a [`Config`] by layering configuration sources.
453///
454/// - Call [`Builder::default`] to start with a blank slate,
455///   or call [`Builder::new`] to start from a deserialised configuration file.
456/// - Populate the fields from overriding sources (e.g. CLI arguments).
457/// - Finish with [`Builder::build`].
458#[derive(Debug, Clone, Default, Deserialize, Serialize)]
459#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
460pub struct Builder {
461    /// The LuaRocks repository server to fetch rocks and rockspecs from.
462    /// Default: "https://luarocks.org/".
463    #[serde(
464        default,
465        deserialize_with = "deserialize_url",
466        serialize_with = "serialize_url"
467    )]
468    #[cfg_attr(feature = "schema", schemars(with = "Option<String>"))]
469    server: Option<Url>,
470    /// Additional LuaRocks repository servers.
471    #[serde(
472        default,
473        deserialize_with = "deserialize_url_vec",
474        serialize_with = "serialize_url_vec"
475    )]
476    #[cfg_attr(feature = "schema", schemars(with = "Option<Vec<String>>"))]
477    extra_servers: Option<Vec<Url>>,
478    /// Additional wally package registries (git-index URLs), in addition to the
479    /// official wally index.
480    #[serde(
481        default,
482        deserialize_with = "deserialize_url_vec",
483        serialize_with = "serialize_url_vec"
484    )]
485    #[cfg_attr(feature = "schema", schemars(with = "Option<Vec<String>>"))]
486    extra_wally_registries: Option<Vec<Url>>,
487    /// The LuaRocks server namespace to use.
488    namespace: Option<String>,
489    /// The Lua version to use. Default: the detected installed Lua version.
490    lua_version: Option<lua::Version>,
491    /// The tree in which to install rocks.
492    user_tree: Option<PathBuf>,
493    /// The tree to use when in a workspace.
494    /// Default: a ".lux" directory in the workspace root.
495    workspace_tree: Option<PathBuf>,
496    /// The directory in which to install Lua if it is not found.
497    lua_dir: Option<PathBuf>,
498    /// The URLs from which to download Lua sources, in order of preference.
499    /// Default: the official Lua FTP server, falling back to its PUC-Rio mirror.
500    #[serde(
501        default,
502        deserialize_with = "deserialize_url_vec",
503        serialize_with = "serialize_url_vec"
504    )]
505    #[cfg_attr(feature = "schema", schemars(with = "Option<Vec<String>>"))]
506    lua_mirrors: Option<Vec<Url>>,
507    /// The cache directory, e.g. for LuaRocks manifests.
508    cache_dir: Option<PathBuf>,
509    /// The data directory, in which the default user install tree resides.
510    data_dir: Option<PathBuf>,
511    /// A directory with locally vendored sources and rockspecs, used instead of
512    /// a remote server.
513    vendor_dir: Option<PathBuf>,
514    /// Whether to fetch development/scm rocks. Default: `false`.
515    enable_development_packages: Option<bool>,
516    /// Whether to display verbose output of executed commands. Default: `false`.
517    verbose: Option<bool>,
518    /// Whether to disable progress bars and spinners. Default: `false`.
519    no_progress: Option<bool>,
520    /// Whether to skip prompts, selecting the default option. Default: `false`.
521    no_prompt: Option<bool>,
522    /// Timeout for network operations, in seconds. `0` disables the timeout.
523    /// Default: `0`.
524    #[cfg_attr(feature = "schema", schemars(with = "Option<u64>"))]
525    timeout: Option<Duration>,
526    /// Maximum number of parallel jobs, e.g. for downloads and installs.
527    /// `0` means no limit.
528    max_jobs: Option<usize>,
529    /// Variable names mapped to their values. Lux substitutes these in the
530    /// `lux.toml` and in rockspecs before building.
531    variables: Option<HashMap<String, String>>,
532    /// Access tokens for fetching sources from private hosts, mapped by host.
533    /// These can also be set via the `LUX_ACCESS_TOKENS` environment variable.
534    #[serde(default, skip_serializing)]
535    #[cfg_attr(feature = "schema", schemars(with = "Option<HashMap<String, String>>"))]
536    access_tokens: Option<HashMap<String, AccessToken>>,
537    #[serde(default)]
538    external_deps: ExternalDependencySearchConfig,
539    #[serde(default)]
540    build: BuildConfig,
541
542    #[serde(skip)]
543    entrypoint_layout: Option<Arc<dyn CustomRockLayout>>,
544    /// The user agent to use when making web requests.
545    /// Default: "lux/<version>" (CLI), "lux-lua/<version>" (lux-lua) or "lux-lib/<version>".
546    user_agent: Option<String>,
547    /// Whether to generate a ".luarc.json" on build. Default: `true`.
548    generate_luarc: Option<bool>,
549    /// The Lua language server configuration file name. Default: ".luarc.json".
550    luarc_file_name: Option<String>,
551    /// Whether to wrap installed Lua bin scripts to run with the detected or
552    /// configured Lua installation. Default: `true`.
553    wrap_bin_scripts: Option<bool>,
554    /// Which package types to include in searches.
555    package_types: Option<remote::package::kind::FilterSpec>,
556    /// Whether to disable prompts for two-factor authentication (2FA) codes.
557    /// Default: `false`.
558    no_tfa: Option<bool>,
559}
560
561/// A builder for the lux `Config`.
562impl Builder {
563    /// Create a new `Builder` by deserializing from a config file
564    /// if present, or otherwise by instantiating the default config.
565    pub fn new() -> Result<Self, Error> {
566        let config_file = Self::config_file()?;
567        if config_file.is_file() {
568            Self::from_file(&config_file)
569        } else {
570            Ok(Self::default())
571        }
572    }
573
574    pub(crate) fn from_file(config_file: &Path) -> Result<Self, Error> {
575        let config_file_name = config_file.to_string_lossy().to_string();
576        let content = fs::sync::read_to_string(config_file)?;
577        crate::project::parse_toml(&config_file_name, &content).map_err(|source| {
578            Error::Deserialize {
579                config_file: config_file_name,
580                source,
581            }
582        })
583    }
584
585    /// Get the path to the lux config file.
586    pub fn config_file() -> Result<PathBuf, NoValidHomeDirectory> {
587        let project_dirs = directories::ProjectDirs::from("org", "lumenlabs", "lux")
588            .ok_or(NoValidHomeDirectory)?;
589        Ok(project_dirs.config_dir().join("config.toml").to_path_buf())
590    }
591
592    /// Whether to enable development packages
593    /// Default: `false`
594    pub fn dev(self, dev: Option<bool>) -> Self {
595        Self {
596            enable_development_packages: dev.or(self.enable_development_packages),
597            ..self
598        }
599    }
600
601    /// Fetch rocks/rockspecs from this luarocks server
602    /// Default: `"https://luarocks.org/"`
603    pub fn server(self, server: Option<Url>) -> Self {
604        Self {
605            server: server.or(self.server),
606            ..self
607        }
608    }
609
610    /// Fetch rocks/rockspecs from these servers in addition to the main server
611    pub fn extra_servers(self, extra_servers: Option<Vec<Url>>) -> Self {
612        Self {
613            extra_servers: extra_servers.or(self.extra_servers),
614            ..self
615        }
616    }
617
618    /// Additional wally package registries, in addition to the official wally index
619    pub fn extra_wally_registries(self, extra_wally_registries: Option<Vec<Url>>) -> Self {
620        Self {
621            extra_wally_registries: extra_wally_registries.or(self.extra_wally_registries),
622            ..self
623        }
624    }
625
626    /// The luarocks server namespace to use
627    pub fn namespace(self, namespace: Option<String>) -> Self {
628        Self {
629            namespace: namespace.or(self.namespace),
630            ..self
631        }
632    }
633
634    /// The directory in which to install Lua if not found
635    pub fn lua_dir(self, lua_dir: Option<PathBuf>) -> Self {
636        Self {
637            lua_dir: lua_dir.or(self.lua_dir),
638            ..self
639        }
640    }
641
642    /// The URLs from which to download Lua sources.
643    pub fn lua_mirrors(self, lua_mirrors: Option<Vec<Url>>) -> Self {
644        Self {
645            lua_mirrors: lua_mirrors.or(self.lua_mirrors),
646            ..self
647        }
648    }
649
650    /// Which Lua version to use.
651    /// Default: The installed Lua version, if detected
652    pub fn lua_version(self, lua_version: Option<lua::Version>) -> Self {
653        Self {
654            lua_version: lua_version.or(self.lua_version),
655            ..self
656        }
657    }
658
659    /// Which tree to operate on
660    pub fn user_tree(self, tree: Option<PathBuf>) -> Self {
661        Self {
662            user_tree: tree.or(self.user_tree),
663            ..self
664        }
665    }
666
667    /// Which tree to operate on when in a workspace
668    /// Default: A `.lux` directory in the workspace root.
669    pub fn workspace_tree(self, tree: Option<PathBuf>) -> Self {
670        Self {
671            workspace_tree: tree.or(self.workspace_tree),
672            ..self
673        }
674    }
675
676    /// Variable names, mapped to their values.
677    /// Lux populates variables in the `lux.toml` and in RockSpecs
678    /// with these before building.
679    pub fn variables(self, variables: Option<HashMap<String, String>>) -> Self {
680        Self {
681            variables: variables.or(self.variables),
682            ..self
683        }
684    }
685
686    /// Whether to display verbose output of commands executed.
687    /// Default: `false`
688    pub fn verbose(self, verbose: Option<bool>) -> Self {
689        Self {
690            verbose: verbose.or(self.verbose),
691            ..self
692        }
693    }
694
695    /// Whether to disable printing progress bars and spinners
696    /// Default: `false`
697    pub fn no_progress(self, no_progress: Option<bool>) -> Self {
698        Self {
699            no_progress: no_progress.or(self.no_progress),
700            ..self
701        }
702    }
703
704    /// Whether to disable user prompts
705    /// Default: `false`
706    pub fn no_prompt(self, no_prompt: Option<bool>) -> Self {
707        Self {
708            no_prompt: no_prompt.or(self.no_prompt),
709            ..self
710        }
711    }
712
713    /// Timeout on network operations, in seconds.
714    /// 0 means no timeout (wait forever).
715    /// Default: 0 s
716    pub fn timeout(self, timeout: Option<Duration>) -> Self {
717        Self {
718            timeout: timeout.or(self.timeout),
719            ..self
720        }
721    }
722
723    /// Maximum buffer size for parallel jobs, such as downloading rockspecs and installing rocks.
724    /// 0 means no limit.
725    /// Default: 0
726    pub fn max_jobs(self, max_jobs: Option<usize>) -> Self {
727        Self {
728            max_jobs: max_jobs.or(self.max_jobs),
729            ..self
730        }
731    }
732
733    /// The cache directory, e.g. for luarocks manifests.
734    pub fn cache_dir(self, cache_dir: Option<PathBuf>) -> Self {
735        Self {
736            cache_dir: cache_dir.or(self.cache_dir),
737            ..self
738        }
739    }
740
741    /// The data directory, in which the default user install tree resides.
742    pub fn data_dir(self, data_dir: Option<PathBuf>) -> Self {
743        Self {
744            data_dir: data_dir.or(self.data_dir),
745            ..self
746        }
747    }
748
749    /// Specifies a directory with locally vendored sources and RockSpecs.
750    /// When building or installing a package with this flag,
751    /// Lux will fetch sources from the <vendor-dir> instead of from a remote server.
752    pub fn vendor_dir(self, vendor_dir: Option<PathBuf>) -> Self {
753        Self {
754            vendor_dir: vendor_dir.or(self.vendor_dir),
755            ..self
756        }
757    }
758
759    /// The custom layout to apply to entrypoint packages.
760    pub fn entrypoint_layout(self, layout: impl CustomRockLayout + 'static) -> Self {
761        Self {
762            entrypoint_layout: Some(Arc::new(layout)),
763            ..self
764        }
765    }
766
767    /// The user agent to set when making web requests.
768    /// Default: "lux-lib/<version>".
769    pub fn user_agent(self, user_agent: Option<String>) -> Self {
770        Self {
771            user_agent: user_agent.or(self.user_agent),
772            ..self
773        }
774    }
775
776    /// Whether to generate a `.luarc.json` on build.
777    /// Default: `true`
778    pub fn generate_luarc(self, generate: Option<bool>) -> Self {
779        Self {
780            generate_luarc: generate.or(self.generate_luarc),
781            ..self
782        }
783    }
784
785    /// Lua runtime configuration file name
786    /// Default: `.luarc.json`
787    pub fn luarc_file_name(self, file: Option<String>) -> Self {
788        Self {
789            luarc_file_name: file.or(self.luarc_file_name),
790            ..self
791        }
792    }
793
794    /// Whether to wrap installed Lua bin scripts to be executed with
795    /// the detected or configured Lua installation.
796    /// Setting this to `false` disables wrapping globally.
797    /// If set to `true`, individual rocks can still disable wrapping of their own bin scripts.
798    /// Default: `true`.
799    pub fn wrap_bin_scripts(self, generate: Option<bool>) -> Self {
800        Self {
801            wrap_bin_scripts: generate.or(self.generate_luarc),
802            ..self
803        }
804    }
805    /// Whether to disable prompts for two-factor authentication (2FA) codes.
806    /// Default: `false`.
807    pub fn no_tfa(self, tfa: Option<bool>) -> Self {
808        Self {
809            no_tfa: tfa.or(self.no_tfa),
810            ..self
811        }
812    }
813
814    /// The command prefix with which to wrap all build commands.
815    ///
816    /// If set, every command spawned by the build backends (`make`, `cmake`,
817    /// `rust-mlua`, `command`, and `luarocks`) is invoked as
818    /// `runner + [command, arguments...]`.
819    ///
820    /// If unset, no wrapping is performed.
821    ///
822    /// # Examples
823    ///
824    /// Use [`bubblewrap`](https://github.com/containers/bubblewrap) to run
825    /// builds in a sandbox with read-only access to the rest of the
826    /// filesystem (Linux):
827    ///
828    /// ```toml
829    /// [build]
830    /// runner = [
831    ///     "bwrap",
832    ///     "--ro-bind", "/", "/",
833    ///     "--dev-bind", "/dev", "/dev",
834    ///     "--proc", "/proc",
835    ///     "--bind", "/tmp", "/tmp",
836    ///     "--bind", "/home/user/.cache/lux", "/home/user/.cache/lux",
837    ///     "--bind", "/home/user/.local/share/lux", "/home/user/.local/share/lux",
838    ///     "--unshare-net",
839    ///     "--new-session",
840    /// ]
841    /// ```
842    ///
843    /// Or use `sandbox-exec` with a seatbelt profile (macOS):
844    ///
845    /// ```text
846    /// (version 1)
847    /// (deny default)
848    /// (allow file-read*)
849    /// (allow process*)
850    /// (allow sysctl-read)
851    /// (allow file-write* (subpath "/tmp") (subpath "/Users/user/Library/Caches/lux") (subpath "/Users/user/.local/share/lux"))
852    /// ```
853    ///
854    /// ```toml
855    /// [build]
856    /// runner = ["sandbox-exec", "-f", "/Users/user/sandbox.sb"]
857    /// ```
858    ///
859    /// The writable directories must cover the places lux writes to during a
860    /// build: the temporary build directory (a tempfile, usually under
861    /// `/tmp`), the install tree (under the data directory), and cache
862    /// directories used by the various build backends.
863    pub fn build_runner(self, runner: Option<Vec<String>>) -> Self {
864        Self {
865            build: BuildConfig {
866                runner: runner.unwrap_or(self.build.runner),
867                ..self.build
868            },
869            ..self
870        }
871    }
872
873    /// The build profile to use when compiling packages.
874    /// Default: [`BuildProfile::Release`], if not set by [`Self::default_build_profile`].
875    pub fn build_profile(self, profile: Option<build::Profile>) -> Self {
876        Self {
877            build: BuildConfig {
878                profile: profile.or(self.build.profile),
879                ..self.build
880            },
881            ..self
882        }
883    }
884
885    /// set the default build profile to use when compiling packages.
886    pub fn default_build_profile(self, profile: build::Profile) -> Self {
887        Self {
888            build: BuildConfig {
889                profile: self.build.profile.or(Some(profile)),
890                ..self.build
891            },
892            ..self
893        }
894    }
895
896    /// Merge with another [`Builder`]. The other one takes precedence.
897    pub fn merge(self, other: Self) -> Self {
898        Self {
899            server: other.server.or(self.server),
900            extra_servers: other.extra_servers.or(self.extra_servers),
901            extra_wally_registries: other.extra_wally_registries.or(self.extra_wally_registries),
902            namespace: other.namespace.or(self.namespace),
903            lua_version: other.lua_version.or(self.lua_version),
904            user_tree: other.user_tree.or(self.user_tree),
905            workspace_tree: other.workspace_tree.or(self.workspace_tree),
906            lua_dir: other.lua_dir.or(self.lua_dir),
907            lua_mirrors: other.lua_mirrors.or(self.lua_mirrors),
908            cache_dir: other.cache_dir.or(self.cache_dir),
909            data_dir: other.data_dir.or(self.data_dir),
910            vendor_dir: other.vendor_dir.or(self.vendor_dir),
911            enable_development_packages: other
912                .enable_development_packages
913                .or(self.enable_development_packages),
914            verbose: other.verbose.or(self.verbose),
915            no_progress: other.no_progress.or(self.no_progress),
916            no_prompt: other.no_prompt.or(self.no_prompt),
917            timeout: other.timeout.or(self.timeout),
918            max_jobs: other.max_jobs.or(self.max_jobs),
919            variables: other.variables.or(self.variables),
920            access_tokens: other.access_tokens.or(self.access_tokens),
921            external_deps: other.external_deps,
922            build: BuildConfig {
923                profile: other.build.profile.or(self.build.profile),
924                ..other.build
925            },
926            entrypoint_layout: other.entrypoint_layout.or(self.entrypoint_layout),
927            user_agent: other.user_agent.or(self.user_agent),
928            generate_luarc: other.generate_luarc.or(self.generate_luarc),
929            luarc_file_name: other.luarc_file_name.or(self.luarc_file_name),
930            wrap_bin_scripts: other.wrap_bin_scripts.or(self.wrap_bin_scripts),
931            package_types: other.package_types.or(self.package_types),
932            no_tfa: other.no_tfa.or(self.no_tfa),
933        }
934    }
935
936    #[tracing::instrument(level = "trace")]
937    pub fn build(self) -> Result<Config, Error> {
938        let data_dir = self.data_dir.unwrap_or(Config::default_data_path());
939        let cache_dir = self.cache_dir.unwrap_or(Config::default_cache_path());
940        let user_tree = self.user_tree.unwrap_or(data_dir.join("tree"));
941
942        let lua_version = self.lua_version.or(lua::detect::installed_version());
943
944        Ok(normalise_base_urls(Config {
945            enable_development_packages: self.enable_development_packages.unwrap_or(false),
946            server: self.server.unwrap_or_else(|| unsafe {
947                Url::parse("https://luarocks.org/").unwrap_unchecked()
948            }),
949            extra_servers: self.extra_servers.unwrap_or_default(),
950            extra_wally_registries: self.extra_wally_registries.unwrap_or_default(),
951            namespace: self.namespace,
952            lua_dir: self.lua_dir,
953            lua_mirrors: self.lua_mirrors.unwrap_or_else(default_lua_mirrors),
954            lua_version,
955            user_tree,
956            workspace_tree: self.workspace_tree,
957            verbose: self.verbose.unwrap_or(false),
958            no_progress: self.no_progress.unwrap_or(false),
959            no_prompt: self.no_prompt.unwrap_or(false),
960            timeout: self.timeout.unwrap_or_else(|| Duration::from_secs(0)),
961            max_jobs: match self.max_jobs.unwrap_or_else(|| {
962                std::thread::available_parallelism().map_or(1, |available| available.get())
963            }) {
964                0 => usize::MAX,
965                max_jobs => max_jobs,
966            },
967            variables: default_variables()
968                .chain(self.variables.unwrap_or_default())
969                .collect(),
970            access_tokens: self.access_tokens.unwrap_or_default(),
971            external_deps: self.external_deps,
972            build: self.build,
973            entrypoint_layout: self.entrypoint_layout,
974            cache_dir,
975            data_dir,
976            vendor_dir: self.vendor_dir,
977            user_agent: self.user_agent.unwrap_or(DEFAULT_USER_AGENT.into()),
978            generate_luarc: self.generate_luarc.unwrap_or(true),
979            luarc_file_name: self
980                .luarc_file_name
981                .unwrap_or_else(|| ".luarc.json".to_string()),
982            wrap_bin_scripts: self.wrap_bin_scripts.unwrap_or(true),
983            package_types: self.package_types.unwrap_or_default(),
984            no_tfa: self.no_tfa.unwrap_or(false),
985            https_client_cache: OnceLock::new(),
986            http_client_cache: OnceLock::new(),
987        }))
988    }
989}
990
991/// Useful for printing the current config
992impl From<Config> for Builder {
993    fn from(value: Config) -> Self {
994        Builder {
995            enable_development_packages: Some(value.enable_development_packages),
996            server: Some(value.server),
997            extra_servers: Some(value.extra_servers),
998            extra_wally_registries: Some(value.extra_wally_registries),
999            namespace: value.namespace,
1000            lua_dir: value.lua_dir,
1001            lua_mirrors: Some(value.lua_mirrors),
1002            lua_version: value.lua_version,
1003            user_tree: Some(value.user_tree),
1004            workspace_tree: value.workspace_tree,
1005            verbose: Some(value.verbose),
1006            no_progress: Some(value.no_progress),
1007            no_prompt: Some(value.no_prompt),
1008            timeout: Some(value.timeout),
1009            max_jobs: if value.max_jobs == usize::MAX {
1010                None
1011            } else {
1012                Some(value.max_jobs)
1013            },
1014            variables: Some(value.variables),
1015            access_tokens: Some(value.access_tokens),
1016            cache_dir: Some(value.cache_dir),
1017            data_dir: Some(value.data_dir),
1018            vendor_dir: value.vendor_dir,
1019            external_deps: value.external_deps,
1020            build: value.build,
1021            entrypoint_layout: value.entrypoint_layout,
1022            user_agent: Some(value.user_agent),
1023            generate_luarc: Some(value.generate_luarc),
1024            luarc_file_name: Some(value.luarc_file_name),
1025            wrap_bin_scripts: Some(value.wrap_bin_scripts),
1026            package_types: Some(value.package_types),
1027            no_tfa: Some(value.no_tfa),
1028        }
1029    }
1030}
1031
1032fn default_variables() -> impl Iterator<Item = (String, String)> {
1033    let cflags = env::var("CFLAGS").unwrap_or(target::default_cflags().into());
1034    let ldflags = env::var("LDFLAGS").unwrap_or("".into());
1035    vec![
1036        ("MAKE".into(), "make".into()),
1037        ("CMAKE".into(), "cmake".into()),
1038        ("LIB_EXTENSION".into(), target::c_dylib_extension().into()),
1039        ("OBJ_EXTENSION".into(), target::c_obj_extension().into()),
1040        ("CFLAGS".into(), cflags),
1041        ("LDFLAGS".into(), ldflags),
1042        ("LIBFLAG".into(), target::default_libflag().into()),
1043    ]
1044    .into_iter()
1045}
1046
1047fn default_lua_mirrors() -> Vec<Url> {
1048    DEFAULT_LUA_MIRRORS
1049        .into_iter()
1050        .map(|mirror| unsafe { Url::parse(mirror).unwrap_unchecked() })
1051        .collect()
1052}
1053
1054fn normalise_base_url(mut url: Url) -> Url {
1055    if !url.path().ends_with('/') {
1056        url.set_path(&format!("{}/", url.path()));
1057    }
1058    url
1059}
1060
1061fn normalise_base_urls(mut config: Config) -> Config {
1062    config.server = normalise_base_url(config.server);
1063    config.extra_servers = config
1064        .extra_servers
1065        .into_iter()
1066        .map(normalise_base_url)
1067        .collect();
1068    config.lua_mirrors = config
1069        .lua_mirrors
1070        .into_iter()
1071        .map(normalise_base_url)
1072        .collect();
1073    config
1074}
1075
1076fn deserialize_url<'de, D>(deserializer: D) -> Result<Option<Url>, D::Error>
1077where
1078    D: serde::Deserializer<'de>,
1079{
1080    let s = Option::<String>::deserialize(deserializer)?;
1081    s.map(|s| Url::parse(&s).map_err(serde::de::Error::custom))
1082        .transpose()
1083}
1084
1085fn serialize_url<S>(url: &Option<Url>, serializer: S) -> Result<S::Ok, S::Error>
1086where
1087    S: Serializer,
1088{
1089    match url {
1090        Some(url) => serializer.serialize_some(url.as_str()),
1091        None => serializer.serialize_none(),
1092    }
1093}
1094
1095fn deserialize_url_vec<'de, D>(deserializer: D) -> Result<Option<Vec<Url>>, D::Error>
1096where
1097    D: serde::Deserializer<'de>,
1098{
1099    let s = Option::<Vec<String>>::deserialize(deserializer)?;
1100    s.map(|v| {
1101        v.into_iter()
1102            .map(|s| Url::parse(&s).map_err(serde::de::Error::custom))
1103            .try_collect()
1104    })
1105    .transpose()
1106}
1107
1108fn serialize_url_vec<S>(urls: &Option<Vec<Url>>, serializer: S) -> Result<S::Ok, S::Error>
1109where
1110    S: Serializer,
1111{
1112    match urls {
1113        Some(urls) => {
1114            let url_strings: Vec<String> = urls.iter().map(|url| url.to_string()).collect();
1115            serializer.serialize_some(&url_strings)
1116        }
1117        None => serializer.serialize_none(),
1118    }
1119}
1120
1121#[cfg(test)]
1122mod tests {
1123    use std::time::Duration;
1124
1125    use httptest::{
1126        matchers::request,
1127        responders::{delay_and_then, status_code},
1128        Expectation, Server,
1129    };
1130
1131    use super::*;
1132
1133    #[tokio::test]
1134    async fn wrapped_command_without_runner() {
1135        let echo = which::which("echo").unwrap();
1136        let config = Builder::default().build().unwrap();
1137        let output = config
1138            .wrapped_command(&echo, ["hello", "world"])
1139            .output()
1140            .await
1141            .unwrap();
1142        assert!(output.status.success());
1143        assert_eq!(
1144            String::from_utf8_lossy(&output.stdout).trim(),
1145            "hello world"
1146        );
1147    }
1148
1149    #[tokio::test]
1150    async fn configured_timeout_is_applied() {
1151        let server = Server::run();
1152        server.expect(
1153            Expectation::matching(request::method_path("GET", "/"))
1154                .respond_with(delay_and_then(Duration::from_secs(5), status_code(200))),
1155        );
1156        let config = Builder::new()
1157            .unwrap()
1158            .timeout(Some(Duration::from_millis(100)))
1159            .build()
1160            .unwrap();
1161        let error = config
1162            .http_client()
1163            .unwrap()
1164            .get(server.url_str("/"))
1165            .send()
1166            .await
1167            .unwrap_err();
1168        assert!(error.is_timeout());
1169    }
1170
1171    #[tokio::test]
1172    async fn wrapped_command_prepends_runner_argv() {
1173        let echo = which::which("echo").unwrap();
1174        let config = Builder::default()
1175            .build_runner(Some(vec![echo.to_string_lossy().into(), "--prefix".into()]))
1176            .build()
1177            .unwrap();
1178        let output = config
1179            .wrapped_command("world", Vec::<String>::new())
1180            .output()
1181            .await
1182            .unwrap();
1183        assert!(output.status.success());
1184        assert_eq!(
1185            String::from_utf8_lossy(&output.stdout).trim(),
1186            "--prefix world"
1187        );
1188    }
1189
1190    #[test]
1191    fn base_urls_resolve_relative_paths() {
1192        let config = Builder::default()
1193            .server(Some(Url::parse("https://example.com/texrocks").unwrap()))
1194            .extra_servers(Some(vec![
1195                Url::parse("https://example.com/texrocks").unwrap()
1196            ]))
1197            .build()
1198            .unwrap();
1199
1200        assert_eq!(
1201            config.server().join("manifest-5.1.zip").unwrap().as_str(),
1202            "https://example.com/texrocks/manifest-5.1.zip"
1203        );
1204        assert_eq!(
1205            config.extra_servers()[0]
1206                .join("manifest-5.1.zip")
1207                .unwrap()
1208                .as_str(),
1209            "https://example.com/texrocks/manifest-5.1.zip"
1210        );
1211
1212        let rebuilt = Builder::from(config.clone()).build().unwrap();
1213        assert_eq!(rebuilt.server(), config.server());
1214        assert_eq!(rebuilt.extra_servers(), config.extra_servers());
1215    }
1216
1217    #[test]
1218    fn lua_mirrors_default_to_the_official_download_area_and_its_mirror() {
1219        let config = Builder::default().build().unwrap();
1220        assert_eq!(
1221            config.lua_mirrors(),
1222            [
1223                Url::parse("https://www.lua.org/ftp/").unwrap(),
1224                Url::parse("https://www.tecgraf.puc-rio.br/lua/ftp/").unwrap()
1225            ]
1226        );
1227    }
1228
1229    #[test]
1230    fn lua_mirrors_are_treated_as_base_urls() {
1231        let config = Builder::default()
1232            .lua_mirrors(Some(vec![Url::parse("https://example.com/lua").unwrap()]))
1233            .build()
1234            .unwrap();
1235        assert_eq!(
1236            config.lua_mirrors()[0]
1237                .join("lua-5.4.9.tar.gz")
1238                .unwrap()
1239                .as_str(),
1240            "https://example.com/lua/lua-5.4.9.tar.gz"
1241        );
1242    }
1243
1244    #[test]
1245    fn debug_redacts_access_tokens() {
1246        let config: Config =
1247            toml::from_str::<Builder>("[access_tokens]\n\"github.com\" = \"supersecret\"\n")
1248                .unwrap()
1249                .build()
1250                .unwrap();
1251        let debug = format!("{config:?}");
1252        assert!(!debug.contains("supersecret"));
1253        assert!(debug.contains("access_tokens"));
1254    }
1255
1256    #[test]
1257    fn external_deps_prefixes_default_empty() {
1258        let config = toml::from_str::<Builder>(
1259            "[external_deps]\nlib_subdirs = [\"lib/x86_64-linux-gnu\"]\n",
1260        )
1261        .unwrap()
1262        .build()
1263        .unwrap();
1264        assert!(config.external_deps().prefixes.is_empty());
1265        assert_eq!(
1266            config.external_deps().lib_subdirs,
1267            vec![PathBuf::from("lib/x86_64-linux-gnu")]
1268        );
1269    }
1270}