prismtty 1.0.9

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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
//! 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),
    /// YAML decoding failed for a specific file.
    #[error("failed to parse YAML in {path}: {source}")]
    YamlFile {
        /// Path that failed to parse.
        path: PathBuf,
        /// Underlying YAML parser error.
        source: 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)]
#[serde(deny_unknown_fields)]
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)]
#[serde(deny_unknown_fields)]
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)]
#[serde(deny_unknown_fields)]
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)?;
        Self::from_rules_doc(doc)
    }

    fn from_rules_doc(doc: RulesDoc) -> Result<Self, ConfigError> {
        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 = read_config_file(path).map_err(|source| ConfigError::Read {
            path: path.to_path_buf(),
            source,
        })?;
        let doc: RulesDoc =
            serde_norway::from_str(&input).map_err(|source| ConfigError::YamlFile {
                path: path.to_path_buf(),
                source,
            })?;
        Self::from_rules_doc(doc)
    }

    /// 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 store.top_level_profile_names(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
    }
}

/// Largest config / profile file PrismTTY will read. Profiles and ChromaTerm
/// configs are kilobytes; this bounds the read so a giant (or non-regular) file
/// cannot be slurped without limit.
const MAX_CONFIG_FILE_BYTES: u64 = 1024 * 1024;

/// Reads a config / profile file as UTF-8, rejecting anything larger than
/// [`MAX_CONFIG_FILE_BYTES`].
fn read_config_file(path: &Path) -> std::io::Result<String> {
    use std::io::Read as _;
    let file = fs::File::open(path)?;
    let metadata = file.metadata()?;
    if !metadata.file_type().is_file() {
        return Err(std::io::Error::new(
            std::io::ErrorKind::InvalidInput,
            format!("config path is not a regular file: {}", path.display()),
        ));
    }
    let len = metadata.len();
    if len > MAX_CONFIG_FILE_BYTES {
        return Err(std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            format!("config file is too large ({len} bytes; limit {MAX_CONFIG_FILE_BYTES})"),
        ));
    }
    let mut input = Vec::new();
    file.take(MAX_CONFIG_FILE_BYTES + 1)
        .read_to_end(&mut input)?;
    if input.len() as u64 > MAX_CONFIG_FILE_BYTES {
        return Err(std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            format!("config file is too large (more than {MAX_CONFIG_FILE_BYTES} bytes)"),
        ));
    }
    String::from_utf8(input)
        .map_err(|source| std::io::Error::new(std::io::ErrorKind::InvalidData, source))
}

pub fn load_profile_file(path: impl AsRef<Path>) -> Result<LoadedProfileFile, ConfigError> {
    let path = path.as_ref();
    let input = read_config_file(path).map_err(|source| ConfigError::Read {
        path: path.to_path_buf(),
        source,
    })?;
    let doc: RulesDoc = serde_norway::from_str(&input).map_err(|source| ConfigError::YamlFile {
        path: path.to_path_buf(),
        source,
    })?;
    profile_file_from_doc(doc, ProfileYamlMode::User)
}

/// 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)?;
    profile_file_from_doc(doc, mode)
}

fn profile_file_from_doc(
    doc: RulesDoc,
    mode: ProfileYamlMode,
) -> Result<LoadedProfileFile, ConfigError> {
    let mut meta = doc.profile.ok_or(ConfigError::MissingProfileName)?;
    if meta.name.trim().is_empty() {
        return Err(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) => parse_capture_ref_string(description, name),
        other => Err(ConfigError::InvalidCaptureKey {
            description: description.to_string(),
            key: format!("{other:?}"),
        }),
    }
}

fn parse_capture_ref_string(description: &str, name: String) -> Result<CaptureRef, ConfigError> {
    if name.bytes().all(|byte| byte.is_ascii_digit()) {
        return name.parse::<usize>().map(CaptureRef::Index).map_err(|_| {
            ConfigError::InvalidCaptureKey {
                description: description.to_string(),
                key: name,
            }
        });
    }

    if is_valid_capture_name(&name) {
        Ok(CaptureRef::Name(name))
    } else {
        Err(ConfigError::InvalidCaptureKey {
            description: description.to_string(),
            key: name,
        })
    }
}

fn is_valid_capture_name(name: &str) -> bool {
    let mut bytes = name.bytes();
    let Some(first) = bytes.next() else {
        return false;
    };
    (first.is_ascii_alphabetic() || first == b'_')
        && bytes.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
}

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::{
        PrismConfig, RESERVED_PROFILE_RUNTIME_MESSAGE, load_profile_file,
        parse_builtin_profile_yaml, parse_profile_yaml,
    };

    #[test]
    fn read_config_file_rejects_oversized_files() {
        let small = tempfile::NamedTempFile::new().expect("temp file");
        std::fs::write(small.path(), "rules: []\n").expect("write small");
        assert!(
            super::read_config_file(small.path()).is_ok(),
            "a normal config file should read"
        );

        let big = tempfile::NamedTempFile::new().expect("temp file");
        std::fs::write(
            big.path(),
            vec![b'#'; super::MAX_CONFIG_FILE_BYTES as usize + 1],
        )
        .expect("write big");
        assert!(
            super::read_config_file(big.path()).is_err(),
            "an oversized config file should be rejected"
        );
    }

    #[test]
    fn read_config_file_rejects_non_regular_files() {
        let dir = tempfile::tempdir().expect("tempdir creates");

        let error =
            super::read_config_file(dir.path()).expect_err("directory paths should be rejected");

        assert_eq!(error.kind(), std::io::ErrorKind::InvalidInput);
    }

    #[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"));
    }

    #[test]
    fn chromaterm_file_yaml_errors_include_path() {
        let file = tempfile::NamedTempFile::new().expect("temp file creates");
        std::fs::write(file.path(), "rules: [").expect("invalid yaml writes");

        let err = PrismConfig::from_chromaterm_file(file.path())
            .expect_err("invalid file YAML should fail");
        let message = err.to_string();

        assert!(message.contains(&file.path().display().to_string()));
        assert!(message.contains("failed to parse YAML in"));
    }

    #[test]
    fn profile_file_yaml_errors_include_path() {
        let file = tempfile::NamedTempFile::new().expect("temp file creates");
        std::fs::write(file.path(), "profile: [").expect("invalid yaml writes");

        let err = load_profile_file(file.path()).expect_err("invalid profile YAML should fail");
        let message = err.to_string();

        assert!(message.contains(&file.path().display().to_string()));
        assert!(message.contains("failed to parse YAML in"));
    }

    #[test]
    fn capture_names_must_match_pcre2_identifier_shape() {
        let yaml = r#"
rules:
  - description: named capture
    regex: '(?P<name>\w+)'
    color:
      _valid_name_1: f#ffffff
      bad-name: f#ff0000
"#;

        let err = PrismConfig::from_chromaterm_yaml(yaml)
            .expect_err("invalid capture name should fail during config parsing");

        assert_eq!(
            err.to_string(),
            "rule 'named capture' has invalid capture key: bad-name"
        );
    }
}