1use build::BuildConfig;
2use directories::ProjectDirs;
3use external_deps::ExternalDependencySearchConfig;
4use itertools::Itertools;
5
6use miette::Diagnostic;
7use reqwest::Client;
8use serde::{Deserialize, Serialize, Serializer};
9use std::ffi::OsStr;
10use std::path::Path;
11use std::{
12 collections::HashMap,
13 env,
14 path::PathBuf,
15 sync::{Arc, OnceLock},
16 time::Duration,
17};
18use thiserror::Error;
19use tokio::process::Command;
20use url::Url;
21
22use crate::config::access_tokens::AccessToken;
23use crate::fs;
24use crate::lua;
25use crate::project::TomlDeError;
26use crate::remote;
27use crate::tree::{self, CustomRockLayout, Tree};
28use crate::variables::GetVariableError;
29use crate::{target, variables::HasVariables};
30
31pub mod access_tokens;
32pub mod build;
33pub mod external_deps;
34
35const DEV_PATH: &str = "dev/";
36const DEFAULT_LUA_MIRRORS: [&str; 2] = [
37 "https://www.lua.org/ftp",
38 "https://www.tecgraf.puc-rio.br/lua/ftp",
39];
40const DEFAULT_USER_AGENT: &str = concat!("lux-lib/", env!("CARGO_PKG_VERSION"));
41
42#[derive(Error, Debug, Diagnostic)]
43#[error("could not find a valid home directory")]
44#[diagnostic(
45 code(lux_lib::no_home_directory),
46 help("this usually means you're running Lux in a managed environment like LDAP or a live session.")
47)]
48pub struct NoValidHomeDirectory;
49
50#[derive(Debug, Clone)]
54pub struct Config {
55 enable_development_packages: bool,
56 server: Url,
57 extra_servers: Vec<Url>,
58 extra_wally_registries: Vec<Url>,
59 namespace: Option<String>,
60 lua_dir: Option<PathBuf>,
61 lua_mirrors: Vec<Url>,
62 lua_version: Option<lua::Version>,
63 user_tree: PathBuf,
64 workspace_tree: Option<PathBuf>,
65 verbose: bool,
66 no_progress: bool,
68 no_prompt: bool,
70 timeout: Duration,
71 max_jobs: usize,
72 variables: HashMap<String, String>,
73 access_tokens: HashMap<String, AccessToken>,
74 external_deps: ExternalDependencySearchConfig,
75
76 build: BuildConfig,
77 entrypoint_layout: Option<Arc<dyn CustomRockLayout>>,
78
79 cache_dir: PathBuf,
80 data_dir: PathBuf,
81 vendor_dir: Option<PathBuf>,
82
83 user_agent: String,
84
85 generate_luarc: bool,
86 luarc_file_name: String,
87 wrap_bin_scripts: bool,
88 package_types: remote::package::kind::FilterSpec,
89 no_tfa: bool,
90
91 https_client_cache: OnceLock<Client>,
92 http_client_cache: OnceLock<Client>,
93}
94
95impl Config {
96 pub(crate) fn project_dirs() -> Result<ProjectDirs, NoValidHomeDirectory> {
98 directories::ProjectDirs::from("org", "lumenlabs", "lux")
99 .filter(|_| Self::home_dir_exists())
100 .ok_or(NoValidHomeDirectory)
101 }
102
103 fn home_dir_exists() -> bool {
104 directories::BaseDirs::new().is_some_and(|base| base.home_dir().is_dir())
105 }
106
107 fn default_cache_path() -> PathBuf {
109 match Config::project_dirs() {
110 Ok(project_dirs) => project_dirs.cache_dir().to_path_buf(),
111 Err(_) => Self::fallback_data_dir("cache"),
112 }
113 }
114
115 fn default_data_path() -> PathBuf {
117 match Config::project_dirs() {
118 Ok(project_dirs) => project_dirs.data_local_dir().to_path_buf(),
119 Err(_) => Self::fallback_data_dir("data"),
120 }
121 }
122
123 fn fallback_data_dir(subdir: &str) -> PathBuf {
125 let path = std::env::temp_dir().join("lux").join(subdir);
126 tracing::warn!(
127 "no valid home directory found; falling back to `{}`",
128 path.display()
129 );
130 path
131 }
132
133 pub fn with_lua_version(self, lua_version: lua::Version) -> Self {
135 Self {
136 lua_version: Some(lua_version),
137 ..self
138 }
139 }
140
141 pub fn with_tree(self, tree: PathBuf) -> Self {
143 Self {
144 user_tree: tree,
145 ..self
146 }
147 }
148
149 pub fn with_workspace_tree(self, tree: Option<PathBuf>) -> Self {
151 Self {
152 workspace_tree: tree,
153 ..self
154 }
155 }
156
157 pub fn server(&self) -> &Url {
159 &self.server
160 }
161
162 pub fn extra_servers(&self) -> &Vec<Url> {
164 self.extra_servers.as_ref()
165 }
166
167 pub fn extra_wally_registries(&self) -> &Vec<Url> {
170 self.extra_wally_registries.as_ref()
171 }
172
173 pub fn enabled_dev_servers(&self) -> Result<Vec<Url>, Error> {
175 let mut enabled_dev_servers = Vec::new();
176 if self.enable_development_packages {
177 let config_file = Builder::config_file()
178 .map(|p| p.to_string_lossy().to_string())
179 .unwrap_or_default();
180 enabled_dev_servers.push(self.server().join(DEV_PATH).map_err(|source| {
181 Error::UrlParseError {
182 source,
183 help: Some(format!("check the `server` URL in {config_file}")),
184 }
185 })?);
186 for server in self.extra_servers() {
187 enabled_dev_servers.push(server.join(DEV_PATH).map_err(|source| {
188 Error::UrlParseError {
189 source,
190 help: Some(format!("check the `extra_servers` URLs in {config_file}")),
191 }
192 })?);
193 }
194 }
195 Ok(enabled_dev_servers)
196 }
197
198 pub fn namespace(&self) -> Option<&String> {
200 self.namespace.as_ref()
201 }
202
203 pub fn lua_dir(&self) -> Option<&PathBuf> {
205 self.lua_dir.as_ref()
206 }
207
208 pub fn lua_mirrors(&self) -> &[Url] {
210 &self.lua_mirrors
211 }
212
213 pub fn lua_version(&self) -> Option<&lua::Version> {
215 self.lua_version.as_ref()
216 }
217
218 pub fn user_tree(&self, version: lua::Version) -> Result<Tree, tree::Error> {
221 Tree::new(self.user_tree.clone(), version, self)
222 }
223
224 pub fn workspace_tree(&self) -> Option<&PathBuf> {
226 self.workspace_tree.as_ref()
227 }
228
229 pub fn verbose(&self) -> bool {
231 self.verbose
232 }
233
234 pub fn no_progress(&self) -> bool {
236 self.no_progress
237 }
238
239 pub fn no_prompt(&self) -> bool {
241 self.no_prompt
242 }
243
244 pub fn timeout(&self) -> &Duration {
247 &self.timeout
248 }
249
250 pub fn max_jobs(&self) -> usize {
253 self.max_jobs
254 }
255
256 pub fn make_cmd(&self) -> String {
258 match self.variables.get("MAKE") {
259 Some(make) => make.clone(),
260 None => "make".into(),
261 }
262 }
263
264 pub fn cmake_cmd(&self) -> String {
266 match self.variables.get("CMAKE") {
267 Some(cmake) => cmake.clone(),
268 None => "cmake".into(),
269 }
270 }
271
272 pub(crate) fn wrapped_command<P, A>(&self, program: P, args: A) -> Command
278 where
279 P: AsRef<OsStr>,
280 A: IntoIterator,
281 A::Item: AsRef<OsStr>,
282 {
283 if self.build.runner.is_empty() {
284 let mut cmd = Command::new(program);
285 cmd.args(args);
286 cmd
287 } else {
288 let runner = &self.build.runner;
289 let mut cmd = Command::new(&runner[0]);
290 cmd.args(&runner[1..]).arg(program).args(args);
291 cmd
292 }
293 }
294
295 pub(crate) fn build_profile(&self) -> build::Profile {
297 self.build
298 .profile
299 .as_ref()
300 .cloned()
301 .unwrap_or(build::Profile::Release)
302 }
303
304 pub fn variables(&self) -> &HashMap<String, String> {
308 &self.variables
309 }
310
311 pub fn access_token(&self, host: &str) -> Option<AccessToken> {
316 access_tokens::env_access_tokens()
317 .get(host)
318 .cloned()
319 .or_else(|| self.access_tokens.get(host).cloned())
320 .or_else(|| {
321 (host == "github.com")
322 .then(|| env::var("GITHUB_TOKEN").ok())
323 .flatten()
324 .map(|raw| AccessToken::from(raw.as_str()))
325 })
326 }
327
328 pub fn external_deps(&self) -> &ExternalDependencySearchConfig {
329 &self.external_deps
330 }
331
332 pub fn entrypoint_layout(&self) -> Option<&Arc<dyn CustomRockLayout>> {
334 self.entrypoint_layout.as_ref()
335 }
336
337 pub fn cache_dir(&self) -> &PathBuf {
339 &self.cache_dir
340 }
341
342 pub fn data_dir(&self) -> &PathBuf {
344 &self.data_dir
345 }
346
347 pub fn vendor_dir(&self) -> Option<&PathBuf> {
351 self.vendor_dir.as_ref()
352 }
353
354 pub fn user_agent(&self) -> &str {
356 &self.user_agent
357 }
358
359 pub fn https_client(&self) -> Result<&Client, reqwest::Error> {
361 self.cached_client(true)
362 }
363
364 pub(crate) fn http_client(&self) -> Result<&Client, reqwest::Error> {
367 self.cached_client(false)
368 }
369
370 fn cached_client(&self, https_only: bool) -> Result<&Client, reqwest::Error> {
371 let cache = if https_only {
372 &self.https_client_cache
373 } else {
374 &self.http_client_cache
375 };
376 if let Some(client) = cache.get() {
377 return Ok(client);
378 }
379 let client = self.build_client(https_only)?;
380 Ok(cache.get_or_init(|| client))
381 }
382
383 fn build_client(&self, https_only: bool) -> Result<Client, reqwest::Error> {
384 let mut builder = Client::builder();
385 if https_only && !cfg!(test) {
387 builder = builder.https_only(true);
388 }
389 if !self.timeout().is_zero() {
390 let timeout = *self.timeout();
391 builder = builder.connect_timeout(timeout).read_timeout(timeout);
392 }
393 builder.user_agent(self.user_agent()).build()
394 }
395
396 pub fn generate_luarc(&self) -> bool {
398 self.generate_luarc
399 }
400
401 pub fn luarc_file_name(&self) -> &str {
403 &self.luarc_file_name
404 }
405
406 pub fn wrap_bin_scripts(&self) -> bool {
410 self.wrap_bin_scripts
411 }
412
413 pub fn package_types(&self) -> &remote::package::kind::FilterSpec {
415 &self.package_types
416 }
417 pub fn no_tfa(&self) -> bool {
419 self.no_tfa
420 }
421}
422
423impl HasVariables for Config {
424 #[tracing::instrument(level = "trace")]
425 fn get_variable(&self, input: &str) -> Result<Option<String>, GetVariableError> {
426 Ok(self.variables.get(input).cloned())
427 }
428}
429
430#[derive(Error, Debug, Diagnostic)]
431pub enum Error {
432 #[error(transparent)]
433 #[diagnostic(transparent)]
434 Fs(#[from] fs::Error),
435 #[error(transparent)]
436 #[diagnostic(transparent)]
437 NoValidHomeDirectory(#[from] NoValidHomeDirectory),
438 #[error("error parsing {config_file}")]
439 Deserialize {
440 config_file: String,
441 #[diagnostic_source]
442 source: TomlDeError,
443 },
444 #[error("error parsing URL: {source}")]
445 UrlParseError {
446 source: url::ParseError,
447 #[help]
448 help: Option<String>,
449 },
450}
451
452#[derive(Debug, Clone, Default, Deserialize, Serialize)]
459#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
460pub struct Builder {
461 #[serde(
464 default,
465 deserialize_with = "deserialize_url",
466 serialize_with = "serialize_url"
467 )]
468 #[cfg_attr(feature = "schema", schemars(with = "Option<String>"))]
469 server: Option<Url>,
470 #[serde(
472 default,
473 deserialize_with = "deserialize_url_vec",
474 serialize_with = "serialize_url_vec"
475 )]
476 #[cfg_attr(feature = "schema", schemars(with = "Option<Vec<String>>"))]
477 extra_servers: Option<Vec<Url>>,
478 #[serde(
481 default,
482 deserialize_with = "deserialize_url_vec",
483 serialize_with = "serialize_url_vec"
484 )]
485 #[cfg_attr(feature = "schema", schemars(with = "Option<Vec<String>>"))]
486 extra_wally_registries: Option<Vec<Url>>,
487 namespace: Option<String>,
489 lua_version: Option<lua::Version>,
491 user_tree: Option<PathBuf>,
493 workspace_tree: Option<PathBuf>,
496 lua_dir: Option<PathBuf>,
498 #[serde(
501 default,
502 deserialize_with = "deserialize_url_vec",
503 serialize_with = "serialize_url_vec"
504 )]
505 #[cfg_attr(feature = "schema", schemars(with = "Option<Vec<String>>"))]
506 lua_mirrors: Option<Vec<Url>>,
507 cache_dir: Option<PathBuf>,
509 data_dir: Option<PathBuf>,
511 vendor_dir: Option<PathBuf>,
514 enable_development_packages: Option<bool>,
516 verbose: Option<bool>,
518 no_progress: Option<bool>,
520 no_prompt: Option<bool>,
522 #[cfg_attr(feature = "schema", schemars(with = "Option<u64>"))]
525 timeout: Option<Duration>,
526 max_jobs: Option<usize>,
529 variables: Option<HashMap<String, String>>,
532 #[serde(default, skip_serializing)]
535 #[cfg_attr(feature = "schema", schemars(with = "Option<HashMap<String, String>>"))]
536 access_tokens: Option<HashMap<String, AccessToken>>,
537 #[serde(default)]
538 external_deps: ExternalDependencySearchConfig,
539 #[serde(default)]
540 build: BuildConfig,
541
542 #[serde(skip)]
543 entrypoint_layout: Option<Arc<dyn CustomRockLayout>>,
544 user_agent: Option<String>,
547 generate_luarc: Option<bool>,
549 luarc_file_name: Option<String>,
551 wrap_bin_scripts: Option<bool>,
554 package_types: Option<remote::package::kind::FilterSpec>,
556 no_tfa: Option<bool>,
559}
560
561impl Builder {
563 pub fn new() -> Result<Self, Error> {
566 let config_file = Self::config_file()?;
567 if config_file.is_file() {
568 Self::from_file(&config_file)
569 } else {
570 Ok(Self::default())
571 }
572 }
573
574 pub(crate) fn from_file(config_file: &Path) -> Result<Self, Error> {
575 let config_file_name = config_file.to_string_lossy().to_string();
576 let content = fs::sync::read_to_string(config_file)?;
577 crate::project::parse_toml(&config_file_name, &content).map_err(|source| {
578 Error::Deserialize {
579 config_file: config_file_name,
580 source,
581 }
582 })
583 }
584
585 pub fn config_file() -> Result<PathBuf, NoValidHomeDirectory> {
587 let project_dirs = directories::ProjectDirs::from("org", "lumenlabs", "lux")
588 .ok_or(NoValidHomeDirectory)?;
589 Ok(project_dirs.config_dir().join("config.toml").to_path_buf())
590 }
591
592 pub fn dev(self, dev: Option<bool>) -> Self {
595 Self {
596 enable_development_packages: dev.or(self.enable_development_packages),
597 ..self
598 }
599 }
600
601 pub fn server(self, server: Option<Url>) -> Self {
604 Self {
605 server: server.or(self.server),
606 ..self
607 }
608 }
609
610 pub fn extra_servers(self, extra_servers: Option<Vec<Url>>) -> Self {
612 Self {
613 extra_servers: extra_servers.or(self.extra_servers),
614 ..self
615 }
616 }
617
618 pub fn extra_wally_registries(self, extra_wally_registries: Option<Vec<Url>>) -> Self {
620 Self {
621 extra_wally_registries: extra_wally_registries.or(self.extra_wally_registries),
622 ..self
623 }
624 }
625
626 pub fn namespace(self, namespace: Option<String>) -> Self {
628 Self {
629 namespace: namespace.or(self.namespace),
630 ..self
631 }
632 }
633
634 pub fn lua_dir(self, lua_dir: Option<PathBuf>) -> Self {
636 Self {
637 lua_dir: lua_dir.or(self.lua_dir),
638 ..self
639 }
640 }
641
642 pub fn lua_mirrors(self, lua_mirrors: Option<Vec<Url>>) -> Self {
644 Self {
645 lua_mirrors: lua_mirrors.or(self.lua_mirrors),
646 ..self
647 }
648 }
649
650 pub fn lua_version(self, lua_version: Option<lua::Version>) -> Self {
653 Self {
654 lua_version: lua_version.or(self.lua_version),
655 ..self
656 }
657 }
658
659 pub fn user_tree(self, tree: Option<PathBuf>) -> Self {
661 Self {
662 user_tree: tree.or(self.user_tree),
663 ..self
664 }
665 }
666
667 pub fn workspace_tree(self, tree: Option<PathBuf>) -> Self {
670 Self {
671 workspace_tree: tree.or(self.workspace_tree),
672 ..self
673 }
674 }
675
676 pub fn variables(self, variables: Option<HashMap<String, String>>) -> Self {
680 Self {
681 variables: variables.or(self.variables),
682 ..self
683 }
684 }
685
686 pub fn verbose(self, verbose: Option<bool>) -> Self {
689 Self {
690 verbose: verbose.or(self.verbose),
691 ..self
692 }
693 }
694
695 pub fn no_progress(self, no_progress: Option<bool>) -> Self {
698 Self {
699 no_progress: no_progress.or(self.no_progress),
700 ..self
701 }
702 }
703
704 pub fn no_prompt(self, no_prompt: Option<bool>) -> Self {
707 Self {
708 no_prompt: no_prompt.or(self.no_prompt),
709 ..self
710 }
711 }
712
713 pub fn timeout(self, timeout: Option<Duration>) -> Self {
717 Self {
718 timeout: timeout.or(self.timeout),
719 ..self
720 }
721 }
722
723 pub fn max_jobs(self, max_jobs: Option<usize>) -> Self {
727 Self {
728 max_jobs: max_jobs.or(self.max_jobs),
729 ..self
730 }
731 }
732
733 pub fn cache_dir(self, cache_dir: Option<PathBuf>) -> Self {
735 Self {
736 cache_dir: cache_dir.or(self.cache_dir),
737 ..self
738 }
739 }
740
741 pub fn data_dir(self, data_dir: Option<PathBuf>) -> Self {
743 Self {
744 data_dir: data_dir.or(self.data_dir),
745 ..self
746 }
747 }
748
749 pub fn vendor_dir(self, vendor_dir: Option<PathBuf>) -> Self {
753 Self {
754 vendor_dir: vendor_dir.or(self.vendor_dir),
755 ..self
756 }
757 }
758
759 pub fn entrypoint_layout(self, layout: impl CustomRockLayout + 'static) -> Self {
761 Self {
762 entrypoint_layout: Some(Arc::new(layout)),
763 ..self
764 }
765 }
766
767 pub fn user_agent(self, user_agent: Option<String>) -> Self {
770 Self {
771 user_agent: user_agent.or(self.user_agent),
772 ..self
773 }
774 }
775
776 pub fn generate_luarc(self, generate: Option<bool>) -> Self {
779 Self {
780 generate_luarc: generate.or(self.generate_luarc),
781 ..self
782 }
783 }
784
785 pub fn luarc_file_name(self, file: Option<String>) -> Self {
788 Self {
789 luarc_file_name: file.or(self.luarc_file_name),
790 ..self
791 }
792 }
793
794 pub fn wrap_bin_scripts(self, generate: Option<bool>) -> Self {
800 Self {
801 wrap_bin_scripts: generate.or(self.generate_luarc),
802 ..self
803 }
804 }
805 pub fn no_tfa(self, tfa: Option<bool>) -> Self {
808 Self {
809 no_tfa: tfa.or(self.no_tfa),
810 ..self
811 }
812 }
813
814 pub fn build_runner(self, runner: Option<Vec<String>>) -> Self {
864 Self {
865 build: BuildConfig {
866 runner: runner.unwrap_or(self.build.runner),
867 ..self.build
868 },
869 ..self
870 }
871 }
872
873 pub fn build_profile(self, profile: Option<build::Profile>) -> Self {
876 Self {
877 build: BuildConfig {
878 profile: profile.or(self.build.profile),
879 ..self.build
880 },
881 ..self
882 }
883 }
884
885 pub fn default_build_profile(self, profile: build::Profile) -> Self {
887 Self {
888 build: BuildConfig {
889 profile: self.build.profile.or(Some(profile)),
890 ..self.build
891 },
892 ..self
893 }
894 }
895
896 pub fn merge(self, other: Self) -> Self {
898 Self {
899 server: other.server.or(self.server),
900 extra_servers: other.extra_servers.or(self.extra_servers),
901 extra_wally_registries: other.extra_wally_registries.or(self.extra_wally_registries),
902 namespace: other.namespace.or(self.namespace),
903 lua_version: other.lua_version.or(self.lua_version),
904 user_tree: other.user_tree.or(self.user_tree),
905 workspace_tree: other.workspace_tree.or(self.workspace_tree),
906 lua_dir: other.lua_dir.or(self.lua_dir),
907 lua_mirrors: other.lua_mirrors.or(self.lua_mirrors),
908 cache_dir: other.cache_dir.or(self.cache_dir),
909 data_dir: other.data_dir.or(self.data_dir),
910 vendor_dir: other.vendor_dir.or(self.vendor_dir),
911 enable_development_packages: other
912 .enable_development_packages
913 .or(self.enable_development_packages),
914 verbose: other.verbose.or(self.verbose),
915 no_progress: other.no_progress.or(self.no_progress),
916 no_prompt: other.no_prompt.or(self.no_prompt),
917 timeout: other.timeout.or(self.timeout),
918 max_jobs: other.max_jobs.or(self.max_jobs),
919 variables: other.variables.or(self.variables),
920 access_tokens: other.access_tokens.or(self.access_tokens),
921 external_deps: other.external_deps,
922 build: BuildConfig {
923 profile: other.build.profile.or(self.build.profile),
924 ..other.build
925 },
926 entrypoint_layout: other.entrypoint_layout.or(self.entrypoint_layout),
927 user_agent: other.user_agent.or(self.user_agent),
928 generate_luarc: other.generate_luarc.or(self.generate_luarc),
929 luarc_file_name: other.luarc_file_name.or(self.luarc_file_name),
930 wrap_bin_scripts: other.wrap_bin_scripts.or(self.wrap_bin_scripts),
931 package_types: other.package_types.or(self.package_types),
932 no_tfa: other.no_tfa.or(self.no_tfa),
933 }
934 }
935
936 #[tracing::instrument(level = "trace")]
937 pub fn build(self) -> Result<Config, Error> {
938 let data_dir = self.data_dir.unwrap_or(Config::default_data_path());
939 let cache_dir = self.cache_dir.unwrap_or(Config::default_cache_path());
940 let user_tree = self.user_tree.unwrap_or(data_dir.join("tree"));
941
942 let lua_version = self.lua_version.or(lua::detect::installed_version());
943
944 Ok(normalise_base_urls(Config {
945 enable_development_packages: self.enable_development_packages.unwrap_or(false),
946 server: self.server.unwrap_or_else(|| unsafe {
947 Url::parse("https://luarocks.org/").unwrap_unchecked()
948 }),
949 extra_servers: self.extra_servers.unwrap_or_default(),
950 extra_wally_registries: self.extra_wally_registries.unwrap_or_default(),
951 namespace: self.namespace,
952 lua_dir: self.lua_dir,
953 lua_mirrors: self.lua_mirrors.unwrap_or_else(default_lua_mirrors),
954 lua_version,
955 user_tree,
956 workspace_tree: self.workspace_tree,
957 verbose: self.verbose.unwrap_or(false),
958 no_progress: self.no_progress.unwrap_or(false),
959 no_prompt: self.no_prompt.unwrap_or(false),
960 timeout: self.timeout.unwrap_or_else(|| Duration::from_secs(0)),
961 max_jobs: match self.max_jobs.unwrap_or_else(|| {
962 std::thread::available_parallelism().map_or(1, |available| available.get())
963 }) {
964 0 => usize::MAX,
965 max_jobs => max_jobs,
966 },
967 variables: default_variables()
968 .chain(self.variables.unwrap_or_default())
969 .collect(),
970 access_tokens: self.access_tokens.unwrap_or_default(),
971 external_deps: self.external_deps,
972 build: self.build,
973 entrypoint_layout: self.entrypoint_layout,
974 cache_dir,
975 data_dir,
976 vendor_dir: self.vendor_dir,
977 user_agent: self.user_agent.unwrap_or(DEFAULT_USER_AGENT.into()),
978 generate_luarc: self.generate_luarc.unwrap_or(true),
979 luarc_file_name: self
980 .luarc_file_name
981 .unwrap_or_else(|| ".luarc.json".to_string()),
982 wrap_bin_scripts: self.wrap_bin_scripts.unwrap_or(true),
983 package_types: self.package_types.unwrap_or_default(),
984 no_tfa: self.no_tfa.unwrap_or(false),
985 https_client_cache: OnceLock::new(),
986 http_client_cache: OnceLock::new(),
987 }))
988 }
989}
990
991impl From<Config> for Builder {
993 fn from(value: Config) -> Self {
994 Builder {
995 enable_development_packages: Some(value.enable_development_packages),
996 server: Some(value.server),
997 extra_servers: Some(value.extra_servers),
998 extra_wally_registries: Some(value.extra_wally_registries),
999 namespace: value.namespace,
1000 lua_dir: value.lua_dir,
1001 lua_mirrors: Some(value.lua_mirrors),
1002 lua_version: value.lua_version,
1003 user_tree: Some(value.user_tree),
1004 workspace_tree: value.workspace_tree,
1005 verbose: Some(value.verbose),
1006 no_progress: Some(value.no_progress),
1007 no_prompt: Some(value.no_prompt),
1008 timeout: Some(value.timeout),
1009 max_jobs: if value.max_jobs == usize::MAX {
1010 None
1011 } else {
1012 Some(value.max_jobs)
1013 },
1014 variables: Some(value.variables),
1015 access_tokens: Some(value.access_tokens),
1016 cache_dir: Some(value.cache_dir),
1017 data_dir: Some(value.data_dir),
1018 vendor_dir: value.vendor_dir,
1019 external_deps: value.external_deps,
1020 build: value.build,
1021 entrypoint_layout: value.entrypoint_layout,
1022 user_agent: Some(value.user_agent),
1023 generate_luarc: Some(value.generate_luarc),
1024 luarc_file_name: Some(value.luarc_file_name),
1025 wrap_bin_scripts: Some(value.wrap_bin_scripts),
1026 package_types: Some(value.package_types),
1027 no_tfa: Some(value.no_tfa),
1028 }
1029 }
1030}
1031
1032fn default_variables() -> impl Iterator<Item = (String, String)> {
1033 let cflags = env::var("CFLAGS").unwrap_or(target::default_cflags().into());
1034 let ldflags = env::var("LDFLAGS").unwrap_or("".into());
1035 vec![
1036 ("MAKE".into(), "make".into()),
1037 ("CMAKE".into(), "cmake".into()),
1038 ("LIB_EXTENSION".into(), target::c_dylib_extension().into()),
1039 ("OBJ_EXTENSION".into(), target::c_obj_extension().into()),
1040 ("CFLAGS".into(), cflags),
1041 ("LDFLAGS".into(), ldflags),
1042 ("LIBFLAG".into(), target::default_libflag().into()),
1043 ]
1044 .into_iter()
1045}
1046
1047fn default_lua_mirrors() -> Vec<Url> {
1048 DEFAULT_LUA_MIRRORS
1049 .into_iter()
1050 .map(|mirror| unsafe { Url::parse(mirror).unwrap_unchecked() })
1051 .collect()
1052}
1053
1054fn normalise_base_url(mut url: Url) -> Url {
1055 if !url.path().ends_with('/') {
1056 url.set_path(&format!("{}/", url.path()));
1057 }
1058 url
1059}
1060
1061fn normalise_base_urls(mut config: Config) -> Config {
1062 config.server = normalise_base_url(config.server);
1063 config.extra_servers = config
1064 .extra_servers
1065 .into_iter()
1066 .map(normalise_base_url)
1067 .collect();
1068 config.lua_mirrors = config
1069 .lua_mirrors
1070 .into_iter()
1071 .map(normalise_base_url)
1072 .collect();
1073 config
1074}
1075
1076fn deserialize_url<'de, D>(deserializer: D) -> Result<Option<Url>, D::Error>
1077where
1078 D: serde::Deserializer<'de>,
1079{
1080 let s = Option::<String>::deserialize(deserializer)?;
1081 s.map(|s| Url::parse(&s).map_err(serde::de::Error::custom))
1082 .transpose()
1083}
1084
1085fn serialize_url<S>(url: &Option<Url>, serializer: S) -> Result<S::Ok, S::Error>
1086where
1087 S: Serializer,
1088{
1089 match url {
1090 Some(url) => serializer.serialize_some(url.as_str()),
1091 None => serializer.serialize_none(),
1092 }
1093}
1094
1095fn deserialize_url_vec<'de, D>(deserializer: D) -> Result<Option<Vec<Url>>, D::Error>
1096where
1097 D: serde::Deserializer<'de>,
1098{
1099 let s = Option::<Vec<String>>::deserialize(deserializer)?;
1100 s.map(|v| {
1101 v.into_iter()
1102 .map(|s| Url::parse(&s).map_err(serde::de::Error::custom))
1103 .try_collect()
1104 })
1105 .transpose()
1106}
1107
1108fn serialize_url_vec<S>(urls: &Option<Vec<Url>>, serializer: S) -> Result<S::Ok, S::Error>
1109where
1110 S: Serializer,
1111{
1112 match urls {
1113 Some(urls) => {
1114 let url_strings: Vec<String> = urls.iter().map(|url| url.to_string()).collect();
1115 serializer.serialize_some(&url_strings)
1116 }
1117 None => serializer.serialize_none(),
1118 }
1119}
1120
1121#[cfg(test)]
1122mod tests {
1123 use std::time::Duration;
1124
1125 use httptest::{
1126 matchers::request,
1127 responders::{delay_and_then, status_code},
1128 Expectation, Server,
1129 };
1130
1131 use super::*;
1132
1133 #[tokio::test]
1134 async fn wrapped_command_without_runner() {
1135 let echo = which::which("echo").unwrap();
1136 let config = Builder::default().build().unwrap();
1137 let output = config
1138 .wrapped_command(&echo, ["hello", "world"])
1139 .output()
1140 .await
1141 .unwrap();
1142 assert!(output.status.success());
1143 assert_eq!(
1144 String::from_utf8_lossy(&output.stdout).trim(),
1145 "hello world"
1146 );
1147 }
1148
1149 #[tokio::test]
1150 async fn configured_timeout_is_applied() {
1151 let server = Server::run();
1152 server.expect(
1153 Expectation::matching(request::method_path("GET", "/"))
1154 .respond_with(delay_and_then(Duration::from_secs(5), status_code(200))),
1155 );
1156 let config = Builder::new()
1157 .unwrap()
1158 .timeout(Some(Duration::from_millis(100)))
1159 .build()
1160 .unwrap();
1161 let error = config
1162 .http_client()
1163 .unwrap()
1164 .get(server.url_str("/"))
1165 .send()
1166 .await
1167 .unwrap_err();
1168 assert!(error.is_timeout());
1169 }
1170
1171 #[tokio::test]
1172 async fn wrapped_command_prepends_runner_argv() {
1173 let echo = which::which("echo").unwrap();
1174 let config = Builder::default()
1175 .build_runner(Some(vec![echo.to_string_lossy().into(), "--prefix".into()]))
1176 .build()
1177 .unwrap();
1178 let output = config
1179 .wrapped_command("world", Vec::<String>::new())
1180 .output()
1181 .await
1182 .unwrap();
1183 assert!(output.status.success());
1184 assert_eq!(
1185 String::from_utf8_lossy(&output.stdout).trim(),
1186 "--prefix world"
1187 );
1188 }
1189
1190 #[test]
1191 fn base_urls_resolve_relative_paths() {
1192 let config = Builder::default()
1193 .server(Some(Url::parse("https://example.com/texrocks").unwrap()))
1194 .extra_servers(Some(vec![
1195 Url::parse("https://example.com/texrocks").unwrap()
1196 ]))
1197 .build()
1198 .unwrap();
1199
1200 assert_eq!(
1201 config.server().join("manifest-5.1.zip").unwrap().as_str(),
1202 "https://example.com/texrocks/manifest-5.1.zip"
1203 );
1204 assert_eq!(
1205 config.extra_servers()[0]
1206 .join("manifest-5.1.zip")
1207 .unwrap()
1208 .as_str(),
1209 "https://example.com/texrocks/manifest-5.1.zip"
1210 );
1211
1212 let rebuilt = Builder::from(config.clone()).build().unwrap();
1213 assert_eq!(rebuilt.server(), config.server());
1214 assert_eq!(rebuilt.extra_servers(), config.extra_servers());
1215 }
1216
1217 #[test]
1218 fn lua_mirrors_default_to_the_official_download_area_and_its_mirror() {
1219 let config = Builder::default().build().unwrap();
1220 assert_eq!(
1221 config.lua_mirrors(),
1222 [
1223 Url::parse("https://www.lua.org/ftp/").unwrap(),
1224 Url::parse("https://www.tecgraf.puc-rio.br/lua/ftp/").unwrap()
1225 ]
1226 );
1227 }
1228
1229 #[test]
1230 fn lua_mirrors_are_treated_as_base_urls() {
1231 let config = Builder::default()
1232 .lua_mirrors(Some(vec![Url::parse("https://example.com/lua").unwrap()]))
1233 .build()
1234 .unwrap();
1235 assert_eq!(
1236 config.lua_mirrors()[0]
1237 .join("lua-5.4.9.tar.gz")
1238 .unwrap()
1239 .as_str(),
1240 "https://example.com/lua/lua-5.4.9.tar.gz"
1241 );
1242 }
1243
1244 #[test]
1245 fn debug_redacts_access_tokens() {
1246 let config: Config =
1247 toml::from_str::<Builder>("[access_tokens]\n\"github.com\" = \"supersecret\"\n")
1248 .unwrap()
1249 .build()
1250 .unwrap();
1251 let debug = format!("{config:?}");
1252 assert!(!debug.contains("supersecret"));
1253 assert!(debug.contains("access_tokens"));
1254 }
1255
1256 #[test]
1257 fn external_deps_prefixes_default_empty() {
1258 let config = toml::from_str::<Builder>(
1259 "[external_deps]\nlib_subdirs = [\"lib/x86_64-linux-gnu\"]\n",
1260 )
1261 .unwrap()
1262 .build()
1263 .unwrap();
1264 assert!(config.external_deps().prefixes.is_empty());
1265 assert_eq!(
1266 config.external_deps().lib_subdirs,
1267 vec![PathBuf::from("lib/x86_64-linux-gnu")]
1268 );
1269 }
1270}