fernctl/adapters/mod.rs
1//! # Adapters — External System Integration
2//!
3//! Adapters implement the port traits to connect the domain to external systems.
4//!
5//! ## Overview
6//!
7//! ```text
8//! PORTS ADAPTERS
9//! ┌──────────────┐ ┌─────────────────────┐
10//! │ ConfigPort │◄─────────────│ TomlConfigAdapter │
11//! └──────────────┘ │ JsonConfigAdapter │
12//! └─────────────────────┘
13//! ┌──────────────┐ ┌─────────────────────┐
14//! │ PersistPort │◄─────────────│ FileSystemAdapter │
15//! └──────────────┘ └─────────────────────┘
16//! ┌──────────────┐ ┌─────────────────────┐
17//! │ NotifyPort │◄─────────────│ DbusNotifyAdapter │
18//! └──────────────┘ └─────────────────────┘
19//! ┌──────────────┐ ┌─────────────────────┐
20//! │ IpcPort │◄─────────────│ DbusIpcAdapter │
21//! └──────────────┘ └─────────────────────┘
22//! ```
23//!
24//! ## Available Adapters
25//!
26//! | Adapter | Port | Description |
27//! |---------|------|-------------|
28//! | `TomlConfigAdapter` | `ConfigPort` | Load config from TOML files |
29//! | `JsonConfigAdapter` | `ConfigPort` | Load config from JSON files |
30//! | `FileSystemAdapter` | `PersistPort` | Save themes to filesystem |
31//! | `DbusNotifyAdapter` | `NotifyPort` | Send notifications via D-Bus |
32//! | `DbusIpcAdapter` | `IpcPort` | Communicate with QuickShell via D-Bus |
33//!
34//! ## Feature Flags
35//!
36//! Some adapters are behind feature flags:
37//!
38//! - `dbus` — Enables `DbusNotifyAdapter` and `DbusIpcAdapter`
39//! - `watch` — Enables file watching capabilities
40//!
41//! ## Example
42//!
43//! ```rust,ignore
44//! use fernctl::adapters::{TomlConfigAdapter, FileSystemAdapter};
45//! use fernctl::ports::inbound::ConfigPort;
46//! use fernctl::ports::outbound::PersistPort;
47//!
48//! // Load configuration
49//! let config_adapter = TomlConfigAdapter::new();
50//! let raw = config_adapter.load_from_file("config.toml")?;
51//! let theme = raw.validate()?.into_theme();
52//!
53//! // Save as JSON for QuickShell
54//! let persist_adapter = FileSystemAdapter::new();
55//! persist_adapter.save_theme(&theme, "config.json")?;
56//! ```
57
58// Adapters will be implemented in a future PR.
59// This module provides the structure for external system integration.
60
61use crate::domain::theme::Theme;
62use crate::error::{FernError, Result};
63use crate::ports::inbound::{ConfigPort, RawConfig, SourceFormat};
64use crate::ports::outbound::PersistPort;
65use std::path::Path;
66
67// ============================================================================
68// TomlConfigAdapter
69// ============================================================================
70
71/// Adapter for loading configuration from TOML files.
72///
73/// This is the primary configuration format for Fern Shell. Users write
74/// their configuration in TOML, and this adapter parses it into the domain
75/// types.
76///
77/// # Example
78///
79/// ```rust,ignore
80/// use fernctl::adapters::TomlConfigAdapter;
81/// use fernctl::ports::inbound::ConfigPort;
82///
83/// let adapter = TomlConfigAdapter::new();
84/// let raw = adapter.load_from_file("~/.config/fern/config.toml")?;
85/// let theme = raw.validate()?.into_theme();
86/// ```
87#[derive(Debug, Clone, Default)]
88pub struct TomlConfigAdapter;
89
90impl TomlConfigAdapter {
91 /// Creates a new TOML configuration adapter.
92 #[must_use]
93 pub fn new() -> Self {
94 Self
95 }
96}
97
98impl ConfigPort for TomlConfigAdapter {
99 fn load(&self, source: &str) -> Result<RawConfig> {
100 // Parse TOML to a generic Value
101 let toml_value: toml::Value = toml::from_str(source).map_err(|e| {
102 FernError::Config(crate::error::ConfigError::ParseError {
103 source: e,
104 src: source.to_string(),
105 })
106 })?;
107
108 // Convert TOML Value to JSON Value for unified internal representation
109 let json_value = toml_to_json(toml_value);
110
111 Ok(RawConfig::new(json_value, SourceFormat::Toml))
112 }
113
114 fn format_name(&self) -> &'static str {
115 "TOML"
116 }
117}
118
119/// Converts a TOML value to a JSON value.
120///
121/// This allows the domain to work with a single internal representation
122/// regardless of the input format.
123fn toml_to_json(toml: toml::Value) -> serde_json::Value {
124 match toml {
125 toml::Value::String(s) => serde_json::Value::String(s),
126 toml::Value::Integer(i) => serde_json::Value::Number(i.into()),
127 toml::Value::Float(f) => {
128 serde_json::Number::from_f64(f)
129 .map(serde_json::Value::Number)
130 .unwrap_or(serde_json::Value::Null)
131 }
132 toml::Value::Boolean(b) => serde_json::Value::Bool(b),
133 toml::Value::Array(arr) => {
134 serde_json::Value::Array(arr.into_iter().map(toml_to_json).collect())
135 }
136 toml::Value::Table(table) => {
137 let map = table
138 .into_iter()
139 .map(|(k, v)| (k, toml_to_json(v)))
140 .collect();
141 serde_json::Value::Object(map)
142 }
143 toml::Value::Datetime(dt) => serde_json::Value::String(dt.to_string()),
144 }
145}
146
147// ============================================================================
148// JsonConfigAdapter
149// ============================================================================
150
151/// Adapter for loading configuration from JSON files.
152///
153/// JSON configuration is primarily used internally (generated from TOML)
154/// but can also be written directly by users who prefer JSON.
155///
156/// # Example
157///
158/// ```rust,ignore
159/// use fernctl::adapters::JsonConfigAdapter;
160/// use fernctl::ports::inbound::ConfigPort;
161///
162/// let adapter = JsonConfigAdapter::new();
163/// let raw = adapter.load_from_file("config.json")?;
164/// ```
165#[derive(Debug, Clone, Default)]
166pub struct JsonConfigAdapter;
167
168impl JsonConfigAdapter {
169 /// Creates a new JSON configuration adapter.
170 #[must_use]
171 pub fn new() -> Self {
172 Self
173 }
174}
175
176impl ConfigPort for JsonConfigAdapter {
177 fn load(&self, source: &str) -> Result<RawConfig> {
178 let json_value: serde_json::Value = serde_json::from_str(source).map_err(|e| {
179 FernError::Config(crate::error::ConfigError::MissingField {
180 key: "root".to_string(),
181 expected_type: format!("valid JSON: {e}"),
182 })
183 })?;
184
185 Ok(RawConfig::new(json_value, SourceFormat::Json))
186 }
187
188 fn format_name(&self) -> &'static str {
189 "JSON"
190 }
191}
192
193// ============================================================================
194// FileSystemAdapter
195// ============================================================================
196
197/// Adapter for persisting themes to the filesystem.
198///
199/// This adapter handles saving and loading theme files, following platform
200/// conventions for configuration directories.
201///
202/// # Example
203///
204/// ```rust,ignore
205/// use fernctl::adapters::FileSystemAdapter;
206/// use fernctl::ports::outbound::PersistPort;
207///
208/// let adapter = FileSystemAdapter::new();
209/// adapter.save_theme(&theme, "config.json")?;
210/// ```
211#[derive(Debug, Clone, Default)]
212pub struct FileSystemAdapter;
213
214impl FileSystemAdapter {
215 /// Creates a new filesystem adapter.
216 #[must_use]
217 pub fn new() -> Self {
218 Self
219 }
220}
221
222impl PersistPort for FileSystemAdapter {
223 fn save_theme(&self, theme: &Theme, path: impl AsRef<Path>) -> Result<()> {
224 let path = path.as_ref();
225 let json = serde_json::to_string_pretty(theme).map_err(|e| {
226 FernError::io(format!("serializing theme: {e}"), std::io::Error::other(e.to_string()))
227 })?;
228
229 std::fs::write(path, json)
230 .map_err(|e| FernError::io(format!("writing {}", path.display()), e))?;
231
232 Ok(())
233 }
234
235 fn load_theme(&self, path: impl AsRef<Path>) -> Result<Theme> {
236 let path = path.as_ref();
237 let content = std::fs::read_to_string(path)
238 .map_err(|e| FernError::io(format!("reading {}", path.display()), e))?;
239
240 let theme: Theme = serde_json::from_str(&content).map_err(|e| {
241 FernError::Config(crate::error::ConfigError::MissingField {
242 key: "theme".to_string(),
243 expected_type: format!("valid theme JSON: {e}"),
244 })
245 })?;
246
247 Ok(theme)
248 }
249
250 fn config_dir(&self) -> Option<std::path::PathBuf> {
251 dirs::config_dir().map(|p| p.join("fern"))
252 }
253
254 fn ensure_config_dir(&self) -> Result<std::path::PathBuf> {
255 let dir = self.config_dir().ok_or_else(|| {
256 FernError::io(
257 "determining config directory",
258 std::io::Error::new(
259 std::io::ErrorKind::NotFound,
260 "could not determine config directory",
261 ),
262 )
263 })?;
264
265 std::fs::create_dir_all(&dir)
266 .map_err(|e| FernError::io(format!("creating {}", dir.display()), e))?;
267
268 Ok(dir)
269 }
270
271 fn exists(&self, path: impl AsRef<Path>) -> bool {
272 path.as_ref().exists()
273 }
274}