Skip to main content

asterust_junos/
lib.rs

1//! Typed views of common JunOS config statements, extracted from a tree parsed by
2//! [`asterust::config::juniper`] (brace-delimited `show configuration` output).
3//!
4//! JunOS nests everything under a few top-level blocks (`interfaces`, `protocols`, `routing-options`,
5//! `routing-instances`, `policy-options`, `firewall`), so each module exposes a free function that reads the relevant block from a
6//! [`asterust::config::Config`] rather than a per-block constructor. [`JunosDevice`] bundles a parsed
7//! config with all of them as getters.
8//!
9//! Statements deactivated with `inactive:` are skipped. `| display set` output is not supported.
10
11pub mod bgp;
12pub mod device;
13pub mod firewall;
14pub mod interface;
15pub mod isis;
16pub mod ospf;
17pub mod policy_options;
18pub mod routing_instance;
19pub mod routing_options;
20
21pub use device::JunosDevice;
22
23use asterust::config::{Config, ConfigLine};
24
25/// Drop the quotes JunOS puts around values containing spaces.
26pub(crate) fn unquote(value: &str) -> &str {
27    value.trim().trim_matches('"')
28}
29
30/// Direct children of `line`, minus statements deactivated with `inactive:`.
31pub(crate) fn active_children(line: &ConfigLine) -> impl Iterator<Item = &ConfigLine> {
32    line.children.iter().filter(|c| !c.text.starts_with("inactive:"))
33}
34
35/// Argument of the first active child that is `<keyword> <argument>`.
36pub(crate) fn arg_of<'a>(line: &'a ConfigLine, keyword: &str) -> Option<&'a str> {
37    active_children(line).find_map(|c| c.arg(keyword)).map(unquote)
38}
39
40/// Arguments of every active child that is `<keyword> <argument>`.
41pub(crate) fn args_of<'a>(line: &'a ConfigLine, keyword: &str) -> Vec<&'a str> {
42    active_children(line)
43        .filter_map(|c| c.arg(keyword))
44        .map(unquote)
45        .collect()
46}
47
48/// Whether `line` has an active child that is exactly `name` (a flag such as `passive`).
49pub(crate) fn has_leaf(line: &ConfigLine, name: &str) -> bool {
50    active_children(line).any(|c| c.text == name)
51}
52
53/// Active children written `<keyword> <name>` (as a block or a leaf), with the name.
54pub(crate) fn named_children<'a>(
55    line: &'a ConfigLine,
56    keyword: &'a str,
57) -> impl Iterator<Item = (&'a str, &'a ConfigLine)> {
58    // Names can be quoted, e.g. `neighbor "fe80::20%ge-0/0/1.1";`.
59    active_children(line).filter_map(move |c| Some((unquote(c.arg(keyword)?), c)))
60}
61
62/// The active child that is exactly `name`.
63pub(crate) fn child_block<'a>(line: &'a ConfigLine, name: &str) -> Option<&'a ConfigLine> {
64    active_children(line).find(|c| c.text == name)
65}
66
67/// The top-level block called `name`.
68pub(crate) fn top_level<'a>(config: &'a Config, name: &str) -> Option<&'a ConfigLine> {
69    config.blocks.iter().map(|b| b.get_root_line()).find(|l| l.text == name)
70}
71
72/// Values of a JunOS list: `[ a b ]` or a single bare value. A quoted value may contain spaces.
73pub(crate) fn list_values(arg: &str) -> Vec<String> {
74    let inner = arg.trim().trim_start_matches('[').trim_end_matches(']');
75    let mut values = Vec::new();
76    let mut current = String::new();
77    let mut quoted = false;
78    for ch in inner.chars() {
79        match ch {
80            '"' => quoted = !quoted,
81            c if c.is_whitespace() && !quoted => {
82                if !current.is_empty() {
83                    values.push(std::mem::take(&mut current));
84                }
85            }
86            c => current.push(c),
87        }
88    }
89    if !current.is_empty() {
90        values.push(current);
91    }
92    values
93}
94
95/// Split `<name> <rest>`, where the name may be quoted.
96pub(crate) fn split_name(arg: &str) -> (&str, &str) {
97    if let Some((name, rest)) = arg.strip_prefix('"').and_then(|quoted| quoted.split_once('"')) {
98        return (name, rest.trim());
99    }
100    arg.split_once(char::is_whitespace)
101        .map_or((arg, ""), |(name, rest)| (name, rest.trim()))
102}
103
104/// Split `<keyword> <argument>` into its two parts; the argument is empty for a bare keyword.
105pub(crate) fn split_keyword(statement: &str) -> (&str, &str) {
106    statement
107        .split_once(char::is_whitespace)
108        .map_or((statement, ""), |(keyword, arg)| (keyword, arg.trim()))
109}
110
111/// Statements under `line`'s `keyword` entries, whether written `then x;` or `then { x; y; }`.
112pub(crate) fn statements<'a>(line: &'a ConfigLine, keyword: &str) -> Vec<&'a str> {
113    let mut found = Vec::new();
114    for child in active_children(line) {
115        if child.text == keyword {
116            found.extend(active_children(child).map(|s| s.text.as_str()));
117        } else if let Some(arg) = child.arg(keyword) {
118            found.push(arg);
119        }
120    }
121    found
122}
123
124/// First whitespace-separated word of `arg`.
125pub(crate) fn first_word(arg: &str) -> Option<&str> {
126    arg.split_whitespace().next()
127}