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