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