devalang_core/config/
driver.rs1use devalang_types::{
2 PluginEntry as SharedPluginEntry, ProjectConfig as SharedProjectConfig,
3 ProjectConfigBankEntry as SharedProjectConfigBankEntry,
4 ProjectConfigDefaults as SharedProjectConfigDefaults,
5 ProjectConfigPluginEntry as SharedProjectConfigPluginEntry,
6};
7use devalang_utils::path as path_utils;
8use std::path::PathBuf;
9
10pub type ProjectConfig = SharedProjectConfig;
11pub type ProjectConfigDefaults = SharedProjectConfigDefaults;
12pub type ProjectConfigBankEntry = SharedProjectConfigBankEntry;
13pub type ProjectConfigPluginEntry = SharedProjectConfigPluginEntry;
14pub type PluginEntry = SharedPluginEntry;
15
16pub trait ProjectConfigExt {
17 fn new_config() -> Self;
18 fn with_defaults(
19 entry: Option<String>,
20 output: Option<String>,
21 watch: Option<bool>,
22 repeat: Option<bool>,
23 debug: Option<bool>,
24 compress: Option<bool>,
25 ) -> Self;
26 fn get() -> Result<Self, String>
27 where
28 Self: Sized;
29 fn from_string(config_string: &str) -> Result<(Self, String), String>
30 where
31 Self: Sized;
32 fn write_config(&self, new_config: &Self) -> Result<(), String>
33 where
34 Self: Sized;
35}
36
37impl ProjectConfigExt for SharedProjectConfig {
38 fn new_config() -> Self {
39 SharedProjectConfig::default()
40 }
41
42 fn with_defaults(
43 entry: Option<String>,
44 output: Option<String>,
45 watch: Option<bool>,
46 repeat: Option<bool>,
47 debug: Option<bool>,
48 compress: Option<bool>,
49 ) -> Self {
50 SharedProjectConfig {
51 defaults: SharedProjectConfigDefaults {
52 entry,
53 output,
54 watch,
55 repeat,
56 debug,
57 compress,
58 },
59 banks: Some(Vec::new()),
60 plugins: Some(Vec::new()),
61 }
62 }
63
64 fn get() -> Result<Self, String> {
65 let config_path = path_utils::get_devalang_config_path()?;
66
67 let config_content = std::fs::read_to_string(&config_path)
68 .map_err(|e| format!("Failed to read config file: {}", e))?;
69
70 let config: SharedProjectConfig = toml::from_str(&config_content)
71 .map_err(|e| format!("Failed to parse config file: {}", e))?;
72
73 Ok(config)
74 }
75
76 fn from_string(config_string: &str) -> Result<(Self, String), String> {
77 let config: SharedProjectConfig = toml::from_str(config_string)
78 .map_err(|e| format!("Failed to parse config string: {}", e))?;
79 let config_path = ".devalang".to_string();
80
81 Ok((config, config_path))
82 }
83
84 fn write_config(&self, new_config: &Self) -> Result<(), String> {
85 let config_path: PathBuf = match path_utils::get_project_root() {
86 Ok(root) => root.join(path_utils::DEVALANG_CONFIG),
87 Err(_) => PathBuf::from(path_utils::DEVALANG_CONFIG),
88 };
89
90 let content = toml::to_string(new_config)
91 .map_err(|e| format!("Failed to serialize config: {}", e))?;
92
93 std::fs::write(&config_path, content).map_err(|e| {
94 format!(
95 "Failed to write config to file '{}': {}",
96 config_path.display(),
97 e
98 )
99 })?;
100
101 Ok(())
102 }
103}