intelli_shell/utils/
variable.rs

1use std::sync::LazyLock;
2
3use regex::{CaptureMatches, Captures, Regex};
4
5const VARIABLE_REGEX: &str = r"\{\{((?:\{[^}]+\}|[^}]+))\}\}";
6const ALT_VARIABLE_REGEX: &str = r"<([\w.*-]+)>";
7
8// Regex to match exclusively variables in the alternative syntax `<name>`
9static ALT_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(ALT_VARIABLE_REGEX).unwrap());
10
11/// Regex to match variables from a command, with a capturing group for the name
12pub static COMMAND_VARIABLE_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(VARIABLE_REGEX).unwrap());
13
14/// Regex to match variables from a command, with two capturing groups for the name
15/// - Group 1: Will exist if intelli-shell's variable syntax like `{{name}}` is matched
16/// - Group 2: Will exist if an alternative syntax like `<name>` is matched
17pub static COMMAND_VARIABLE_REGEX_ALT: LazyLock<Regex> =
18    LazyLock::new(|| Regex::new(&format!(r#"{VARIABLE_REGEX}|{ALT_VARIABLE_REGEX}"#)).unwrap());
19
20/// Regex to match variables from a command, with a capturing group for the name.
21///
22/// This regex identifies if variables are unquoted, single-quoted, or double-quoted:
23/// - Group 1: Will exist if a single-quoted placeholder like '{{name}}' is matched
24/// - Group 2: Will exist if a double-quoted placeholder like "{{name}}" is matched
25/// - Group 3: Will exist if an unquoted placeholder like {{name}} is matched
26pub static COMMAND_VARIABLE_REGEX_QUOTES: LazyLock<Regex> =
27    LazyLock::new(|| Regex::new(&format!(r#"'{VARIABLE_REGEX}'|"{VARIABLE_REGEX}"|{VARIABLE_REGEX}"#)).unwrap());
28
29/// Converts alternative variable syntax `<var>` to the regular `{{var}}` syntax
30pub fn convert_alt_to_regular(command: &str) -> String {
31    ALT_REGEX.replace_all(command, "{{$1}}").into_owned()
32}
33
34/// An iterator that splits a text string based on a regular expression, yielding both the substrings that _don't_ match
35/// the regex and the `Captures` objects for the parts that _do_ match.
36///
37/// This is useful when you need to process parts of a string separated by delimiters defined by a regex, but you also
38/// need access to the captured groups within those delimiters.
39///
40/// # Examples
41///
42/// ```rust
43/// # use intelli_shell::utils::{SplitCaptures, SplitItem};
44/// # use regex::Regex;
45/// let regex = Regex::new(r"\{(\w+)\}").unwrap();
46/// let text = "Hello {name}, welcome to {place}!";
47/// let mut parts = vec![];
48/// for item in SplitCaptures::new(&regex, text) {
49///     match item {
50///         SplitItem::Unmatched(s) => parts.push(format!("Unmatched: '{}'", s)),
51///         SplitItem::Captured(caps) => {
52///             parts.push(format!("Captured: '{}', Group 1: '{}'", &caps[0], &caps[1]))
53///         }
54///     }
55/// }
56/// assert_eq!(
57///     parts,
58///     vec![
59///         "Unmatched: 'Hello '",
60///         "Captured: '{name}', Group 1: 'name'",
61///         "Unmatched: ', welcome to '",
62///         "Captured: '{place}', Group 1: 'place'",
63///         "Unmatched: '!'",
64///     ]
65/// );
66/// ```
67pub struct SplitCaptures<'r, 't> {
68    /// Iterator over regex captures
69    finder: CaptureMatches<'r, 't>,
70    /// The original text being split
71    text: &'t str,
72    /// The byte index marking the end of the last match/unmatched part
73    last: usize,
74    /// Holds the captures of the _next_ match to be returned
75    caps: Option<Captures<'t>>,
76}
77
78impl<'r, 't> SplitCaptures<'r, 't> {
79    /// Creates a new [SplitCaptures] iterator.
80    pub fn new(regex: &'r Regex, text: &'t str) -> SplitCaptures<'r, 't> {
81        SplitCaptures {
82            finder: regex.captures_iter(text),
83            text,
84            last: 0,
85            caps: None,
86        }
87    }
88}
89
90/// Represents an item yielded by the [SplitCaptures] iterator.
91///
92/// It can be either a part of the string that did not match the regex ([Unmatched](SplitItem::Unmatched)) or the
93/// [Captures] object from a part that did match ([Captured](SplitItem::Captured)).
94#[derive(Debug)]
95pub enum SplitItem<'t> {
96    /// A string slice that did not match the regex separator
97    Unmatched(&'t str),
98    /// The [Captures] object resulting from a regex match
99    Captured(Captures<'t>),
100}
101
102impl<'t> Iterator for SplitCaptures<'_, 't> {
103    type Item = SplitItem<'t>;
104
105    /// Advances the iterator, returning the next unmatched slice or captured group.
106    ///
107    /// The iterator alternates between returning `SplitItem::Unmatched` and `SplitItem::Captured`,
108    /// starting and ending with `Unmatched` (unless the string is empty or fully matched).
109    fn next(&mut self) -> Option<SplitItem<'t>> {
110        // If we have pending captures from the previous iteration, return them now
111        if let Some(caps) = self.caps.take() {
112            return Some(SplitItem::Captured(caps));
113        }
114        // Find the next match using the internal captures iterator
115        match self.finder.next() {
116            // No more matches found
117            None => {
118                if self.last >= self.text.len() {
119                    None
120                } else {
121                    // If there's remaining text after the last match (or if the string was never matched), return it.
122                    // Get the final unmatched slice
123                    let s = &self.text[self.last..];
124                    // Mark the end of the string as processed
125                    self.last = self.text.len();
126                    Some(SplitItem::Unmatched(s))
127                }
128            }
129            // A match was found
130            Some(caps) => {
131                // Get the match bounds
132                let m = caps.get(0).unwrap();
133                // Extract the text between the end of the last item and the start of this match
134                let unmatched = &self.text[self.last..m.start()];
135                // Update the position to the end of the current match
136                self.last = m.end();
137                // Store the captures to be returned in the next iteration
138                self.caps = Some(caps);
139                // Return the unmatched part before the captures
140                Some(SplitItem::Unmatched(unmatched))
141            }
142        }
143    }
144}