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`, `system`), 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;
20pub mod system;
21
22pub use device::JunosDevice;
23
24use asterust::config::{Config, ConfigLine};
25
26/// Drop the quotes JunOS puts around values containing spaces.
27pub(crate) fn unquote(value: &str) -> &str {
28    value.trim().trim_matches('"')
29}
30
31/// Direct children of `line`, minus statements deactivated with `inactive:`.
32pub(crate) fn active_children(line: &ConfigLine) -> impl Iterator<Item = &ConfigLine> {
33    line.children.iter().filter(|c| !c.text.starts_with("inactive:"))
34}
35
36/// Argument of the first active child that is `<keyword> <argument>`.
37pub(crate) fn arg_of<'a>(line: &'a ConfigLine, keyword: &str) -> Option<&'a str> {
38    active_children(line).find_map(|c| c.arg(keyword)).map(unquote)
39}
40
41/// Arguments of every active child that is `<keyword> <argument>`.
42pub(crate) fn args_of<'a>(line: &'a ConfigLine, keyword: &str) -> Vec<&'a str> {
43    active_children(line)
44        .filter_map(|c| c.arg(keyword))
45        .map(unquote)
46        .collect()
47}
48
49/// Whether `line` has an active child that is exactly `name` (a flag such as `passive`).
50pub(crate) fn has_leaf(line: &ConfigLine, name: &str) -> bool {
51    active_children(line).any(|c| c.text == name)
52}
53
54/// Active children written `<keyword> <name>` (as a block or a leaf), with the name.
55pub(crate) fn named_children<'a>(
56    line: &'a ConfigLine,
57    keyword: &'a str,
58) -> impl Iterator<Item = (&'a str, &'a ConfigLine)> {
59    // Names can be quoted, e.g. `neighbor "fe80::20%ge-0/0/1.1";`.
60    active_children(line).filter_map(move |c| Some((unquote(c.arg(keyword)?), c)))
61}
62
63/// The active child that is exactly `name`.
64pub(crate) fn child_block<'a>(line: &'a ConfigLine, name: &str) -> Option<&'a ConfigLine> {
65    active_children(line).find(|c| c.text == name)
66}
67
68/// The top-level block called `name`.
69pub(crate) fn top_level<'a>(config: &'a Config, name: &str) -> Option<&'a ConfigLine> {
70    config.blocks.iter().map(|b| b.get_root_line()).find(|l| l.text == name)
71}
72
73/// Values of a JunOS list: `[ a b ]` or a single bare value. A quoted value may contain spaces.
74pub(crate) fn list_values(arg: &str) -> Vec<String> {
75    let inner = arg.trim().trim_start_matches('[').trim_end_matches(']');
76    let mut values = Vec::new();
77    let mut current = String::new();
78    let mut quoted = false;
79    for ch in inner.chars() {
80        match ch {
81            '"' => quoted = !quoted,
82            c if c.is_whitespace() && !quoted => {
83                if !current.is_empty() {
84                    values.push(std::mem::take(&mut current));
85                }
86            }
87            c => current.push(c),
88        }
89    }
90    if !current.is_empty() {
91        values.push(current);
92    }
93    values
94}
95
96/// Split `<name> <rest>`, where the name may be quoted.
97pub(crate) fn split_name(arg: &str) -> (&str, &str) {
98    if let Some((name, rest)) = arg.strip_prefix('"').and_then(|quoted| quoted.split_once('"')) {
99        return (name, rest.trim());
100    }
101    arg.split_once(char::is_whitespace)
102        .map_or((arg, ""), |(name, rest)| (name, rest.trim()))
103}
104
105/// Split `<keyword> <argument>` into its two parts; the argument is empty for a bare keyword.
106pub(crate) fn split_keyword(statement: &str) -> (&str, &str) {
107    statement
108        .split_once(char::is_whitespace)
109        .map_or((statement, ""), |(keyword, arg)| (keyword, arg.trim()))
110}
111
112/// Statements under `line`'s `keyword` entries, whether written `then x;` or `then { x; y; }`.
113pub(crate) fn statements<'a>(line: &'a ConfigLine, keyword: &str) -> Vec<&'a str> {
114    let mut found = Vec::new();
115    for child in active_children(line) {
116        if child.text == keyword {
117            found.extend(active_children(child).map(|s| s.text.as_str()));
118        } else if let Some(arg) = child.arg(keyword) {
119            found.push(arg);
120        }
121    }
122    found
123}
124
125/// Words of the first active `<keyword> ...` statement: those on its own line, then those of each child statement.
126pub(crate) fn statement_words<'a>(parent: &'a ConfigLine, keyword: &str) -> Option<Vec<&'a str>> {
127    let statement = active_children(parent).find(|c| c.text == keyword || c.arg(keyword).is_some())?;
128    Some(
129        statement
130            .text
131            .split_whitespace()
132            .skip(1)
133            .chain(active_children(statement).flat_map(|c| c.text.split_whitespace()))
134            .collect(),
135    )
136}
137
138/// The word after the first occurrence of `name` in `words`.
139pub(crate) fn value_after(words: &[&str], name: &str) -> Option<String> {
140    let position = words.iter().position(|w| *w == name)?;
141    words.get(position + 1).map(|w| w.to_string())
142}
143
144/// First whitespace-separated word of `arg`.
145pub(crate) fn first_word(arg: &str) -> Option<&str> {
146    arg.split_whitespace().next()
147}