1use std::collections::HashMap;
2use std::fs;
3use std::path::{Path, PathBuf};
4
5use figment::Figment;
6use figment::providers::{Env, Format, Serialized, Toml};
7use serde::{Deserialize, Serialize};
8use thiserror::Error;
9
10#[derive(Debug, Error)]
11pub enum ConfigError {
12 #[error("io error: {0}")]
13 Io(#[from] std::io::Error),
14 #[error("parse error: {0}")]
15 Parse(#[from] toml::de::Error),
16 #[error("serialize error: {0}")]
17 Serialize(#[from] toml::ser::Error),
18 #[error("config error: {0}")]
19 Figment(#[from] Box<figment::Error>),
20}
21
22#[derive(Debug, Clone, Default, Serialize, Deserialize)]
23#[serde(default)]
24pub struct Config {
25 pub library: LibraryConfig,
26 pub playback: PlaybackConfig,
27 pub remote: RemoteConfig,
28 pub organize: OrganizeConfig,
29 #[serde(alias = "visualiser")]
30 pub visualizer: VisualizerConfig,
31 pub radio: RadioConfig,
32 pub graphql: GraphqlConfig,
33 pub discovery: DiscoveryConfig,
34}
35
36#[derive(Debug, Clone, Serialize, Deserialize)]
37#[serde(default)]
38pub struct LibraryConfig {
39 pub folders: Vec<PathBuf>,
40}
41
42#[derive(Debug, Clone, Serialize, Deserialize)]
43#[serde(default)]
44pub struct PlaybackConfig {
45 pub software_volume: bool,
46 pub replaygain: ReplayGainMode,
47 pub ticker_fps: u8,
50 pub target_fps: u8,
53 pub show_fps: bool,
55 pub pre_amp_db: f64,
58 #[serde(default, skip_serializing_if = "Option::is_none")]
61 pub output_device: Option<String>,
62 pub art_size: u16,
65}
66
67#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
68#[serde(rename_all = "lowercase")]
69pub enum ReplayGainMode {
70 Off,
71 Track,
72 Album,
73}
74
75#[derive(Debug, Clone, Serialize, Deserialize)]
76#[serde(default)]
77pub struct RemoteConfig {
78 pub enabled: bool,
79 pub url: String,
80 pub username: String,
81 #[serde(default, skip_serializing_if = "String::is_empty")]
83 pub password: String,
84 pub transcode_quality: String,
86 pub cache_dir: Option<PathBuf>,
88 pub download_workers: usize,
90 #[serde(default, skip_serializing_if = "Option::is_none")]
93 pub cache_limit: Option<String>,
94}
95
96impl Default for LibraryConfig {
97 fn default() -> Self {
98 let music_dir = dirs::audio_dir().unwrap_or_else(|| {
99 dirs::home_dir()
100 .map(|h| h.join("Music"))
101 .unwrap_or_else(|| PathBuf::from("/Music"))
102 });
103 Self {
104 folders: vec![music_dir],
105 }
106 }
107}
108
109impl Default for PlaybackConfig {
110 fn default() -> Self {
111 Self {
112 software_volume: false,
113 replaygain: ReplayGainMode::Album,
114 ticker_fps: 8,
115 target_fps: 60,
116 show_fps: false,
117 pre_amp_db: 0.0,
118 output_device: None,
119 art_size: 24,
120 }
121 }
122}
123
124#[derive(Debug, Clone, Serialize, Deserialize)]
125#[serde(default)]
126pub struct VisualizerConfig {
127 pub enabled: bool,
128 pub fps: u8,
129 pub scale: String,
131 pub amplitude_scale: String,
133 pub bar_decay_ms: u32,
135 pub peak_decay_ms: u32,
137}
138
139impl Default for VisualizerConfig {
140 fn default() -> Self {
141 Self {
142 enabled: true,
143 fps: 60,
144 scale: "bark".into(),
145 amplitude_scale: "aweight".into(),
146 bar_decay_ms: 50,
147 peak_decay_ms: 180,
148 }
149 }
150}
151
152impl Default for RemoteConfig {
153 fn default() -> Self {
154 Self {
155 enabled: false,
156 url: String::new(),
157 username: String::new(),
158 password: String::new(),
159 transcode_quality: "original".into(),
160 cache_dir: None,
161 download_workers: 5,
162 cache_limit: None,
163 }
164 }
165}
166
167pub fn parse_size_bytes(s: &str) -> Option<u64> {
170 let s = s.trim();
171 if s.is_empty() {
172 return None;
173 }
174
175 let mut num_end = 0;
177 for (i, c) in s.char_indices() {
178 if c.is_ascii_digit() || c == '.' {
179 num_end = i + c.len_utf8();
180 } else if !c.is_whitespace() {
181 break;
182 }
183 }
184
185 let num_str = s[..num_end].trim();
186 let suffix = s[num_end..].trim().to_ascii_uppercase();
187
188 let value: f64 = num_str.parse().ok()?;
189 let multiplier: u64 = match suffix.as_str() {
190 "" | "B" => 1,
191 "KB" | "K" => 1024,
192 "MB" | "M" => 1024 * 1024,
193 "GB" | "G" => 1024 * 1024 * 1024,
194 "TB" | "T" => 1024 * 1024 * 1024 * 1024,
195 _ => return None,
196 };
197
198 Some((value * multiplier as f64) as u64)
199}
200
201#[derive(Debug, Clone, Default, Serialize, Deserialize)]
202#[serde(default)]
203pub struct OrganizeConfig {
204 #[serde(default, skip_serializing_if = "Option::is_none")]
206 pub default: Option<String>,
207 #[serde(default, skip_serializing_if = "HashMap::is_empty")]
209 pub patterns: HashMap<String, String>,
210}
211
212impl OrganizeConfig {
213 pub fn resolve_pattern<'a>(&'a self, name_or_raw: &'a str) -> &'a str {
216 self.patterns
217 .get(name_or_raw)
218 .map(|s| s.as_str())
219 .unwrap_or(name_or_raw)
220 }
221
222 pub fn default_pattern(&self) -> Option<&str> {
224 self.default
225 .as_ref()
226 .and_then(|name| self.patterns.get(name))
227 .map(|s| s.as_str())
228 }
229}
230
231#[derive(Debug, Clone, Serialize, Deserialize)]
233#[serde(default)]
234pub struct GraphqlConfig {
235 pub enabled: bool,
238 pub port: u16,
240 #[serde(default = "default_bind")]
243 pub bind: std::net::IpAddr,
244 pub playground: bool,
246 #[serde(default, skip_serializing_if = "Option::is_none")]
248 pub subsonic_port: Option<u16>,
249}
250
251fn default_bind() -> std::net::IpAddr {
252 std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST)
253}
254
255impl Default for GraphqlConfig {
256 fn default() -> Self {
257 Self {
258 enabled: true,
259 port: 4000,
260 bind: default_bind(),
261 playground: false,
262 subsonic_port: None,
263 }
264 }
265}
266
267#[derive(Debug, Clone, Serialize, Deserialize)]
269#[serde(default)]
270pub struct RadioConfig {
271 pub lookahead: usize,
273 pub batch_size: usize,
275 pub use_subsonic: bool,
277 pub history_window: usize,
279 pub seed_window: usize,
281 pub discovery_weight: f64,
284}
285
286impl Default for RadioConfig {
287 fn default() -> Self {
288 Self {
289 lookahead: 5,
290 batch_size: 5,
291 use_subsonic: true,
292 history_window: 200,
293 seed_window: 5,
294 discovery_weight: 0.3,
295 }
296 }
297}
298
299#[derive(Debug, Clone, Serialize, Deserialize)]
301#[serde(default)]
302pub struct DiscoveryConfig {
303 pub analysis_on_scan: bool,
305 pub acoustic_weight: f64,
307}
308
309impl Default for DiscoveryConfig {
310 fn default() -> Self {
311 Self {
312 analysis_on_scan: false,
313 acoustic_weight: 0.5,
314 }
315 }
316}
317
318impl Config {
319 fn figment() -> Figment {
325 let base_path = config_file_path();
326 let local_path = config_local_file_path();
327
328 Figment::from(Serialized::defaults(Config::default()))
329 .merge(Toml::file(&base_path))
330 .merge(Toml::file(&local_path))
331 .merge(Env::prefixed("KOAN_").split("__"))
332 }
333
334 pub fn load() -> Result<Self, ConfigError> {
336 Self::figment()
337 .extract()
338 .map_err(|e| ConfigError::Figment(Box::new(e)))
339 }
340
341 pub fn load_or_default() -> Self {
343 Self::load().unwrap_or_else(|e| {
344 log::warn!("failed to load config, using defaults: {}", e);
345 Self::default()
346 })
347 }
348
349 pub fn load_from(path: &Path) -> Result<Self, ConfigError> {
351 let contents = fs::read_to_string(path)?;
352 let config: Config = toml::from_str(&contents)?;
353 Ok(config)
354 }
355
356 pub fn update_base<F>(mutate: F) -> Result<(), ConfigError>
360 where
361 F: FnOnce(&mut Config),
362 {
363 let path = config_file_path();
364 let mut cfg = if path.exists() {
365 Config::load_from(&path)?
366 } else {
367 Config::default()
368 };
369 mutate(&mut cfg);
370 cfg.write_to(&path)?;
371 Ok(())
372 }
373
374 fn write_to(&self, path: &Path) -> Result<(), ConfigError> {
376 if let Some(parent) = path.parent() {
377 fs::create_dir_all(parent)?;
378 }
379 let contents = toml::to_string_pretty(self)?;
380 fs::write(path, contents)?;
381 Ok(())
382 }
383
384 pub fn save(&self) -> Result<(), ConfigError> {
390 self.write_to(&config_file_path())
391 }
392
393 pub fn save_local(&self) -> Result<(), ConfigError> {
395 let path = config_local_file_path();
396 self.write_to(&path)?;
397 #[cfg(unix)]
398 {
399 use std::os::unix::fs::PermissionsExt;
400 fs::set_permissions(&path, fs::Permissions::from_mode(0o600))?;
401 }
402 Ok(())
403 }
404
405 pub fn cache_dir(&self) -> PathBuf {
407 self.remote
408 .cache_dir
409 .clone()
410 .unwrap_or_else(|| config_dir().join("cache"))
411 }
412
413 pub fn cache_limit_bytes(&self) -> Option<u64> {
415 self.remote
416 .cache_limit
417 .as_deref()
418 .and_then(parse_size_bytes)
419 }
420}
421
422pub fn config_dir() -> PathBuf {
424 dirs::home_dir()
425 .unwrap_or_else(|| PathBuf::from("."))
426 .join(".config")
427 .join("koan")
428}
429
430pub fn config_file_path() -> PathBuf {
432 config_dir().join("config.toml")
433}
434
435pub fn config_local_file_path() -> PathBuf {
437 config_dir().join("config.local.toml")
438}
439
440pub fn db_path() -> PathBuf {
442 config_dir().join("koan.db")
443}
444
445#[cfg(test)]
446mod tests {
447 use super::*;
448 use std::fs;
449
450 fn tmp_dir() -> PathBuf {
451 let dir = std::env::temp_dir().join(format!("koan-test-{}", std::process::id()));
452 fs::create_dir_all(&dir).unwrap();
453 dir
454 }
455
456 #[test]
457 fn test_defaults() {
458 let cfg = Config::default();
459 assert_eq!(cfg.playback.replaygain, ReplayGainMode::Album);
460 assert!(!cfg.remote.enabled);
461 assert_eq!(cfg.remote.transcode_quality, "original");
462 }
463
464 #[test]
465 fn test_roundtrip_toml() {
466 let cfg = Config::default();
467 let serialized = toml::to_string_pretty(&cfg).unwrap();
468 let deserialized: Config = toml::from_str(&serialized).unwrap();
469 assert_eq!(deserialized.playback.replaygain, cfg.playback.replaygain);
470 assert_eq!(
471 deserialized.remote.transcode_quality,
472 cfg.remote.transcode_quality
473 );
474 }
475
476 #[test]
477 fn test_load_from_file() {
478 let dir = tempfile::tempdir().unwrap();
479 let path = dir.path().join("config.toml");
480 fs::write(
481 &path,
482 r#"
483[library]
484folders = ["/tmp/music"]
485
486[playback]
487replaygain = "track"
488"#,
489 )
490 .unwrap();
491
492 let cfg = Config::load_from(&path).unwrap();
493 assert_eq!(cfg.library.folders, vec![PathBuf::from("/tmp/music")]);
494 assert_eq!(cfg.playback.replaygain, ReplayGainMode::Track);
495 assert!(!cfg.remote.enabled);
496 }
497
498 #[test]
499 fn test_partial_toml_uses_defaults() {
500 let dir = tempfile::tempdir().unwrap();
501 let path = dir.path().join("partial.toml");
502 fs::write(&path, "[playback]\nsoftware_volume = true\n").unwrap();
503
504 let cfg = Config::load_from(&path).unwrap();
505 assert!(cfg.playback.software_volume);
506 }
507
508 #[test]
509 fn test_figment_layered_loading() {
510 let dir = tempfile::tempdir().unwrap();
511 let base_path = dir.path().join("config.toml");
512 let local_path = dir.path().join("config.local.toml");
513
514 fs::write(
515 &base_path,
516 r#"
517[remote]
518url = "https://base.example.com"
519"#,
520 )
521 .unwrap();
522 fs::write(
523 &local_path,
524 r#"
525[remote]
526enabled = true
527url = "https://local.example.com"
528username = "admin"
529password = "secret"
530"#,
531 )
532 .unwrap();
533
534 let cfg: Config = Figment::from(Serialized::defaults(Config::default()))
536 .merge(Toml::file(&base_path))
537 .merge(Toml::file(&local_path))
538 .extract()
539 .unwrap();
540
541 assert!(cfg.remote.enabled);
542 assert_eq!(cfg.remote.url, "https://local.example.com");
543 assert_eq!(cfg.remote.username, "admin");
544 assert_eq!(cfg.remote.password, "secret");
545 }
546
547 #[test]
548 fn test_figment_missing_keys_preserved() {
549 let dir = tempfile::tempdir().unwrap();
550 let base_path = dir.path().join("config.toml");
551 let local_path = dir.path().join("config.local.toml");
552
553 fs::write(
554 &base_path,
555 r#"
556[remote]
557url = "https://keep.me"
558username = "keepuser"
559"#,
560 )
561 .unwrap();
562 fs::write(
563 &local_path,
564 r#"
565[remote]
566password = "secret"
567"#,
568 )
569 .unwrap();
570
571 let cfg: Config = Figment::from(Serialized::defaults(Config::default()))
572 .merge(Toml::file(&base_path))
573 .merge(Toml::file(&local_path))
574 .extract()
575 .unwrap();
576
577 assert_eq!(cfg.remote.url, "https://keep.me");
578 assert_eq!(cfg.remote.username, "keepuser");
579 assert_eq!(cfg.remote.password, "secret");
580 }
581
582 #[test]
583 fn test_env_var_override() {
584 let dir = tempfile::tempdir().unwrap();
585 let base_path = dir.path().join("config.toml");
586
587 fs::write(
588 &base_path,
589 r#"
590[remote]
591url = "https://file.example.com"
592"#,
593 )
594 .unwrap();
595
596 unsafe {
598 std::env::set_var("KOAN_REMOTE__URL", "https://env.example.com");
599 std::env::set_var("KOAN_REMOTE__PASSWORD", "env-secret");
600 std::env::set_var("KOAN_GRAPHQL__PORT", "9999");
601 }
602
603 let cfg: Config = Figment::from(Serialized::defaults(Config::default()))
604 .merge(Toml::file(&base_path))
605 .merge(Env::prefixed("KOAN_").split("__"))
606 .extract()
607 .unwrap();
608
609 assert_eq!(cfg.remote.url, "https://env.example.com");
610 assert_eq!(cfg.remote.password, "env-secret");
611 assert_eq!(cfg.graphql.port, 9999);
612
613 unsafe {
615 std::env::remove_var("KOAN_REMOTE__URL");
616 std::env::remove_var("KOAN_REMOTE__PASSWORD");
617 std::env::remove_var("KOAN_GRAPHQL__PORT");
618 }
619 }
620
621 #[test]
622 fn test_update_base_does_not_leak_secrets() {
623 let dir = tempfile::tempdir().unwrap();
624 let base_path = dir.path().join("config.toml");
625
626 fs::write(
628 &base_path,
629 r#"
630[playback]
631target_fps = 60
632
633[remote]
634url = "https://base.example.com"
635"#,
636 )
637 .unwrap();
638
639 let mut base_cfg = Config::load_from(&base_path).unwrap();
641 base_cfg.visualizer.enabled = false;
642 base_cfg.write_to(&base_path).unwrap();
643
644 let written = fs::read_to_string(&base_path).unwrap();
646 assert!(!written.contains("secret"));
647 assert!(!written.contains("password"));
648
649 let reloaded = Config::load_from(&base_path).unwrap();
651 assert!(!reloaded.visualizer.enabled);
652 assert_eq!(reloaded.remote.url, "https://base.example.com");
653 }
654
655 #[test]
656 fn test_cache_dir_default() {
657 let cfg = Config::default();
658 assert!(cfg.cache_dir().ends_with("cache"));
659 }
660
661 #[test]
662 fn test_cache_dir_explicit() {
663 let mut cfg = Config::default();
664 cfg.remote.cache_dir = Some(PathBuf::from("/custom/cache"));
665 assert_eq!(cfg.cache_dir(), PathBuf::from("/custom/cache"));
666 }
667
668 #[test]
669 fn test_organize_config_defaults() {
670 let cfg = Config::default();
671 assert!(cfg.organize.default.is_none());
672 assert!(cfg.organize.patterns.is_empty());
673 }
674
675 #[test]
676 fn test_organize_config_from_toml() {
677 let dir = tmp_dir();
678 let path = dir.join("organize.toml");
679 fs::write(
680 &path,
681 r#"
682[organize]
683default = "standard"
684
685[organize.patterns]
686standard = "%album artist%/(%date%) %album%/%tracknumber%. %title%"
687va-aware = "%album artist%/$if($stricmp(%album artist%,Various Artists),,%album%)"
688"#,
689 )
690 .unwrap();
691
692 let cfg = Config::load_from(&path).unwrap();
693 assert_eq!(cfg.organize.default.as_deref(), Some("standard"));
694 assert_eq!(cfg.organize.patterns.len(), 2);
695 assert!(cfg.organize.patterns.contains_key("standard"));
696 assert!(cfg.organize.patterns.contains_key("va-aware"));
697
698 fs::remove_dir_all(&dir).ok();
699 }
700
701 #[test]
702 fn test_organize_resolve_named_pattern() {
703 let mut cfg = OrganizeConfig::default();
704 cfg.patterns
705 .insert("standard".into(), "%artist%/%title%".into());
706
707 assert_eq!(cfg.resolve_pattern("standard"), "%artist%/%title%");
708 assert_eq!(cfg.resolve_pattern("%raw%pattern%"), "%raw%pattern%");
710 }
711
712 #[test]
713 fn test_organize_default_pattern() {
714 let mut cfg = OrganizeConfig {
715 default: Some("standard".into()),
716 ..OrganizeConfig::default()
717 };
718 cfg.patterns
719 .insert("standard".into(), "%artist%/%title%".into());
720
721 assert_eq!(cfg.default_pattern(), Some("%artist%/%title%"));
722 }
723
724 #[test]
725 fn test_organize_default_pattern_missing_name() {
726 let cfg = OrganizeConfig {
727 default: Some("nonexistent".into()),
728 ..OrganizeConfig::default()
729 };
730 assert_eq!(cfg.default_pattern(), None);
732 }
733
734 #[test]
735 fn test_figment_organize_patterns_merge() {
736 let dir = tempfile::tempdir().unwrap();
737 let base_path = dir.path().join("config.toml");
738 let local_path = dir.path().join("config.local.toml");
739
740 fs::write(
741 &base_path,
742 r#"
743[organize]
744default = "standard"
745
746[organize.patterns]
747standard = "base-pattern"
748"#,
749 )
750 .unwrap();
751 fs::write(
752 &local_path,
753 r#"
754[organize]
755default = "custom"
756
757[organize.patterns]
758custom = "local-pattern"
759"#,
760 )
761 .unwrap();
762
763 let cfg: Config = Figment::from(Serialized::defaults(Config::default()))
764 .merge(Toml::file(&base_path))
765 .merge(Toml::file(&local_path))
766 .extract()
767 .unwrap();
768
769 assert_eq!(cfg.organize.default.as_deref(), Some("custom"));
771 assert_eq!(cfg.organize.patterns.len(), 2);
773 assert_eq!(cfg.organize.patterns["standard"], "base-pattern");
774 assert_eq!(cfg.organize.patterns["custom"], "local-pattern");
775 }
776
777 #[test]
778 fn test_output_device_config_roundtrip() {
779 let mut cfg = Config::default();
780 cfg.playback.output_device = Some("My DAC".into());
781
782 let serialized = toml::to_string_pretty(&cfg).unwrap();
783 let deserialized: Config = toml::from_str(&serialized).unwrap();
784 assert_eq!(
785 deserialized.playback.output_device.as_deref(),
786 Some("My DAC")
787 );
788 }
789
790 #[test]
791 fn test_output_device_config_default_is_none() {
792 let cfg = Config::default();
793 assert!(cfg.playback.output_device.is_none());
794
795 let serialized = toml::to_string_pretty(&cfg).unwrap();
797 assert!(!serialized.contains("output_device"));
798 let deserialized: Config = toml::from_str(&serialized).unwrap();
799 assert!(deserialized.playback.output_device.is_none());
800 }
801
802 #[test]
803 fn test_output_device_config_from_toml() {
804 let dir = tempfile::tempdir().unwrap();
805 let path = dir.path().join("config.toml");
806 fs::write(
807 &path,
808 r#"
809[playback]
810output_device = "External Speakers"
811"#,
812 )
813 .unwrap();
814
815 let cfg = Config::load_from(&path).unwrap();
816 assert_eq!(
817 cfg.playback.output_device.as_deref(),
818 Some("External Speakers")
819 );
820 }
821
822 #[test]
823 fn test_graphql_bind_defaults_to_localhost() {
824 let cfg = GraphqlConfig::default();
825 assert_eq!(
826 cfg.bind,
827 std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST)
828 );
829 }
830
831 #[test]
832 fn test_graphql_bind_from_toml() {
833 let toml_str = r#"
834[graphql]
835bind = "0.0.0.0"
836port = 5000
837"#;
838 let cfg: Config = toml::from_str(toml_str).unwrap();
839 assert_eq!(
840 cfg.graphql.bind,
841 std::net::IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED)
842 );
843 assert_eq!(cfg.graphql.port, 5000);
844 }
845
846 #[test]
847 fn test_graphql_bind_omitted_defaults_to_localhost() {
848 let toml_str = r#"
849[graphql]
850port = 4000
851"#;
852 let cfg: Config = toml::from_str(toml_str).unwrap();
853 assert_eq!(
854 cfg.graphql.bind,
855 std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST)
856 );
857 }
858
859 #[test]
860 fn test_organize_config_roundtrip() {
861 let mut cfg = Config::default();
862 cfg.organize.default = Some("standard".into());
863 cfg.organize
864 .patterns
865 .insert("standard".into(), "%artist%/%title%".into());
866
867 let serialized = toml::to_string_pretty(&cfg).unwrap();
868 let deserialized: Config = toml::from_str(&serialized).unwrap();
869 assert_eq!(deserialized.organize.default.as_deref(), Some("standard"));
870 assert_eq!(
871 deserialized.organize.patterns["standard"],
872 "%artist%/%title%"
873 );
874 }
875
876 #[test]
877 fn test_parse_size_bytes() {
878 assert_eq!(parse_size_bytes("50GB"), Some(50 * 1024 * 1024 * 1024));
879 assert_eq!(parse_size_bytes("500MB"), Some(500 * 1024 * 1024));
880 assert_eq!(parse_size_bytes("1TB"), Some(1024 * 1024 * 1024 * 1024));
881 assert_eq!(parse_size_bytes("100KB"), Some(100 * 1024));
882 assert_eq!(parse_size_bytes("1024B"), Some(1024));
883 assert_eq!(parse_size_bytes("1024"), Some(1024));
884
885 assert_eq!(parse_size_bytes("50gb"), Some(50 * 1024 * 1024 * 1024));
887 assert_eq!(parse_size_bytes("50Gb"), Some(50 * 1024 * 1024 * 1024));
888
889 assert_eq!(parse_size_bytes("50G"), Some(50 * 1024 * 1024 * 1024));
891 assert_eq!(parse_size_bytes("500M"), Some(500 * 1024 * 1024));
892
893 assert_eq!(parse_size_bytes("50 GB"), Some(50 * 1024 * 1024 * 1024));
895 assert_eq!(parse_size_bytes(" 50GB "), Some(50 * 1024 * 1024 * 1024));
896
897 assert_eq!(
899 parse_size_bytes("1.5GB"),
900 Some((1.5 * 1024.0 * 1024.0 * 1024.0) as u64)
901 );
902
903 assert_eq!(parse_size_bytes(""), None);
905 assert_eq!(parse_size_bytes("abc"), None);
906 assert_eq!(parse_size_bytes("50XB"), None);
907 }
908
909 #[test]
910 fn test_cache_limit_config_from_toml() {
911 let toml_str = r#"
912[remote]
913cache_limit = "50GB"
914"#;
915 let cfg: Config = toml::from_str(toml_str).unwrap();
916 assert_eq!(cfg.remote.cache_limit.as_deref(), Some("50GB"));
917 assert_eq!(cfg.cache_limit_bytes(), Some(50 * 1024 * 1024 * 1024));
918 }
919
920 #[test]
921 fn test_cache_limit_none_by_default() {
922 let cfg = Config::default();
923 assert!(cfg.remote.cache_limit.is_none());
924 assert!(cfg.cache_limit_bytes().is_none());
925 }
926
927 #[test]
928 fn test_cache_limit_not_serialized_when_none() {
929 let cfg = Config::default();
930 let serialized = toml::to_string_pretty(&cfg).unwrap();
931 assert!(!serialized.contains("cache_limit"));
932 }
933}