Skip to main content

tilo_actions/tree/
address.rs

1//! An address, taken apart: the resources it walks, each inside the one
2//! before, and the action after `#` (`notes/Todo/body#append-paragraph`).
3
4/// One step of an address: the name of a resource among the others under its parent, and
5/// what it is pinned to after `@` (`browser@4711`, one window of an app), when
6/// anything is.
7#[derive(Clone, Debug, PartialEq, Eq)]
8pub struct Segment {
9    /// The name as written before the pin.
10    pub name: String,
11    /// What follows the last unescaped `@`, as written.
12    pub pin: Option<String>,
13}
14
15impl Segment {
16    /// A segment that is `name` whole, pinned to nothing.
17    #[must_use]
18    pub fn named(name: impl Into<String>) -> Self {
19        Self {
20            name: name.into(),
21            pin: None,
22        }
23    }
24
25    /// The segment as it was written: its name, then `@` and its pin.
26    #[must_use]
27    pub fn written(&self) -> String {
28        match &self.pin {
29            Some(pin) => format!("{}@{pin}", self.name),
30            None => self.name.clone(),
31        }
32    }
33}
34
35/// A path of resources, each inside the one before, and the action it ends
36/// in, if it names one.
37#[derive(Clone, Debug, PartialEq, Eq)]
38pub struct Address {
39    /// The resources walked, outermost first; never empty once parsed.
40    pub segments: Vec<Segment>,
41    /// The action after `#`.
42    pub action: Option<String>,
43}
44
45impl Address {
46    /// Parse `text`. A name containing `/`, `#` or `\` writes it with a
47    /// leading backslash; an `@` written so is part of the name, not a pin.
48    ///
49    /// # Errors
50    /// `text` names no resource.
51    pub fn parse(text: &str) -> Result<Self, String> {
52        // Each part as written, and the place of its last unescaped `@`.
53        let mut parts: Vec<(String, Option<usize>)> = vec![(String::new(), None)];
54        let mut action = String::new();
55        let mut in_action = false;
56        let mut escaped = false;
57        for character in text.trim().chars() {
58            if escaped {
59                escaped = false;
60                push_char(&mut parts, &mut action, in_action, character);
61                continue;
62            }
63            match character {
64                '\\' => escaped = true,
65                '#' if !in_action => in_action = true,
66                '/' if !in_action => parts.push((String::new(), None)),
67                '@' if !in_action => {
68                    if let Some((part, pin)) = parts.last_mut() {
69                        *pin = Some(part.len());
70                        part.push('@');
71                    }
72                }
73                other => push_char(&mut parts, &mut action, in_action, other),
74            }
75        }
76        let action = in_action
77            .then_some(action)
78            .map(|action| action.trim().to_owned())
79            .filter(|action| !action.is_empty());
80        let segments: Vec<Segment> = parts
81            .into_iter()
82            .filter_map(|(part, pin)| segment(&part, pin))
83            .collect();
84        if segments.is_empty() {
85            return Err("a path starts with an app: notes/Todo".to_owned());
86        }
87        Ok(Self { segments, action })
88    }
89
90    /// The address as it names a resource, whole: every segment as written,
91    /// without an action after `#`.
92    #[must_use]
93    pub fn resource(&self) -> String {
94        self.segments
95            .iter()
96            .map(Segment::written)
97            .collect::<Vec<_>>()
98            .join("/")
99    }
100}
101
102/// The segment `part` is, trimmed as a whole, with its pin split off at
103/// `pin`; `None` for a part that is blank.
104fn segment(part: &str, pin: Option<usize>) -> Option<Segment> {
105    let start = part.len().saturating_sub(part.trim_start().len());
106    let trimmed = part.trim();
107    if trimmed.is_empty() {
108        return None;
109    }
110    let pin = pin
111        .and_then(|at| at.checked_sub(start))
112        .filter(|at| *at < trimmed.len());
113    Some(match pin {
114        Some(at) => Segment {
115            name: trimmed.get(..at).unwrap_or_default().to_owned(),
116            pin: Some(
117                trimmed
118                    .get(at.saturating_add(1)..)
119                    .unwrap_or_default()
120                    .to_owned(),
121            ),
122        },
123        None => Segment::named(trimmed),
124    })
125}
126
127fn push_char(
128    parts: &mut [(String, Option<usize>)],
129    action: &mut String,
130    in_action: bool,
131    character: char,
132) {
133    if in_action {
134        action.push(character);
135    } else if let Some((part, _)) = parts.last_mut() {
136        part.push(character);
137    }
138}
139
140#[cfg(test)]
141mod tests {
142    use super::{Address, Segment};
143
144    #[test]
145    fn an_address_is_resources_and_an_action() {
146        assert_eq!(
147            Address::parse("notes/Todo/body#append-paragraph").unwrap(),
148            Address {
149                segments: vec![
150                    Segment::named("notes"),
151                    Segment::named("Todo"),
152                    Segment::named("body")
153                ],
154                action: Some("append-paragraph".into()),
155            }
156        );
157        assert_eq!(
158            Address::parse("  notes ").unwrap(),
159            Address {
160                segments: vec![Segment::named("notes")],
161                action: None,
162            }
163        );
164        // A title with a slash or a hash writes it escaped.
165        let parsed = Address::parse(r"notes/Q1\/Q2 plan\#1#rename").unwrap();
166        assert_eq!(parsed.segments[1], Segment::named("Q1/Q2 plan#1"));
167        assert_eq!(parsed.action.as_deref(), Some("rename"));
168        assert_eq!(super::super::path_name("Q1/Q2 plan#1"), r"Q1\/Q2 plan\#1");
169        assert!(Address::parse("").is_err());
170        assert!(Address::parse("#rename").is_err());
171    }
172
173    #[test]
174    fn a_pin_follows_the_last_at_and_writes_back_as_it_was() {
175        let parsed = Address::parse("browser@4711/page#read-page").unwrap();
176        assert_eq!(
177            parsed.segments[0],
178            Segment {
179                name: "browser".into(),
180                pin: Some("4711".into()),
181            }
182        );
183        assert_eq!(parsed.resource(), "browser@4711/page");
184        // An escaped `@` is part of the name, and every form writes back whole.
185        for written in ["a@b@c", r"me\@example.com", "notes@", "notes @ 1", "@x"] {
186            let parsed = Address::parse(written).unwrap();
187            assert_eq!(parsed.resource(), written.replace('\\', ""), "{written}");
188        }
189        assert_eq!(
190            Address::parse(r"me\@example.com").unwrap().segments[0],
191            Segment::named("me@example.com")
192        );
193        assert_eq!(
194            Address::parse("a@b@c").unwrap().segments[0].pin.as_deref(),
195            Some("c")
196        );
197    }
198}