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#[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 no_progress: bool,
56 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 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 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 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 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 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 pub fn with_tree(self, tree: PathBuf) -> Self {
128 Self {
129 user_tree: tree,
130 ..self
131 }
132 }
133
134 pub fn with_workspace_tree(self, tree: Option<PathBuf>) -> Self {
136 Self {
137 workspace_tree: tree,
138 ..self
139 }
140 }
141
142 pub fn server(&self) -> &Url {
144 &self.server
145 }
146
147 pub fn extra_servers(&self) -> &Vec<Url> {
149 self.extra_servers.as_ref()
150 }
151
152 pub fn extra_wally_registries(&self) -> &Vec<Url> {
155 self.extra_wally_registries.as_ref()
156 }
157
158 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 pub fn namespace(&self) -> Option<&String> {
185 self.namespace.as_ref()
186 }
187
188 pub fn lua_dir(&self) -> Option<&PathBuf> {
190 self.lua_dir.as_ref()
191 }
192
193 pub fn lua_version(&self) -> Option<&lua::Version> {
195 self.lua_version.as_ref()
196 }
197
198 pub fn user_tree(&self, version: lua::Version) -> Result<Tree, tree::Error> {
201 Tree::new(self.user_tree.clone(), version, self)
202 }
203
204 pub fn workspace_tree(&self) -> Option<&PathBuf> {
206 self.workspace_tree.as_ref()
207 }
208
209 pub fn verbose(&self) -> bool {
211 self.verbose
212 }
213
214 pub fn no_progress(&self) -> bool {
216 self.no_progress
217 }
218
219 pub fn no_prompt(&self) -> bool {
221 self.no_prompt
222 }
223
224 pub fn timeout(&self) -> &Duration {
227 &self.timeout
228 }
229
230 pub fn max_jobs(&self) -> usize {
233 self.max_jobs
234 }
235
236 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 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 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 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 pub fn variables(&self) -> &HashMap<String, String> {
288 &self.variables
289 }
290
291 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 pub fn entrypoint_layout(&self) -> Option<&Arc<dyn CustomRockLayout>> {
314 self.entrypoint_layout.as_ref()
315 }
316
317 pub fn cache_dir(&self) -> &PathBuf {
319 &self.cache_dir
320 }
321
322 pub fn data_dir(&self) -> &PathBuf {
324 &self.data_dir
325 }
326
327 pub fn vendor_dir(&self) -> Option<&PathBuf> {
331 self.vendor_dir.as_ref()
332 }
333
334 pub fn user_agent(&self) -> &str {
336 &self.user_agent
337 }
338
339 pub fn generate_luarc(&self) -> bool {
341 self.generate_luarc
342 }
343
344 pub fn luarc_file_name(&self) -> &str {
346 &self.luarc_file_name
347 }
348
349 pub fn wrap_bin_scripts(&self) -> bool {
353 self.wrap_bin_scripts
354 }
355
356 pub fn package_types(&self) -> &remote::package::kind::FilterSpec {
358 &self.package_types
359 }
360 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#[derive(Debug, Clone, Default, Deserialize, Serialize)]
402#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
403pub struct Builder {
404 #[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 #[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 #[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 namespace: Option<String>,
432 lua_version: Option<lua::Version>,
434 user_tree: Option<PathBuf>,
436 workspace_tree: Option<PathBuf>,
439 lua_dir: Option<PathBuf>,
441 cache_dir: Option<PathBuf>,
443 data_dir: Option<PathBuf>,
445 vendor_dir: Option<PathBuf>,
448 enable_development_packages: Option<bool>,
450 verbose: Option<bool>,
452 no_progress: Option<bool>,
454 no_prompt: Option<bool>,
456 #[cfg_attr(feature = "schema", schemars(with = "Option<u64>"))]
459 timeout: Option<Duration>,
460 max_jobs: Option<usize>,
463 variables: Option<HashMap<String, String>>,
466 #[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 user_agent: Option<String>,
481 generate_luarc: Option<bool>,
483 luarc_file_name: Option<String>,
485 wrap_bin_scripts: Option<bool>,
488 package_types: Option<remote::package::kind::FilterSpec>,
490 no_tfa: Option<bool>,
493}
494
495impl Builder {
497 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 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 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 pub fn server(self, server: Option<Url>) -> Self {
538 Self {
539 server: server.or(self.server),
540 ..self
541 }
542 }
543
544 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 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 pub fn namespace(self, namespace: Option<String>) -> Self {
562 Self {
563 namespace: namespace.or(self.namespace),
564 ..self
565 }
566 }
567
568 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 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 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 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 pub fn variables(self, variables: Option<HashMap<String, String>>) -> Self {
606 Self {
607 variables: variables.or(self.variables),
608 ..self
609 }
610 }
611
612 pub fn verbose(self, verbose: Option<bool>) -> Self {
615 Self {
616 verbose: verbose.or(self.verbose),
617 ..self
618 }
619 }
620
621 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 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 pub fn timeout(self, timeout: Option<Duration>) -> Self {
643 Self {
644 timeout: timeout.or(self.timeout),
645 ..self
646 }
647 }
648
649 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 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 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 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 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 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 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 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 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 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 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 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 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 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
913impl 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}