fernctl/commands/
query.rs

1//! # Theme Query Command
2//!
3//! The `query` command retrieves specific values from a configuration file.
4//! This is useful for shell scripts, debugging, and integration with other tools.
5//!
6//! ## Usage
7//!
8//! ```bash
9//! # Query a specific value
10//! fernctl query colors.background
11//!
12//! # Query from a specific config file
13//! fernctl query bar.height --config ./my-config.toml
14//!
15//! # Use in shell scripts
16//! ACCENT=$(fernctl query colors.accent)
17//! echo "Accent color is: $ACCENT"
18//! ```
19//!
20//! ## Query Paths
21//!
22//! Values are addressed using dot-separated paths that mirror the configuration
23//! structure:
24//!
25//! ```text
26//! config.toml                        Query Path
27//! ───────────                        ──────────
28//! [colors]
29//! background = "#1e1e2e"      →     colors.background
30//! accent = "#89b4fa"          →     colors.accent
31//!
32//! [bar]
33//! height = 32                 →     bar.height
34//! position = "top"            →     bar.position
35//!
36//! [typography]
37//! family = "Inter"            →     typography.family
38//! ```
39//!
40//! ## Available Paths
41//!
42//! ### Theme
43//!
44//! | Path | Type | Description |
45//! |------|------|-------------|
46//! | `variant` | string | Theme variant ("dark" or "light") |
47//!
48//! ### Colors
49//!
50//! | Path | Type | Description |
51//! |------|------|-------------|
52//! | `colors.background` | hex | Primary background color |
53//! | `colors.foreground` | hex | Primary text color |
54//! | `colors.accent` | hex | Accent/highlight color |
55//! | `colors.surface` | hex | Surface/card background |
56//! | `colors.error` | hex | Error state color |
57//! | `colors.warning` | hex | Warning state color |
58//! | `colors.success` | hex | Success state color |
59//! | `colors.info` | hex | Informational state color |
60//!
61//! ### Bar
62//!
63//! | Path | Type | Description |
64//! |------|------|-------------|
65//! | `bar.height` | integer | Bar height in pixels |
66//! | `bar.position` | string | Bar position ("top" or "bottom") |
67//!
68//! ### Typography
69//!
70//! | Path | Type | Description |
71//! |------|------|-------------|
72//! | `typography.family` | string | Primary font family |
73//! | `typography.mono` | string | Monospace font family |
74//!
75//! ### Radius
76//!
77//! | Path | Type | Description |
78//! |------|------|-------------|
79//! | `radius.sm` | integer | Small border radius (px) |
80//! | `radius.md` | integer | Medium border radius (px) |
81//! | `radius.lg` | integer | Large border radius (px) |
82//!
83//! ## Output Format
84//!
85//! Query results are printed to stdout without any decoration, making them
86//! suitable for shell script consumption:
87//!
88//! ```bash
89//! $ fernctl query colors.accent
90//! #89b4fa
91//!
92//! $ fernctl query bar.height
93//! 32
94//! ```
95//!
96//! ## Error Handling
97//!
98//! If a path is not recognized, the command prints available paths to stderr
99//! and exits with code 0 (this is intentional — unknown paths are not errors,
100//! they might be from a newer config version).
101//!
102//! ```bash
103//! $ fernctl query colors.prple
104//! Unknown path: colors.prple
105//!
106//! Available paths:
107//!   colors.background, colors.foreground, colors.accent, ...
108//!
109//! Did you mean: colors.purple?
110//! ```
111//!
112//! ## Programmatic Usage
113//!
114//! ```rust,ignore
115//! use fernctl::commands::query::{run, QueryOptions};
116//! use fernctl::adapters::TomlConfigAdapter;
117//!
118//! let adapter = TomlConfigAdapter::new();
119//! let options = QueryOptions { verbose: false };
120//!
121//! if let Some(value) = run(&config_path, "colors.accent", options, &adapter)? {
122//!     println!("Accent: {}", value);
123//! }
124//! ```
125
126use crate::error::Result;
127use crate::ports::inbound::ConfigPort;
128use std::path::Path;
129
130/// Options for the query command.
131///
132/// # Example
133///
134/// ```rust
135/// use fernctl::commands::query::QueryOptions;
136///
137/// let options = QueryOptions {
138///     verbose: true,
139/// };
140/// ```
141#[derive(Debug, Clone, Default)]
142pub struct QueryOptions {
143    /// Whether to print additional context about the query.
144    pub verbose: bool,
145}
146
147/// All available query paths.
148///
149/// This constant is used for help text and "did you mean?" suggestions.
150pub const AVAILABLE_PATHS: &[&str] = &[
151    "variant",
152    "bar.height",
153    "bar.position",
154    "colors.background",
155    "colors.foreground",
156    "colors.accent",
157    "colors.surface",
158    "colors.error",
159    "colors.warning",
160    "colors.success",
161    "colors.info",
162    "typography.family",
163    "typography.mono",
164    "radius.sm",
165    "radius.md",
166    "radius.lg",
167];
168
169/// Queries a theme value by path.
170///
171/// Loads the configuration, validates it, and extracts the value at the
172/// specified path. Returns `None` if the path is not recognized.
173///
174/// # Arguments
175///
176/// * `config_path` — Path to the configuration file
177/// * `query_path` — Dot-separated path to the value (e.g., "colors.accent")
178/// * `options` — Query options
179/// * `adapter` — Configuration adapter for loading TOML
180///
181/// # Returns
182///
183/// - `Ok(Some(value))` — Path found, value returned as string
184/// - `Ok(None)` — Path not recognized
185/// - `Err(FernError)` — Configuration error
186///
187/// # Example
188///
189/// ```rust,ignore
190/// use fernctl::commands::query::{run, QueryOptions};
191/// use fernctl::adapters::TomlConfigAdapter;
192///
193/// let adapter = TomlConfigAdapter::new();
194/// let options = QueryOptions::default();
195///
196/// match run(&config_path, "colors.accent", options, &adapter)? {
197///     Some(value) => println!("{}", value),
198///     None => eprintln!("Unknown path"),
199/// }
200/// ```
201pub fn run<P: AsRef<Path>>(
202    config_path: P,
203    query_path: &str,
204    options: QueryOptions,
205    adapter: &impl ConfigPort,
206) -> Result<Option<String>> {
207    let config_path = config_path.as_ref();
208
209    if options.verbose {
210        eprintln!("Querying: {} from {}", query_path, config_path.display());
211    }
212
213    // Load and validate configuration
214    let raw = adapter.load_from_file(config_path)?;
215    let validated = raw.validate()?;
216    let theme = validated.into_theme();
217
218    // Extract value by path
219    let value = match query_path {
220        "variant" => Some(theme.variant.name().to_string()),
221        "bar.height" => Some(theme.bar.height.to_string()),
222        "bar.position" => Some(theme.bar.position.name().to_string()),
223        "colors.background" => Some(theme.colors.background.to_hex()),
224        "colors.foreground" => Some(theme.colors.foreground.to_hex()),
225        "colors.accent" => Some(theme.colors.accent.to_hex()),
226        "colors.surface" => Some(theme.colors.surface.to_hex()),
227        "colors.error" => Some(theme.colors.error.to_hex()),
228        "colors.warning" => Some(theme.colors.warning.to_hex()),
229        "colors.success" => Some(theme.colors.success.to_hex()),
230        "colors.info" => Some(theme.colors.info.to_hex()),
231        "typography.family" => Some(theme.typography.family.name().to_string()),
232        "typography.mono" => Some(theme.typography.mono.name().to_string()),
233        "radius.sm" => Some(theme.radius.sm.to_string()),
234        "radius.md" => Some(theme.radius.md.to_string()),
235        "radius.lg" => Some(theme.radius.lg.to_string()),
236        _ => None,
237    };
238
239    Ok(value)
240}
241
242/// Finds similar paths for "did you mean?" suggestions.
243///
244/// Uses string similarity to find paths that are close to the given
245/// unknown path, helping users correct typos.
246///
247/// # Arguments
248///
249/// * `unknown` — The unrecognized path
250///
251/// # Returns
252///
253/// A vector of similar paths, sorted by similarity (most similar first).
254/// Returns at most 3 suggestions.
255///
256/// # Example
257///
258/// ```rust
259/// use fernctl::commands::query::find_similar_paths;
260///
261/// let suggestions = find_similar_paths("colors.backgroud");
262/// assert!(suggestions.contains(&"colors.background".to_string()));
263/// ```
264#[must_use]
265pub fn find_similar_paths(unknown: &str) -> Vec<String> {
266    let mut candidates: Vec<(f64, &str)> = AVAILABLE_PATHS
267        .iter()
268        .map(|&path| (strsim::jaro_winkler(unknown, path), path))
269        .filter(|(score, _)| *score > 0.6)
270        .collect();
271
272    candidates.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal));
273
274    candidates
275        .into_iter()
276        .take(3)
277        .map(|(_, path)| path.to_string())
278        .collect()
279}
280
281/// Prints help text showing all available query paths.
282///
283/// This is called when an unknown path is queried, providing guidance
284/// to the user about what paths are valid.
285pub fn print_available_paths() {
286    eprintln!("\nAvailable paths:");
287    eprintln!("  variant");
288    eprintln!("  bar.height, bar.position");
289    eprintln!(
290        "  colors.background, colors.foreground, colors.accent, colors.surface"
291    );
292    eprintln!("  colors.error, colors.warning, colors.success, colors.info");
293    eprintln!("  typography.family, typography.mono");
294    eprintln!("  radius.sm, radius.md, radius.lg");
295}
296
297#[cfg(test)]
298mod tests {
299    use super::*;
300
301    #[test]
302    fn find_similar_detects_typo() {
303        let suggestions = find_similar_paths("colors.backgroud");
304        assert!(suggestions.contains(&"colors.background".to_string()));
305    }
306
307    #[test]
308    fn find_similar_returns_empty_for_gibberish() {
309        let suggestions = find_similar_paths("xyzzy123");
310        assert!(suggestions.is_empty());
311    }
312
313    #[test]
314    fn find_similar_limits_to_three() {
315        let suggestions = find_similar_paths("colors");
316        assert!(suggestions.len() <= 3);
317    }
318}