fernctl/ports/inbound.rs
1//! # Inbound Ports — Driving the Application
2//!
3//! Inbound ports define how external systems can **drive** the fernctl
4//! application. They are the entry points through which configuration
5//! is loaded, validated, and queried.
6//!
7//! ## Overview
8//!
9//! ```text
10//! ┌─────────────────────────────────────────────────────────────┐
11//! │ DRIVING ADAPTERS │
12//! │ │
13//! │ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
14//! │ │ TomlAdapter │ │ CliAdapter │ │ JsonAdapter │ │
15//! │ │ │ │ │ │ │ │
16//! │ │ Reads .toml │ │ Parses args │ │ Reads .json │ │
17//! │ └──────┬───────┘ └──────┬───────┘ └──────┬───────┘ │
18//! │ │ │ │ │
19//! └──────────┼─────────────────┼─────────────────┼──────────────┘
20//! │ │ │
21//! ╔═════╧═════════════════╧═════════════════╧═════════════╗
22//! ║ INBOUND PORTS ║
23//! ║ ║
24//! ║ ConfigPort ──────► Load raw configuration ║
25//! ║ ValidatePort ────► Validate and transform ║
26//! ║ QueryPort ───────► Query theme values ║
27//! ║ ║
28//! ╚═══════════════════════════╤═══════════════════════════╝
29//! │
30//! ▼
31//! ┌──────────────┐
32//! │ DOMAIN │
33//! │ Theme │
34//! │ Tokens │
35//! └──────────────┘
36//! ```
37//!
38//! ## Port Responsibilities
39//!
40//! | Port | Responsibility | Input | Output |
41//! |------|----------------|-------|--------|
42//! | [`ConfigPort`] | Load raw configuration | Source (file content, path) | Raw config data |
43//! | [`ValidatePort`] | Validate and transform | Raw config | Validated theme |
44//! | [`QueryPort`] | Query theme values | Theme + query | Token values |
45//!
46//! ## Usage Pattern
47//!
48//! Inbound ports are typically used in this sequence:
49//!
50//! ```rust,ignore
51//! use fernctl::ports::inbound::*;
52//! use fernctl::adapters::TomlConfigAdapter;
53//!
54//! // 1. Load raw configuration
55//! let config_adapter = TomlConfigAdapter::new();
56//! let raw_config = config_adapter.load_from_file("config.toml")?;
57//!
58//! // 2. Validate and transform
59//! let theme = raw_config.validate()?.into_theme();
60//!
61//! // 3. Query values (optional)
62//! let bg_color = query_adapter.get_color(&theme, "background")?;
63//! ```
64//!
65//! ## Implementing Custom Adapters
66//!
67//! To add support for a new configuration format (e.g., YAML):
68//!
69//! ```rust,ignore
70//! use fernctl::ports::inbound::ConfigPort;
71//! use fernctl::domain::config::RawConfig;
72//! use fernctl::error::Result;
73//!
74//! struct YamlConfigAdapter;
75//!
76//! impl ConfigPort for YamlConfigAdapter {
77//! fn load(&self, source: &str) -> Result<RawConfig> {
78//! // Parse YAML and convert to RawConfig
79//! let yaml: serde_yaml::Value = serde_yaml::from_str(source)?;
80//! RawConfig::from_yaml(yaml)
81//! }
82//!
83//! fn format_name(&self) -> &'static str {
84//! "YAML"
85//! }
86//! }
87//! ```
88
89use crate::domain::theme::Theme;
90use crate::error::{ConfigError, FernError, Notification, Result, Severity};
91use std::path::Path;
92
93// ============================================================================
94// Raw Configuration Types
95// ============================================================================
96
97/// Raw configuration data before validation.
98///
99/// `RawConfig` represents configuration data that has been parsed from a file
100/// format (TOML, JSON) but has not yet been validated against the theme schema.
101///
102/// This type is intentionally opaque — its internal structure may change. Use
103/// the [`ValidatePort`] trait to convert it into a validated [`Theme`].
104///
105/// # Type-State Pattern
106///
107/// `RawConfig` is part of a type-state pattern that prevents using invalid
108/// configurations:
109///
110/// ```text
111/// RawConfig ──validate()──► ValidatedConfig ──into_theme()──► Theme
112/// │ │
113/// │ Cannot be used │ Cannot be modified
114/// │ directly in UI │ but can be used
115/// ▼ ▼
116/// Must validate Safe to use
117/// ```
118///
119/// # Example
120///
121/// ```rust,ignore
122/// use fernctl::ports::inbound::{ConfigPort, RawConfig};
123///
124/// // Load produces RawConfig
125/// let raw: RawConfig = adapter.load(toml_content)?;
126///
127/// // Must validate before use
128/// let validated = raw.validate()?;
129/// let theme = validated.into_theme();
130/// ```
131#[derive(Debug, Clone)]
132pub struct RawConfig {
133 /// The parsed configuration as a generic value.
134 ///
135 /// This is kept as a serde_json::Value internally for maximum flexibility
136 /// across different input formats (TOML, JSON, YAML can all convert to this).
137 inner: serde_json::Value,
138 /// The source format this config was parsed from.
139 source_format: SourceFormat,
140}
141
142/// The format a configuration was parsed from.
143///
144/// Used for providing helpful error messages that reference the original format.
145#[derive(Debug, Clone, Copy, PartialEq, Eq)]
146pub enum SourceFormat {
147 /// TOML format (.toml files)
148 Toml,
149 /// JSON format (.json files)
150 Json,
151 /// Unknown or in-memory format
152 Unknown,
153}
154
155impl RawConfig {
156 /// Creates a new raw configuration from a JSON value.
157 ///
158 /// This is the internal constructor used by adapters. The JSON value
159 /// should represent the full configuration structure.
160 ///
161 /// # Arguments
162 ///
163 /// * `value` — The parsed configuration as a JSON value
164 /// * `source_format` — The original format this was parsed from
165 ///
166 /// # Example
167 ///
168 /// ```rust,ignore
169 /// let value = serde_json::from_str(json_content)?;
170 /// let raw = RawConfig::new(value, SourceFormat::Json);
171 /// ```
172 #[must_use]
173 pub fn new(value: serde_json::Value, source_format: SourceFormat) -> Self {
174 Self {
175 inner: value,
176 source_format,
177 }
178 }
179
180 /// Returns the source format this configuration was parsed from.
181 #[must_use]
182 pub fn source_format(&self) -> SourceFormat {
183 self.source_format
184 }
185
186 /// Validates this raw configuration and returns a validated configuration.
187 ///
188 /// Validation checks:
189 /// - All required fields are present
190 /// - Color values are valid hex format
191 /// - Numeric values are within valid ranges
192 /// - Unknown keys trigger warnings (not errors)
193 ///
194 /// # Errors
195 ///
196 /// Returns [`ConfigError`] if validation fails, with detailed information
197 /// about what went wrong and how to fix it.
198 ///
199 /// # Example
200 ///
201 /// ```rust,ignore
202 /// let raw = adapter.load(content)?;
203 /// let validated = raw.validate()?;
204 /// let theme = validated.into_theme();
205 /// ```
206 pub fn validate(self) -> Result<ValidatedConfig> {
207 // Deserialize into UserConfig (matches TOML structure)
208 let user_config: crate::domain::user_config::UserConfig =
209 serde_json::from_value(self.inner.clone()).map_err(|e| {
210 FernError::Config(ConfigError::MissingField {
211 key: "config".to_string(),
212 expected_type: format!("valid configuration structure: {e}"),
213 })
214 })?;
215
216 // Transform UserConfig to Theme, applying overrides
217 let theme = user_config.into_theme()?;
218
219 Ok(ValidatedConfig {
220 theme,
221 warnings: Vec::new(), // Future: collect warnings about unknown keys
222 })
223 }
224
225 /// Returns the inner JSON value for inspection.
226 ///
227 /// This is primarily useful for debugging and error reporting.
228 #[must_use]
229 pub fn as_value(&self) -> &serde_json::Value {
230 &self.inner
231 }
232}
233
234/// Configuration that has passed validation.
235///
236/// `ValidatedConfig` represents a configuration that has been checked for
237/// correctness. It contains a valid [`Theme`] and optionally warnings about
238/// non-critical issues (like unknown keys).
239///
240/// # Consuming the Configuration
241///
242/// Once validated, the configuration can be converted into a usable `Theme`:
243///
244/// ```rust,ignore
245/// let validated = raw.validate()?;
246///
247/// // Check for warnings
248/// for warning in validated.warnings() {
249/// log::warn!("{}", warning);
250/// }
251///
252/// // Extract the theme
253/// let theme = validated.into_theme();
254/// ```
255#[derive(Debug, Clone)]
256pub struct ValidatedConfig {
257 /// The validated theme.
258 theme: Theme,
259 /// Non-fatal warnings encountered during validation.
260 warnings: Vec<ConfigWarning>,
261}
262
263impl ValidatedConfig {
264 /// Returns any warnings encountered during validation.
265 ///
266 /// Warnings are non-fatal issues that don't prevent the theme from loading
267 /// but may indicate configuration problems:
268 ///
269 /// - Unknown keys (possible typos)
270 /// - Deprecated options
271 /// - Values outside recommended ranges
272 ///
273 /// # Example
274 ///
275 /// ```rust,ignore
276 /// for warning in validated.warnings() {
277 /// eprintln!("Warning: {}", warning);
278 /// }
279 /// ```
280 #[must_use]
281 pub fn warnings(&self) -> &[ConfigWarning] {
282 &self.warnings
283 }
284
285 /// Returns `true` if validation produced any warnings.
286 #[must_use]
287 pub fn has_warnings(&self) -> bool {
288 !self.warnings.is_empty()
289 }
290
291 /// Consumes this validated configuration and returns the theme.
292 ///
293 /// After calling this method, the `ValidatedConfig` is consumed and the
294 /// theme is ready for use in the application.
295 ///
296 /// # Example
297 ///
298 /// ```rust,ignore
299 /// let theme = validated.into_theme();
300 /// let bg_color = &theme.colors.background;
301 /// ```
302 #[must_use]
303 pub fn into_theme(self) -> Theme {
304 self.theme
305 }
306
307 /// Returns a reference to the theme without consuming the configuration.
308 ///
309 /// Use this when you need to inspect the theme but still want access to
310 /// warnings or other metadata.
311 #[must_use]
312 pub fn theme(&self) -> &Theme {
313 &self.theme
314 }
315}
316
317/// A non-fatal warning from configuration validation.
318///
319/// Warnings indicate issues that don't prevent the configuration from loading
320/// but may indicate problems that should be addressed.
321#[derive(Debug, Clone)]
322pub struct ConfigWarning {
323 /// The warning message.
324 pub message: String,
325 /// The severity level.
326 pub severity: Severity,
327 /// Optional suggestion for fixing the issue.
328 pub suggestion: Option<String>,
329 /// The configuration key that triggered the warning, if applicable.
330 pub key: Option<String>,
331}
332
333impl ConfigWarning {
334 /// Creates a new configuration warning.
335 #[must_use]
336 pub fn new(message: impl Into<String>) -> Self {
337 Self {
338 message: message.into(),
339 severity: Severity::Warning,
340 suggestion: None,
341 key: None,
342 }
343 }
344
345 /// Adds a suggestion to this warning.
346 #[must_use]
347 pub fn with_suggestion(mut self, suggestion: impl Into<String>) -> Self {
348 self.suggestion = Some(suggestion.into());
349 self
350 }
351
352 /// Associates this warning with a configuration key.
353 #[must_use]
354 pub fn with_key(mut self, key: impl Into<String>) -> Self {
355 self.key = Some(key.into());
356 self
357 }
358
359 /// Converts this warning to a notification.
360 #[must_use]
361 pub fn to_notification(&self) -> Notification {
362 let mut notification = Notification::warning("Config Warning", &self.message);
363 if let Some(ref suggestion) = self.suggestion {
364 notification = notification.with_suggestion(suggestion);
365 }
366 notification
367 }
368}
369
370impl std::fmt::Display for ConfigWarning {
371 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
372 if let Some(ref key) = self.key {
373 write!(f, "[{}] ", key)?;
374 }
375 write!(f, "{}", self.message)?;
376 if let Some(ref suggestion) = self.suggestion {
377 write!(f, " ({})", suggestion)?;
378 }
379 Ok(())
380 }
381}
382
383// ============================================================================
384// ConfigPort Trait
385// ============================================================================
386
387/// Port for loading configuration from external sources.
388///
389/// `ConfigPort` is the primary inbound port for configuration loading. It
390/// abstracts over different configuration formats (TOML, JSON, etc.) and
391/// sources (files, environment, in-memory).
392///
393/// # Implementing ConfigPort
394///
395/// Adapters implement this trait to add support for new configuration formats:
396///
397/// ```rust,ignore
398/// use fernctl::ports::inbound::{ConfigPort, RawConfig, SourceFormat};
399/// use fernctl::error::Result;
400///
401/// struct TomlConfigAdapter;
402///
403/// impl ConfigPort for TomlConfigAdapter {
404/// fn load(&self, source: &str) -> Result<RawConfig> {
405/// let value: toml::Value = toml::from_str(source)?;
406/// let json = serde_json::to_value(value)?;
407/// Ok(RawConfig::new(json, SourceFormat::Toml))
408/// }
409///
410/// fn format_name(&self) -> &'static str {
411/// "TOML"
412/// }
413/// }
414/// ```
415///
416/// # Object Safety
417///
418/// This trait is object-safe and can be used as a trait object:
419///
420/// ```rust,ignore
421/// let adapter: Box<dyn ConfigPort> = Box::new(TomlConfigAdapter::new());
422/// let config = adapter.load(content)?;
423/// ```
424///
425/// # Error Handling
426///
427/// All loading operations return `Result<RawConfig>`. Errors should be
428/// wrapped in [`ConfigError`] variants for rich diagnostics.
429pub trait ConfigPort: Send + Sync {
430 /// Loads configuration from a string source.
431 ///
432 /// The source string should contain the full configuration in the format
433 /// supported by this adapter (e.g., TOML content for a TOML adapter).
434 ///
435 /// # Arguments
436 ///
437 /// * `source` — The configuration content as a string
438 ///
439 /// # Returns
440 ///
441 /// A [`RawConfig`] that can be validated into a [`Theme`].
442 ///
443 /// # Errors
444 ///
445 /// Returns [`ConfigError`] if the source cannot be parsed.
446 ///
447 /// # Example
448 ///
449 /// ```rust,ignore
450 /// let toml_content = r#"
451 /// [appearance]
452 /// variant = "dark"
453 /// "#;
454 ///
455 /// let raw = adapter.load(toml_content)?;
456 /// ```
457 fn load(&self, source: &str) -> Result<RawConfig>;
458
459 /// Loads configuration from a file path.
460 ///
461 /// This is a convenience method that reads the file and calls [`load`].
462 /// The default implementation handles file I/O and provides appropriate
463 /// error messages.
464 ///
465 /// # Arguments
466 ///
467 /// * `path` — Path to the configuration file
468 ///
469 /// # Returns
470 ///
471 /// A [`RawConfig`] that can be validated into a [`Theme`].
472 ///
473 /// # Errors
474 ///
475 /// - [`FernError::Io`] if the file cannot be read
476 /// - [`ConfigError`] if the content cannot be parsed
477 ///
478 /// # Example
479 ///
480 /// ```rust,ignore
481 /// let raw = adapter.load_from_file("~/.config/fern/config.toml")?;
482 /// ```
483 fn load_from_file(&self, path: impl AsRef<Path>) -> Result<RawConfig> {
484 let path = path.as_ref();
485 let content = std::fs::read_to_string(path).map_err(|e| {
486 FernError::io(format!("reading configuration file: {}", path.display()), e)
487 })?;
488 self.load(&content)
489 }
490
491 /// Returns the human-readable name of this configuration format.
492 ///
493 /// Used in error messages and logging.
494 ///
495 /// # Example
496 ///
497 /// ```rust,ignore
498 /// println!("Loading {} configuration...", adapter.format_name());
499 /// // Prints: "Loading TOML configuration..."
500 /// ```
501 fn format_name(&self) -> &'static str;
502
503 /// Returns the typical file extension for this format.
504 ///
505 /// Used for auto-detecting the appropriate adapter based on file path.
506 ///
507 /// # Example
508 ///
509 /// ```rust,ignore
510 /// assert_eq!(toml_adapter.file_extension(), "toml");
511 /// ```
512 fn file_extension(&self) -> &'static str {
513 match self.format_name().to_lowercase().as_str() {
514 "toml" => "toml",
515 "json" => "json",
516 "yaml" => "yaml",
517 _ => "",
518 }
519 }
520}
521
522// ============================================================================
523// ValidatePort Trait
524// ============================================================================
525
526/// Port for validating configuration data.
527///
528/// `ValidatePort` handles the validation of raw configuration data, checking
529/// that all values are correct and producing helpful error messages when
530/// they are not.
531///
532/// # Validation Rules
533///
534/// The validator checks:
535///
536/// | Category | Validation |
537/// |----------|------------|
538/// | Colors | Valid hex format, correct length |
539/// | Numbers | Within valid ranges |
540/// | Strings | Non-empty where required |
541/// | Structure | Required fields present |
542/// | Keys | Warning for unknown keys |
543///
544/// # Example
545///
546/// ```rust,ignore
547/// use fernctl::ports::inbound::ValidatePort;
548///
549/// let validator = DefaultValidator::new();
550/// let result = validator.validate(&raw_config);
551///
552/// match result {
553/// Ok(validated) => {
554/// for warning in validated.warnings() {
555/// log::warn!("{}", warning);
556/// }
557/// let theme = validated.into_theme();
558/// }
559/// Err(errors) => {
560/// for error in errors {
561/// eprintln!("Error: {}", error);
562/// }
563/// }
564/// }
565/// ```
566pub trait ValidatePort: Send + Sync {
567 /// Validates raw configuration and returns a validated configuration.
568 ///
569 /// # Arguments
570 ///
571 /// * `raw` — The raw configuration to validate
572 ///
573 /// # Returns
574 ///
575 /// A [`ValidatedConfig`] containing the theme and any warnings.
576 ///
577 /// # Errors
578 ///
579 /// Returns a vector of [`ConfigError`] if validation fails. Multiple
580 /// errors may be returned to show all problems at once.
581 fn validate(&self, raw: RawConfig) -> std::result::Result<ValidatedConfig, Vec<ConfigError>>;
582
583 /// Validates a single color value.
584 ///
585 /// # Arguments
586 ///
587 /// * `value` — The color value to validate (e.g., "#1e1e2e")
588 /// * `key` — The configuration key for error reporting
589 ///
590 /// # Errors
591 ///
592 /// Returns [`ConfigError::InvalidColor`] if the value is not valid.
593 fn validate_color(&self, value: &str, key: &str) -> Result<()>;
594
595 /// Validates a spacing value.
596 ///
597 /// # Arguments
598 ///
599 /// * `value` — The spacing value in pixels
600 /// * `key` — The configuration key for error reporting
601 ///
602 /// # Errors
603 ///
604 /// Returns [`ConfigError::InvalidValue`] if the value is out of range.
605 fn validate_spacing(&self, value: u16, key: &str) -> Result<()>;
606}
607
608// ============================================================================
609// QueryPort Trait
610// ============================================================================
611
612/// Port for querying theme values.
613///
614/// `QueryPort` provides a way to query specific values from a theme using
615/// string-based paths. This is useful for:
616///
617/// - CLI tools that need to extract specific values
618/// - Templates that reference theme tokens by name
619/// - Testing that specific tokens have expected values
620///
621/// # Query Paths
622///
623/// Queries use dot-separated paths to navigate the theme structure:
624///
625/// | Path | Returns |
626/// |------|---------|
627/// | `colors.background` | Background color as hex |
628/// | `typography.family` | Primary font family name |
629/// | `radius.button` | Button radius in pixels |
630/// | `bar.height` | Bar height in pixels |
631///
632/// # Example
633///
634/// ```rust,ignore
635/// use fernctl::ports::inbound::QueryPort;
636///
637/// let query = DefaultQueryAdapter::new();
638/// let theme = Theme::dark();
639///
640/// // Query color
641/// let bg = query.get(&theme, "colors.background")?;
642/// assert_eq!(bg, "#1e1e2e");
643///
644/// // Query number
645/// let height = query.get(&theme, "bar.height")?;
646/// assert_eq!(height, "40");
647/// ```
648pub trait QueryPort: Send + Sync {
649 /// Queries a value from the theme by path.
650 ///
651 /// # Arguments
652 ///
653 /// * `theme` — The theme to query
654 /// * `path` — Dot-separated path to the value
655 ///
656 /// # Returns
657 ///
658 /// The value as a string representation.
659 ///
660 /// # Errors
661 ///
662 /// Returns an error if the path does not exist in the theme.
663 ///
664 /// # Example
665 ///
666 /// ```rust,ignore
667 /// let color = query.get(&theme, "colors.accent")?;
668 /// ```
669 fn get(&self, theme: &Theme, path: &str) -> Result<String>;
670
671 /// Queries a color value from the theme.
672 ///
673 /// This is a typed version of [`get`] that returns the color in hex format.
674 ///
675 /// # Arguments
676 ///
677 /// * `theme` — The theme to query
678 /// * `name` — The color name (e.g., "background", "accent")
679 ///
680 /// # Returns
681 ///
682 /// The color as a hex string (e.g., "#1e1e2e").
683 ///
684 /// # Errors
685 ///
686 /// Returns an error if the color name is not recognized.
687 fn get_color(&self, theme: &Theme, name: &str) -> Result<String>;
688
689 /// Returns all available query paths.
690 ///
691 /// Useful for auto-completion and documentation.
692 ///
693 /// # Example
694 ///
695 /// ```rust,ignore
696 /// for path in query.available_paths() {
697 /// println!(" {}", path);
698 /// }
699 /// ```
700 fn available_paths(&self) -> Vec<&'static str>;
701}
702
703// ============================================================================
704// Tests
705// ============================================================================
706
707#[cfg(test)]
708mod tests {
709 use super::*;
710
711 #[test]
712 fn raw_config_creation() {
713 let value = serde_json::json!({
714 "variant": "dark"
715 });
716 let raw = RawConfig::new(value, SourceFormat::Toml);
717 assert_eq!(raw.source_format(), SourceFormat::Toml);
718 }
719
720 #[test]
721 fn config_warning_display() {
722 let warning = ConfigWarning::new("unknown key 'colour'")
723 .with_key("appearance.colour")
724 .with_suggestion("did you mean 'color'?");
725
726 let display = warning.to_string();
727 assert!(display.contains("appearance.colour"));
728 assert!(display.contains("unknown key"));
729 assert!(display.contains("did you mean 'color'?"));
730 }
731
732 #[test]
733 fn config_warning_to_notification() {
734 let warning = ConfigWarning::new("test warning").with_suggestion("fix it");
735 let notification = warning.to_notification();
736 assert_eq!(notification.severity, Severity::Warning);
737 assert!(notification.suggestion.is_some());
738 }
739}