1use std::collections::{BTreeMap, BTreeSet};
6
7use serde_json::Value;
8
9use crate::model::{Graph, Node};
10
11#[derive(Debug, Default, PartialEq)]
13pub struct Edit {
14 pub write: Vec<Node>,
16 pub delete: Vec<String>,
18 pub renamed: Vec<(String, String)>,
20}
21
22pub fn id_problem(graph: &Graph, from: &str, to: &str) -> Option<String> {
24 if to.is_empty() {
25 return Some("An id cannot be empty.".into());
26 }
27 if to != to.trim() {
28 return Some("An id cannot start or end with a space.".into());
29 }
30 if to.contains(['/', '\\']) {
31 return Some("An id cannot contain / or \\.".into());
32 }
33 if to.starts_with('.') {
34 return Some("An id cannot start with a dot.".into());
35 }
36 if to.chars().any(char::is_control) {
37 return Some("An id cannot contain control characters.".into());
38 }
39 if to.len() > 200 {
40 return Some("An id is at most 200 characters.".into());
41 }
42 if to != from {
43 if graph.get(to).is_some() {
44 return Some(format!("“{to}” already exists."));
45 }
46 let lower = to.to_lowercase();
47 if graph.nodes().any(|n| n.id != from && n.id.to_lowercase() == lower) {
48 return Some(format!("“{to}” only differs by capitals from an existing id; they would be one file on macOS and Windows."));
49 }
50 }
51 None
52}
53
54struct Work {
56 nodes: BTreeMap<String, Node>,
57 changed: BTreeSet<String>,
58 deleted: BTreeSet<String>,
59 renamed: Vec<(String, String)>,
60}
61
62impl Work {
63 fn new(graph: &Graph) -> Work {
64 Work { nodes: graph.nodes().map(|n| (n.id.clone(), n.clone())).collect(), changed: BTreeSet::new(), deleted: BTreeSet::new(), renamed: Vec::new() }
65 }
66
67 fn finish(self) -> Edit {
68 let write = self.changed.iter().filter_map(|id| self.nodes.get(id).cloned()).collect();
69 Edit { write, delete: self.deleted.into_iter().collect(), renamed: self.renamed }
70 }
71
72 fn rename(&mut self, from: &str, to: &str) {
74 if from == to {
75 return;
76 }
77 let Some(mut node) = self.nodes.remove(from) else { return };
78 self.renamed.push((from.to_string(), to.to_string()));
79 let is_plane = node.kind.as_deref() == Some("plane");
80 node.id = to.to_string();
81 self.nodes.insert(to.to_string(), node);
82 self.changed.remove(from);
83 self.changed.insert(to.to_string());
84 if !self.deleted.remove(to) {
85 self.deleted.insert(from.to_string());
86 }
87 for (id, m) in self.nodes.iter_mut() {
88 let mut hit = false;
89 if m.parent.as_deref() == Some(from) {
90 m.parent = Some(to.to_string());
91 hit = true;
92 }
93 if is_plane && m.plane.as_deref() == Some(from) {
94 m.plane = Some(to.to_string());
95 hit = true;
96 }
97 for l in m.links.iter_mut().filter(|l| l.to == from) {
98 l.to = to.to_string();
99 hit = true;
100 }
101 if m.kind.as_deref() == Some("rule") {
102 for key in ["applies_to", "check"] {
103 if let Some(v) = m.fields.get_mut(key) {
104 hit |= rewrite_ids(v, from, to, is_plane, "");
105 }
106 }
107 }
108 if hit {
109 self.changed.insert(id.clone());
110 }
111 }
112 }
113
114 fn touch(&mut self, id: &str) {
115 self.changed.insert(id.to_string());
116 }
117}
118
119const PLANE_KEYS: [&str; 3] = ["plane", "node_plane", "to_plane"];
120
121fn rewrite_ids(v: &mut Value, from: &str, to: &str, is_plane: bool, key: &str) -> bool {
123 match v {
124 Value::String(s) => {
125 if s == from && (key == "under" || (is_plane && PLANE_KEYS.contains(&key))) {
126 *s = to.to_string();
127 true
128 } else {
129 false
130 }
131 }
132 Value::Array(a) => a.iter_mut().fold(false, |h, x| rewrite_ids(x, from, to, is_plane, key) | h),
133 Value::Object(o) => o.iter_mut().fold(false, |h, (k, x)| rewrite_ids(x, from, to, is_plane, k) | h),
134 _ => false,
135 }
136}
137
138pub fn rename_node(graph: &Graph, from: &str, to: &str) -> Result<Edit, String> {
140 let to = to.trim();
141 if let Some(p) = id_problem(graph, from, to) {
142 return Err(p);
143 }
144 if graph.get(from).is_none() {
145 return Err(format!("“{from}” does not exist."));
146 }
147 let mut w = Work::new(graph);
148 w.rename(from, to);
149 Ok(w.finish())
150}
151
152fn rename_in(v: &mut Value, keys: &[&str], old: &str, new: &str) -> bool {
154 match v {
155 Value::Array(a) => a.iter_mut().fold(false, |h, x| rename_in(x, keys, old, new) | h),
156 Value::Object(o) => o.iter_mut().fold(false, |h, (k, x)| {
157 if keys.contains(&k.as_str()) && x.as_str() == Some(old) {
158 *x = Value::String(new.to_string());
159 true | h
160 } else {
161 rename_in(x, keys, old, new) | h
162 }
163 }),
164 _ => false,
165 }
166}
167
168fn rename_link_in(check: &mut Value, old: &str, new: &str) -> bool {
170 let Some(c) = check.as_object_mut() else { return false };
171 let mut hit = false;
172 for key in ["require_link", "forbid_link", "path", "require_link_fields"] {
173 let items: Vec<&mut Value> = match c.get_mut(key) {
174 Some(Value::Array(a)) => a.iter_mut().collect(),
175 Some(v @ Value::Object(_)) => vec![v],
176 _ => vec![],
177 };
178 for it in items {
179 if let Some(t) = it.get_mut("type").filter(|t| t.as_str() == Some(old)) {
180 *t = Value::String(new.to_string());
181 hit = true;
182 }
183 }
184 }
185 match c.get_mut("acyclic") {
186 Some(a @ Value::String(_)) if a.as_str() == Some(old) => {
187 *a = Value::String(new.to_string());
188 hit = true;
189 }
190 Some(Value::Array(a)) => {
191 for t in a.iter_mut().filter(|t| t.as_str() == Some(old)) {
192 *t = Value::String(new.to_string());
193 hit = true;
194 }
195 }
196 _ => {}
197 }
198 hit
199}
200
201fn followed_id(id: &str, old: &str, new: &str) -> Option<String> {
203 let (ns, local) = match id.split_once("--") {
204 Some((ns, local)) => (format!("{ns}--"), local),
205 None => (String::new(), id),
206 };
207 local.strip_prefix(&format!("{old}-")).map(|rest| format!("{ns}{new}-{rest}"))
208}
209
210pub fn rename_def(graph: &Graph, def_id: &str, name: &str, ids: bool) -> Result<Edit, String> {
214 let def = graph.get(def_id).ok_or(format!("“{def_id}” does not exist."))?;
215 let kind = def.kind.clone().unwrap_or_default();
216 if kind != "type" && kind != "link-type" {
217 return Err(format!("“{def_id}” is not a type or a link type."));
218 }
219 let old = def.fields.get("name").and_then(Value::as_str).unwrap_or("").to_string();
220 let new = if name.trim().is_empty() { def.id.clone() } else { name.trim().to_string() };
221 if new == old {
222 return Ok(Edit::default());
223 }
224 if graph.nodes().any(|n| n.id != def_id && n.kind.as_deref() == Some(kind.as_str()) && n.fields.get("name").and_then(Value::as_str) == Some(new.as_str())) {
225 return Err(format!("There is already a {} called “{new}”.", if kind == "type" { "type" } else { "link type" }));
226 }
227 let mut w = Work::new(graph);
228 {
229 let d = w.nodes.get_mut(def_id).expect("it was just read");
230 d.fields.insert("name".into(), Value::String(new.clone()));
231 d.title = new.clone();
232 }
233 w.touch(def_id);
234 let ids_of = |w: &Work| w.nodes.keys().cloned().collect::<Vec<_>>();
235 if kind == "type" {
236 let mut moved = Vec::new();
237 for id in ids_of(&w) {
238 let n = w.nodes.get_mut(&id).expect("listed");
239 match n.kind.as_deref() {
240 Some(k) if k == old => {
241 n.kind = Some(new.clone());
242 moved.push(id.clone());
243 w.changed.insert(id);
244 }
245 Some("rule") => {
246 let mut hit = false;
247 if let Some(a) = n.fields.get_mut("applies_to").and_then(Value::as_object_mut) {
248 if a.get("type").and_then(Value::as_str) == Some(old.as_str()) {
249 a.insert("type".into(), Value::String(new.clone()));
250 hit = true;
251 }
252 }
253 if let Some(c) = n.fields.get_mut("check") {
254 hit |= rename_in(c, &["node_type", "to_type", "ancestor_type"], &old, &new);
255 }
256 if hit {
257 w.changed.insert(id);
258 }
259 }
260 Some("link-type") => {
261 let mut hit = false;
262 for key in ["from", "to"] {
263 if let Some(Value::Array(a)) = n.fields.get_mut(key) {
264 for t in a.iter_mut().filter(|t| t.as_str() == Some(old.as_str())) {
265 *t = Value::String(new.clone());
266 hit = true;
267 }
268 }
269 }
270 if hit {
271 w.changed.insert(id);
272 }
273 }
274 _ => {}
275 }
276 }
277 if ids {
278 for id in moved {
279 if let Some(to) = followed_id(&id, &old, &new) {
280 if id_problem(graph, &id, &to).is_none() && !w.nodes.contains_key(&to) {
281 w.rename(&id, &to);
282 }
283 }
284 }
285 }
286 } else {
287 for id in ids_of(&w) {
288 let n = w.nodes.get_mut(&id).expect("listed");
289 let mut hit = false;
290 for l in n.links.iter_mut().filter(|l| l.kind == old) {
291 l.kind = new.clone();
292 hit = true;
293 }
294 if n.kind.as_deref() == Some("rule") {
295 if let Some(c) = n.fields.get_mut("check") {
296 hit |= rename_link_in(c, &old, &new);
297 }
298 }
299 if hit {
300 w.changed.insert(id);
301 }
302 }
303 }
304 Ok(w.finish())
305}
306
307#[cfg(test)]
308mod tests {
309 use super::*;
310 use crate::load::load;
311
312 fn graph(files: &[(&str, &str)]) -> Graph {
313 load(files.iter().map(|(p, t)| (p.to_string(), t.to_string())).collect()).0
314 }
315
316 const MODEL: &[(&str, &str)] = &[
317 ("type-table.md", "---\nid: type-table\ntype: type\nfields: {name: table}\n---\n"),
318 ("link-type-contains.md", "---\nid: link-type-contains\ntype: link-type\nfields: {name: contains, from: [table], to: [column]}\n---\n"),
319 ("table-a.md", "---\nid: table-a\ntype: table\nlinks: [{type: contains, to: column-x}]\n---\n"),
320 ("column-x.md", "---\nid: column-x\ntype: column\nparent: table-a\n---\n"),
321 ("r.md", "---\nid: r\ntype: rule\nfields: {applies_to: {type: table, under: table-a}, check: {require_link: [{type: contains, node_type: column}], acyclic: contains}}\n---\n"),
322 ("p.md", "---\nid: p\ntype: plane\n---\n"),
323 ("m.md", "---\nid: m\ntype: component\nplane: p\n---\n"),
324 ];
325
326 #[test]
327 fn renames_a_node_everywhere_it_is_named() {
328 let g = graph(MODEL);
329 let e = rename_node(&g, "table-a", "tbl-a").unwrap();
330 assert_eq!(e.delete, vec!["table-a".to_string()]);
331 let ids: Vec<_> = e.write.iter().map(|n| n.id.as_str()).collect();
332 assert_eq!(ids, ["column-x", "r", "tbl-a"]);
333 let col = e.write.iter().find(|n| n.id == "column-x").unwrap();
334 assert_eq!(col.parent.as_deref(), Some("tbl-a"));
335 let r = e.write.iter().find(|n| n.id == "r").unwrap();
336 assert_eq!(r.fields["applies_to"]["under"], "tbl-a");
337 }
338
339 #[test]
340 fn renames_a_plane_and_its_members() {
341 let e = rename_node(&graph(MODEL), "p", "layer").unwrap();
342 assert_eq!(e.write.iter().find(|n| n.id == "m").unwrap().plane.as_deref(), Some("layer"));
343 }
344
345 #[test]
346 fn refuses_a_bad_or_taken_id() {
347 let g = graph(MODEL);
348 assert!(rename_node(&g, "table-a", "column-x").unwrap_err().contains("already exists"));
349 assert!(rename_node(&g, "table-a", "Column-X").unwrap_err().contains("capitals"));
350 assert!(rename_node(&g, "table-a", "a/b").is_err());
351 assert!(rename_node(&g, "nope", "x").unwrap_err().contains("does not exist"));
352 }
353
354 #[test]
355 fn renames_a_type_and_its_users() {
356 let e = rename_def(&graph(MODEL), "type-table", "data-table", true).unwrap();
357 let by = |id: &str| e.write.iter().find(|n| n.id == id).unwrap_or_else(|| panic!("{id} not written"));
358 assert_eq!(by("type-table").fields["name"], "data-table");
359 assert_eq!(by("data-table-a").kind.as_deref(), Some("data-table"));
360 assert_eq!(by("column-x").parent.as_deref(), Some("data-table-a"));
361 assert_eq!(by("r").fields["applies_to"]["type"], "data-table");
362 assert_eq!(by("link-type-contains").fields["from"][0], "data-table");
363 assert!(e.delete.contains(&"table-a".to_string()));
364 }
365
366 #[test]
367 fn without_ids_the_ids_stay() {
368 let e = rename_def(&graph(MODEL), "type-table", "data-table", false).unwrap();
369 assert!(e.delete.is_empty());
370 assert_eq!(e.write.iter().find(|n| n.id == "table-a").unwrap().kind.as_deref(), Some("data-table"));
371 }
372
373 #[test]
374 fn renames_a_link_type_in_links_and_checks() {
375 let e = rename_def(&graph(MODEL), "link-type-contains", "holds", false).unwrap();
376 let by = |id: &str| e.write.iter().find(|n| n.id == id).unwrap();
377 assert_eq!(by("table-a").links[0].kind, "holds");
378 assert_eq!(by("r").fields["check"]["require_link"][0]["type"], "holds");
379 assert_eq!(by("r").fields["check"]["acyclic"], "holds");
380 }
381
382 #[test]
383 fn refuses_a_name_that_is_taken_and_does_nothing_for_the_same_name() {
384 let g = graph(MODEL);
385 assert!(rename_def(&g, "type-table", "table", false).unwrap().write.is_empty());
386 let mut files: Vec<(&str, &str)> = MODEL.to_vec();
387 files.push(("type-column.md", "---\nid: type-column\ntype: type\nfields: {name: column}\n---\n"));
388 assert!(rename_def(&graph(&files), "type-table", "column", false).unwrap_err().contains("already a type"));
389 assert!(rename_def(&g, "table-a", "x", false).unwrap_err().contains("not a type"));
390 }
391}