Skip to main content

code_system_graph_core/
config.rs

1use std::collections::BTreeMap;
2use std::path::{Path, PathBuf};
3
4use code_system_graph_model::stable_id;
5use schemars::JsonSchema;
6use serde::{Deserialize, Serialize};
7use thiserror::Error;
8
9use crate::ignore_policy::discover_repository_files_matching;
10use crate::{
11    CapabilityDir, CapabilityError, ContractImplementationConfig, HttpConsumerConfig, IgnorePatternError, IgnorePolicy, IntegrationTestConfig, MAX_REPOSITORY_CONFIG_BYTES, RegularFileEntry, RepositoryConfig, RepositoryDiscoveryError, validate_excludes, validate_include_defaults
12};
13
14const LOCAL_CONFIG_NAME: &str = ".code-system-graph.yaml";
15const MAX_OPENAPI_DISCOVERY_DEPTH: usize = 8;
16const MAX_OPENAPI_CANDIDATES: usize = 32;
17
18/// Origin of an effective repository configuration value.
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
20#[serde(rename_all = "snake_case")]
21pub enum ConfigSource {
22    /// Explicit command-line override.
23    CliOverride,
24    /// Explicit workspace manifest value.
25    WorkspaceManifest,
26    /// Repository-local `.code-system-graph.yaml` value.
27    RepositoryLocal,
28    /// Deterministic filesystem auto-detection.
29    AutoDetected,
30    /// Safe built-in default.
31    Default,
32}
33
34/// Applies the highest-precedence command-line `OpenAPI` override.
35///
36/// # Errors
37///
38/// Returns [`ConfigError::EmptyField`] when the override is empty.
39pub fn apply_openapi_override(
40    config: &mut EffectiveRepositoryConfig,
41    openapi: &str,
42) -> Result<(), ConfigError> {
43    if openapi.trim().is_empty() {
44        return Err(ConfigError::EmptyField {
45            path: PathBuf::from("<cli>"),
46            field: "repoOpenapi".to_owned(),
47        });
48    }
49    let previous_fingerprint = config.fingerprint.clone();
50    config.openapi = vec![openapi.to_owned()];
51    config.openapi_source = ConfigSource::CliOverride;
52    config.fingerprint = stable_id(
53        "repo-config",
54        &format!("base={previous_fingerprint};cli_openapi={openapi}"),
55    );
56    Ok(())
57}
58
59/// Strict merged repository configuration after precedence resolution.
60#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
61pub struct EffectiveRepositoryConfig {
62    /// Effective automatic-discovery exclusion policy.
63    pub ignore_policy: IgnorePolicy,
64    /// Selected `OpenAPI` artifacts relative to the checkout root.
65    pub openapi: Vec<String>,
66    /// Source that selected the `OpenAPI` artifacts.
67    pub openapi_source: ConfigSource,
68    /// Selected explicit HTTP consumers.
69    pub http_consumers: Vec<HttpConsumerConfig>,
70    /// Source that selected the HTTP consumers.
71    pub http_consumers_source: ConfigSource,
72    /// Selected explicit cross-language integration tests.
73    pub integration_tests: Vec<IntegrationTestConfig>,
74    /// Source that selected integration tests.
75    pub integration_tests_source: ConfigSource,
76    /// Selected explicit contract implementation anchors.
77    pub implementations: Vec<ContractImplementationConfig>,
78    /// Source that selected implementation anchors.
79    pub implementations_source: ConfigSource,
80    /// Fingerprint of all effective values and relevant local configuration.
81    pub fingerprint: String,
82}
83
84#[derive(Debug, Deserialize)]
85#[serde(rename_all = "camelCase", deny_unknown_fields)]
86struct RepositoryLocalConfig {
87    version: u32,
88    openapi: Option<String>,
89    http_consumers: Option<Vec<HttpConsumerConfig>>,
90    integration_tests: Option<Vec<IntegrationTestConfig>>,
91    implementations: Option<Vec<ContractImplementationConfig>>,
92    excludes: Option<Vec<String>>,
93    include_defaults: Option<Vec<String>>,
94    use_gitignore: Option<bool>,
95}
96
97/// Error returned while resolving repository configuration precedence.
98#[derive(Debug, Error)]
99pub enum ConfigError {
100    /// Repository-local configuration could not be read.
101    #[error("failed to read repository config `{path}`: {source}")]
102    Read {
103        /// Configuration path.
104        path: PathBuf,
105        /// Underlying filesystem error.
106        source: std::io::Error,
107    },
108    /// Repository-local configuration is malformed or contains unknown keys.
109    #[error("invalid repository config `{path}`: {source}")]
110    Invalid {
111        /// Configuration path.
112        path: PathBuf,
113        /// YAML decoding error.
114        source: Box<serde_saphyr::DeserializeError>,
115    },
116    /// Repository-local configuration schema version is unsupported.
117    #[error("unsupported repository config version {found} in `{path}`; expected version 1")]
118    UnsupportedVersion {
119        /// Configuration path.
120        path: PathBuf,
121        /// Version found in the file.
122        found: u32,
123    },
124    /// A configured value is empty.
125    #[error("repository config field `{field}` in `{path}` must not be empty")]
126    EmptyField {
127        /// Configuration path.
128        path: PathBuf,
129        /// Dot-style field location.
130        field: String,
131    },
132    /// Auto-detection found multiple plausible `OpenAPI` artifacts.
133    #[error("ambiguous OpenAPI auto-detection in `{root}`: {candidates:?}")]
134    AmbiguousOpenApi {
135        /// Repository checkout root.
136        root: PathBuf,
137        /// Candidate paths in deterministic order.
138        candidates: Vec<String>,
139    },
140    /// A repository-local discovery pattern is malformed or unsafe.
141    #[error("repository config field `{field}` in `{path}` is invalid: {source}")]
142    InvalidIgnorePattern {
143        /// Configuration path.
144        path: PathBuf,
145        /// Dot-style field location.
146        field: String,
147        /// Pattern validation failure.
148        #[source]
149        source: IgnorePatternError,
150    },
151    /// Automatic repository discovery or an enabled `.gitignore` file failed.
152    #[error(transparent)]
153    Discovery(#[from] RepositoryDiscoveryError),
154    /// Repository-local configuration is a symbolic link or reparse point.
155    #[error("repository config `{path}` is a symbolic link or reparse point")]
156    Symlink {
157        /// Configuration path.
158        path: PathBuf,
159    },
160    /// Repository-local configuration is not a regular file.
161    #[error("repository config `{path}` is not a regular file")]
162    NotRegularFile {
163        /// Configuration path.
164        path: PathBuf,
165    },
166    /// Repository-local configuration exceeds the accepted size limit.
167    #[error("repository config `{path}` exceeds {limit} bytes")]
168    TooLarge {
169        /// Configuration path.
170        path: PathBuf,
171        /// Maximum accepted size in bytes.
172        limit: usize,
173    },
174    /// Repository-local configuration resolves outside the checkout root.
175    #[error("repository config `{path}` is outside checkout `{checkout}`")]
176    OutsideCheckout {
177        /// Configuration path.
178        path: PathBuf,
179        /// Canonical checkout root.
180        checkout: PathBuf,
181    },
182}
183
184/// Resolves workspace, repository-local, auto-detected, and default values in that order.
185///
186/// An explicit empty workspace `httpConsumers` list suppresses lower-precedence values.
187/// Auto-detection never chooses among multiple candidates.
188///
189/// # Errors
190///
191/// Returns [`ConfigError`] for unreadable or invalid local configuration, empty values, or
192/// ambiguous auto-detection.
193pub fn resolve_repository_config(
194    checkout_path: &Path,
195    workspace: &RepositoryConfig,
196) -> Result<EffectiveRepositoryConfig, ConfigError> {
197    resolve_repository_config_with_use_gitignore(checkout_path, workspace, None)
198}
199
200/// Resolves repository configuration with an additive workspace-level `.gitignore` choice.
201///
202/// This companion API keeps [`RepositoryConfig`] exhaustively constructible for patch-version
203/// source compatibility.
204///
205/// # Errors
206///
207/// Returns the same errors as [`resolve_repository_config`].
208pub fn resolve_repository_config_with_use_gitignore(
209    checkout_path: &Path,
210    workspace: &RepositoryConfig,
211    workspace_use_gitignore: Option<bool>,
212) -> Result<EffectiveRepositoryConfig, ConfigError> {
213    let checkout = CapabilityDir::open(checkout_path)
214        .map_err(|error| map_capability_error(error, checkout_path, LOCAL_CONFIG_NAME))?;
215    let local_relative = Path::new(LOCAL_CONFIG_NAME);
216    let (local, local_source) = match checkout
217        .classify_regular_file_entry(local_relative)
218        .map_err(|error| map_capability_error(error, checkout_path, LOCAL_CONFIG_NAME))?
219    {
220        RegularFileEntry::Absent => (None, None),
221        RegularFileEntry::Regular => {
222            let local_path = checkout_path.join(LOCAL_CONFIG_NAME);
223            let source = checkout
224                .read_utf8_file_bounded(local_relative, MAX_REPOSITORY_CONFIG_BYTES)
225                .map_err(|error| map_capability_error(error, checkout_path, LOCAL_CONFIG_NAME))?;
226            let config: RepositoryLocalConfig =
227                crate::yaml::from_str(&source).map_err(|source| ConfigError::Invalid {
228                    path: local_path.clone(),
229                    source: Box::new(source),
230                })?;
231            validate_local(&local_path, &config)?;
232            (Some(config), Some(source))
233        }
234    };
235
236    let ignore_policy = resolve_ignore_policy(
237        checkout_path,
238        workspace,
239        workspace_use_gitignore,
240        local.as_ref(),
241    )?;
242    let (openapi, openapi_source) = if let Some(openapi) = &workspace.openapi {
243        (vec![openapi.clone()], ConfigSource::WorkspaceManifest)
244    } else if let Some(openapi) = local.as_ref().and_then(|config| config.openapi.clone()) {
245        (vec![openapi], ConfigSource::RepositoryLocal)
246    } else {
247        let candidates = discover_openapi_candidates(checkout_path, &ignore_policy)?;
248        if candidates.is_empty() {
249            (Vec::new(), ConfigSource::Default)
250        } else {
251            reject_competing_openapi_formats(checkout_path, &candidates)?;
252            (candidates, ConfigSource::AutoDetected)
253        }
254    };
255    let (http_consumers, http_consumers_source) = if let Some(consumers) = &workspace.http_consumers
256    {
257        (consumers.clone(), ConfigSource::WorkspaceManifest)
258    } else if let Some(consumers) = local
259        .as_ref()
260        .and_then(|config| config.http_consumers.clone())
261    {
262        (consumers, ConfigSource::RepositoryLocal)
263    } else {
264        (Vec::new(), ConfigSource::Default)
265    };
266    let (integration_tests, integration_tests_source) =
267        if let Some(tests) = &workspace.integration_tests {
268            (tests.clone(), ConfigSource::WorkspaceManifest)
269        } else if let Some(tests) = local
270            .as_ref()
271            .and_then(|config| config.integration_tests.clone())
272        {
273            (tests, ConfigSource::RepositoryLocal)
274        } else {
275            (Vec::new(), ConfigSource::Default)
276        };
277    let (implementations, implementations_source) =
278        if let Some(implementations) = &workspace.implementations {
279            (implementations.clone(), ConfigSource::WorkspaceManifest)
280        } else if let Some(implementations) = local
281            .as_ref()
282            .and_then(|config| config.implementations.clone())
283        {
284            (implementations, ConfigSource::RepositoryLocal)
285        } else {
286            (Vec::new(), ConfigSource::Default)
287        };
288    let fingerprint_material = format!(
289        "openapi={openapi:?};openapi_source={openapi_source:?};\
290         consumers={http_consumers:?};consumers_source={http_consumers_source:?};\
291         tests={integration_tests:?};tests_source={integration_tests_source:?};\
292         implementations={implementations:?};implementations_source={implementations_source:?};\
293         ignore_policy={};\
294         local={local_source:?}",
295        ignore_policy.fingerprint_material()
296    );
297    Ok(EffectiveRepositoryConfig {
298        ignore_policy,
299        openapi,
300        openapi_source,
301        http_consumers,
302        http_consumers_source,
303        integration_tests,
304        integration_tests_source,
305        implementations,
306        implementations_source,
307        fingerprint: stable_id("repo-config", &fingerprint_material),
308    })
309}
310
311fn map_capability_error(error: CapabilityError, checkout: &Path, config_name: &str) -> ConfigError {
312    let path = checkout.join(config_name);
313    match error {
314        CapabilityError::Io { path, source } => ConfigError::Read { path, source },
315        CapabilityError::Symlink { .. } => ConfigError::Symlink { path },
316        CapabilityError::NotRegularFile { .. } => ConfigError::NotRegularFile { path },
317        CapabilityError::TooLarge { limit, .. } => ConfigError::TooLarge { path, limit },
318        CapabilityError::OutsideRoot { root, .. } => ConfigError::OutsideCheckout {
319            path,
320            checkout: root,
321        },
322        CapabilityError::InvalidRelativePath { .. }
323        | CapabilityError::NotDirectory { .. }
324        | CapabilityError::InvalidUtf8 { .. } => ConfigError::Read {
325            path,
326            source: std::io::Error::new(std::io::ErrorKind::InvalidData, error.to_string()),
327        },
328    }
329}
330
331fn discover_openapi_candidates(
332    root: &Path,
333    ignore_policy: &IgnorePolicy,
334) -> Result<Vec<String>, ConfigError> {
335    let mut candidates = Vec::new();
336    for relative in discover_repository_files_matching(
337        root,
338        ignore_policy,
339        Some(MAX_OPENAPI_DISCOVERY_DEPTH.saturating_add(1)),
340        Some(MAX_OPENAPI_CANDIDATES),
341        |relative| {
342            relative
343                .file_name()
344                .and_then(|value| value.to_str())
345                .is_some_and(openapi_filename)
346        },
347    )? {
348        candidates.push(relative.to_string_lossy().replace('\\', "/"));
349    }
350    candidates.sort();
351    candidates.dedup();
352    Ok(candidates)
353}
354
355fn openapi_filename(name: &str) -> bool {
356    let lower = name.to_ascii_lowercase();
357    lower.contains("openapi")
358        && matches!(
359            Path::new(&lower)
360                .extension()
361                .and_then(|value| value.to_str()),
362            Some("json" | "yaml" | "yml")
363        )
364}
365
366fn reject_competing_openapi_formats(root: &Path, candidates: &[String]) -> Result<(), ConfigError> {
367    let mut by_stem = BTreeMap::<String, Vec<String>>::new();
368    for candidate in candidates {
369        let path = Path::new(candidate);
370        let parent = path.parent().unwrap_or_else(|| Path::new(""));
371        let stem = path
372            .file_stem()
373            .and_then(|value| value.to_str())
374            .unwrap_or(candidate);
375        by_stem
376            .entry(parent.join(stem).to_string_lossy().to_string())
377            .or_default()
378            .push(candidate.clone());
379    }
380    let ambiguous = by_stem
381        .into_values()
382        .filter(|values| values.len() > 1)
383        .flatten()
384        .collect::<Vec<_>>();
385    if ambiguous.is_empty() {
386        Ok(())
387    } else {
388        Err(ConfigError::AmbiguousOpenApi {
389            root: root.to_path_buf(),
390            candidates: ambiguous,
391        })
392    }
393}
394
395fn validate_local(path: &Path, config: &RepositoryLocalConfig) -> Result<(), ConfigError> {
396    if config.version != 1 {
397        return Err(ConfigError::UnsupportedVersion {
398            path: path.to_path_buf(),
399            found: config.version,
400        });
401    }
402    if config
403        .openapi
404        .as_ref()
405        .is_some_and(|value| value.trim().is_empty())
406    {
407        return Err(ConfigError::EmptyField {
408            path: path.to_path_buf(),
409            field: "openapi".to_owned(),
410        });
411    }
412    for (index, consumer) in config.http_consumers.iter().flatten().enumerate() {
413        for (field, value) in [
414            ("method", consumer.method.as_str()),
415            ("path", consumer.path.as_str()),
416            ("source", consumer.source.as_str()),
417        ] {
418            if value.trim().is_empty() {
419                return Err(ConfigError::EmptyField {
420                    path: path.to_path_buf(),
421                    field: format!("httpConsumers[{index}].{field}"),
422                });
423            }
424        }
425    }
426    for (index, test) in config.integration_tests.iter().flatten().enumerate() {
427        for (field, value) in [
428            ("name", test.name.as_str()),
429            ("path", test.path.as_str()),
430            ("framework", test.framework.as_str()),
431            ("language", test.language.as_str()),
432            ("validates.method", test.validates.method.as_str()),
433            ("validates.path", test.validates.path.as_str()),
434        ] {
435            if value.trim().is_empty() {
436                return Err(ConfigError::EmptyField {
437                    path: path.to_path_buf(),
438                    field: format!("integrationTests[{index}].{field}"),
439                });
440            }
441        }
442    }
443    for (index, implementation) in config.implementations.iter().flatten().enumerate() {
444        for (field, value) in [
445            ("language", implementation.language.as_str()),
446            ("path", implementation.path.as_str()),
447            ("symbol", implementation.symbol.as_str()),
448            (
449                "implements.method",
450                implementation.implements.method.as_str(),
451            ),
452            ("implements.path", implementation.implements.path.as_str()),
453        ] {
454            if value.trim().is_empty() {
455                return Err(ConfigError::EmptyField {
456                    path: path.to_path_buf(),
457                    field: format!("implementations[{index}].{field}"),
458                });
459            }
460        }
461    }
462    if let Some(patterns) = &config.excludes {
463        validate_excludes(patterns).map_err(|source| ConfigError::InvalidIgnorePattern {
464            path: path.to_path_buf(),
465            field: "excludes".to_owned(),
466            source,
467        })?;
468    }
469    if let Some(patterns) = &config.include_defaults {
470        validate_include_defaults(patterns).map_err(|source| {
471            ConfigError::InvalidIgnorePattern {
472                path: path.to_path_buf(),
473                field: "includeDefaults".to_owned(),
474                source,
475            }
476        })?;
477    }
478    Ok(())
479}
480
481fn select_patterns(
482    workspace: Option<&Vec<String>>,
483    local: Option<&Vec<String>>,
484) -> (Vec<String>, ConfigSource) {
485    if let Some(patterns) = workspace {
486        (patterns.clone(), ConfigSource::WorkspaceManifest)
487    } else if let Some(patterns) = local {
488        (patterns.clone(), ConfigSource::RepositoryLocal)
489    } else {
490        (Vec::new(), ConfigSource::Default)
491    }
492}
493
494fn select_flag(workspace: Option<bool>, local: Option<bool>) -> (bool, ConfigSource) {
495    if let Some(value) = workspace {
496        (value, ConfigSource::WorkspaceManifest)
497    } else if let Some(value) = local {
498        (value, ConfigSource::RepositoryLocal)
499    } else {
500        (false, ConfigSource::Default)
501    }
502}
503
504fn resolve_ignore_policy(
505    checkout_path: &Path,
506    workspace: &RepositoryConfig,
507    workspace_use_gitignore: Option<bool>,
508    local: Option<&RepositoryLocalConfig>,
509) -> Result<IgnorePolicy, ConfigError> {
510    let (excludes, excludes_source) = select_patterns(
511        workspace.excludes.as_ref(),
512        local.and_then(|config| config.excludes.as_ref()),
513    );
514    let (include_defaults, include_defaults_source) = select_patterns(
515        workspace.include_defaults.as_ref(),
516        local.and_then(|config| config.include_defaults.as_ref()),
517    );
518    let (use_gitignore, use_gitignore_source) = select_flag(
519        workspace_use_gitignore,
520        local.and_then(|config| config.use_gitignore),
521    );
522    IgnorePolicy::with_gitignore(
523        excludes,
524        excludes_source,
525        include_defaults,
526        include_defaults_source,
527        use_gitignore,
528        use_gitignore_source,
529    )
530    .map_err(|source| ConfigError::InvalidIgnorePattern {
531        path: checkout_path.to_path_buf(),
532        field: "ignorePolicy".to_owned(),
533        source,
534    })
535}
536
537#[cfg(test)]
538mod tests {
539    use std::fs;
540
541    use super::{
542        ConfigError, ConfigSource, resolve_repository_config, resolve_repository_config_with_use_gitignore
543    };
544    use crate::{HttpConsumerConfig, RepositoryConfig};
545
546    #[test]
547    fn workspace_manifest_should_override_repository_local_values()
548    -> Result<(), Box<dyn std::error::Error>> {
549        let repository = tempfile::tempdir()?;
550        fs::write(
551            repository.path().join(".code-system-graph.yaml"),
552            "version: 1\nopenapi: local.yaml\nhttpConsumers: []\n",
553        )?;
554        let workspace = RepositoryConfig {
555            path: ".".to_owned(),
556            openapi: Some("workspace.yaml".to_owned()),
557            http_consumers: Some(vec![HttpConsumerConfig {
558                method: "GET".to_owned(),
559                path: "/health".to_owned(),
560                source: "client.rs".to_owned(),
561            }]),
562            integration_tests: None,
563            implementations: None,
564            excludes: None,
565            include_defaults: None,
566        };
567
568        let resolved = resolve_repository_config(repository.path(), &workspace)?;
569
570        assert_eq!(
571            (
572                resolved.openapi,
573                resolved.openapi_source,
574                resolved.http_consumers.len(),
575                resolved.http_consumers_source,
576            ),
577            (
578                vec!["workspace.yaml".to_owned()],
579                ConfigSource::WorkspaceManifest,
580                1,
581                ConfigSource::WorkspaceManifest,
582            )
583        );
584        Ok(())
585    }
586
587    #[test]
588    fn workspace_ignore_fields_should_override_repository_local_lists()
589    -> Result<(), Box<dyn std::error::Error>> {
590        let repository = tempfile::tempdir()?;
591        fs::write(
592            repository.path().join(".code-system-graph.yaml"),
593            "version: 1\nexcludes: [local/**]\nincludeDefaults: [vendor/local/**]\n",
594        )?;
595        let workspace = RepositoryConfig {
596            path: ".".to_owned(),
597            openapi: None,
598            http_consumers: None,
599            integration_tests: None,
600            implementations: None,
601            excludes: Some(vec!["workspace/**".to_owned()]),
602            include_defaults: Some(Vec::new()),
603        };
604
605        let resolved = resolve_repository_config(repository.path(), &workspace)?;
606
607        assert_eq!(
608            (
609                resolved.ignore_policy.configured_excludes().to_vec(),
610                resolved.ignore_policy.configured_excludes_source(),
611                resolved.ignore_policy.include_defaults().to_vec(),
612                resolved.ignore_policy.include_defaults_source(),
613            ),
614            (
615                vec!["workspace/**".to_owned()],
616                ConfigSource::WorkspaceManifest,
617                Vec::new(),
618                ConfigSource::WorkspaceManifest,
619            )
620        );
621        Ok(())
622    }
623
624    #[test]
625    fn workspace_use_gitignore_should_override_repository_local_value()
626    -> Result<(), Box<dyn std::error::Error>> {
627        let repository = tempfile::tempdir()?;
628        fs::write(
629            repository.path().join(".code-system-graph.yaml"),
630            "version: 1\nuseGitignore: true\n",
631        )?;
632        let workspace = RepositoryConfig {
633            path: ".".to_owned(),
634            openapi: None,
635            http_consumers: None,
636            integration_tests: None,
637            implementations: None,
638            excludes: None,
639            include_defaults: None,
640        };
641
642        let resolved = resolve_repository_config_with_use_gitignore(
643            repository.path(),
644            &workspace,
645            Some(false),
646        )?;
647
648        assert!(!resolved.ignore_policy.use_gitignore());
649        assert_eq!(
650            resolved.ignore_policy.use_gitignore_source(),
651            ConfigSource::WorkspaceManifest
652        );
653        Ok(())
654    }
655
656    #[test]
657    fn repository_local_use_gitignore_should_apply_when_workspace_omits_it()
658    -> Result<(), Box<dyn std::error::Error>> {
659        let repository = tempfile::tempdir()?;
660        fs::write(
661            repository.path().join(".code-system-graph.yaml"),
662            "version: 1\nuseGitignore: true\n",
663        )?;
664        let workspace = RepositoryConfig {
665            path: ".".to_owned(),
666            openapi: None,
667            http_consumers: None,
668            integration_tests: None,
669            implementations: None,
670            excludes: None,
671            include_defaults: None,
672        };
673
674        let resolved = resolve_repository_config(repository.path(), &workspace)?;
675
676        assert!(resolved.ignore_policy.use_gitignore());
677        assert_eq!(
678            resolved.ignore_policy.use_gitignore_source(),
679            ConfigSource::RepositoryLocal
680        );
681        Ok(())
682    }
683
684    #[test]
685    fn openapi_auto_detection_should_respect_gitignore_when_enabled()
686    -> Result<(), Box<dyn std::error::Error>> {
687        let repository = tempfile::tempdir()?;
688        fs::write(repository.path().join(".gitignore"), "ignored/\n")?;
689        fs::create_dir(repository.path().join("ignored"))?;
690        fs::write(repository.path().join("ignored/openapi.yaml"), "{}")?;
691        fs::write(repository.path().join("openapi.json"), "{}")?;
692        let workspace = RepositoryConfig {
693            path: ".".to_owned(),
694            openapi: None,
695            http_consumers: None,
696            integration_tests: None,
697            implementations: None,
698            excludes: None,
699            include_defaults: None,
700        };
701
702        let resolved = resolve_repository_config_with_use_gitignore(
703            repository.path(),
704            &workspace,
705            Some(true),
706        )?;
707
708        assert_eq!(resolved.openapi, vec!["openapi.json"]);
709        Ok(())
710    }
711
712    #[test]
713    fn canonical_equivalent_patterns_should_produce_the_same_repository_fingerprint()
714    -> Result<(), Box<dyn std::error::Error>> {
715        let repository = tempfile::tempdir()?;
716        let canonical = RepositoryConfig {
717            path: ".".to_owned(),
718            openapi: None,
719            http_consumers: None,
720            integration_tests: None,
721            implementations: None,
722            excludes: Some(vec!["coverage/**".to_owned()]),
723            include_defaults: Some(vec!["vendor/internal-sdk/**".to_owned()]),
724        };
725        let redundant = RepositoryConfig {
726            excludes: Some(vec!["./coverage//./**".to_owned()]),
727            include_defaults: Some(vec!["./vendor//internal-sdk/./**".to_owned()]),
728            ..canonical.clone()
729        };
730
731        let canonical = resolve_repository_config(repository.path(), &canonical)?;
732        let redundant = resolve_repository_config(repository.path(), &redundant)?;
733
734        assert_eq!(canonical.fingerprint, redundant.fingerprint);
735        Ok(())
736    }
737
738    #[test]
739    fn openapi_auto_detection_should_respect_reopened_default_subtree()
740    -> Result<(), Box<dyn std::error::Error>> {
741        let repository = tempfile::tempdir()?;
742        fs::create_dir_all(repository.path().join("vendor/internal-sdk"))?;
743        fs::create_dir_all(repository.path().join("vendor/external"))?;
744        fs::write(
745            repository.path().join("vendor/internal-sdk/openapi.yaml"),
746            "{}",
747        )?;
748        fs::write(repository.path().join("vendor/external/openapi.yaml"), "{}")?;
749        let workspace = RepositoryConfig {
750            path: ".".to_owned(),
751            openapi: None,
752            http_consumers: None,
753            integration_tests: None,
754            implementations: None,
755            excludes: None,
756            include_defaults: Some(vec!["vendor/internal-sdk/**".to_owned()]),
757        };
758
759        let resolved = resolve_repository_config(repository.path(), &workspace)?;
760
761        assert_eq!(
762            resolved.openapi,
763            vec!["vendor/internal-sdk/openapi.yaml".to_owned()]
764        );
765        Ok(())
766    }
767
768    #[test]
769    fn auto_detection_should_keep_distinct_nested_openapi_documents()
770    -> Result<(), Box<dyn std::error::Error>> {
771        let repository = tempfile::tempdir()?;
772        fs::create_dir_all(repository.path().join("backend/docs"))?;
773        fs::create_dir_all(repository.path().join("frontend/mockoon"))?;
774        fs::write(repository.path().join("backend/docs/openapi.json"), "{}")?;
775        fs::write(
776            repository
777                .path()
778                .join("frontend/mockoon/mock_openapi3.json"),
779            "{}",
780        )?;
781        let workspace = RepositoryConfig {
782            path: ".".to_owned(),
783            openapi: None,
784            http_consumers: None,
785            integration_tests: None,
786            implementations: None,
787            excludes: None,
788            include_defaults: None,
789        };
790
791        let resolved = resolve_repository_config(repository.path(), &workspace)?;
792
793        assert_eq!(
794            resolved.openapi,
795            vec![
796                "backend/docs/openapi.json".to_owned(),
797                "frontend/mockoon/mock_openapi3.json".to_owned(),
798            ]
799        );
800        assert_eq!(resolved.openapi_source, ConfigSource::AutoDetected);
801        Ok(())
802    }
803
804    #[test]
805    fn auto_detection_should_reject_multiple_openapi_candidates()
806    -> Result<(), Box<dyn std::error::Error>> {
807        let repository = tempfile::tempdir()?;
808        fs::write(repository.path().join("openapi.yaml"), "openapi: 3.1.0")?;
809        fs::write(repository.path().join("openapi.json"), "{}")?;
810        let workspace = RepositoryConfig {
811            path: ".".to_owned(),
812            openapi: None,
813            http_consumers: None,
814            integration_tests: None,
815            implementations: None,
816            excludes: None,
817            include_defaults: None,
818        };
819
820        let result = resolve_repository_config(repository.path(), &workspace);
821
822        assert!(matches!(result, Err(ConfigError::AmbiguousOpenApi { .. })));
823        Ok(())
824    }
825
826    #[test]
827    fn repository_local_config_should_reject_unknown_keys() -> Result<(), Box<dyn std::error::Error>>
828    {
829        let repository = tempfile::tempdir()?;
830        fs::write(
831            repository.path().join(".code-system-graph.yaml"),
832            "version: 1\nunknown: true\n",
833        )?;
834        let workspace = RepositoryConfig {
835            path: ".".to_owned(),
836            openapi: None,
837            http_consumers: None,
838            integration_tests: None,
839            implementations: None,
840            excludes: None,
841            include_defaults: None,
842        };
843
844        let result = resolve_repository_config(repository.path(), &workspace);
845
846        assert!(matches!(result, Err(ConfigError::Invalid { .. })));
847        Ok(())
848    }
849
850    #[test]
851    fn repository_local_config_should_reject_symlink() -> Result<(), Box<dyn std::error::Error>> {
852        let temporary = tempfile::tempdir()?;
853        let repository = temporary.path().join("repository");
854        let outside = temporary.path().join("outside.yaml");
855        std::fs::create_dir_all(&repository)?;
856        std::fs::write(&outside, "version: 1\n")?;
857        #[cfg(unix)]
858        std::os::unix::fs::symlink(&outside, repository.join(".code-system-graph.yaml"))?;
859        #[cfg(windows)]
860        std::os::windows::fs::symlink_file(&outside, repository.join(".code-system-graph.yaml"))?;
861        let workspace = RepositoryConfig {
862            path: ".".to_owned(),
863            openapi: None,
864            http_consumers: None,
865            integration_tests: None,
866            implementations: None,
867            excludes: None,
868            include_defaults: None,
869        };
870
871        let result = resolve_repository_config(&repository, &workspace);
872
873        assert!(matches!(
874            result,
875            Err(ConfigError::Symlink { .. }
876                | ConfigError::OutsideCheckout { .. }
877                | ConfigError::NotRegularFile { .. })
878        ));
879        Ok(())
880    }
881
882    #[test]
883    fn repository_local_config_should_reject_oversized_file()
884    -> Result<(), Box<dyn std::error::Error>> {
885        let repository = tempfile::tempdir()?;
886        std::fs::write(
887            repository.path().join(".code-system-graph.yaml"),
888            "x".repeat(crate::capability_dir::MAX_REPOSITORY_CONFIG_BYTES + 1),
889        )?;
890        let workspace = RepositoryConfig {
891            path: ".".to_owned(),
892            openapi: None,
893            http_consumers: None,
894            integration_tests: None,
895            implementations: None,
896            excludes: None,
897            include_defaults: None,
898        };
899
900        let result = resolve_repository_config(repository.path(), &workspace);
901
902        assert!(matches!(result, Err(ConfigError::TooLarge { .. })));
903        Ok(())
904    }
905
906    #[test]
907    fn repository_local_config_should_reject_directory_entry()
908    -> Result<(), Box<dyn std::error::Error>> {
909        let repository = tempfile::tempdir()?;
910        std::fs::create_dir_all(repository.path().join(".code-system-graph.yaml"))?;
911        let workspace = RepositoryConfig {
912            path: ".".to_owned(),
913            openapi: None,
914            http_consumers: None,
915            integration_tests: None,
916            implementations: None,
917            excludes: None,
918            include_defaults: None,
919        };
920
921        let result = resolve_repository_config(repository.path(), &workspace);
922
923        assert!(matches!(result, Err(ConfigError::NotRegularFile { .. })));
924        Ok(())
925    }
926
927    #[test]
928    fn cli_openapi_should_override_workspace_value() -> Result<(), Box<dyn std::error::Error>> {
929        let repository = tempfile::tempdir()?;
930        let workspace = RepositoryConfig {
931            path: ".".to_owned(),
932            openapi: Some("workspace.yaml".to_owned()),
933            http_consumers: None,
934            integration_tests: None,
935            implementations: None,
936            excludes: None,
937            include_defaults: None,
938        };
939        let mut resolved = resolve_repository_config(repository.path(), &workspace)?;
940
941        super::apply_openapi_override(&mut resolved, "cli.yaml")?;
942
943        assert_eq!(
944            (resolved.openapi, resolved.openapi_source),
945            (vec!["cli.yaml".to_owned()], ConfigSource::CliOverride)
946        );
947        Ok(())
948    }
949}