textfsm-core 0.3.1

Core parsing library for TextFSM template-based state machine
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
//! Index file parsing and template matching.
//!
//! Parses CSV-format index files that map attributes (Command, Platform, Hostname)
//! to template files.

use std::collections::HashMap;
use std::io::BufRead;
use std::path::Path;

use fancy_regex::Regex;

use super::completion::expand_completion;
use super::CliTableError;

/// Parsed index file.
#[derive(Debug, Clone)]
pub struct Index {
    /// Column names from header row.
    columns: Vec<String>,

    /// Index entries (data rows).
    entries: Vec<IndexEntry>,
}

impl Index {
    /// Parse an index from a reader.
    pub fn parse<R: BufRead>(reader: R) -> Result<Self, CliTableError> {
        let mut columns: Vec<String> = Vec::new();
        let mut entries: Vec<IndexEntry> = Vec::new();
        let mut line_num = 0;

        for line in reader.lines() {
            line_num += 1;
            let line = line.map_err(|e| CliTableError::IndexParse {
                line: line_num,
                message: e.to_string(),
            })?;

            let trimmed = line.trim();

            // Skip empty lines and comments
            if trimmed.is_empty() || trimmed.starts_with('#') {
                continue;
            }

            // Parse CSV line
            let fields: Vec<String> = parse_csv_line(trimmed);

            if columns.is_empty() {
                // First non-comment line is the header
                columns = fields.into_iter().map(|s| s.trim().to_string()).collect();

                // Validate required Template column
                if !columns.iter().any(|c| c == "Template") {
                    return Err(CliTableError::MissingColumn("Template".into()));
                }
            } else {
                // Data row
                let entry = IndexEntry::parse(&columns, fields, line_num)?;
                entries.push(entry);
            }
        }

        if columns.is_empty() {
            return Err(CliTableError::IndexParse {
                line: 0,
                message: "empty index file (no header row)".into(),
            });
        }

        Ok(Self { columns, entries })
    }

    /// Parse an index from a string.
    pub fn parse_str(s: &str) -> Result<Self, CliTableError> {
        Self::parse(s.as_bytes())
    }

    /// Parse an index from a file.
    pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self, CliTableError> {
        let file = std::fs::File::open(path)?;
        let reader = std::io::BufReader::new(file);
        Self::parse(reader)
    }

    /// Find the first matching entry for the given attributes.
    ///
    /// Returns the first entry where all provided attributes match.
    /// Attributes not present in the index are silently ignored.
    pub fn find_match(&self, attributes: &HashMap<String, String>) -> Option<&IndexEntry> {
        self.entries.iter().find(|entry| entry.matches(&self.columns, attributes))
    }

    /// Get all matching entries.
    pub fn find_all_matches(&self, attributes: &HashMap<String, String>) -> Vec<&IndexEntry> {
        self.entries
            .iter()
            .filter(|entry| entry.matches(&self.columns, attributes))
            .collect()
    }

    /// Get column names.
    pub fn columns(&self) -> &[String] {
        &self.columns
    }

    /// Get all entries.
    pub fn entries(&self) -> &[IndexEntry] {
        &self.entries
    }

    /// Get all unique template names referenced in this index.
    pub fn all_templates(&self) -> Vec<&str> {
        let mut templates: Vec<&str> = Vec::new();
        for entry in &self.entries {
            for template in &entry.templates {
                if !templates.contains(&template.as_str()) {
                    templates.push(template);
                }
            }
        }
        templates
    }
}

/// A single row in the index file.
#[derive(Debug, Clone)]
pub struct IndexEntry {
    /// Template file names (colon-separated in the CSV).
    templates: Vec<String>,

    /// Compiled regex patterns for each attribute column.
    /// None for the Template column (index 0).
    patterns: Vec<Option<Regex>>,

    /// Original string values from CSV (for debugging).
    raw_values: Vec<String>,

    /// Line number in the index file (for error reporting).
    line_num: usize,
}

impl IndexEntry {
    /// Parse an index entry from CSV fields.
    fn parse(columns: &[String], fields: Vec<String>, line_num: usize) -> Result<Self, CliTableError> {
        let mut templates: Vec<String> = Vec::new();
        let mut patterns: Vec<Option<Regex>> = Vec::new();
        let mut raw_values: Vec<String> = Vec::new();

        for (i, column) in columns.iter().enumerate() {
            let value = fields.get(i).map(|s| s.trim().to_string()).unwrap_or_default();
            raw_values.push(value.clone());

            if column == "Template" {
                // Split on ':' for multi-template entries
                templates = value
                    .split(':')
                    .map(|s| s.trim().to_string())
                    .filter(|s| !s.is_empty())
                    .collect();
                patterns.push(None);
            } else {
                // Expand completion syntax and compile regex
                if value.is_empty() {
                    patterns.push(None);
                } else {
                    let expanded = if column == "Command" {
                        expand_completion(&value)?
                    } else {
                        value.clone()
                    };

                    // Anchor pattern at start to match Python's re.match() behavior
                    let anchored = if expanded.starts_with('^') {
                        expanded
                    } else {
                        format!("^{}", expanded)
                    };

                    let regex = Regex::new(&anchored).map_err(|e| CliTableError::InvalidRegex {
                        line: line_num,
                        message: format!("{}: {}", column, e),
                    })?;
                    patterns.push(Some(regex));
                }
            }
        }

        if templates.is_empty() {
            return Err(CliTableError::IndexParse {
                line: line_num,
                message: "empty Template field".into(),
            });
        }

        Ok(Self {
            templates,
            patterns,
            raw_values,
            line_num,
        })
    }

    /// Check if this entry matches the given attributes.
    ///
    /// All provided attributes must match (AND logic).
    /// Attributes not in the index are silently ignored.
    pub fn matches(&self, columns: &[String], attributes: &HashMap<String, String>) -> bool {
        for (i, column) in columns.iter().enumerate() {
            // Skip Template column
            if column == "Template" {
                continue;
            }

            // Get the pattern for this column
            if let Some(Some(pattern)) = self.patterns.get(i) {
                // Get the attribute value (empty string if not provided)
                let attr_value = attributes.get(column).map(|s| s.as_str()).unwrap_or("");

                // Check if pattern matches
                match pattern.is_match(attr_value) {
                    Ok(true) => continue,
                    Ok(false) => return false,
                    Err(_) => return false,
                }
            }
            // If no pattern for this column, it matches anything
        }

        true
    }

    /// Get template names.
    pub fn templates(&self) -> &[String] {
        &self.templates
    }

    /// Get the raw CSV values.
    pub fn raw_values(&self) -> &[String] {
        &self.raw_values
    }

    /// Get the line number in the index file.
    pub fn line_num(&self) -> usize {
        self.line_num
    }
}

/// Simple CSV line parser (handles quoted fields with commas).
fn parse_csv_line(line: &str) -> Vec<String> {
    let mut fields = Vec::new();
    let mut current = String::new();
    let mut in_quotes = false;
    let mut chars = line.chars().peekable();

    while let Some(c) = chars.next() {
        match c {
            '"' if !in_quotes => {
                in_quotes = true;
            }
            '"' if in_quotes => {
                // Check for escaped quote
                if chars.peek() == Some(&'"') {
                    chars.next();
                    current.push('"');
                } else {
                    in_quotes = false;
                }
            }
            ',' if !in_quotes => {
                fields.push(current.trim().to_string());
                current = String::new();
            }
            _ => {
                current.push(c);
            }
        }
    }

    fields.push(current.trim().to_string());
    fields
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_simple_index() {
        let csv = r#"Template, Hostname, Command
template_a.textfsm, .*, show version
template_b.textfsm, .*, show interfaces
"#;
        let index = Index::parse_str(csv).unwrap();
        assert_eq!(index.columns().len(), 3);
        assert_eq!(index.entries().len(), 2);
        assert_eq!(index.entries()[0].templates(), &["template_a.textfsm"]);
        assert_eq!(index.entries()[1].templates(), &["template_b.textfsm"]);
    }

    #[test]
    fn test_parse_with_comments() {
        let csv = r#"# This is a comment
Template, Command

# Another comment
template.textfsm, show version
"#;
        let index = Index::parse_str(csv).unwrap();
        assert_eq!(index.entries().len(), 1);
    }

    #[test]
    fn test_parse_multi_template() {
        let csv = r#"Template, Command
template_a.textfsm:template_b.textfsm, show version
"#;
        let index = Index::parse_str(csv).unwrap();
        assert_eq!(
            index.entries()[0].templates(),
            &["template_a.textfsm", "template_b.textfsm"]
        );
    }

    #[test]
    fn test_find_match() {
        let csv = r#"Template, Platform, Command
cisco_show_version.textfsm, cisco_ios, show version
arista_show_version.textfsm, arista_eos, show version
cisco_show_interfaces.textfsm, cisco_ios, show interfaces
"#;
        let index = Index::parse_str(csv).unwrap();

        let mut attrs = HashMap::new();
        attrs.insert("Platform".into(), "cisco_ios".into());
        attrs.insert("Command".into(), "show version".into());

        let entry = index.find_match(&attrs).unwrap();
        assert_eq!(entry.templates(), &["cisco_show_version.textfsm"]);
    }

    #[test]
    fn test_find_match_with_regex() {
        let csv = r#"Template, Platform, Command
cisco_show_version.textfsm, cisco_.*, show version
"#;
        let index = Index::parse_str(csv).unwrap();

        let mut attrs = HashMap::new();
        attrs.insert("Platform".into(), "cisco_ios".into());
        attrs.insert("Command".into(), "show version".into());

        let entry = index.find_match(&attrs);
        assert!(entry.is_some());

        // Different platform should not match
        attrs.insert("Platform".into(), "arista_eos".into());
        let entry = index.find_match(&attrs);
        assert!(entry.is_none());
    }

    #[test]
    fn test_find_match_with_completion() {
        let csv = r#"Template, Platform, Command
cisco_show_version.textfsm, cisco_ios, sh[[ow]] ver[[sion]]
"#;
        let index = Index::parse_str(csv).unwrap();

        // Full command
        let mut attrs = HashMap::new();
        attrs.insert("Platform".into(), "cisco_ios".into());
        attrs.insert("Command".into(), "show version".into());
        assert!(index.find_match(&attrs).is_some(), "show version should match");

        // Abbreviated command - both prefixes must still be present
        // sh[[ow]] means: sh, sho, or show
        // ver[[sion]] means: ver, vers, versi, versio, or version
        attrs.insert("Command".into(), "sh ver".into());
        assert!(index.find_match(&attrs).is_some(), "sh ver should match");

        // Partial completion
        attrs.insert("Command".into(), "sho vers".into());
        assert!(index.find_match(&attrs).is_some(), "sho vers should match");

        // "sh v" should NOT match because "ver" is the minimum required for the second word
        attrs.insert("Command".into(), "sh v".into());
        assert!(index.find_match(&attrs).is_none(), "sh v should NOT match (ver is required)");
    }

    #[test]
    fn test_missing_template_column() {
        let csv = r#"Platform, Command
cisco_ios, show version
"#;
        let result = Index::parse_str(csv);
        assert!(matches!(result, Err(CliTableError::MissingColumn(_))));
    }

    #[test]
    fn test_empty_template() {
        let csv = r#"Template, Command
, show version
"#;
        let result = Index::parse_str(csv);
        assert!(matches!(result, Err(CliTableError::IndexParse { .. })));
    }

    #[test]
    fn test_all_templates() {
        let csv = r#"Template, Command
template_a.textfsm, show version
template_b.textfsm:template_c.textfsm, show interfaces
template_a.textfsm, show ip route
"#;
        let index = Index::parse_str(csv).unwrap();
        let templates = index.all_templates();
        assert_eq!(templates.len(), 3);
        assert!(templates.contains(&"template_a.textfsm"));
        assert!(templates.contains(&"template_b.textfsm"));
        assert!(templates.contains(&"template_c.textfsm"));
    }

    #[test]
    fn test_csv_with_quotes() {
        let csv = r#"Template, Command
template.textfsm, "show interfaces, all"
"#;
        let index = Index::parse_str(csv).unwrap();
        assert_eq!(index.entries()[0].raw_values()[1], "show interfaces, all");
    }
}