commit_wizard/engine/models/runtime/
mod.rs1use std::path::PathBuf;
2
3use crate::engine::{
4 LoggerTrait,
5 config::{
6 BaseConfig,
7 env::build_env_config,
8 registry::{RegistrySpec, load_registry, resolve_registry_spec},
9 resolver::{resolve_global_configs, resolve_project_configs},
10 },
11 constants::resolve_project_config_path,
12 models::policy::Policy,
13};
14
15pub mod mode;
16pub mod options;
17pub mod resolution;
18pub use options::*;
19pub use resolution::*;
20
21#[derive(Debug, Clone)]
22pub struct Runtime {
23 mode: mode::RunMode,
25 options: RuntimeOptions,
27 paths: RuntimePaths,
29 resolution: RuntimeResolution,
31}
32
33impl Default for Runtime {
34 fn default() -> Self {
35 Self::new()
36 }
37}
38
39impl Runtime {
40 pub fn output_config(&self) -> scriba::Config {
41 scriba::Config {
42 interactive: matches!(self.mode, mode::RunMode::Interactive),
43 format: self.options.output_format(),
44 color: self.options.output_color(),
45 level: self.options.log_level(),
46 auto_yes: self.options.auto_yes(),
47 }
48 }
49
50 pub fn is_ci(&self) -> bool {
55 matches!(self.mode, mode::RunMode::Ci)
56 }
57
58 pub fn is_non_interactive(&self) -> bool {
59 matches!(self.mode, mode::RunMode::NonInteractive)
60 }
61
62 pub fn is_interactive(&self) -> bool {
63 matches!(self.mode, mode::RunMode::Interactive)
64 }
65
66 pub fn mode(&self) -> &mode::RunMode {
67 &self.mode
68 }
69
70 pub fn options(&self) -> &RuntimeOptions {
71 &self.options
72 }
73
74 pub fn options_mut(&mut self) -> &mut RuntimeOptions {
75 &mut self.options
76 }
77
78 pub fn cwd(&self) -> &PathBuf {
79 &self.paths.cwd
80 }
81
82 pub fn in_git_repo(&self) -> bool {
83 self.paths.in_git_repo
84 }
85
86 pub fn repo_root(&self) -> &PathBuf {
87 self.paths.repo_root.as_ref().unwrap_or(&self.paths.cwd)
88 }
89
90 pub fn global_paths(&self) -> &RuntimeGlobalPaths {
91 &self.paths.global
92 }
93
94 pub fn global_config_path(&self) -> &PathBuf {
95 &self.paths.global.config
96 }
97
98 pub fn global_cache_path(&self) -> &PathBuf {
99 &self.paths.global.cache
100 }
101
102 pub fn global_state_path(&self) -> &PathBuf {
103 &self.paths.global.state
104 }
105
106 pub fn state_file_path(&self) -> PathBuf {
107 use crate::engine::constants::STATE_FILE_NAME;
108 self.paths.global.state.join(STATE_FILE_NAME)
109 }
110
111 pub fn sources(&self) -> &AvailableConfigOptions {
112 &self.resolution.sources
113 }
114
115 pub fn sources_mut(&mut self) -> &mut AvailableConfigOptions {
116 &mut self.resolution.sources
117 }
118
119 pub fn config(&self) -> Option<&ResolvedConfig> {
120 self.resolution.config.as_ref()
121 }
122
123 pub fn config_mut(&mut self) -> Option<&mut ResolvedConfig> {
124 self.resolution.config.as_mut()
125 }
126
127 pub fn policy(&self) -> &Policy {
128 &self.resolution.policy
129 }
130
131 pub fn policy_mut(&mut self) -> &mut Policy {
132 &mut self.resolution.policy
133 }
134
135 pub fn set_mode(&mut self, mode: mode::RunMode) -> &mut Self {
140 self.mode = mode;
141 self
142 }
143
144 pub fn set_dry_run(&mut self, dry_run: bool) -> &mut Self {
145 self.options.set_dry_run(dry_run);
146 self
147 }
148
149 pub fn set_auto_yes(&mut self, auto_yes: bool) -> &mut Self {
150 self.options.set_auto_yes(auto_yes);
151 self
152 }
153
154 pub fn set_force(&mut self, force: bool) -> &mut Self {
155 self.options.set_force(force);
156 self
157 }
158
159 pub fn set_output_envelope(&mut self, envelope: scriba::EnvelopeMode) -> &mut Self {
160 self.options.set_output_envelope(envelope);
161 self
162 }
163
164 pub fn set_output_format(&mut self, format: scriba::Format) -> &mut Self {
165 self.options.set_output_format(format);
166 self
167 }
168
169 pub fn set_output_color(&mut self, color: scriba::ColorMode) -> &mut Self {
170 self.options.set_output_color(color);
171 self
172 }
173
174 pub fn set_log_level(&mut self, level: scriba::Level) -> &mut Self {
175 self.options.set_log_level(level);
176 self
177 }
178
179 pub fn set_cwd(&mut self, cwd: PathBuf) -> &mut Self {
180 self.paths.cwd = std::fs::canonicalize(&cwd).unwrap_or_else(|e| {
182 eprintln!(
183 "[warn] Failed to canonicalize cwd {:?}: {e} — using path as-is",
184 cwd
185 );
186 cwd
187 });
188 self
189 }
190
191 pub fn set_in_git_repo(&mut self, in_git_repo: bool) -> &mut Self {
192 self.paths.in_git_repo = in_git_repo;
193 self
194 }
195
196 pub fn set_repo_root(&mut self, repo_root: PathBuf) -> &mut Self {
197 self.paths.repo_root = Some(std::fs::canonicalize(&repo_root).unwrap_or_else(|e| {
199 eprintln!(
200 "[warn] Failed to canonicalize repo_root {:?}: {e} — using path as-is",
201 repo_root
202 );
203 repo_root
204 }));
205 self
206 }
207
208 pub fn set_sources(&mut self, sources: AvailableConfigOptions) -> &mut Self {
209 self.resolution.sources = sources;
210 self
211 }
212
213 pub fn set_config(&mut self, config: ResolvedConfig) -> &mut Self {
214 self.resolution.config = Some(config);
215 self
216 }
217
218 pub fn set_policy(&mut self, policy: Policy) -> &mut Self {
219 self.resolution.policy = policy;
220 self
221 }
222
223 pub fn new() -> Self {
224 Self {
225 mode: mode::RunMode::Interactive,
226 options: RuntimeOptions::new(),
227 paths: RuntimePaths::new(),
228 resolution: RuntimeResolution {
229 sources: AvailableConfigOptions {
230 cli_config: None,
231 env_config: None,
232 repo_config: None,
233 global_config: None,
234 registries: Vec::new(),
235 registry_failures: Vec::new(),
236 },
237 config: None,
238 policy: Policy::default(),
239 },
240 }
241 }
242
243 pub fn resolve_cli_source(&mut self, logger: Option<&dyn LoggerTrait>) {
244 if let Some(path) = self.explicit_config_path().cloned() {
245 let (base_config, rules_config) = resolve_project_configs(&path, logger);
246 self.resolution.sources.cli_config =
247 Some(resolve_available_config(base_config, rules_config));
248 }
249 }
250
251 pub fn resolve_repo_source(&mut self, logger: &dyn LoggerTrait) {
252 let cwd = self.cwd().clone();
253 let repo_root = self.repo_root().clone();
254 let in_git = self.in_git_repo();
255
256 let msg = format!(
257 "Resolving repo config: cwd={:?}, repo_root={:?}, in_git_repo={}",
258 cwd, repo_root, in_git
259 );
260 logger.debug(&msg);
261
262 if let Some(path) = resolve_project_config_path(&cwd, Some(&repo_root), in_git, None) {
263 let msg = format!("Found config path: {:?}", path);
264 logger.debug(&msg);
265 let (base_config, rules_config) = resolve_project_configs(&path, Some(logger));
266 let msg = format!(
267 "Config loaded: base={}, rules={}",
268 base_config.is_some(),
269 rules_config.is_some()
270 );
271 logger.debug(&msg);
272 self.resolution.sources.repo_config =
273 Some(resolve_available_config(base_config, rules_config));
274 } else {
275 logger.info("No project config found");
276 }
277 }
278
279 pub fn resolve_global_source(&mut self) {
280 let (base_config, rules_config) = resolve_global_configs();
281 self.resolution.sources.global_config =
282 Some(resolve_available_config(base_config, rules_config));
283 }
284
285 pub fn resolve_env_source(&mut self) {
286 if let Some(base) = build_env_config() {
287 self.resolution.sources.env_config = Some(resolve_available_config(Some(base), None));
288 }
289 }
290
291 pub fn resolve_registry_source(
294 &mut self,
295 logger: &dyn LoggerTrait,
296 ) -> crate::engine::error::Result<()> {
297 let partial_base = self.build_partial_config_for_registry();
298
299 let cli_url = self.explicit_registry().map(String::to_owned);
300 let cli_ref = self.explicit_registry_ref().map(String::to_owned);
301 let cli_section = self.explicit_registry_section().map(String::to_owned);
302
303 let active_spec = resolve_registry_spec(
305 cli_url.as_deref(),
306 cli_ref.as_deref(),
307 cli_section.as_deref(),
308 Some(&partial_base),
309 );
310
311 let partial_rules = self.build_partial_rules_for_registry();
314 let active_spec = active_spec.map(|mut spec| {
315 if let Some(rules) = &partial_rules
316 && let Ok(resolved) = rules.resolve_string(&spec.url)
317 {
318 spec.url = resolved;
319 }
320 spec
321 });
322
323 let required = partial_base.registry_required();
324 let use_cache = partial_base.registry_cache();
325
326 if required && active_spec.is_none() && partial_base.registry_use().is_some() {
328 return Err(crate::engine::error::ErrorCode::RegistryUnknown
329 .error()
330 .with_context("registry", partial_base.registry_use().unwrap_or_default())
331 .with_context("reason", "registry is required but not configured"));
332 }
333
334 let mut all_specs = self.collect_all_registry_specs();
336
337 if let Some(ref a) = active_spec {
341 let already_present = all_specs.iter().any(|(_, s)| {
342 s.url == a.url && s.r#ref == a.r#ref
344 });
345 if !already_present {
346 all_specs.push(("cli".to_string(), a.clone()));
347 }
348 }
349
350 let cache_dir = self.global_cache_path().clone();
352 let state_file_path = self.state_file_path();
353
354 for (name, spec) in all_specs {
355 let spec_to_load = if let Some(ref a) = active_spec {
358 if spec.url == a.url && spec.r#ref == a.r#ref {
359 a.clone()
360 } else {
361 spec.clone()
362 }
363 } else {
364 spec.clone()
365 };
366
367 let is_active = active_spec
368 .as_ref()
369 .is_some_and(|a| a.url == spec.url && a.r#ref == spec.r#ref);
370
371 let registry_id = match &spec_to_load.section {
373 Some(section) => {
374 format!("{}##{}/{}", spec_to_load.url, spec_to_load.r#ref, section)
375 }
376 None => format!("{}##{}", spec_to_load.url, spec_to_load.r#ref),
377 };
378
379 match load_registry(
380 &spec_to_load,
381 &cache_dir,
382 &state_file_path,
383 use_cache,
384 logger,
385 ) {
386 Ok(result) => {
387 let status = if is_active { "[ACTIVE]" } else { "[available]" };
388 logger.debug(&format!(
389 "Registry loaded: url={}, ref={}, section={} {status}",
390 spec_to_load.url,
391 spec_to_load.r#ref,
392 spec_to_load.section.as_deref().unwrap_or("(root)")
393 ));
394
395 if is_active {
397 use crate::engine::config::registry::registry_cache_path;
398 let cache_path =
399 registry_cache_path(&spec_to_load.url, &spec_to_load.r#ref, &cache_dir);
400
401 use crate::engine::models::state::{AppState, RegistryState};
402 let mut state = AppState::new();
403 state.registry = Some(RegistryState::new(
404 Some(name.clone()),
405 spec_to_load.url.clone(),
406 spec_to_load.r#ref.clone(),
407 spec_to_load.section.clone(),
408 result.resolved_commit.clone(),
409 cache_path,
410 ));
411
412 if let Err(e) = state.save(&state_file_path) {
413 logger.warn(&format!("Failed to save registry state: {e}"));
414 }
415 }
416
417 self.resolution.sources.registries.push(RegistryOptions {
418 id: registry_id,
419 tag: name,
420 url: spec_to_load.url,
421 r#ref: spec_to_load.r#ref,
422 section: spec_to_load.section,
423 config: Some(result.config),
424 sections: None,
425 is_active,
426 });
427 }
428 Err(e) if is_active && required => {
429 return Err(e.with_context("registry", name.clone()));
430 }
431 Err(e) => {
432 let message = format!("Registry load failed ({name}): {e}");
433 logger.warn(&message);
434 self.resolution.sources.registry_failures.push(message);
435 }
436 }
437 }
438
439 Ok(())
440 }
441
442 fn build_partial_config_for_registry(&self) -> BaseConfig {
445 let global = self
446 .resolution
447 .sources
448 .global_config
449 .as_ref()
450 .and_then(|c| c.base.clone());
451 let env = self
452 .resolution
453 .sources
454 .env_config
455 .as_ref()
456 .and_then(|c| c.base.clone());
457 let repo = self
458 .resolution
459 .sources
460 .repo_config
461 .as_ref()
462 .and_then(|c| c.base.clone());
463 let cli = self
464 .resolution
465 .sources
466 .cli_config
467 .as_ref()
468 .and_then(|c| c.base.clone());
469 let base = global.unwrap_or_else(BaseConfig::empty);
470 let base = if let Some(r) = repo {
471 r.merge(base)
472 } else {
473 base
474 };
475 let base = if let Some(e) = env {
476 e.merge(base)
477 } else {
478 base
479 };
480 if let Some(c) = cli {
481 c.merge(base)
482 } else {
483 base
484 }
485 }
486
487 fn build_partial_rules_for_registry(&self) -> Option<crate::engine::config::RulesConfig> {
490 self.resolution
491 .sources
492 .cli_config
493 .as_ref()
494 .and_then(|c| c.rules.clone())
495 .or_else(|| {
496 self.resolution
497 .sources
498 .repo_config
499 .as_ref()
500 .and_then(|c| c.rules.clone())
501 })
502 .or_else(|| {
503 self.resolution
504 .sources
505 .global_config
506 .as_ref()
507 .and_then(|c| c.rules.clone())
508 })
509 }
510
511 fn collect_all_registry_specs(&self) -> Vec<(String, RegistrySpec)> {
515 let mut specs: Vec<(String, RegistrySpec)> = Vec::new();
516
517 for available_config in [
518 self.resolution.sources.global_config.as_ref(),
519 self.resolution.sources.repo_config.as_ref(),
520 ]
521 .into_iter()
522 .flatten()
523 {
524 if let Some(cfg) = available_config.base.as_ref() {
525 for (name, reg) in cfg.registries_map() {
526 if let Some(url) = reg.url {
527 let resolved_url = if let Some(rules) = &available_config.rules {
530 match rules.resolve_string(&url) {
531 Ok(s) => s,
532 Err(_) => {
533 continue;
536 }
537 }
538 } else {
539 url.clone()
540 };
541
542 specs.push((
545 name,
546 RegistrySpec {
547 url: resolved_url,
548 r#ref: reg.r#ref.unwrap_or_else(|| "HEAD".to_string()),
549 section: reg.section,
550 },
551 ));
552 }
553 }
554 }
555 }
556
557 let mut seen = std::collections::HashSet::new();
559 specs.retain(|(name, spec)| seen.insert((name.clone(), spec.url.clone())));
560 specs
561 }
562
563 pub fn resolve_available_sources(
564 &mut self,
565 logger: &dyn LoggerTrait,
566 ) -> crate::engine::error::Result<()> {
567 self.resolve_cli_source(Some(logger));
568 self.resolve_env_source();
569 self.resolve_repo_source(logger);
570 self.resolve_global_source();
571 self.resolve_registry_source(logger)
572 }
573
574 pub fn resolve_active_config(
575 &mut self,
576 logger: &dyn LoggerTrait,
577 ) -> crate::engine::error::Result<()> {
578 let global_base = self
586 .resolution
587 .sources
588 .global_config
589 .as_ref()
590 .and_then(|c| c.base.clone());
591 let registry_base = self
592 .resolution
593 .sources
594 .registries
595 .iter()
596 .find(|r| r.is_active)
597 .and_then(|r| r.config.as_ref())
598 .and_then(|c| c.base.clone());
599 let repo_base = self
600 .resolution
601 .sources
602 .repo_config
603 .as_ref()
604 .and_then(|c| c.base.clone());
605 let cli_base = self
606 .resolution
607 .sources
608 .cli_config
609 .as_ref()
610 .and_then(|c| c.base.clone());
611
612 let has_registry_repo_or_cli =
614 registry_base.is_some() || repo_base.is_some() || cli_base.is_some();
615
616 if has_registry_repo_or_cli {
617 let base = {
619 let base = registry_base.unwrap_or_else(BaseConfig::empty);
620 let base = if let Some(r) = repo_base {
621 r.merge(base)
622 } else {
623 base
624 };
625 if let Some(c) = cli_base {
626 c.merge(base)
627 } else {
628 base
629 }
630 };
631
632 let registry_rules = self
635 .resolution
636 .sources
637 .registries
638 .iter()
639 .find(|r| r.is_active)
640 .and_then(|r| r.config.as_ref())
641 .and_then(|c| c.rules.clone());
642
643 let rules = self
644 .resolution
645 .sources
646 .cli_config
647 .as_ref()
648 .and_then(|c| c.rules.clone())
649 .or_else(|| {
650 self.resolution
651 .sources
652 .repo_config
653 .as_ref()
654 .and_then(|c| c.rules.clone())
655 })
656 .or_else(|| registry_rules.clone());
657
658 let rules = if registry_rules.is_none() {
660 rules.or_else(|| {
661 self.resolution
662 .sources
663 .global_config
664 .as_ref()
665 .and_then(|c| c.rules.clone())
666 })
667 } else {
668 rules
669 }
670 .unwrap_or_default();
671
672 use crate::engine::config::resolver::merge_rules_into_base;
675 let base = merge_rules_into_base(base, &rules)?;
676
677 logger.debug(&format!(
678 "[config] resolved commit.types: {:?}",
679 base.commit
680 .as_ref()
681 .and_then(|c| c.types.as_ref())
682 .map(|t| t.keys().cloned().collect::<Vec<_>>()),
683 ));
684
685 let path = self.project_config_path();
686 self.resolution.config = Some(ResolvedConfig { path, rules, base });
687 self.resolve_policy();
688 } else if global_base.is_some() {
689 let base = global_base.unwrap();
691 let rules = self
692 .resolution
693 .sources
694 .global_config
695 .as_ref()
696 .and_then(|c| c.rules.clone())
697 .unwrap_or_default();
698
699 use crate::engine::config::resolver::merge_rules_into_base;
700 let base = merge_rules_into_base(base, &rules)?;
701
702 logger.debug(&format!(
703 "[config] resolved commit.types: {:?}",
704 base.commit
705 .as_ref()
706 .and_then(|c| c.types.as_ref())
707 .map(|t| t.keys().cloned().collect::<Vec<_>>()),
708 ));
709
710 let path = self.project_config_path();
711 self.resolution.config = Some(ResolvedConfig { path, rules, base });
712 self.resolve_policy();
713 } else {
714 use crate::engine::config::resolver::merge_rules_into_base;
718 let rules = crate::engine::config::RulesConfig::default();
719 let base = merge_rules_into_base(
720 crate::engine::constants::defaults::config::standard_base_config(),
721 &rules,
722 )?;
723 self.resolution.config = Some(ResolvedConfig {
724 path: None,
725 rules,
726 base,
727 });
728 self.resolve_policy();
729 }
730
731 Ok(())
732 }
733
734 pub fn resolve_policy(&mut self) {
735 let policy = resolve_policy(self.config());
736 self.resolution.policy = policy;
737 }
738
739 pub fn explicit_config_path(&self) -> Option<&PathBuf> {
740 self.paths.explicit_config_path.as_ref()
741 }
742
743 pub fn explicit_registry(&self) -> Option<&String> {
744 self.paths.explicit_registry.as_ref()
745 }
746
747 pub fn explicit_registry_ref(&self) -> Option<&String> {
748 self.paths.explicit_registry_ref.as_ref()
749 }
750
751 pub fn explicit_registry_section(&self) -> Option<&String> {
752 self.paths.explicit_registry_section.as_ref()
753 }
754
755 pub fn set_explicit_config_path(&mut self, path: Option<PathBuf>) -> &mut Self {
756 self.paths.explicit_config_path = path;
757 self
758 }
759
760 pub fn set_explicit_registry(&mut self, registry: Option<String>) -> &mut Self {
761 self.paths.explicit_registry = registry;
762 self
763 }
764
765 pub fn set_explicit_registry_ref(&mut self, registry_ref: Option<String>) -> &mut Self {
766 self.paths.explicit_registry_ref = registry_ref;
767 self
768 }
769
770 pub fn set_explicit_registry_section(&mut self, registry_section: Option<String>) -> &mut Self {
771 self.paths.explicit_registry_section = registry_section;
772 self
773 }
774
775 pub fn project_config_path(&self) -> Option<PathBuf> {
776 resolve_project_config_path(
777 self.cwd(),
778 Some(self.repo_root().as_path()),
779 self.in_git_repo(),
780 self.explicit_config_path().map(|p| p.as_path()),
781 )
782 }
783}