1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
use crate::config::loader::load_config;
use crate::config::validator::validate_config;
use crate::error::{FileSystemError, Result};
use crate::formatter::FormatterManager;
use crate::generator::swagger_parser::filter_common_schemas;
use crate::generator::writer::write_api_client_with_options;
use colored::*;
use std::path::{Path, PathBuf};
pub async fn run() -> Result<()> {
println!("{}", "🔄 Updating generated code...".bright_cyan());
println!();
// Load config
let config = load_config()?;
validate_config(&config)?;
use crate::error::{FileSystemError, GenerationError};
use crate::specs::manager::list_specs;
// Get specs from config
let specs = list_specs(&config);
if specs.is_empty() {
return Err(GenerationError::SpecPathRequired.into());
}
// Update all specs
type SpecSummary = (String, usize, Vec<(String, usize)>);
let mut all_specs_summary: Vec<SpecSummary> = Vec::new();
let mut all_generated_files = Vec::new();
// Track which URLs we've already printed the fetch message for
let mut printed_urls: std::collections::HashSet<String> = std::collections::HashSet::new();
for spec in &specs {
println!();
println!(
"{}",
format!("🔄 Updating spec: {}", spec.name).bright_cyan()
);
println!();
let spec_path = &spec.path;
// Check if spec path is a temporary file that might not exist anymore
if !spec_path.starts_with("http://")
&& !spec_path.starts_with("https://")
&& !std::path::Path::new(spec_path).exists()
{
println!(
"{}",
format!(
"⚠️ Skipping spec '{}': spec file no longer exists at {}",
spec.name, spec_path
)
.yellow()
);
continue;
}
// Use spec-specific configs (required per spec)
let schemas_config = &spec.schemas;
let apis_config = &spec.apis;
let modules_config = &spec.modules;
// Get hooks config (use defaults if not specified)
let hooks_config = spec.hooks.clone().unwrap_or_default();
// Ensure runtime client exists at root_dir (shared across all specs)
use crate::generator::writer::{ensure_directory, write_runtime_client};
let root_dir_path = PathBuf::from(&config.root_dir);
ensure_directory(&root_dir_path)?;
let runtime_dir = root_dir_path.join("runtime");
if !runtime_dir.exists() {
write_runtime_client(&root_dir_path, None, Some(apis_config))?;
}
// Print fetch message only once per unique URL
if !printed_urls.contains(spec_path) {
println!(
"{}",
format!("📥 Fetching spec from: {}", spec_path).bright_blue()
);
printed_urls.insert(spec_path.clone());
}
// Use caching for update command (same as generate)
let use_cache = config.generation.enable_cache;
let parsed = crate::generator::swagger_parser::fetch_and_parse_spec_with_cache_and_name(
spec_path,
use_cache,
Some(&spec.name),
)
.await?;
// Get selected modules from config, or select interactively if empty
let selected_modules = if modules_config.selected.is_empty() {
// No modules selected in config, select interactively
println!(
"{}",
format!(
"No modules selected for spec '{}'. Please select modules to update:",
spec.name
)
.bright_yellow()
);
println!();
// Filter out ignored modules
let available_modules: Vec<String> = parsed
.modules
.iter()
.filter(|m| !modules_config.ignore.contains(m))
.cloned()
.collect();
if available_modules.is_empty() {
println!(
"{}",
format!("⚠️ Skipping spec '{}': No modules available", spec.name).yellow()
);
continue;
}
// Select modules interactively
use crate::generator::module_selector::select_modules;
let selected = select_modules(&available_modules, &modules_config.ignore)?;
// Update config with selected modules
use crate::config::loader::load_config;
let mut config = load_config()?;
if let Some(spec_entry) = config.specs.iter_mut().find(|s| s.name == spec.name) {
spec_entry.modules.selected = selected.clone();
}
use crate::config::loader::save_config;
save_config(&config)?;
selected
} else {
modules_config.selected.clone()
};
println!(
"{}",
format!("✅ Parsed spec with {} modules", parsed.modules.len()).green()
);
println!();
println!(
"{}",
format!(
"📦 Updating {} module(s): {}",
selected_modules.len(),
selected_modules.join(", ")
)
.bright_green()
);
println!();
// Filter common schemas based on selected modules only
let (filtered_module_schemas, common_schemas) =
filter_common_schemas(&parsed.module_schemas, &selected_modules);
// Initialize template engine once for all modules
let project_root = std::env::current_dir().ok();
let template_engine =
crate::templates::engine::TemplateEngine::new(project_root.as_deref())?;
// Generate code for each module (using spec-specific or global output directories)
let schemas_dir = PathBuf::from(&schemas_config.output);
let apis_dir = PathBuf::from(&apis_config.output);
let mut total_files = 0;
let mut module_summary: Vec<(String, usize)> = Vec::new();
// Get force and backup settings from config
let use_force = config.generation.conflict_strategy == "force";
let use_backup = config.generation.enable_backup;
// Generate common module first if there are shared schemas
if !common_schemas.is_empty() {
println!("{}", "🔨 Regenerating common schemas...".bright_cyan());
// Shared enum registry to ensure consistent naming between TypeScript and Zod
let mut shared_enum_registry = std::collections::HashMap::new();
// Generate TypeScript typings for common schemas
// Pass empty common_schemas list so common schemas don't prefix themselves with "Common."
let common_types =
crate::generator::ts_typings::generate_typings_with_registry_and_engine_and_spec(
&parsed.openapi,
&parsed.schemas,
&common_schemas,
&mut shared_enum_registry,
&[], // Empty list - common schemas shouldn't prefix themselves
Some(&template_engine),
Some(&spec.name),
)?;
// Generate Zod schemas for common schemas (using same registry)
// Pass empty common_schemas list so common schemas don't prefix themselves with "Common."
let common_zod_schemas =
crate::generator::zod_schema::generate_zod_schemas_with_registry_and_engine_and_spec(
&parsed.openapi,
&parsed.schemas,
&common_schemas,
&mut shared_enum_registry,
&[], // Empty list - common schemas shouldn't prefix themselves
Some(&template_engine),
Some(&spec.name),
)?;
// Write common schemas (use force if config says so)
use crate::generator::writer::write_schemas_with_module_mapping;
let common_files = write_schemas_with_module_mapping(
&schemas_dir,
"common",
&common_types,
&common_zod_schemas,
Some(&spec.name), // spec_name for multi-spec mode
use_backup,
use_force,
Some(&filtered_module_schemas),
&common_schemas,
)?;
total_files += common_files.len();
module_summary.push(("common".to_string(), common_files.len()));
}
for module in &selected_modules {
println!(
"{}",
format!("🔨 Regenerating code for module: {}", module).bright_cyan()
);
// Get operations for this module
let operations = parsed
.operations_by_tag
.get(module)
.cloned()
.unwrap_or_default();
if operations.is_empty() {
println!(
"{}",
format!("⚠️ No operations found for module: {}", module).yellow()
);
continue;
}
// Get schema names used by this module (from filtered schemas)
let module_schema_names = filtered_module_schemas
.get(module)
.cloned()
.unwrap_or_default();
// Shared enum registry to ensure consistent naming between TypeScript and Zod
let mut shared_enum_registry = std::collections::HashMap::new();
// Generate TypeScript typings
let types = if !module_schema_names.is_empty() {
crate::generator::ts_typings::generate_typings_with_registry_and_engine_and_spec(
&parsed.openapi,
&parsed.schemas,
&module_schema_names,
&mut shared_enum_registry,
&common_schemas,
Some(&template_engine),
Some(&spec.name),
)?
} else {
Vec::new()
};
// Generate Zod schemas (using same registry)
let zod_schemas = if !module_schema_names.is_empty() {
crate::generator::zod_schema::generate_zod_schemas_with_registry_and_engine_and_spec(
&parsed.openapi,
&parsed.schemas,
&module_schema_names,
&mut shared_enum_registry,
&common_schemas,
Some(&template_engine),
Some(&spec.name),
)?
} else {
Vec::new()
};
// Generate query params types and Zod schemas
use crate::generator::query_params::{
generate_query_params_for_module, QueryParamsContext,
};
let query_params_result = generate_query_params_for_module(QueryParamsContext {
openapi: &parsed.openapi,
operations: &operations,
enum_registry: &mut shared_enum_registry,
template_engine: Some(&template_engine),
spec_name: Some(&spec.name),
existing_types: &types,
existing_zod_schemas: &zod_schemas,
})?;
// Generate API client (using same enum registry as schemas)
let api_result =
crate::generator::api_client::generate_api_client_with_registry_and_engine_and_spec(
&parsed.openapi,
&operations,
module,
&common_schemas,
&mut shared_enum_registry,
Some(&template_engine),
Some(&spec.name),
Some(&config.root_dir),
Some(&apis_config.output),
Some(&schemas_config.output),
)?;
// Response types are written to API files, not schema files
// Combine schema types with query params types
let mut all_types = types;
all_types.extend(query_params_result.types);
// Combine Zod schemas with query params Zod schemas
let mut all_zod_schemas = zod_schemas;
all_zod_schemas.extend(query_params_result.zod_schemas);
// Write schemas (use force if config says so)
use crate::generator::writer::write_schemas_with_module_mapping;
let schema_files = write_schemas_with_module_mapping(
&schemas_dir,
module,
&all_types,
&all_zod_schemas,
Some(&spec.name), // spec_name for multi-spec mode
use_backup,
use_force,
Some(&filtered_module_schemas),
&common_schemas,
)?;
total_files += schema_files.len();
// Write API client (use force if config says so)
let api_files = write_api_client_with_options(
&apis_dir,
module,
&api_result.functions,
Some(&spec.name), // spec_name for multi-spec mode
use_backup,
use_force,
)?;
total_files += api_files.len();
// Determine hook type from hooks config
use crate::specs::runner::HookType;
let hook_type = hooks_config
.library
.as_ref()
.and_then(|lib| match lib.as_str() {
"react-query" => Some(HookType::ReactQuery),
"swr" => Some(HookType::Swr),
_ => None,
});
// Generate hooks if configured
let mut hook_files_count = 0;
if let Some(hook_type) = hook_type {
println!(
"{}",
format!("🔨 Generating hooks for module: {}", module).bright_cyan()
);
// Generate query keys first (hooks depend on them)
use crate::generator::query_keys::generate_query_keys;
let query_keys_context = generate_query_keys(&operations, module, Some(&spec.name));
// Render query keys template
let query_keys_content = template_engine.render(
crate::templates::registry::TemplateId::QueryKeys,
&query_keys_context,
)?;
// Write query keys file using configured output directory
// Note: output_dir already includes spec_name if needed (from config), just like schemas/apis
let query_keys_output = PathBuf::from(&hooks_config.query_keys_output);
use crate::generator::writer::write_query_keys_with_options;
write_query_keys_with_options(
&query_keys_output,
module,
&query_keys_content,
Some(&spec.name),
use_backup,
use_force,
)?;
total_files += 1;
// Generate hooks based on type
let hooks = match hook_type {
HookType::ReactQuery => {
use crate::generator::hooks::react_query::generate_react_query_hooks;
generate_react_query_hooks(
&parsed.openapi,
&operations,
module,
Some(&spec.name),
&common_schemas,
&mut shared_enum_registry,
&template_engine,
Some(&apis_config.output),
Some(&schemas_config.output),
Some(&hooks_config.output),
Some(&hooks_config.query_keys_output),
)?
}
HookType::Swr => {
use crate::generator::hooks::swr::generate_swr_hooks;
generate_swr_hooks(
&parsed.openapi,
&operations,
module,
Some(&spec.name),
&common_schemas,
&mut shared_enum_registry,
&template_engine,
Some(&apis_config.output),
Some(&schemas_config.output),
Some(&hooks_config.output),
Some(&hooks_config.query_keys_output),
)?
}
};
// Write hooks files using configured output directory
// Note: output_dir already includes spec_name if needed (from config), just like schemas/apis
let hooks_output = PathBuf::from(&hooks_config.output);
use crate::generator::writer::write_hooks_with_options;
let hook_files = write_hooks_with_options(
&hooks_output,
module,
&hooks,
Some(&spec.name),
use_backup,
use_force,
)?;
hook_files_count = hook_files.len();
total_files += hook_files_count;
}
let module_file_count = schema_files.len()
+ api_files.len()
+ if hook_type.is_some() {
1 + hook_files_count
} else {
0
};
module_summary.push((module.clone(), module_file_count));
println!(
"{}",
format!(
"✅ Regenerated {} files for module: {}",
module_file_count, module
)
.green()
);
}
println!();
println!(
"{}",
format!(
"✨ Successfully updated {} files for spec '{}'!",
total_files, spec.name
)
.bright_green()
);
println!();
println!(
"{}",
format!("Updated files for '{}':", spec.name).bright_cyan()
);
println!(" 📁 Schemas: {}", schemas_config.output);
println!(" 📁 APIs: {}", apis_config.output);
if hooks_config.library.is_some() {
println!(" 📁 Hooks: {}", hooks_config.output);
println!(" 📁 Query Keys: {}", hooks_config.query_keys_output);
}
// Store summary for this spec
all_specs_summary.push((spec.name.clone(), total_files, module_summary.clone()));
// Collect files for this spec for formatting
let current_dir = std::env::current_dir().map_err(|e| FileSystemError::ReadFileFailed {
path: ".".to_string(),
source: e,
})?;
let schemas_dir_abs = if schemas_dir.is_absolute() {
schemas_dir.clone()
} else {
current_dir.join(&schemas_dir)
};
let apis_dir_abs = if apis_dir.is_absolute() {
apis_dir.clone()
} else {
current_dir.join(&apis_dir)
};
// Collect schema files recursively
if schemas_dir_abs.exists() {
collect_ts_files(&schemas_dir_abs, &mut all_generated_files)?;
}
// Collect API files recursively
if apis_dir_abs.exists() {
collect_ts_files(&apis_dir_abs, &mut all_generated_files)?;
}
}
// Print overall summary
println!();
println!("{}", "=".repeat(60).bright_black());
println!();
let total_all_files: usize = all_specs_summary.iter().map(|(_, count, _)| count).sum();
println!(
"{}",
format!(
"✨ Successfully updated {} files across {} spec(s)!",
total_all_files,
all_specs_summary.len()
)
.bright_green()
);
println!();
println!("{}", "Summary by spec:".bright_cyan());
for (spec_name, file_count, module_summary) in &all_specs_summary {
println!(" 📦 {}: {} files", spec_name, file_count);
if !module_summary.is_empty() {
for (module, count) in module_summary {
println!(" • {}: {} files", module, count);
}
}
}
println!();
// Format files if formatter is available
if !all_generated_files.is_empty() {
// Find the common parent directory (where config files are likely located)
// Try to find it from the first file path, or use current directory
let output_base = all_generated_files.first().and_then(|first_file| {
first_file
.parent()
.and_then(|p| p.parent())
.and_then(|p| p.parent())
});
let formatter = if let Some(base_dir) = output_base {
FormatterManager::detect_formatter_from_dir(base_dir)
.or_else(FormatterManager::detect_formatter)
} else {
FormatterManager::detect_formatter()
};
if let Some(formatter) = formatter {
println!("{}", "Formatting generated files...".bright_cyan());
let original_dir =
std::env::current_dir().map_err(|e| FileSystemError::ReadFileFailed {
path: ".".to_string(),
source: e,
})?;
if let Some(output_base) = output_base {
// Ensure output_base is not empty
if output_base.as_os_str().is_empty() {
// Fallback: use current directory
FormatterManager::format_files(&all_generated_files, formatter)?;
} else {
std::env::set_current_dir(output_base).map_err(|e| {
FileSystemError::ReadFileFailed {
path: output_base.display().to_string(),
source: e,
}
})?;
// Convert paths to relative paths from output base directory
let relative_files: Vec<PathBuf> = all_generated_files
.iter()
.filter_map(|p| {
p.strip_prefix(output_base)
.ok()
.map(|p| p.to_path_buf())
.filter(|p| !p.as_os_str().is_empty())
})
.collect();
if !relative_files.is_empty() {
let result = FormatterManager::format_files(&relative_files, formatter);
// Restore original directory
std::env::set_current_dir(&original_dir).map_err(|e| {
FileSystemError::ReadFileFailed {
path: original_dir.display().to_string(),
source: e,
}
})?;
result?;
// Update metadata for formatted files to reflect formatted content hash (batch update)
use crate::generator::writer::batch_update_file_metadata_from_disk;
if let Err(e) = batch_update_file_metadata_from_disk(&all_generated_files) {
// Log but don't fail - metadata update is best effort
eprintln!("Warning: Failed to update metadata: {}", e);
}
} else {
// Restore original directory
std::env::set_current_dir(&original_dir).map_err(|e| {
FileSystemError::ReadFileFailed {
path: original_dir.display().to_string(),
source: e,
}
})?;
}
}
} else {
FormatterManager::format_files(&all_generated_files, formatter)?;
// Update metadata for formatted files to reflect formatted content hash (batch update)
use crate::generator::writer::batch_update_file_metadata_from_disk;
if let Err(e) = batch_update_file_metadata_from_disk(&all_generated_files) {
// Log but don't fail - metadata update is best effort
eprintln!("Warning: Failed to update metadata: {}", e);
}
}
println!("{}", "✅ Files formatted".green());
}
}
Ok(())
}
fn collect_ts_files(dir: &Path, files: &mut Vec<PathBuf>) -> Result<()> {
if dir.is_dir() {
for entry in std::fs::read_dir(dir).map_err(|e| FileSystemError::ReadFileFailed {
path: dir.display().to_string(),
source: e,
})? {
let entry = entry.map_err(|e| FileSystemError::ReadFileFailed {
path: dir.display().to_string(),
source: e,
})?;
let path = entry.path();
// Skip if path is empty or invalid
if path.as_os_str().is_empty() {
continue;
}
if path.is_dir() {
collect_ts_files(&path, files)?;
} else if path.extension().and_then(|s| s.to_str()) == Some("ts") {
files.push(path);
}
}
}
Ok(())
}