Skip to main content

tilo_actions/tree/
pick.rs

1//! Which node a segment of an address names, and which action a name asks
2//! for: by rank, the best one, or an error naming the several it could be.
3
4use super::{CLOSE_MATCHES, NAMES_LISTED, Node, close_matches};
5use crate::{ActionDescriptor, OperationKind};
6
7/// The names programs give the types of resources: what tells
8/// whether a segment written the way a program types a type (`tasks.Task`)
9/// names a resource of `resource_type`.
10pub trait TypeNames: Send + Sync {
11    /// Whether `name` is what a program calls `resource_type`.
12    fn calls(&self, name: &str, resource_type: &str) -> bool;
13}
14
15/// Whether `segment`, a segment of a path, is written the way a program types a type
16/// (`tasks.Task`): a package's alias, a dot, and a name that begins with a capital letter.
17/// Nothing else is asked of the task's programs: a title, a key or a kind (`notes.notebook`)
18/// is never a program form, so a path that reads one does not start a task's host.
19pub fn is_program_form(segment: &str) -> bool {
20    segment.rsplit_once('.').is_some_and(|(alias, name)| {
21        !alias.is_empty() && name.starts_with(|c: char| c.is_ascii_uppercase())
22    })
23}
24
25/// How well `name`, a segment of a path, names `node`: [`Node::answers_to`]'s rank, and a type
26/// named the way a program types it (`tasks.Task`) is rank 2 too, as its resource type is: a listing
27/// names a resource by that program form, so a name read off a row walks back to the resource.
28pub fn rank(name: &str, node: &Node, types: Option<&dyn TypeNames>) -> Option<u8> {
29    node.answers_to(name).or_else(|| {
30        types
31            .is_some_and(|types| types.calls(name, &node.resource_type))
32            .then_some(2)
33    })
34}
35
36/// Pick the node `name` means among `nodes`: the best-ranked one, when one
37/// is. Several equally good is an error naming them.
38pub fn pick<'a>(
39    name: &str,
40    nodes: &'a [Node],
41    types: Option<&dyn TypeNames>,
42) -> Result<Option<&'a Node>, String> {
43    let ranked: Vec<(u8, &Node)> = nodes
44        .iter()
45        .filter_map(|node| Some((rank(name, node, types)?, node)))
46        .collect();
47    let Some(best) = ranked.iter().map(|(rank, _)| *rank).min() else {
48        return Ok(None);
49    };
50    let mut found: Vec<&Node> = Vec::new();
51    for (_, node) in ranked.iter().filter(|(rank, _)| *rank == best) {
52        if !found.iter().any(|seen| seen.id == node.id) {
53            found.push(node);
54        }
55    }
56    // One that owns the rest (their keys name it) is the one meant: a note,
57    // not the body published beside it under the same title.
58    let owners: Vec<&&Node> = found
59        .iter()
60        .filter(|node| {
61            found
62                .iter()
63                .all(|other| other.id == node.id || node.owns(other))
64        })
65        .collect();
66    if let [owner] = owners.as_slice() {
67        return Ok(Some(**owner));
68    }
69    match found.as_slice() {
70        [one] => Ok(Some(one)),
71        many => Err(format!(
72            "{name} names {} resources: {}; name one by its key",
73            many.len(),
74            many.iter()
75                .take(NAMES_LISTED)
76                .map(|node| format!("{} ({})", node.label.trim(), node.key))
77                .collect::<Vec<_>>()
78                .join(", ")
79        )),
80    }
81}
82
83/// The action `name` means among `actions`: its id, its label, or the one id
84/// that starts with it.
85pub fn pick_action<'a>(
86    name: &str,
87    actions: &'a [ActionDescriptor],
88    at: &str,
89) -> Result<&'a ActionDescriptor, String> {
90    let id = |action: &ActionDescriptor| action.address.action.clone();
91    if let Some(found) = actions
92        .iter()
93        .find(|action| id(action).eq_ignore_ascii_case(name))
94        .or_else(|| {
95            actions
96                .iter()
97                .find(|action| action.action_label.eq_ignore_ascii_case(name))
98        })
99    {
100        return Ok(found);
101    }
102    let lower = name.to_lowercase();
103    let mut starts = actions
104        .iter()
105        .filter(|action| id(action).to_lowercase().starts_with(&lower));
106    if let (Some(only), None) = (starts.next(), starts.next()) {
107        return Ok(only);
108    }
109    let mut ids: Vec<String> = actions.iter().map(id).collect();
110    ids.dedup();
111    // What the caller may have meant, not everything there is: an app with
112    // ninety actions is not told as one wall of names.
113    let close = close_matches(name, &ids, CLOSE_MATCHES);
114    // An empty list is what this caller is offered here, never the app's whole: what the app
115    // offers deeper, or keeps for the person at its device, is not in it.
116    Err(if close.is_empty() {
117        format!("{at} has no action {name}")
118    } else {
119        format!(
120            "{at} has no action {name}; close matches: {}",
121            close.join(", ")
122        )
123    })
124}
125
126/// The one action among `published` whose id is `name`, with its path; `None` when none is or
127/// several resources offer one.
128pub fn only_by_id<'a>(
129    name: &str,
130    published: &'a [(String, ActionDescriptor)],
131) -> Option<(&'a str, &'a ActionDescriptor)> {
132    let mut by_id = published
133        .iter()
134        .filter(|(_, action)| action_rank(name, action) == Some(0));
135    let (path, first) = by_id.next()?;
136    by_id
137        .all(|(_, other)| other.address == first.address)
138        .then_some((path.as_str(), first))
139}
140
141/// How well `name` names `action`: its id, its label, the start of its id,
142/// or not at all.
143pub fn action_rank(name: &str, action: &ActionDescriptor) -> Option<u8> {
144    if action.address.action.eq_ignore_ascii_case(name) {
145        return Some(0);
146    }
147    if action.action_label.eq_ignore_ascii_case(name) {
148        return Some(1);
149    }
150    action
151        .address
152        .action
153        .to_lowercase()
154        .starts_with(&name.to_lowercase())
155        .then_some(2)
156}
157
158/// `picked`, the action `name` was found to mean at `path`, unless `name` is
159/// the word that starts an app (`starts`) and names the action by nothing
160/// but the start of its id: `open` begins `open-link` and is neither its id
161/// nor its label, so it is not that action.
162pub fn named_beyond_its_start(
163    starts: bool,
164    name: &str,
165    path: &str,
166    picked: Result<(String, ActionDescriptor), String>,
167) -> Result<(String, ActionDescriptor), String> {
168    match picked {
169        Ok((_, found)) if starts && action_rank(name, &found) == Some(2) => Err(format!(
170            "{path} has no action {name}; its {} is another action",
171            found.address.action
172        )),
173        picked => picked,
174    }
175}
176
177/// The action that reads a resource, among those its directory level offers:
178/// the one declared to read its document, else one named `read`, else a view
179/// whose action starts with `read` (`read-settings` next to `read`).
180pub fn reads_action(actions: &[ActionDescriptor]) -> Option<ActionDescriptor> {
181    actions
182        .iter()
183        .find(|action| action.contract.reads_document())
184        .or_else(|| {
185            actions
186                .iter()
187                .find(|action| action.address.action == "read")
188        })
189        .or_else(|| {
190            actions.iter().find(|action| {
191                action.kind == OperationKind::View && action.address.action.starts_with("read")
192            })
193        })
194        .cloned()
195}
196
197#[cfg(test)]
198mod tests {
199    use super::{Node, TypeNames, pick};
200
201    fn page(id: &str, label: &str, parent: &str, ordinal: usize) -> Node {
202        Node {
203            id: format!("notes.page:{id}"),
204            resource_type: "notes.page".into(),
205            label: label.into(),
206            key: format!("notes.page:{id}"),
207            parent: parent.into(),
208            ordinal,
209            container: false,
210            actions: Vec::new(),
211        }
212    }
213
214    #[test]
215    fn a_repeated_title_is_named_by_its_place_and_the_path_takes_it() {
216        // Two pages titled alike are named by their places, and that name is a
217        // path back to each: the first keeps the title, the second its place.
218        let nodes = vec![
219            page("aaaaaaaa", "TODO", "notes.pages", 1),
220            page("bbbbbbbb", "TODO", "notes.pages", 2),
221        ];
222        assert_eq!(nodes[0].name(&nodes), "TODO");
223        assert_eq!(nodes[1].name(&nodes), "TODO 2");
224        let id = |name: &str| {
225            pick(name, &nodes, None)
226                .unwrap()
227                .map(|found| found.id.clone())
228        };
229        assert_eq!(id("TODO"), Some("notes.page:aaaaaaaa".into()));
230        assert_eq!(id("TODO 2"), Some("notes.page:bbbbbbbb".into()));
231        assert_eq!(id("TODO 3"), None);
232    }
233
234    #[test]
235    fn a_title_that_names_several_offers_the_keys_that_tell_them_apart() {
236        // A title several resources share is refused with the key each one goes by:
237        // the key is a name the next path can use.
238        let nodes = vec![
239            page("aaaaaaaa", "README", "notes.notebook", 1),
240            page("bbbbbbbb", "README", "notes.notebook", 1),
241        ];
242        let error = pick("README", &nodes, None).unwrap_err();
243        assert_eq!(
244            error,
245            "README names 2 resources: README (notes.page:aaaaaaaa), README (notes.page:bbbbbbbb); \
246         name one by its key"
247        );
248    }
249
250    #[test]
251    fn a_type_written_as_a_program_types_it_names_its_resources() {
252        struct Pages;
253        impl TypeNames for Pages {
254            fn calls(&self, name: &str, resource_type: &str) -> bool {
255                resource_type == "notes.page" && name == "notes.Note"
256            }
257        }
258        let nodes = vec![page("aaaaaaaa", "Todo", "notes.pages", 1)];
259        assert!(pick("notes.Note", &nodes, None).unwrap().is_none());
260        let found = pick("notes.Note", &nodes, Some(&Pages)).unwrap();
261        assert_eq!(
262            found.map(|node| node.id.as_str()),
263            Some("notes.page:aaaaaaaa")
264        );
265    }
266}