1use super::{CLOSE_MATCHES, NAMES_LISTED, Node, close_matches};
5use crate::{ActionDescriptor, OperationKind};
6
7pub trait TypeNames: Send + Sync {
11 fn calls(&self, name: &str, resource_type: &str) -> bool;
13}
14
15pub 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
25pub 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
36pub 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 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
83pub 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 let close = close_matches(name, &ids, CLOSE_MATCHES);
114 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
126pub 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
141pub 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
158pub 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
177pub 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 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 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}