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