tauri_plugin_typegen/interface/
config.rs1use serde::{Deserialize, Serialize};
2use std::fs;
3use std::path::Path;
4use thiserror::Error;
5
6#[derive(Error, Debug)]
7pub enum ConfigError {
8 #[error("IO error: {0}")]
9 Io(#[from] std::io::Error),
10 #[error("JSON parsing error: {0}")]
11 Json(#[from] serde_json::Error),
12 #[error("Invalid validation library: {0}. Use 'zod' or 'none'")]
13 InvalidValidationLibrary(String),
14 #[error("Invalid configuration: {0}")]
15 InvalidConfig(String),
16}
17
18#[derive(Debug, Serialize, Deserialize, Clone)]
19pub struct GenerateConfig {
20 #[serde(default = "default_project_path")]
22 pub project_path: String,
23
24 #[serde(default = "default_output_path")]
26 pub output_path: String,
27
28 #[serde(default = "default_validation_library")]
30 pub validation_library: String,
31
32 #[serde(default)]
34 pub verbose: Option<bool>,
35
36 #[serde(default)]
38 pub visualize_deps: Option<bool>,
39
40 #[serde(default)]
42 pub include_private: Option<bool>,
43
44 #[serde(default)]
46 pub type_mappings: Option<std::collections::HashMap<String, String>>,
47
48 #[serde(default)]
50 pub exclude_patterns: Option<Vec<String>>,
51
52 #[serde(default)]
54 pub include_patterns: Option<Vec<String>>,
55}
56
57fn default_project_path() -> String {
58 "./src-tauri".to_string()
59}
60
61fn default_output_path() -> String {
62 "./src/generated".to_string()
63}
64
65fn default_validation_library() -> String {
66 "zod".to_string()
67}
68
69impl Default for GenerateConfig {
70 fn default() -> Self {
71 Self {
72 project_path: default_project_path(),
73 output_path: default_output_path(),
74 validation_library: default_validation_library(),
75 verbose: Some(false),
76 visualize_deps: Some(false),
77 include_private: Some(false),
78 type_mappings: None,
79 exclude_patterns: None,
80 include_patterns: None,
81 }
82 }
83}
84
85impl GenerateConfig {
86 pub fn new() -> Self {
88 Self::default()
89 }
90
91 pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self, ConfigError> {
93 let content = fs::read_to_string(path)?;
94 let config: Self = serde_json::from_str(&content)?;
95 config.validate()?;
96 Ok(config)
97 }
98
99 pub fn from_tauri_config<P: AsRef<Path>>(path: P) -> Result<Self, ConfigError> {
101 let content = fs::read_to_string(path)?;
102 let tauri_config: serde_json::Value = serde_json::from_str(&content)?;
103
104 let mut config = Self::default();
105
106 if let Some(plugins) = tauri_config.get("plugins") {
108 if let Some(typegen) = plugins.get("typegen") {
109 if let Some(project_path) = typegen.get("projectPath").and_then(|v| v.as_str()) {
110 config.project_path = project_path.to_string();
111 }
112 if let Some(output_path) = typegen.get("outputPath").and_then(|v| v.as_str()) {
113 config.output_path = output_path.to_string();
114 }
115 if let Some(validation) = typegen.get("validationLibrary").and_then(|v| v.as_str())
116 {
117 config.validation_library = validation.to_string();
118 }
119 if let Some(verbose) = typegen.get("verbose").and_then(|v| v.as_bool()) {
120 config.verbose = Some(verbose);
121 }
122 if let Some(visualize_deps) = typegen.get("visualizeDeps").and_then(|v| v.as_bool())
123 {
124 config.visualize_deps = Some(visualize_deps);
125 }
126 if let Some(include_private) =
127 typegen.get("includePrivate").and_then(|v| v.as_bool())
128 {
129 config.include_private = Some(include_private);
130 }
131 if let Some(type_mappings) = typegen.get("typeMappings") {
132 if let Ok(mappings) = serde_json::from_value::<
133 std::collections::HashMap<String, String>,
134 >(type_mappings.clone())
135 {
136 config.type_mappings = Some(mappings);
137 }
138 }
139 if let Some(exclude_patterns) = typegen.get("excludePatterns") {
140 if let Ok(patterns) =
141 serde_json::from_value::<Vec<String>>(exclude_patterns.clone())
142 {
143 config.exclude_patterns = Some(patterns);
144 }
145 }
146 if let Some(include_patterns) = typegen.get("includePatterns") {
147 if let Ok(patterns) =
148 serde_json::from_value::<Vec<String>>(include_patterns.clone())
149 {
150 config.include_patterns = Some(patterns);
151 }
152 }
153 }
154 }
155
156 config.validate()?;
157 Ok(config)
158 }
159
160 pub fn save_to_file<P: AsRef<Path>>(&self, path: P) -> Result<(), ConfigError> {
162 let content = serde_json::to_string_pretty(self)?;
163 fs::write(path, content)?;
164 Ok(())
165 }
166
167 pub fn save_to_tauri_config<P: AsRef<Path>>(&self, path: P) -> Result<(), ConfigError> {
169 let mut tauri_config = if path.as_ref().exists() {
171 let content = fs::read_to_string(&path)?;
172 serde_json::from_str::<serde_json::Value>(&content)?
173 } else {
174 serde_json::json!({
175 "build": {},
176 "package": {},
177 "plugins": {}
178 })
179 };
180
181 let typegen_config = serde_json::json!({
183 "projectPath": self.project_path,
184 "outputPath": self.output_path,
185 "validationLibrary": self.validation_library,
186 "verbose": self.verbose.unwrap_or(false),
187 "visualizeDeps": self.visualize_deps.unwrap_or(false),
188 "includePrivate": self.include_private.unwrap_or(false),
189 "typeMappings": self.type_mappings,
190 "excludePatterns": self.exclude_patterns,
191 "includePatterns": self.include_patterns,
192 });
193
194 if let Some(plugins) = tauri_config.get_mut("plugins") {
196 if let Some(plugins_obj) = plugins.as_object_mut() {
197 plugins_obj.insert("typegen".to_string(), typegen_config);
198 }
199 }
200
201 let content = serde_json::to_string_pretty(&tauri_config)?;
202 fs::write(path, content)?;
203 Ok(())
204 }
205
206 pub fn validate(&self) -> Result<(), ConfigError> {
208 match self.validation_library.as_str() {
210 "zod" | "none" => {}
211 _ => {
212 return Err(ConfigError::InvalidValidationLibrary(
213 self.validation_library.clone(),
214 ))
215 }
216 }
217
218 let project_path = Path::new(&self.project_path);
220 if !project_path.exists() {
221 return Err(ConfigError::InvalidConfig(format!(
222 "Project path does not exist: {}",
223 self.project_path
224 )));
225 }
226
227 Ok(())
228 }
229
230 pub fn merge(&mut self, other: &GenerateConfig) {
232 if other.project_path != default_project_path() {
233 self.project_path = other.project_path.clone();
234 }
235 if other.output_path != default_output_path() {
236 self.output_path = other.output_path.clone();
237 }
238 if other.validation_library != default_validation_library() {
239 self.validation_library = other.validation_library.clone();
240 }
241 if other.verbose.is_some() {
242 self.verbose = other.verbose;
243 }
244 if other.visualize_deps.is_some() {
245 self.visualize_deps = other.visualize_deps;
246 }
247 if other.include_private.is_some() {
248 self.include_private = other.include_private;
249 }
250 if other.type_mappings.is_some() {
251 self.type_mappings = other.type_mappings.clone();
252 }
253 if other.exclude_patterns.is_some() {
254 self.exclude_patterns = other.exclude_patterns.clone();
255 }
256 if other.include_patterns.is_some() {
257 self.include_patterns = other.include_patterns.clone();
258 }
259 }
260
261 pub fn is_verbose(&self) -> bool {
263 self.verbose.unwrap_or(false)
264 }
265
266 pub fn should_visualize_deps(&self) -> bool {
268 self.visualize_deps.unwrap_or(false)
269 }
270
271 pub fn should_include_private(&self) -> bool {
273 self.include_private.unwrap_or(false)
274 }
275}
276
277#[cfg(test)]
278mod tests {
279 use super::*;
280 use tempfile::NamedTempFile;
281
282 #[test]
283 fn test_default_config() {
284 let config = GenerateConfig::default();
285 assert_eq!(config.project_path, "./src-tauri");
286 assert_eq!(config.output_path, "./src/generated");
287 assert_eq!(config.validation_library, "zod");
288 assert!(!config.is_verbose());
289 assert!(!config.should_visualize_deps());
290 assert!(!config.should_include_private());
291 }
292
293 #[test]
294 fn test_config_validation() {
295 let mut config = GenerateConfig::default();
296 config.validation_library = "invalid".to_string();
297
298 let result = config.validate();
299 assert!(result.is_err());
300 if let Err(ConfigError::InvalidValidationLibrary(lib)) = result {
301 assert_eq!(lib, "invalid");
302 } else {
303 panic!("Expected InvalidValidationLibrary error");
304 }
305 }
306
307 #[test]
308 fn test_config_merge() {
309 let mut base = GenerateConfig::default();
310 let override_config = GenerateConfig {
311 output_path: "./custom".to_string(),
312 verbose: Some(true),
313 ..Default::default()
314 };
315
316 base.merge(&override_config);
317 assert_eq!(base.output_path, "./custom");
318 assert!(base.is_verbose());
319 assert_eq!(base.validation_library, "zod"); }
321
322 #[test]
323 fn test_save_and_load_config() {
324 let temp_dir = tempfile::TempDir::new().unwrap();
325 let project_path = temp_dir.path().join("src-tauri");
326 std::fs::create_dir_all(&project_path).unwrap();
327
328 let config = GenerateConfig {
329 project_path: project_path.to_string_lossy().to_string(),
330 output_path: "./test".to_string(),
331 verbose: Some(true),
332 ..Default::default()
333 };
334
335 let temp_file = NamedTempFile::new().unwrap();
336 config.save_to_file(temp_file.path()).unwrap();
337
338 let loaded_config = GenerateConfig::from_file(temp_file.path()).unwrap();
339 assert_eq!(loaded_config.output_path, "./test");
340 assert!(loaded_config.is_verbose());
341 }
342}