Skip to main content

lux_lib/config/
mod.rs

1use directories::ProjectDirs;
2use external_deps::ExternalDependencySearchConfig;
3use itertools::Itertools;
4
5use miette::Diagnostic;
6use serde::{Deserialize, Serialize, Serializer};
7use std::{collections::HashMap, env, io, path::PathBuf, time::Duration};
8use thiserror::Error;
9use tree::RockLayoutConfig;
10use url::Url;
11
12use crate::lua_version::LuaVersion;
13use crate::project::TomlDeError;
14use crate::tree::{Tree, TreeError};
15use crate::variables::GetVariableError;
16use crate::{build::utils, variables::HasVariables};
17
18pub mod external_deps;
19pub mod tree;
20
21const DEV_PATH: &str = "dev/";
22const DEFAULT_USER_AGENT: &str = concat!("lux-lib/", env!("CARGO_PKG_VERSION"));
23
24#[derive(Error, Debug, Diagnostic)]
25#[error("could not find a valid home directory")]
26#[diagnostic(
27    code(lux_lib::no_home_directory),
28    help("this usually means you're running Lux in a managed environment like LDAP or a live session.")
29)]
30pub struct NoValidHomeDirectory;
31
32/// The resolved configuration for a Lux session.
33/// Can be constructed via [`ConfigBuilder`], which supports layering multiple
34/// configuration sources (config file, CLI flags, environment variables).
35#[derive(Debug, Clone)]
36pub struct Config {
37    enable_development_packages: bool,
38    server: Url,
39    extra_servers: Vec<Url>,
40    namespace: Option<String>,
41    lua_dir: Option<PathBuf>,
42    lua_version: Option<LuaVersion>,
43    user_tree: PathBuf,
44    verbose: bool,
45    /// Don't display progress bars
46    no_progress: bool,
47    /// Skip prompts (choosing the default choice)
48    no_prompt: bool,
49    timeout: Duration,
50    max_jobs: usize,
51    variables: HashMap<String, String>,
52    external_deps: ExternalDependencySearchConfig,
53    entrypoint_layout: RockLayoutConfig,
54
55    cache_dir: PathBuf,
56    data_dir: PathBuf,
57    vendor_dir: Option<PathBuf>,
58
59    user_agent: String,
60
61    generate_luarc: bool,
62    luarc_file_name: String,
63    wrap_bin_scripts: bool,
64}
65
66impl Config {
67    /// Lux application directories
68    fn project_dirs() -> Result<ProjectDirs, NoValidHomeDirectory> {
69        directories::ProjectDirs::from("org", "lumenlabs", "lux").ok_or(NoValidHomeDirectory)
70    }
71
72    /// Lux cache directory
73    fn default_cache_path() -> Result<PathBuf, NoValidHomeDirectory> {
74        let project_dirs = Config::project_dirs()?;
75        Ok(project_dirs.cache_dir().to_path_buf())
76    }
77
78    /// Lux data directory
79    fn default_data_path() -> Result<PathBuf, NoValidHomeDirectory> {
80        let project_dirs = Config::project_dirs()?;
81        Ok(project_dirs.data_local_dir().to_path_buf())
82    }
83
84    /// Create a copy of this config for the specified Lua version
85    pub fn with_lua_version(self, lua_version: LuaVersion) -> Self {
86        Self {
87            lua_version: Some(lua_version),
88            ..self
89        }
90    }
91
92    /// Create a copy of this config with the specified install tree
93    pub fn with_tree(self, tree: PathBuf) -> Self {
94        Self {
95            user_tree: tree,
96            ..self
97        }
98    }
99
100    /// The luarocks repository server
101    pub fn server(&self) -> &Url {
102        &self.server
103    }
104
105    /// Additional luarocks repository servers
106    pub fn extra_servers(&self) -> &Vec<Url> {
107        self.extra_servers.as_ref()
108    }
109
110    /// Enabled luarocks repository servers that provide dev/scm rocks
111    pub fn enabled_dev_servers(&self) -> Result<Vec<Url>, ConfigError> {
112        let mut enabled_dev_servers = Vec::new();
113        if self.enable_development_packages {
114            let config_file = ConfigBuilder::config_file()
115                .map(|p| p.to_string_lossy().to_string())
116                .unwrap_or_default();
117            enabled_dev_servers.push(self.server().join(DEV_PATH).map_err(|source| {
118                ConfigError::UrlParseError {
119                    source,
120                    help: Some(format!("check the `server` URL in {config_file}")),
121                }
122            })?);
123            for server in self.extra_servers() {
124                enabled_dev_servers.push(server.join(DEV_PATH).map_err(|source| {
125                    ConfigError::UrlParseError {
126                        source,
127                        help: Some(format!("check the `extra_servers` URLs in {config_file}")),
128                    }
129                })?);
130            }
131        }
132        Ok(enabled_dev_servers)
133    }
134
135    /// The luarocks server namespace to use
136    pub fn namespace(&self) -> Option<&String> {
137        self.namespace.as_ref()
138    }
139
140    /// The directory in which to install Lua{n} if not found
141    pub fn lua_dir(&self) -> Option<&PathBuf> {
142        self.lua_dir.as_ref()
143    }
144
145    // TODO(vhyrro): Remove `LuaVersion::from(&config)` and keep this only.
146    pub fn lua_version(&self) -> Option<&LuaVersion> {
147        self.lua_version.as_ref()
148    }
149
150    /// The tree in which to install rocks.
151    /// If installing packages for a project, use `Project::tree` instead.
152    pub fn user_tree(&self, version: LuaVersion) -> Result<Tree, TreeError> {
153        Tree::new(self.user_tree.clone(), version, self)
154    }
155
156    /// Whether to display verbose output of commands executed
157    pub fn verbose(&self) -> bool {
158        self.verbose
159    }
160
161    /// Whether to disable printing progress bars and spinners
162    pub fn no_progress(&self) -> bool {
163        self.no_progress
164    }
165
166    /// Whether to skip prompts, selecting the default option
167    pub fn no_prompt(&self) -> bool {
168        self.no_prompt
169    }
170
171    /// Timeout on network operations, in seconds.
172    /// 0 means no timeout (wait forever).
173    pub fn timeout(&self) -> &Duration {
174        &self.timeout
175    }
176
177    /// Maximum buffer size for parallel jobs, such as downloading rockspecs and installing rocks.
178    /// 0 means no limit.
179    pub fn max_jobs(&self) -> usize {
180        self.max_jobs
181    }
182
183    /// Command to use for running `make` builds
184    pub fn make_cmd(&self) -> String {
185        match self.variables.get("MAKE") {
186            Some(make) => make.clone(),
187            None => "make".into(),
188        }
189    }
190
191    /// Command to use for running `cmake` builds
192    pub fn cmake_cmd(&self) -> String {
193        match self.variables.get("CMAKE") {
194            Some(cmake) => cmake.clone(),
195            None => "cmake".into(),
196        }
197    }
198
199    /// Variable names, mapped to their values.
200    /// Lux populates variables in the `lux.toml` and in RockSpecs
201    /// with these before building.
202    pub fn variables(&self) -> &HashMap<String, String> {
203        &self.variables
204    }
205
206    pub fn external_deps(&self) -> &ExternalDependencySearchConfig {
207        &self.external_deps
208    }
209
210    /// The rock layout for entrypoints of new install trees.
211    /// Does not affect existing install trees or dependency rock layouts.
212    pub fn entrypoint_layout(&self) -> &RockLayoutConfig {
213        &self.entrypoint_layout
214    }
215
216    /// The Lux cache directory
217    pub fn cache_dir(&self) -> &PathBuf {
218        &self.cache_dir
219    }
220
221    /// The Lux data directory
222    pub fn data_dir(&self) -> &PathBuf {
223        &self.data_dir
224    }
225
226    /// Specifies a directory with locally vendored sources and RockSpecs.
227    /// When building or installing a package with this flag,
228    /// Lux will fetch sources from the <vendor-dir> instead of from a remote server.
229    pub fn vendor_dir(&self) -> Option<&PathBuf> {
230        self.vendor_dir.as_ref()
231    }
232
233    /// The user agent to use when making web requests.
234    pub fn user_agent(&self) -> &str {
235        &self.user_agent
236    }
237
238    /// Whether to generate a `.luarc.json` on build.
239    pub fn generate_luarc(&self) -> bool {
240        self.generate_luarc
241    }
242
243    // Lua runtime configuration file name
244    pub fn luarc_file_name(&self) -> &str {
245        &self.luarc_file_name
246    }
247
248    /// Whether to wrap installed Lua bin scripts to be executed with
249    /// the detected or configured Lua installation.
250    /// If `true`, individual rocks can still disable wrapping of their own bin scripts.
251    pub fn wrap_bin_scripts(&self) -> bool {
252        self.wrap_bin_scripts
253    }
254}
255
256impl HasVariables for Config {
257    fn get_variable(&self, input: &str) -> Result<Option<String>, GetVariableError> {
258        Ok(self.variables.get(input).cloned())
259    }
260}
261
262#[derive(Error, Debug, Diagnostic)]
263pub enum ConfigError {
264    #[error("failed to read config file {config_file}")]
265    ConfigRead {
266        config_file: String,
267        source: io::Error,
268        #[help]
269        help: Option<String>,
270    },
271    #[error(transparent)]
272    #[diagnostic(transparent)]
273    NoValidHomeDirectory(#[from] NoValidHomeDirectory),
274    #[error("error parsing {config_file}")]
275    Deserialize {
276        config_file: String,
277        #[diagnostic_source]
278        source: TomlDeError,
279    },
280    #[error("error parsing URL: {source}")]
281    UrlParseError {
282        source: url::ParseError,
283        #[help]
284        help: Option<String>,
285    },
286}
287
288/// Incrementally builds a [`Config`] by layering configuration sources.
289///
290/// - Call [`ConfigBuilder::default`] to start with a blank slate,
291///   or call [`ConfigBuilder::new`] to start from a deserialised configuration file.
292/// - Populate the fields from overriding sources (e.g. CLI arguments).
293/// - Finish with [`ConfigBuilder::build`].
294#[derive(Clone, Default, Deserialize, Serialize)]
295pub struct ConfigBuilder {
296    #[serde(
297        default,
298        deserialize_with = "deserialize_url",
299        serialize_with = "serialize_url"
300    )]
301    server: Option<Url>,
302    #[serde(
303        default,
304        deserialize_with = "deserialize_url_vec",
305        serialize_with = "serialize_url_vec"
306    )]
307    extra_servers: Option<Vec<Url>>,
308    namespace: Option<String>,
309    lua_version: Option<LuaVersion>,
310    user_tree: Option<PathBuf>,
311    lua_dir: Option<PathBuf>,
312    cache_dir: Option<PathBuf>,
313    data_dir: Option<PathBuf>,
314    vendor_dir: Option<PathBuf>,
315    enable_development_packages: Option<bool>,
316    verbose: Option<bool>,
317    no_progress: Option<bool>,
318    no_prompt: Option<bool>,
319    timeout: Option<Duration>,
320    max_jobs: Option<usize>,
321    variables: Option<HashMap<String, String>>,
322    #[serde(default)]
323    external_deps: ExternalDependencySearchConfig,
324    #[serde(default)]
325    entrypoint_layout: RockLayoutConfig,
326    user_agent: Option<String>,
327    generate_luarc: Option<bool>,
328    luarc_file_name: Option<String>,
329    wrap_bin_scripts: Option<bool>,
330}
331
332/// A builder for the lux `Config`.
333impl ConfigBuilder {
334    /// Create a new `ConfigBuilder` by deserializing from a config file
335    /// if present, or otherwise by instantiating the default config.
336    pub fn new() -> Result<Self, ConfigError> {
337        let config_file = Self::config_file()?;
338        if config_file.is_file() {
339            let config_file_name = config_file.to_string_lossy().to_string();
340            let content = std::fs::read_to_string(&config_file).map_err(|source| {
341                ConfigError::ConfigRead {
342                    config_file: config_file_name.clone(),
343                    source,
344                    help: Some(format!(
345                        "check that {} exists and is readable",
346                        config_file.display()
347                    )),
348                }
349            })?;
350            crate::project::parse_toml(&config_file_name, &content).map_err(|source| {
351                ConfigError::Deserialize {
352                    config_file: config_file_name,
353                    source,
354                }
355            })
356        } else {
357            Ok(Self::default())
358        }
359    }
360
361    /// Get the path to the lux config file.
362    pub fn config_file() -> Result<PathBuf, NoValidHomeDirectory> {
363        let project_dirs = directories::ProjectDirs::from("org", "lumenlabs", "lux")
364            .ok_or(NoValidHomeDirectory)?;
365        Ok(project_dirs.config_dir().join("config.toml").to_path_buf())
366    }
367
368    /// Whether to enable development packages
369    /// Default: `false`
370    pub fn dev(self, dev: Option<bool>) -> Self {
371        Self {
372            enable_development_packages: dev.or(self.enable_development_packages),
373            ..self
374        }
375    }
376
377    /// Fetch rocks/rockspecs from this luarocks server
378    /// Default: `"https://luarocks.org/"`
379    pub fn server(self, server: Option<Url>) -> Self {
380        Self {
381            server: server.or(self.server),
382            ..self
383        }
384    }
385
386    /// Fetch rocks/rockspecs from these servers in addition to the main server
387    pub fn extra_servers(self, extra_servers: Option<Vec<Url>>) -> Self {
388        Self {
389            extra_servers: extra_servers.or(self.extra_servers),
390            ..self
391        }
392    }
393
394    /// The luarocks server namespace to use
395    pub fn namespace(self, namespace: Option<String>) -> Self {
396        Self {
397            namespace: namespace.or(self.namespace),
398            ..self
399        }
400    }
401
402    /// The directory in which to install Lua if not found
403    pub fn lua_dir(self, lua_dir: Option<PathBuf>) -> Self {
404        Self {
405            lua_dir: lua_dir.or(self.lua_dir),
406            ..self
407        }
408    }
409
410    /// Which Lua version to use.
411    /// Default: The installed Lua version, if detected
412    pub fn lua_version(self, lua_version: Option<LuaVersion>) -> Self {
413        Self {
414            lua_version: lua_version.or(self.lua_version),
415            ..self
416        }
417    }
418
419    /// Which tree to operate on
420    pub fn user_tree(self, tree: Option<PathBuf>) -> Self {
421        Self {
422            user_tree: tree.or(self.user_tree),
423            ..self
424        }
425    }
426
427    /// Variable names, mapped to their values.
428    /// Lux populates variables in the `lux.toml` and in RockSpecs
429    /// with these before building.
430    pub fn variables(self, variables: Option<HashMap<String, String>>) -> Self {
431        Self {
432            variables: variables.or(self.variables),
433            ..self
434        }
435    }
436
437    /// Whether to display verbose output of commands executed.
438    /// Default: `false`
439    pub fn verbose(self, verbose: Option<bool>) -> Self {
440        Self {
441            verbose: verbose.or(self.verbose),
442            ..self
443        }
444    }
445
446    /// Whether to disable printing progress bars and spinners
447    /// Default: `false`
448    pub fn no_progress(self, no_progress: Option<bool>) -> Self {
449        Self {
450            no_progress: no_progress.or(self.no_progress),
451            ..self
452        }
453    }
454
455    /// Whether to disable user prompts
456    /// Default: `false`
457    pub fn no_prompt(self, no_prompt: Option<bool>) -> Self {
458        Self {
459            no_prompt: no_prompt.or(self.no_prompt),
460            ..self
461        }
462    }
463
464    /// Timeout on network operations, in seconds.
465    /// 0 means no timeout (wait forever).
466    /// Default: 30 s
467    pub fn timeout(self, timeout: Option<Duration>) -> Self {
468        Self {
469            timeout: timeout.or(self.timeout),
470            ..self
471        }
472    }
473
474    /// Maximum buffer size for parallel jobs, such as downloading rockspecs and installing rocks.
475    /// 0 means no limit.
476    /// Default: 0
477    pub fn max_jobs(self, max_jobs: Option<usize>) -> Self {
478        Self {
479            max_jobs: max_jobs.or(self.max_jobs),
480            ..self
481        }
482    }
483
484    /// The cache directory, e.g. for luarocks manifests.
485    pub fn cache_dir(self, cache_dir: Option<PathBuf>) -> Self {
486        Self {
487            cache_dir: cache_dir.or(self.cache_dir),
488            ..self
489        }
490    }
491
492    /// The data directory, in which the default user install tree resides.
493    pub fn data_dir(self, data_dir: Option<PathBuf>) -> Self {
494        Self {
495            data_dir: data_dir.or(self.data_dir),
496            ..self
497        }
498    }
499
500    /// Specifies a directory with locally vendored sources and RockSpecs.
501    /// When building or installing a package with this flag,
502    /// Lux will fetch sources from the <vendor-dir> instead of from a remote server.
503    pub fn vendor_dir(self, vendor_dir: Option<PathBuf>) -> Self {
504        Self {
505            vendor_dir: vendor_dir.or(self.vendor_dir),
506            ..self
507        }
508    }
509
510    /// The rock layout for entrypoints of new install trees.
511    /// Does not affect existing install trees or dependency rock layouts.
512    pub fn entrypoint_layout(self, rock_layout: RockLayoutConfig) -> Self {
513        Self {
514            entrypoint_layout: rock_layout,
515            ..self
516        }
517    }
518
519    /// The user agent to set when making web requests.
520    /// Default: "lux-lib/<version>".
521    pub fn user_agent(self, user_agent: Option<String>) -> Self {
522        Self {
523            user_agent: user_agent.or(self.user_agent),
524            ..self
525        }
526    }
527
528    /// Whether to generate a `.luarc.json` on build.
529    /// Default: `true`
530    pub fn generate_luarc(self, generate: Option<bool>) -> Self {
531        Self {
532            generate_luarc: generate.or(self.generate_luarc),
533            ..self
534        }
535    }
536
537    /// Lua runtime configuration file name
538    /// Default: `.luarc.json`
539    pub fn luarc_file_name(self, file: Option<String>) -> Self {
540        Self {
541            luarc_file_name: file.or(self.luarc_file_name),
542            ..self
543        }
544    }
545
546    /// Whether to wrap installed Lua bin scripts to be executed with
547    /// the detected or configured Lua installation.
548    /// Setting this to `false` disables wrapping globally.
549    /// If set to `true`, individual rocks can still disable wrapping of their own bin scripts.
550    /// Default: `true`.
551    pub fn wrap_bin_scripts(self, generate: Option<bool>) -> Self {
552        Self {
553            wrap_bin_scripts: generate.or(self.generate_luarc),
554            ..self
555        }
556    }
557
558    pub fn build(self) -> Result<Config, ConfigError> {
559        let data_dir = self.data_dir.unwrap_or(Config::default_data_path()?);
560        let cache_dir = self.cache_dir.unwrap_or(Config::default_cache_path()?);
561        let user_tree = self.user_tree.unwrap_or(data_dir.join("tree"));
562
563        let lua_version = self
564            .lua_version
565            .or(crate::lua_installation::detect_installed_lua_version());
566
567        Ok(Config {
568            enable_development_packages: self.enable_development_packages.unwrap_or(false),
569            server: self.server.unwrap_or_else(|| unsafe {
570                Url::parse("https://luarocks.org/").unwrap_unchecked()
571            }),
572            extra_servers: self.extra_servers.unwrap_or_default(),
573            namespace: self.namespace,
574            lua_dir: self.lua_dir,
575            lua_version,
576            user_tree,
577            verbose: self.verbose.unwrap_or(false),
578            no_progress: self.no_progress.unwrap_or(false),
579            no_prompt: self.no_prompt.unwrap_or(false),
580            timeout: self.timeout.unwrap_or_else(|| Duration::from_secs(30)),
581            max_jobs: match self.max_jobs.unwrap_or(usize::MAX) {
582                0 => usize::MAX,
583                max_jobs => max_jobs,
584            },
585            variables: default_variables()
586                .chain(self.variables.unwrap_or_default())
587                .collect(),
588            external_deps: self.external_deps,
589            entrypoint_layout: self.entrypoint_layout,
590            cache_dir,
591            data_dir,
592            vendor_dir: self.vendor_dir,
593            user_agent: self.user_agent.unwrap_or(DEFAULT_USER_AGENT.into()),
594            generate_luarc: self.generate_luarc.unwrap_or(true),
595            luarc_file_name: self
596                .luarc_file_name
597                .unwrap_or_else(|| ".luarc.json".to_string()),
598            wrap_bin_scripts: self.wrap_bin_scripts.unwrap_or(true),
599        })
600    }
601}
602
603/// Useful for printing the current config
604impl From<Config> for ConfigBuilder {
605    fn from(value: Config) -> Self {
606        ConfigBuilder {
607            enable_development_packages: Some(value.enable_development_packages),
608            server: Some(value.server),
609            extra_servers: Some(value.extra_servers),
610            namespace: value.namespace,
611            lua_dir: value.lua_dir,
612            lua_version: value.lua_version,
613            user_tree: Some(value.user_tree),
614            verbose: Some(value.verbose),
615            no_progress: Some(value.no_progress),
616            no_prompt: Some(value.no_prompt),
617            timeout: Some(value.timeout),
618            max_jobs: if value.max_jobs == usize::MAX {
619                None
620            } else {
621                Some(value.max_jobs)
622            },
623            variables: Some(value.variables),
624            cache_dir: Some(value.cache_dir),
625            data_dir: Some(value.data_dir),
626            vendor_dir: value.vendor_dir,
627            external_deps: value.external_deps,
628            entrypoint_layout: value.entrypoint_layout,
629            user_agent: Some(value.user_agent),
630            generate_luarc: Some(value.generate_luarc),
631            luarc_file_name: Some(value.luarc_file_name),
632            wrap_bin_scripts: Some(value.wrap_bin_scripts),
633        }
634    }
635}
636
637fn default_variables() -> impl Iterator<Item = (String, String)> {
638    let cflags = env::var("CFLAGS").unwrap_or(utils::default_cflags().into());
639    let ldflags = env::var("LDFLAGS").unwrap_or("".into());
640    vec![
641        ("MAKE".into(), "make".into()),
642        ("CMAKE".into(), "cmake".into()),
643        ("LIB_EXTENSION".into(), utils::c_dylib_extension().into()),
644        ("OBJ_EXTENSION".into(), utils::c_obj_extension().into()),
645        ("CFLAGS".into(), cflags),
646        ("LDFLAGS".into(), ldflags),
647        ("LIBFLAG".into(), utils::default_libflag().into()),
648    ]
649    .into_iter()
650}
651
652fn deserialize_url<'de, D>(deserializer: D) -> Result<Option<Url>, D::Error>
653where
654    D: serde::Deserializer<'de>,
655{
656    let s = Option::<String>::deserialize(deserializer)?;
657    s.map(|s| Url::parse(&s).map_err(serde::de::Error::custom))
658        .transpose()
659}
660
661fn serialize_url<S>(url: &Option<Url>, serializer: S) -> Result<S::Ok, S::Error>
662where
663    S: Serializer,
664{
665    match url {
666        Some(url) => serializer.serialize_some(url.as_str()),
667        None => serializer.serialize_none(),
668    }
669}
670
671fn deserialize_url_vec<'de, D>(deserializer: D) -> Result<Option<Vec<Url>>, D::Error>
672where
673    D: serde::Deserializer<'de>,
674{
675    let s = Option::<Vec<String>>::deserialize(deserializer)?;
676    s.map(|v| {
677        v.into_iter()
678            .map(|s| Url::parse(&s).map_err(serde::de::Error::custom))
679            .try_collect()
680    })
681    .transpose()
682}
683
684fn serialize_url_vec<S>(urls: &Option<Vec<Url>>, serializer: S) -> Result<S::Ok, S::Error>
685where
686    S: Serializer,
687{
688    match urls {
689        Some(urls) => {
690            let url_strings: Vec<String> = urls.iter().map(|url| url.to_string()).collect();
691            serializer.serialize_some(&url_strings)
692        }
693        None => serializer.serialize_none(),
694    }
695}