prismtty 0.2.5

Fast terminal output highlighter focused on network devices and Unix systems
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
//! Configuration and profile-file parsing.
//!
//! PrismTTY accepts ChromaTerm-style YAML rule files and native profile files
//! that add profile metadata such as inheritance and detection hints.

use crate::profiles::{ProfileRuntimeMeta, ProfileStore};
use crate::style::{Style, parse_palette};
use serde::Deserialize;
use std::collections::{BTreeMap, BTreeSet};
use std::fs;
use std::path::{Path, PathBuf};
use thiserror::Error;

/// Error message returned when user profile files include reserved runtime metadata.
pub const RESERVED_PROFILE_RUNTIME_MESSAGE: &str =
    "the profile.runtime field is reserved for built-in profiles in this PrismTTY version";

/// Errors returned while loading, parsing, or resolving PrismTTY configuration.
#[derive(Debug, Error)]
pub enum ConfigError {
    /// A configuration or profile file could not be read.
    #[error("failed to read {path}: {source}")]
    Read {
        /// Path that failed to load.
        path: PathBuf,
        /// Underlying filesystem error.
        source: std::io::Error,
    },
    /// YAML decoding failed.
    #[error("failed to parse YAML: {0}")]
    Yaml(#[from] serde_norway::Error),
    /// A requested profile name was not registered.
    #[error("unknown profile '{0}'")]
    UnknownProfile(String),
    /// Profile inheritance loops back to a profile already being resolved.
    #[error("cyclic profile inheritance: {0}")]
    CyclicProfileInheritance(String),
    /// A native profile file omitted `profile.name`.
    #[error("profile files must include profile.name")]
    MissingProfileName,
    /// A bundled built-in profile omitted its private runtime metadata.
    #[error("bundled profile files must include profile.runtime")]
    MissingProfileRuntime,
    /// A user profile attempted to set reserved runtime metadata.
    #[error("{0}")]
    ReservedProfileRuntime(&'static str),
    /// A rule style string or capture style mapping is invalid.
    #[error("rule '{description}' has invalid style: {message}")]
    InvalidStyle {
        /// Human-readable rule description.
        description: String,
        /// Style parser error text.
        message: String,
    },
    /// The palette section contains an invalid color name or value.
    #[error("palette has invalid color: {0}")]
    InvalidPalette(String),
    /// A capture style key was neither a group index nor a group name.
    #[error("rule '{description}' has invalid capture key: {key}")]
    InvalidCaptureKey {
        /// Human-readable rule description.
        description: String,
        /// Invalid capture key as it appeared in YAML.
        key: String,
    },
}

/// Fully resolved highlighting configuration.
#[derive(Clone, Debug, Default)]
pub struct PrismConfig {
    /// Rule list in application order.
    pub rules: Vec<RuleSpec>,
    /// Profiles that contributed rules to this configuration.
    pub enabled_profiles: Vec<String>,
}

/// One highlight rule before PCRE2 compilation.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RuleSpec {
    /// Human-readable rule name used in errors and benchmark reports.
    pub description: String,
    /// PCRE2 regular expression matched against visible terminal text.
    pub regex: String,
    /// Style applied to the whole match or selected capture groups.
    pub style: RuleStyle,
    /// Whether this rule prevents later rules from changing the same span.
    pub exclusive: bool,
}

/// Capture group reference used by capture-specific styles.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum CaptureRef {
    /// Numeric capture group index, including `0` for the whole match.
    Index(usize),
    /// Named capture group.
    Name(String),
}

/// Style target for a highlight rule.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum RuleStyle {
    /// Apply one style to the whole regex match.
    Whole(Style),
    /// Apply individual styles to capture groups.
    Captures(BTreeMap<CaptureRef, Style>),
}

#[derive(Debug, Deserialize)]
struct RulesDoc {
    #[serde(default)]
    profile: Option<ProfileMetaDoc>,
    #[serde(default)]
    palette: BTreeMap<String, String>,
    #[serde(default)]
    rules: Vec<RuleDoc>,
}

/// Metadata declared in a native profile YAML file.
#[derive(Clone, Debug, Deserialize)]
pub struct ProfileMetaDoc {
    /// Profile name used on the command line and in inheritance lists.
    pub name: String,
    /// Parent profiles loaded before this profile.
    #[serde(default)]
    pub inherits: Vec<String>,
    /// Startup detection hints used for auto-detection.
    #[serde(default)]
    pub detection: Vec<String>,
    #[serde(default)]
    pub(crate) runtime: Option<ProfileRuntimeMeta>,
}

#[derive(Debug, Deserialize)]
struct RuleDoc {
    #[serde(default)]
    description: String,
    regex: String,
    color: serde_norway::Value,
    #[serde(default)]
    exclusive: bool,
}

/// Parsed native profile file, including metadata and rules.
#[derive(Clone, Debug)]
pub struct LoadedProfileFile {
    /// Public profile metadata from the `profile` YAML section.
    pub meta: ProfileMetaDoc,
    /// Runtime metadata for bundled profiles, or `None` for user profiles.
    pub runtime: Option<ProfileRuntimeMeta>,
    /// Parsed highlighting rules from the file.
    pub rules: Vec<RuleSpec>,
}

impl PrismConfig {
    /// Parses a ChromaTerm-style YAML document into highlighting rules.
    pub fn from_chromaterm_yaml(input: &str) -> Result<Self, ConfigError> {
        let doc: RulesDoc = serde_norway::from_str(input)?;
        let palette = parse_palette(&doc.palette).map_err(ConfigError::InvalidPalette)?;
        Ok(Self {
            rules: parse_rule_docs(doc.rules, &palette)?,
            enabled_profiles: Vec::new(),
        })
    }

    /// Reads and parses a ChromaTerm-style YAML file.
    pub fn from_chromaterm_file(path: impl AsRef<Path>) -> Result<Self, ConfigError> {
        let path = path.as_ref();
        let input = fs::read_to_string(path).map_err(|source| ConfigError::Read {
            path: path.to_path_buf(),
            source,
        })?;
        Self::from_chromaterm_yaml(&input)
    }

    /// Builds a configuration from registered profiles and their inherited rules.
    pub fn from_profiles(
        store: &ProfileStore,
        profile_names: &[&str],
    ) -> Result<Self, ConfigError> {
        let mut rules = Vec::new();
        let mut loaded = BTreeSet::new();

        for profile_name in profile_names {
            store.append_profile_rules(profile_name, &mut loaded, &mut rules)?;
        }

        Ok(Self {
            rules,
            enabled_profiles: loaded.into_iter().collect(),
        })
    }

    /// Appends another configuration, preserving unique enabled-profile names.
    pub fn merge(mut self, mut other: Self) -> Self {
        self.rules.append(&mut other.rules);
        for profile in other.enabled_profiles {
            if !self.enabled_profiles.contains(&profile) {
                self.enabled_profiles.push(profile);
            }
        }
        self
    }
}

/// Reads and parses a native PrismTTY profile YAML file.
pub fn load_profile_file(path: impl AsRef<Path>) -> Result<LoadedProfileFile, ConfigError> {
    let path = path.as_ref();
    let input = fs::read_to_string(path).map_err(|source| ConfigError::Read {
        path: path.to_path_buf(),
        source,
    })?;
    parse_profile_yaml(&input)
}

/// Parses native PrismTTY profile YAML from a string.
///
/// # Example
///
/// ```
/// use prismtty::config::parse_profile_yaml;
///
/// let profile = parse_profile_yaml(r##"
/// profile:
///   name: custom-router
///   inherits: [generic]
///   detection:
///     - CustomOS
/// rules:
///   - description: management IPv4 addresses
///     regex: '\b192\.0\.2\.\d+\b'
///     color: f#00ffff
/// "##)
/// .expect("profile parses");
///
/// assert_eq!(profile.meta.name, "custom-router");
/// assert_eq!(profile.meta.inherits, vec!["generic".to_string()]);
/// assert_eq!(profile.rules.len(), 1);
/// ```
pub fn parse_profile_yaml(input: &str) -> Result<LoadedProfileFile, ConfigError> {
    parse_profile_yaml_with_mode(input, ProfileYamlMode::User)
}

pub(crate) fn parse_builtin_profile_yaml(input: &str) -> Result<LoadedProfileFile, ConfigError> {
    parse_profile_yaml_with_mode(input, ProfileYamlMode::Bundled)
}

#[derive(Clone, Copy)]
enum ProfileYamlMode {
    User,
    Bundled,
}

fn parse_profile_yaml_with_mode(
    input: &str,
    mode: ProfileYamlMode,
) -> Result<LoadedProfileFile, ConfigError> {
    let doc: RulesDoc = serde_norway::from_str(input)?;
    let mut meta = doc.profile.ok_or(ConfigError::MissingProfileName)?;
    let runtime = meta.runtime.take();
    match mode {
        ProfileYamlMode::User if runtime.is_some() => {
            return Err(ConfigError::ReservedProfileRuntime(
                RESERVED_PROFILE_RUNTIME_MESSAGE,
            ));
        }
        ProfileYamlMode::Bundled if runtime.is_none() => {
            return Err(ConfigError::MissingProfileRuntime);
        }
        _ => {}
    }
    let palette = parse_palette(&doc.palette).map_err(ConfigError::InvalidPalette)?;
    Ok(LoadedProfileFile {
        meta,
        runtime,
        rules: parse_rule_docs(doc.rules, &palette)?,
    })
}

fn parse_rule_docs(
    rule_docs: Vec<RuleDoc>,
    palette: &BTreeMap<String, crate::style::Rgb>,
) -> Result<Vec<RuleSpec>, ConfigError> {
    rule_docs
        .into_iter()
        .enumerate()
        .map(|(idx, rule)| {
            let description = if rule.description.trim().is_empty() {
                format!("rule {}", idx + 1)
            } else {
                rule.description
            };
            let style = parse_color_doc(&description, rule.color, palette)?;
            Ok(RuleSpec {
                description,
                regex: rule.regex,
                style,
                exclusive: rule.exclusive,
            })
        })
        .collect()
}

fn parse_color_doc(
    description: &str,
    color: serde_norway::Value,
    palette: &BTreeMap<String, crate::style::Rgb>,
) -> Result<RuleStyle, ConfigError> {
    match color {
        serde_norway::Value::String(spec) => {
            Ok(RuleStyle::Whole(parse_style(description, &spec, palette)?))
        }
        serde_norway::Value::Mapping(captures) => {
            let mut parsed = BTreeMap::new();
            for (group, spec) in captures {
                let group = parse_capture_ref(description, group)?;
                let spec = spec.as_str().ok_or_else(|| ConfigError::InvalidStyle {
                    description: description.to_string(),
                    message: "capture color must be a string".to_string(),
                })?;
                parsed.insert(group, parse_style(description, spec, palette)?);
            }
            Ok(RuleStyle::Captures(parsed))
        }
        _ => Err(ConfigError::InvalidStyle {
            description: description.to_string(),
            message: "color must be a string or capture-group mapping".to_string(),
        }),
    }
}

fn parse_capture_ref(
    description: &str,
    value: serde_norway::Value,
) -> Result<CaptureRef, ConfigError> {
    match value {
        serde_norway::Value::Number(number) => {
            let Some(group) = number.as_u64() else {
                return Err(ConfigError::InvalidCaptureKey {
                    description: description.to_string(),
                    key: number.to_string(),
                });
            };
            Ok(CaptureRef::Index(group as usize))
        }
        serde_norway::Value::String(name) if name.bytes().all(|byte| byte.is_ascii_digit()) => name
            .parse::<usize>()
            .map(CaptureRef::Index)
            .map_err(|_| ConfigError::InvalidCaptureKey {
                description: description.to_string(),
                key: name,
            }),
        serde_norway::Value::String(name) if !name.trim().is_empty() => {
            Ok(CaptureRef::Name(name.to_string()))
        }
        other => Err(ConfigError::InvalidCaptureKey {
            description: description.to_string(),
            key: format!("{other:?}"),
        }),
    }
}

fn parse_style(
    description: &str,
    spec: &str,
    palette: &BTreeMap<String, crate::style::Rgb>,
) -> Result<Style, ConfigError> {
    let palette = (!palette.is_empty()).then_some(palette);
    Style::parse_with_palette(spec, palette).map_err(|message| ConfigError::InvalidStyle {
        description: description.to_string(),
        message,
    })
}

#[cfg(test)]
mod tests {
    use super::{RESERVED_PROFILE_RUNTIME_MESSAGE, parse_builtin_profile_yaml, parse_profile_yaml};

    #[test]
    fn user_profile_runtime_is_reserved() {
        let yaml = r#"
profile:
  name: custom-router
  runtime:
    priority: 5
    startup_prompt: cisco_host_marker
    runtime_prompt: cisco_host_marker
    strong_signals: []
rules: []
"#;

        let err = parse_profile_yaml(yaml).expect_err("user profile.runtime must be rejected");

        assert_eq!(err.to_string(), RESERVED_PROFILE_RUNTIME_MESSAGE);
    }

    #[test]
    fn bundled_profile_runtime_rejects_unknown_prompt_matcher() {
        let yaml = r#"
profile:
  name: broken-builtin
  runtime:
    priority: 1
    startup_prompt: mystery_prompt
    runtime_prompt: none
    strong_signals: []
rules: []
"#;

        let err = parse_builtin_profile_yaml(yaml).expect_err("unknown prompt matcher should fail");

        assert!(err.to_string().contains("mystery_prompt"));
    }
}