Skip to main content

commit_wizard/engine/config/base/
mod.rs

1pub mod types;
2pub use types::*;
3
4use std::collections::{BTreeMap, HashMap};
5
6use crate::engine::{
7    constants::{
8        CONFIG_VERSION, defaults, full_base_config, minimal_base_config, standard_base_config,
9    },
10    models::policy::enforcement::AiProvider,
11};
12
13#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
14#[serde(deny_unknown_fields)]
15pub struct BaseConfig {
16    #[serde(default, skip_serializing_if = "Option::is_none")]
17    pub commit: Option<CommitConfig>,
18    #[serde(default, skip_serializing_if = "Option::is_none")]
19    pub branch: Option<BranchConfig>,
20    #[serde(default, skip_serializing_if = "Option::is_none")]
21    pub pr: Option<PrConfig>,
22    #[serde(default, skip_serializing_if = "Option::is_none")]
23    pub check: Option<CheckConfig>,
24    #[serde(default, skip_serializing_if = "Option::is_none")]
25    pub push: Option<PushConfig>,
26    #[serde(default, skip_serializing_if = "Option::is_none")]
27    pub versioning: Option<VersioningConfig>,
28    #[serde(default, skip_serializing_if = "Option::is_none")]
29    pub changelog: Option<ChangelogConfig>,
30    #[serde(default, skip_serializing_if = "Option::is_none")]
31    pub release: Option<ReleaseConfig>,
32    #[serde(default, skip_serializing_if = "Option::is_none")]
33    pub hooks: Option<HooksConfig>,
34    #[serde(default, skip_serializing_if = "Option::is_none")]
35    pub ai: Option<AiConfig>,
36    #[serde(default, skip_serializing_if = "Option::is_none")]
37    pub registry: Option<RegistryConfig>,
38    #[serde(default, skip_serializing_if = "Option::is_none")]
39    pub registries: Option<HashMap<String, NamedRegistryConfig>>,
40}
41
42impl BaseConfig {
43    pub fn empty() -> Self {
44        Self {
45            commit: None,
46            branch: None,
47            pr: None,
48            check: None,
49            push: None,
50            versioning: None,
51            changelog: None,
52            release: None,
53            hooks: None,
54            ai: None,
55            registry: None,
56            registries: None,
57        }
58    }
59
60    /// Merge two configs. `self` has higher priority — its sections win over `lower` for each
61    /// top-level section, falling back to `lower` only when `self`'s section is `None`.
62    /// Merge two layers, with `self` taking precedence over `lower`.
63    ///
64    /// The merge is recursive: tables are combined key by key and the higher
65    /// layer wins only for the leaves it actually sets. A local config can
66    /// therefore change one commit type, one scope policy value or one
67    /// versioning field and keep everything else from the layer below (for
68    /// example a registry). Arrays are replaced, not concatenated.
69    pub fn merge(self, lower: BaseConfig) -> BaseConfig {
70        match deep_merge_configs(&self, &lower) {
71            Some(merged) => merged,
72            None => self.shallow_merge(lower),
73        }
74    }
75
76    /// Per-table merge used if the recursive merge cannot round-trip.
77    fn shallow_merge(self, lower: BaseConfig) -> BaseConfig {
78        BaseConfig {
79            commit: merge_commit_config(self.commit, lower.commit),
80            branch: self.branch.or(lower.branch),
81            pr: self.pr.or(lower.pr),
82            check: self.check.or(lower.check),
83            push: self.push.or(lower.push),
84            versioning: self.versioning.or(lower.versioning),
85            changelog: self.changelog.or(lower.changelog),
86            release: self.release.or(lower.release),
87            hooks: self.hooks.or(lower.hooks),
88            ai: self.ai.or(lower.ai),
89            registry: merge_registry_config(self.registry, lower.registry),
90            registries: self.registries.or(lower.registries),
91        }
92    }
93
94    pub fn minimal() -> Self {
95        minimal_base_config()
96    }
97
98    pub fn standard() -> Self {
99        standard_base_config()
100    }
101
102    pub fn full() -> Self {
103        full_base_config()
104    }
105
106    pub fn version(&self) -> u32 {
107        CONFIG_VERSION
108    }
109
110    // -------------------------------------------------------------------------
111    // commit
112    // -------------------------------------------------------------------------
113
114    pub fn commit_subject_max_length(&self) -> u32 {
115        self.commit
116            .as_ref()
117            .and_then(|c| c.subject_max_length)
118            .unwrap_or(defaults::COMMIT_SUBJECT_MAX_LENGTH)
119    }
120
121    pub fn commit_use_emojis(&self) -> bool {
122        self.commit
123            .as_ref()
124            .and_then(|c| c.use_emojis)
125            .unwrap_or(defaults::COMMIT_USE_EMOJIS)
126    }
127
128    pub fn commit_types(&self) -> BTreeMap<String, CommitTypeConfig> {
129        self.commit
130            .as_ref()
131            .and_then(|c| c.types.clone())
132            .unwrap_or_else(defaults::default_commit_types)
133    }
134
135    pub fn commit_scopes_mode(&self) -> crate::engine::models::policy::enforcement::ScopeMode {
136        self.commit
137            .as_ref()
138            .and_then(|c| c.scopes.as_ref())
139            .and_then(|s| s.mode)
140            .unwrap_or(defaults::COMMIT_SCOPE_MODE)
141    }
142
143    pub fn commit_scope_restrict_to_defined(&self) -> bool {
144        self.commit
145            .as_ref()
146            .and_then(|c| c.scopes.as_ref())
147            .and_then(|s| s.restrict_to_defined)
148            .unwrap_or(defaults::COMMIT_SCOPE_RESTRICT_TO_DEFINED)
149    }
150
151    pub fn commit_scope_allowed(&self) -> Vec<String> {
152        self.commit
153            .as_ref()
154            .and_then(|c| c.scopes.as_ref())
155            .and_then(|s| {
156                s.definitions
157                    .clone()
158                    .map(|defs| defs.keys().cloned().collect())
159            })
160            .unwrap_or_else(defaults::default_commit_allowed_scopes)
161    }
162
163    pub fn commit_breaking_require_header(&self) -> bool {
164        self.commit
165            .as_ref()
166            .and_then(|c| c.breaking.as_ref())
167            .and_then(|b| b.require_header)
168            .unwrap_or(defaults::COMMIT_BREAKING_REQUIRE_HEADER)
169    }
170
171    pub fn commit_breaking_require_footer(&self) -> bool {
172        self.commit
173            .as_ref()
174            .and_then(|c| c.breaking.as_ref())
175            .and_then(|b| b.require_footer)
176            .unwrap_or(defaults::COMMIT_BREAKING_REQUIRE_FOOTER)
177    }
178
179    pub fn commit_breaking_footer_key(&self) -> String {
180        self.commit
181            .as_ref()
182            .and_then(|c| c.breaking.as_ref())
183            .and_then(|b| b.footer_key.clone())
184            .unwrap_or_else(|| defaults::COMMIT_BREAKING_FOOTER_KEY.to_string())
185    }
186
187    pub fn commit_breaking_footer_keys_normalized(&self) -> Vec<String> {
188        let breaking = self.commit.as_ref().and_then(|c| c.breaking.as_ref());
189
190        if let Some(b) = breaking {
191            let mut keys = Vec::new();
192
193            // Add footer_key if present
194            if let Some(ref key) = b.footer_key
195                && !key.is_empty()
196            {
197                keys.push(key.clone());
198            }
199
200            // Add footer_keys if present
201            if let Some(ref keys_list) = b.footer_keys {
202                for key in keys_list {
203                    if !key.is_empty() && !keys.contains(key) {
204                        keys.push(key.clone());
205                    }
206                }
207            }
208
209            if !keys.is_empty() {
210                return keys;
211            }
212        }
213
214        // Default: BREAKING CHANGE and BREAKING-CHANGE
215        vec!["BREAKING CHANGE".to_string(), "BREAKING-CHANGE".to_string()]
216    }
217
218    pub fn commit_breaking_emoji(&self) -> Option<String> {
219        self.commit
220            .as_ref()
221            .and_then(|c| c.breaking.as_ref())
222            .and_then(|b| b.emoji.clone())
223    }
224
225    pub fn commit_breaking_emoji_mode(
226        &self,
227    ) -> crate::engine::models::policy::enforcement::EmojiMode {
228        self.commit
229            .as_ref()
230            .and_then(|c| c.breaking.as_ref())
231            .and_then(|b| b.emoji_mode)
232            .unwrap_or_default()
233    }
234
235    pub fn commit_ticket_required(&self) -> bool {
236        self.commit
237            .as_ref()
238            .and_then(|c| c.ticket.as_ref())
239            .and_then(|t| t.required)
240            .unwrap_or(defaults::COMMIT_TICKET_REQUIRED)
241    }
242
243    pub fn commit_ticket_pattern(&self) -> Option<String> {
244        self.commit
245            .as_ref()
246            .and_then(|c| c.ticket.as_ref())
247            .and_then(|t| t.pattern.clone())
248    }
249
250    pub fn commit_ticket_source(&self) -> crate::engine::models::policy::enforcement::TicketSource {
251        self.commit
252            .as_ref()
253            .and_then(|c| c.ticket.as_ref())
254            .and_then(|t| t.source)
255            .unwrap_or(defaults::COMMIT_TICKET_SOURCE)
256    }
257
258    pub fn commit_protected_allow(&self) -> bool {
259        self.commit
260            .as_ref()
261            .and_then(|c| c.protected.as_ref())
262            .and_then(|p| p.allow)
263            .unwrap_or(defaults::COMMIT_PROTECTED_ALLOW)
264    }
265
266    pub fn commit_protected_force(&self) -> bool {
267        self.commit
268            .as_ref()
269            .and_then(|c| c.protected.as_ref())
270            .and_then(|p| p.force)
271            .unwrap_or(defaults::COMMIT_PROTECTED_FORCE)
272    }
273
274    pub fn commit_protected_warn(&self) -> bool {
275        self.commit
276            .as_ref()
277            .and_then(|c| c.protected.as_ref())
278            .and_then(|p| p.warn)
279            .unwrap_or(defaults::COMMIT_PROTECTED_WARN)
280    }
281
282    // -------------------------------------------------------------------------
283    // branch
284    // -------------------------------------------------------------------------
285
286    pub fn branch_remote(&self) -> String {
287        self.branch
288            .as_ref()
289            .and_then(|b| b.remote.clone())
290            .unwrap_or_else(|| defaults::BRANCH_REMOTE.to_string())
291    }
292
293    pub fn branch_protected_patterns(&self) -> Vec<String> {
294        self.branch
295            .as_ref()
296            .and_then(|b| b.protected.clone())
297            .unwrap_or_else(defaults::default_branch_protected_patterns)
298    }
299
300    pub fn branch_naming_pattern(&self) -> String {
301        self.branch
302            .as_ref()
303            .and_then(|b| b.naming.as_ref())
304            .and_then(|n| n.pattern.clone())
305            .unwrap_or_else(|| defaults::BRANCH_NAMING_PATTERN.to_string())
306    }
307
308    pub fn branch_naming_enforce(&self) -> bool {
309        defaults::BRANCH_NAMING_ENFORCE
310    }
311
312    pub fn branch_allowed_targets(&self) -> Vec<String> {
313        defaults::default_branch_allowed_targets()
314    }
315
316    // -------------------------------------------------------------------------
317    // pr
318    // -------------------------------------------------------------------------
319
320    pub fn pr_enabled(&self) -> bool {
321        self.pr
322            .as_ref()
323            .and_then(|p| p.enabled)
324            .unwrap_or(defaults::PR_ENABLED)
325    }
326
327    // -------------------------------------------------------------------------
328    // check
329    // -------------------------------------------------------------------------
330
331    pub fn check_require_conventional(&self) -> bool {
332        self.check
333            .as_ref()
334            .and_then(|c| c.require_conventional)
335            .unwrap_or(defaults::CHECK_REQUIRE_CONVENTIONAL)
336    }
337
338    pub fn check_commits_enabled(&self) -> bool {
339        self.check
340            .as_ref()
341            .and_then(|c| c.commits.as_ref())
342            .and_then(|cc| cc.enabled)
343            .unwrap_or(defaults::CHECK_COMMITS_ENABLED)
344    }
345
346    pub fn check_commits_enforce_on(
347        &self,
348    ) -> crate::engine::models::policy::enforcement::CommitEnforcementScope {
349        self.check
350            .as_ref()
351            .and_then(|c| c.commits.as_ref())
352            .and_then(|cc| cc.enforce_on)
353            .unwrap_or(defaults::CHECK_COMMITS_ENFORCE_ON)
354    }
355
356    // -------------------------------------------------------------------------
357    // push
358    // -------------------------------------------------------------------------
359
360    pub fn push_allow_protected(&self) -> bool {
361        self.push
362            .as_ref()
363            .and_then(|p| p.allow.as_ref())
364            .and_then(|a| a.protected)
365            .unwrap_or(defaults::PUSH_ALLOW_PROTECTED)
366    }
367
368    pub fn push_allow_force(&self) -> bool {
369        self.push
370            .as_ref()
371            .and_then(|p| p.allow.as_ref())
372            .and_then(|a| a.force)
373            .unwrap_or(defaults::PUSH_ALLOW_FORCE)
374    }
375
376    pub fn push_check_commits(&self) -> bool {
377        self.push
378            .as_ref()
379            .and_then(|p| p.check.as_ref())
380            .and_then(|c| c.commits)
381            .unwrap_or(defaults::PUSH_CHECK_COMMITS)
382    }
383
384    pub fn push_check_branch_policy(&self) -> bool {
385        self.push
386            .as_ref()
387            .and_then(|p| p.check.as_ref())
388            .and_then(|c| c.branch_policy)
389            .unwrap_or(defaults::PUSH_CHECK_BRANCH_POLICY)
390    }
391
392    // -------------------------------------------------------------------------
393    // versioning
394    // -------------------------------------------------------------------------
395
396    pub fn versioning_tag_prefix(&self) -> String {
397        self.versioning
398            .as_ref()
399            .and_then(|v| v.tag_prefix.clone())
400            .unwrap_or_else(|| defaults::VERSIONING_TAG_PREFIX.to_string())
401    }
402
403    // -------------------------------------------------------------------------
404    // changelog
405    // -------------------------------------------------------------------------
406
407    pub fn changelog_output(&self) -> String {
408        self.changelog
409            .as_ref()
410            .and_then(|c| c.output.clone())
411            .unwrap_or_else(|| defaults::CHANGELOG_OUTPUT.to_string())
412    }
413
414    pub fn changelog_format(&self) -> crate::engine::models::policy::enforcement::ChangelogFormat {
415        self.changelog
416            .as_ref()
417            .and_then(|c| c.format)
418            .unwrap_or(defaults::CHANGELOG_FORMAT)
419    }
420
421    pub fn changelog_group_by(&self) -> Vec<String> {
422        self.changelog
423            .as_ref()
424            .and_then(|c| c.layout.as_ref())
425            .and_then(|l| l.group_by.clone())
426            .unwrap_or_else(defaults::default_changelog_group_by)
427    }
428
429    pub fn changelog_section_order(&self) -> Vec<String> {
430        self.changelog
431            .as_ref()
432            .and_then(|c| c.layout.as_ref())
433            .and_then(|l| l.section_order.clone())
434            .unwrap_or_else(defaults::default_changelog_section_order)
435    }
436
437    pub fn changelog_scope_order(&self) -> Vec<String> {
438        self.changelog
439            .as_ref()
440            .and_then(|c| c.layout.as_ref())
441            .and_then(|l| l.scope_order.clone())
442            .unwrap_or_else(defaults::default_changelog_scope_order)
443    }
444
445    pub fn changelog_show_scope(&self) -> bool {
446        self.changelog
447            .as_ref()
448            .and_then(|c| c.layout.as_ref())
449            .and_then(|l| l.show_scope)
450            .unwrap_or(defaults::CHANGELOG_SHOW_SCOPE)
451    }
452
453    pub fn changelog_show_empty_sections(&self) -> Option<bool> {
454        Some(
455            self.changelog
456                .as_ref()
457                .and_then(|c| c.layout.as_ref())
458                .and_then(|l| l.show_empty_sections)
459                .unwrap_or(defaults::CHANGELOG_SHOW_EMPTY_SECTIONS),
460        )
461    }
462
463    pub fn changelog_show_empty_scopes(&self) -> Option<bool> {
464        Some(
465            self.changelog
466                .as_ref()
467                .and_then(|c| c.layout.as_ref())
468                .and_then(|l| l.show_empty_scopes)
469                .unwrap_or(defaults::CHANGELOG_SHOW_EMPTY_SCOPES),
470        )
471    }
472
473    pub fn changelog_misc_section(&self) -> Option<String> {
474        Some(
475            self.changelog
476                .as_ref()
477                .and_then(|c| c.layout.as_ref())
478                .and_then(|l| l.misc_section.clone())
479                .unwrap_or_else(|| defaults::CHANGELOG_MISC_SECTION.to_string()),
480        )
481    }
482
483    pub fn changelog_header_use(&self) -> bool {
484        self.changelog
485            .as_ref()
486            .and_then(|c| c.header.as_ref())
487            .and_then(|h| h.use_header)
488            .unwrap_or(true)
489    }
490
491    pub fn changelog_header_title(&self) -> String {
492        self.changelog
493            .as_ref()
494            .and_then(|c| c.header.as_ref())
495            .and_then(|h| h.title.clone())
496            .unwrap_or_else(|| "Changelog".to_string())
497    }
498
499    pub fn changelog_header_description(&self) -> Option<String> {
500        self.changelog
501            .as_ref()
502            .and_then(|c| c.header.as_ref())
503            .and_then(|h| h.description.clone())
504    }
505
506    pub fn changelog_sections(
507        &self,
508    ) -> std::collections::BTreeMap<String, crate::engine::config::base::ChangelogSectionConfig>
509    {
510        self.changelog
511            .as_ref()
512            .and_then(|c| c.sections.clone())
513            .unwrap_or_default()
514    }
515
516    pub fn changelog_unreleased_label(&self) -> String {
517        self.changelog
518            .as_ref()
519            .and_then(|c| c.layout.as_ref())
520            .and_then(|l| l.unreleased_label.clone())
521            .unwrap_or_else(|| "Unreleased".to_string())
522    }
523
524    pub fn changelog_date_format(&self) -> Option<String> {
525        self.changelog
526            .as_ref()
527            .and_then(|c| c.layout.as_ref())
528            .and_then(|l| l.date_format.clone())
529    }
530
531    // -------------------------------------------------------------------------
532    // release
533    // -------------------------------------------------------------------------
534
535    pub fn release_enabled(&self) -> bool {
536        self.release
537            .as_ref()
538            .and_then(|r| r.enabled)
539            .unwrap_or(defaults::RELEASE_ENABLED)
540    }
541
542    pub fn release_source_branch(&self) -> String {
543        self.release
544            .as_ref()
545            .and_then(|r| r.source_branch.clone())
546            .unwrap_or_else(|| defaults::RELEASE_SOURCE_BRANCH.to_string())
547    }
548
549    pub fn release_target_branch(&self) -> String {
550        self.release
551            .as_ref()
552            .and_then(|r| r.target_branch.clone())
553            .unwrap_or_else(|| defaults::RELEASE_TARGET_BRANCH.to_string())
554    }
555
556    pub fn release_branch_format(&self) -> String {
557        self.release
558            .as_ref()
559            .and_then(|r| r.branch_format.clone())
560            .unwrap_or_else(|| defaults::RELEASE_BRANCH_FORMAT.to_string())
561    }
562
563    pub fn release_hotfix_pattern(&self) -> String {
564        self.release
565            .as_ref()
566            .and_then(|r| r.hotfix_pattern.clone())
567            .unwrap_or_else(|| defaults::RELEASE_HOTFIX_PATTERN.to_string())
568    }
569
570    pub fn release_require_clean_worktree(&self) -> bool {
571        self.release
572            .as_ref()
573            .and_then(|r| r.validation.as_ref())
574            .and_then(|v| v.require_clean_worktree)
575            .unwrap_or(defaults::RELEASE_REQUIRE_CLEAN_WORKTREE)
576    }
577
578    pub fn release_fail_if_tag_exists(&self) -> bool {
579        self.release
580            .as_ref()
581            .and_then(|r| r.validation.as_ref())
582            .and_then(|v| v.fail_if_tag_exists)
583            .unwrap_or(defaults::RELEASE_FAIL_IF_TAG_EXISTS)
584    }
585
586    pub fn release_fail_if_release_branch_exists(&self) -> bool {
587        self.release
588            .as_ref()
589            .and_then(|r| r.validation.as_ref())
590            .and_then(|v| v.fail_if_release_branch_exists)
591            .unwrap_or(defaults::RELEASE_FAIL_IF_RELEASE_BRANCH_EXISTS)
592    }
593
594    pub fn release_finish_tag(&self) -> bool {
595        self.release
596            .as_ref()
597            .and_then(|r| r.finish.as_ref())
598            .and_then(|f| f.tag)
599            .unwrap_or(defaults::RELEASE_FINISH_TAG)
600    }
601
602    pub fn release_finish_push(&self) -> bool {
603        self.release
604            .as_ref()
605            .and_then(|r| r.finish.as_ref())
606            .and_then(|f| f.push)
607            .unwrap_or(defaults::RELEASE_FINISH_PUSH)
608    }
609
610    pub fn release_finish_backmerge_branch(&self) -> String {
611        self.release
612            .as_ref()
613            .and_then(|r| r.finish.as_ref())
614            .and_then(|f| f.backmerge_branch.clone())
615            .unwrap_or_else(|| defaults::RELEASE_FINISH_BACKMERGE_BRANCH.to_string())
616    }
617
618    // -------------------------------------------------------------------------
619    // hooks
620    // -------------------------------------------------------------------------
621
622    pub fn hooks_pre_commit(&self) -> bool {
623        self.hooks
624            .as_ref()
625            .and_then(|h| h.pre_commit)
626            .unwrap_or(defaults::HOOKS_PRE_COMMIT)
627    }
628
629    pub fn hooks_commit_msg(&self) -> bool {
630        self.hooks
631            .as_ref()
632            .and_then(|h| h.commit_msg)
633            .unwrap_or(defaults::HOOKS_COMMIT_MSG)
634    }
635
636    pub fn hooks_pre_push(&self) -> bool {
637        self.hooks
638            .as_ref()
639            .and_then(|h| h.pre_push)
640            .unwrap_or(defaults::HOOKS_PRE_PUSH)
641    }
642
643    // -------------------------------------------------------------------------
644    // ai
645    // -------------------------------------------------------------------------
646
647    pub fn ai_enabled(&self) -> bool {
648        self.ai
649            .as_ref()
650            .and_then(|a| a.enabled)
651            .unwrap_or(defaults::AI_ENABLED)
652    }
653
654    pub fn ai_provider(&self) -> AiProvider {
655        self.ai
656            .as_ref()
657            .and_then(|a| a.provider.clone())
658            .as_deref()
659            .map(AiProvider::from_str)
660            .unwrap_or(defaults::AI_PROVIDER)
661    }
662
663    pub fn ai_commit_enabled(&self) -> bool {
664        self.ai
665            .as_ref()
666            .and_then(|a| a.commands.as_ref())
667            .and_then(|c| c.commit)
668            .unwrap_or(defaults::AI_COMMAND_COMMIT)
669    }
670
671    pub fn ai_changelog_enabled(&self) -> bool {
672        self.ai
673            .as_ref()
674            .and_then(|a| a.commands.as_ref())
675            .and_then(|c| c.changelog)
676            .unwrap_or(defaults::AI_COMMAND_CHANGELOG)
677    }
678
679    pub fn ai_release_prepare_enabled(&self) -> bool {
680        self.ai
681            .as_ref()
682            .and_then(|a| a.commands.as_ref())
683            .and_then(|c| c.release_prepare)
684            .unwrap_or(defaults::AI_COMMAND_RELEASE_PREPARE)
685    }
686
687    // -------------------------------------------------------------------------
688    // registry
689    // -------------------------------------------------------------------------
690
691    pub fn registry_use(&self) -> Option<String> {
692        self.registry
693            .as_ref()
694            .and_then(|r| r.use_registry.clone())
695            .filter(|s| !s.trim().is_empty())
696    }
697
698    /// Whether a failure to load the active registry must stop the command.
699    pub fn registry_required(&self) -> bool {
700        self.registry
701            .as_ref()
702            .and_then(|r| r.required)
703            .unwrap_or(false)
704    }
705
706    /// Whether registries are kept in (and served from) the local cache.
707    pub fn registry_cache(&self) -> bool {
708        self.registry.as_ref().and_then(|r| r.cache).unwrap_or(true)
709    }
710
711    pub fn registries_map(&self) -> HashMap<String, NamedRegistryConfig> {
712        self.registries
713            .clone()
714            .unwrap_or_else(defaults::default_registries)
715    }
716}
717
718/// Recursively merge `high` over `low` through their TOML representation.
719/// Returns `None` if either side cannot be converted, so callers can fall back.
720fn deep_merge_configs(high: &BaseConfig, low: &BaseConfig) -> Option<BaseConfig> {
721    let mut merged = toml::Value::try_from(low).ok()?;
722    deep_merge_values(&mut merged, toml::Value::try_from(high).ok()?);
723    let mut config: BaseConfig = merged.try_into().ok()?;
724    // `use` has its own rule: an empty value must not mask a lower layer.
725    config.registry = merge_registry_config(high.registry.clone(), low.registry.clone());
726    Some(config)
727}
728
729fn deep_merge_values(low: &mut toml::Value, high: toml::Value) {
730    match (low, high) {
731        (toml::Value::Table(low), toml::Value::Table(high)) => {
732            for (key, value) in high {
733                match low.get_mut(&key) {
734                    Some(existing) => deep_merge_values(existing, value),
735                    None => {
736                        low.insert(key, value);
737                    }
738                }
739            }
740        }
741        (low, high) => *low = high,
742    }
743}
744
745/// Merge two optional `[registry]` tables field by field.
746///
747/// A higher-priority layer that sets only some fields (say `use`) must not
748/// discard the others (`required`, `cache`, `section`) from a lower layer, so
749/// a repo config can pick a registry while a global config makes it required.
750fn merge_registry_config(
751    high: Option<RegistryConfig>,
752    low: Option<RegistryConfig>,
753) -> Option<RegistryConfig> {
754    match (high, low) {
755        (None, low) => low,
756        (high, None) => high,
757        (Some(h), Some(l)) => Some(RegistryConfig {
758            // An empty `use` means "not chosen", so it must not mask a lower layer.
759            use_registry: h
760                .use_registry
761                .filter(|name| !name.trim().is_empty())
762                .or(l.use_registry),
763            section: h.section.or(l.section),
764            required: h.required.or(l.required),
765            cache: h.cache.or(l.cache),
766        }),
767    }
768}
769
770/// Deep-merge two optional CommitConfigs.
771///
772/// Each sub-field is merged independently so that a higher-priority layer can
773/// set `subject_max_length` without blowing away the `types` that came from a
774/// lower-priority layer (e.g. the registry). This is the key behaviour that
775/// allows the registry to supply commit types while the repo only overrides
776/// formatting settings.
777fn merge_commit_config(
778    high: Option<CommitConfig>,
779    low: Option<CommitConfig>,
780) -> Option<CommitConfig> {
781    match (high, low) {
782        (None, low) => low,
783        (high, None) => high,
784        (Some(h), Some(l)) => Some(CommitConfig {
785            subject_max_length: h.subject_max_length.or(l.subject_max_length),
786            use_emojis: h.use_emojis.or(l.use_emojis),
787            // types: high wins if explicitly set; otherwise fall through to lower layer
788            types: h.types.or(l.types),
789            scopes: h.scopes.or(l.scopes),
790            breaking: h.breaking.or(l.breaking),
791            protected: h.protected.or(l.protected),
792            ticket: h.ticket.or(l.ticket),
793        }),
794    }
795}
796
797#[cfg(test)]
798mod tests {
799    use super::*;
800
801    fn with_registry(registry: RegistryConfig) -> BaseConfig {
802        BaseConfig {
803            registry: Some(registry),
804            ..BaseConfig::empty()
805        }
806    }
807
808    fn registry(
809        use_registry: Option<&str>,
810        required: Option<bool>,
811        cache: Option<bool>,
812    ) -> RegistryConfig {
813        RegistryConfig {
814            use_registry: use_registry.map(str::to_string),
815            section: None,
816            required,
817            cache,
818        }
819    }
820
821    #[test]
822    fn registry_fields_merge_instead_of_replacing_the_table() {
823        let global = with_registry(registry(None, Some(true), Some(false)));
824        let repo = with_registry(registry(Some("team"), None, None));
825
826        let merged = repo.merge(global);
827
828        assert_eq!(merged.registry_use().as_deref(), Some("team"));
829        assert!(merged.registry_required(), "global required must survive");
830        assert!(
831            !merged.registry_cache(),
832            "global cache = false must survive"
833        );
834    }
835
836    #[test]
837    fn higher_layer_wins_per_field() {
838        let global = with_registry(registry(Some("global"), Some(true), Some(true)));
839        let repo = with_registry(registry(Some("repo"), Some(false), None));
840
841        let merged = repo.merge(global);
842
843        assert_eq!(merged.registry_use().as_deref(), Some("repo"));
844        assert!(!merged.registry_required());
845        assert!(merged.registry_cache());
846    }
847
848    #[test]
849    fn empty_use_does_not_mask_a_lower_layer() {
850        let global = with_registry(registry(Some("global"), None, None));
851        let repo = with_registry(registry(Some(""), None, None));
852
853        assert_eq!(repo.merge(global).registry_use().as_deref(), Some("global"));
854    }
855
856    #[test]
857    fn registry_defaults_when_no_layer_sets_them() {
858        let merged = BaseConfig::empty().merge(BaseConfig::empty());
859        assert!(!merged.registry_required());
860        assert!(merged.registry_cache());
861    }
862
863    fn parse(toml: &str) -> BaseConfig {
864        toml::from_str(toml).expect("valid config")
865    }
866
867    #[test]
868    fn commit_types_merge_per_type_and_per_field() {
869        let registry = parse(
870            r#"
871[commit.types.fix]
872description = "A bug fix"
873bump = "Patch"
874section = "Bug Fixes"
875
876[commit.types.wip]
877description = "Work in progress"
878bump = "Patch"
879"#,
880        );
881        let local = parse(
882            r#"
883[commit.types.fix]
884bump = "Minor"
885
886[commit.types.wip]
887enabled = false
888
889[commit.types.docs]
890description = "Documentation"
891"#,
892        );
893
894        let types = local.merge(registry).commit_types();
895
896        let fix = &types["fix"];
897        assert_eq!(
898            fix.description.as_deref(),
899            Some("A bug fix"),
900            "kept from below"
901        );
902        assert_eq!(fix.section.as_deref(), Some("Bug Fixes"), "kept from below");
903        assert!(
904            matches!(
905                fix.bump,
906                Some(crate::engine::models::policy::enforcement::BumpLevel::Minor)
907            ),
908            "overridden locally"
909        );
910        assert_eq!(types["wip"].enabled, Some(false));
911        assert_eq!(types["docs"].description.as_deref(), Some("Documentation"));
912        assert_eq!(types.len(), 3);
913    }
914
915    #[test]
916    fn other_tables_merge_per_field() {
917        let registry = parse("[push.allow]\nprotected = true\nforce = false\n");
918        let local = parse("[push.allow]\nforce = true\n");
919
920        let allow = local.merge(registry).push.unwrap().allow.unwrap();
921
922        assert_eq!(allow.protected, Some(true), "kept from below");
923        assert_eq!(allow.force, Some(true), "overridden locally");
924    }
925
926    #[test]
927    fn arrays_are_replaced_not_concatenated() {
928        let registry = parse("[branch]\nprotected = [\"main\", \"release/*\"]\n");
929        let local = parse("[branch]\nprotected = [\"trunk\"]\n");
930
931        let merged = local.merge(registry);
932
933        assert_eq!(
934            merged.branch.unwrap().protected,
935            Some(vec!["trunk".to_string()])
936        );
937    }
938
939    #[test]
940    fn merging_is_associative_across_three_layers() {
941        let low = parse("[commit]\nsubject_max_length = 100\nuse_emojis = false\n");
942        let mid = parse("[commit]\nuse_emojis = true\n");
943        let high = parse("[commit]\nsubject_max_length = 50\n");
944
945        let merged = high.merge(mid.merge(low));
946
947        assert_eq!(merged.commit_subject_max_length(), 50);
948        assert!(merged.commit_use_emojis());
949    }
950}