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 if !path.as_ref().exists() {
171 return Err(ConfigError::InvalidConfig(format!(
172 "tauri.conf.json not found at {}. Please ensure you have a Tauri project initialized.",
173 path.as_ref().display()
174 )));
175 }
176
177 let content = fs::read_to_string(&path)?;
178 let mut tauri_config = serde_json::from_str::<serde_json::Value>(&content)?;
179
180 let typegen_config = serde_json::json!({
182 "projectPath": self.project_path,
183 "outputPath": self.output_path,
184 "validationLibrary": self.validation_library,
185 "verbose": self.verbose.unwrap_or(false),
186 "visualizeDeps": self.visualize_deps.unwrap_or(false),
187 "includePrivate": self.include_private.unwrap_or(false),
188 "typeMappings": self.type_mappings,
189 "excludePatterns": self.exclude_patterns,
190 "includePatterns": self.include_patterns,
191 });
192
193 if !tauri_config.is_object() {
195 tauri_config = serde_json::json!({});
196 }
197
198 let tauri_obj = tauri_config.as_object_mut().unwrap();
199
200 if !tauri_obj.contains_key("plugins") {
202 tauri_obj.insert("plugins".to_string(), serde_json::json!({}));
203 }
204
205 if let Some(plugins) = tauri_obj.get_mut("plugins") {
207 if let Some(plugins_obj) = plugins.as_object_mut() {
208 plugins_obj.insert("typegen".to_string(), typegen_config);
209 }
210 }
211
212 let content = serde_json::to_string_pretty(&tauri_config)?;
213 fs::write(path, content)?;
214 Ok(())
215 }
216
217 pub fn validate(&self) -> Result<(), ConfigError> {
219 match self.validation_library.as_str() {
221 "zod" | "none" => {}
222 _ => {
223 return Err(ConfigError::InvalidValidationLibrary(
224 self.validation_library.clone(),
225 ))
226 }
227 }
228
229 let project_path = Path::new(&self.project_path);
231 if !project_path.exists() {
232 return Err(ConfigError::InvalidConfig(format!(
233 "Project path does not exist: {}",
234 self.project_path
235 )));
236 }
237
238 Ok(())
239 }
240
241 pub fn merge(&mut self, other: &GenerateConfig) {
243 if other.project_path != default_project_path() {
244 self.project_path = other.project_path.clone();
245 }
246 if other.output_path != default_output_path() {
247 self.output_path = other.output_path.clone();
248 }
249 if other.validation_library != default_validation_library() {
250 self.validation_library = other.validation_library.clone();
251 }
252 if other.verbose.is_some() {
253 self.verbose = other.verbose;
254 }
255 if other.visualize_deps.is_some() {
256 self.visualize_deps = other.visualize_deps;
257 }
258 if other.include_private.is_some() {
259 self.include_private = other.include_private;
260 }
261 if other.type_mappings.is_some() {
262 self.type_mappings = other.type_mappings.clone();
263 }
264 if other.exclude_patterns.is_some() {
265 self.exclude_patterns = other.exclude_patterns.clone();
266 }
267 if other.include_patterns.is_some() {
268 self.include_patterns = other.include_patterns.clone();
269 }
270 }
271
272 pub fn is_verbose(&self) -> bool {
274 self.verbose.unwrap_or(false)
275 }
276
277 pub fn should_visualize_deps(&self) -> bool {
279 self.visualize_deps.unwrap_or(false)
280 }
281
282 pub fn should_include_private(&self) -> bool {
284 self.include_private.unwrap_or(false)
285 }
286}
287
288#[cfg(test)]
289mod tests {
290 use super::*;
291 use tempfile::NamedTempFile;
292
293 #[test]
294 fn test_default_config() {
295 let config = GenerateConfig::default();
296 assert_eq!(config.project_path, "./src-tauri");
297 assert_eq!(config.output_path, "./src/generated");
298 assert_eq!(config.validation_library, "zod");
299 assert!(!config.is_verbose());
300 assert!(!config.should_visualize_deps());
301 assert!(!config.should_include_private());
302 }
303
304 #[test]
305 fn test_config_validation() {
306 let mut config = GenerateConfig::default();
307 config.validation_library = "invalid".to_string();
308
309 let result = config.validate();
310 assert!(result.is_err());
311 if let Err(ConfigError::InvalidValidationLibrary(lib)) = result {
312 assert_eq!(lib, "invalid");
313 } else {
314 panic!("Expected InvalidValidationLibrary error");
315 }
316 }
317
318 #[test]
319 fn test_config_merge() {
320 let mut base = GenerateConfig::default();
321 let override_config = GenerateConfig {
322 output_path: "./custom".to_string(),
323 verbose: Some(true),
324 ..Default::default()
325 };
326
327 base.merge(&override_config);
328 assert_eq!(base.output_path, "./custom");
329 assert!(base.is_verbose());
330 assert_eq!(base.validation_library, "zod"); }
332
333 #[test]
334 fn test_save_and_load_config() {
335 let temp_dir = tempfile::TempDir::new().unwrap();
336 let project_path = temp_dir.path().join("src-tauri");
337 std::fs::create_dir_all(&project_path).unwrap();
338
339 let config = GenerateConfig {
340 project_path: project_path.to_string_lossy().to_string(),
341 output_path: "./test".to_string(),
342 verbose: Some(true),
343 ..Default::default()
344 };
345
346 let temp_file = NamedTempFile::new().unwrap();
347 config.save_to_file(temp_file.path()).unwrap();
348
349 let loaded_config = GenerateConfig::from_file(temp_file.path()).unwrap();
350 assert_eq!(loaded_config.output_path, "./test");
351 assert!(loaded_config.is_verbose());
352 }
353
354 #[test]
355 fn test_save_to_tauri_config_preserves_existing_content() {
356 let temp_dir = tempfile::TempDir::new().unwrap();
357 let project_path = temp_dir.path().join("src-tauri");
358 std::fs::create_dir_all(&project_path).unwrap();
359
360 let tauri_conf_path = temp_dir.path().join("tauri.conf.json");
361
362 let existing_content = serde_json::json!({
364 "package": {
365 "productName": "My App",
366 "version": "1.0.0"
367 },
368 "tauri": {
369 "allowlist": {
370 "all": false
371 }
372 },
373 "plugins": {
374 "shell": {
375 "all": false
376 }
377 }
378 });
379
380 fs::write(
381 &tauri_conf_path,
382 serde_json::to_string_pretty(&existing_content).unwrap(),
383 )
384 .unwrap();
385
386 let config = GenerateConfig {
387 project_path: project_path.to_string_lossy().to_string(),
388 output_path: "./test".to_string(),
389 validation_library: "zod".to_string(),
390 verbose: Some(true),
391 ..Default::default()
392 };
393
394 config.save_to_tauri_config(&tauri_conf_path).unwrap();
396
397 let updated_content = fs::read_to_string(&tauri_conf_path).unwrap();
399 let updated_json: serde_json::Value = serde_json::from_str(&updated_content).unwrap();
400
401 assert_eq!(updated_json["package"]["productName"], "My App");
403 assert_eq!(updated_json["package"]["version"], "1.0.0");
404 assert_eq!(updated_json["tauri"]["allowlist"]["all"], false);
405 assert_eq!(updated_json["plugins"]["shell"]["all"], false);
406
407 assert_eq!(updated_json["plugins"]["typegen"]["outputPath"], "./test");
409 assert_eq!(
410 updated_json["plugins"]["typegen"]["validationLibrary"],
411 "zod"
412 );
413 assert_eq!(updated_json["plugins"]["typegen"]["verbose"], true);
414 }
415
416 #[test]
417 fn test_save_to_tauri_config_creates_plugins_section() {
418 let temp_dir = tempfile::TempDir::new().unwrap();
419 let project_path = temp_dir.path().join("src-tauri");
420 std::fs::create_dir_all(&project_path).unwrap();
421
422 let tauri_conf_path = temp_dir.path().join("tauri.conf.json");
423
424 let existing_content = serde_json::json!({
426 "package": {
427 "productName": "My App",
428 "version": "1.0.0"
429 },
430 "tauri": {
431 "allowlist": {
432 "all": false
433 }
434 }
435 });
436
437 fs::write(
438 &tauri_conf_path,
439 serde_json::to_string_pretty(&existing_content).unwrap(),
440 )
441 .unwrap();
442
443 let config = GenerateConfig {
444 project_path: project_path.to_string_lossy().to_string(),
445 output_path: "./test".to_string(),
446 validation_library: "none".to_string(),
447 ..Default::default()
448 };
449
450 config.save_to_tauri_config(&tauri_conf_path).unwrap();
452
453 let updated_content = fs::read_to_string(&tauri_conf_path).unwrap();
455 let updated_json: serde_json::Value = serde_json::from_str(&updated_content).unwrap();
456
457 assert_eq!(updated_json["package"]["productName"], "My App");
459 assert_eq!(updated_json["tauri"]["allowlist"]["all"], false);
460
461 assert!(updated_json["plugins"].is_object());
463 assert_eq!(updated_json["plugins"]["typegen"]["outputPath"], "./test");
464 assert_eq!(
465 updated_json["plugins"]["typegen"]["validationLibrary"],
466 "none"
467 );
468 }
469}