Skip to main content

artifactize_core/config/edit/
annotations.rs

1//! Lossless writes to annotations. Only the known keys of the section being written
2//! are validated; unrelated and future data is never reserialized or discarded.
3use super::*;
4use toml_edit::{DocumentMut, Item, Table, TableLike};
5
6pub type Point = [f64; 2];
7#[derive(Debug, Default, Clone, Serialize)]
8#[serde(rename_all = "camelCase")]
9pub struct Annotations {
10    pub at: Option<Point>,
11    pub parts: BTreeMap<ArtifactName, Point>,
12    pub comment: Option<String>,
13    pub style_error: Option<String>,
14    pub comment_error: Option<String>,
15}
16fn section<'a>(doc: &'a DocumentMut, key: &str) -> Result<Option<&'a dyn TableLike>, String> {
17    let Some(annotations) = doc.get("annotations") else {
18        return Ok(None);
19    };
20    let annotations = annotations
21        .as_table_like()
22        .ok_or("annotations must be a table")?;
23    annotations
24        .get(key)
25        .map(|item| {
26            item.as_table_like()
27                .ok_or_else(|| format!("annotations.{key} must be a table"))
28        })
29        .transpose()
30}
31fn point(item: &Item) -> Result<Point, String> {
32    let array = item.as_array().ok_or("a place must be [x, y]")?;
33    if array.len() != 2 {
34        return Err("a place must have two coordinates".into());
35    }
36    let number = |index| {
37        array
38            .get(index)
39            .and_then(|value| {
40                value
41                    .as_float()
42                    .or_else(|| value.as_integer().map(|number| number as f64))
43            })
44            .filter(|number| number.is_finite())
45            .ok_or_else(|| "coordinates must be finite numbers".to_owned())
46    };
47    Ok([number(0)?, number(1)?])
48}
49fn top_level(config: &RepoConfig, name: &ArtifactName) -> bool {
50    !config
51        .artifacts
52        .values()
53        .any(|artifact| artifact.parts.contains(name))
54}
55fn style(
56    doc: &DocumentMut,
57    config: &RepoConfig,
58    name: &ArtifactName,
59) -> Result<(Option<Point>, BTreeMap<ArtifactName, Point>), String> {
60    let Some(style) = section(doc, "style")? else {
61        return Ok((None, BTreeMap::new()));
62    };
63    Ok((
64        style_at(style, config, name)?,
65        style_parts(style, config, name)?,
66    ))
67}
68fn style_at(
69    style: &dyn TableLike,
70    config: &RepoConfig,
71    name: &ArtifactName,
72) -> Result<Option<Point>, String> {
73    if top_level(config, name) {
74        style.get("at").map(point).transpose()
75    } else {
76        Ok(None)
77    }
78}
79fn style_parts(
80    style: &dyn TableLike,
81    config: &RepoConfig,
82    name: &ArtifactName,
83) -> Result<BTreeMap<ArtifactName, Point>, String> {
84    match style.get("parts") {
85        None => Ok(BTreeMap::new()),
86        Some(parts) => parts
87            .as_table_like()
88            .ok_or("annotations.style.parts must be a table")?
89            .iter()
90            .filter(|(part, _)| {
91                config.artifacts[name]
92                    .parts
93                    .iter()
94                    .any(|name| name.as_str() == *part)
95            })
96            .map(|(part, value)| Ok((part.parse().expect("configured part"), point(value)?)))
97            .collect(),
98    }
99}
100fn comment(doc: &DocumentMut) -> Result<Option<String>, String> {
101    section(doc, "comment")?
102        .and_then(|section| section.get("text"))
103        .map(|item| {
104            item.as_str()
105                .map(str::to_owned)
106                .ok_or_else(|| "annotations.comment.text must be a string".to_owned())
107        })
108        .transpose()
109        .map(|text| text.filter(|text| !text.is_empty()))
110}
111pub(super) fn read(source: &str, config: &RepoConfig, name: &ArtifactName) -> Annotations {
112    let doc = source.parse::<DocumentMut>().expect("validated TOML");
113    let mut annotations = Annotations::default();
114    match section(&doc, "style") {
115        Ok(Some(style)) => {
116            // A node's parent-box place and its own box are independent for drawing.
117            match style_at(style, config, name) {
118                Ok(at) => annotations.at = at,
119                Err(error) => annotations.style_error = Some(error),
120            }
121            match style_parts(style, config, name) {
122                Ok(parts) => annotations.parts = parts,
123                Err(error) => annotations.style_error = Some(error),
124            }
125        }
126        Ok(None) => (),
127        Err(error) => annotations.style_error = Some(error),
128    }
129    match comment(&doc) {
130        Ok(text) => annotations.comment = text,
131        Err(error) => annotations.comment_error = Some(error),
132    }
133    annotations
134}
135fn invalid(doc: &DocumentMut, file: &Path, section: &str, message: String) -> Refusal {
136    let source = doc.to_string();
137    ConfigError::new(
138        file,
139        location::error_at(&source, &["annotations", section], &message),
140    )
141    .into()
142}
143fn section_mut<'a>(doc: &'a mut DocumentMut, key: &str) -> &'a mut dyn TableLike {
144    if doc.get("annotations").is_none() {
145        let mut table = Table::new();
146        table.set_implicit(true);
147        doc["annotations"] = Item::Table(table);
148    }
149    let annotations = doc["annotations"]
150        .as_table_like_mut()
151        .expect("validated annotation table");
152    if annotations.get(key).is_none() {
153        annotations.insert(key, Item::Table(Table::new()));
154    }
155    annotations
156        .get_mut(key)
157        .expect("section inserted")
158        .as_table_like_mut()
159        .expect("validated section")
160}
161fn replace(table: &mut dyn TableLike, key: &str, mut item: Item) {
162    if let Some(old) = table.get(key).and_then(Item::as_value)
163        && let Some(value) = item.as_value_mut()
164    {
165        *value.decor_mut() = old.decor().clone();
166    }
167    table.insert(key, item);
168}
169fn point_value(point: Point) -> Item {
170    toml_edit::value(point.into_iter().collect::<toml_edit::Array>())
171}
172fn cleanup(doc: &mut DocumentMut, section: &str) {
173    let Some(annotations) = doc.get_mut("annotations").and_then(Item::as_table_like_mut) else {
174        return;
175    };
176    if annotations
177        .get(section)
178        .and_then(Item::as_table_like)
179        .is_some_and(|table| table.is_empty())
180    {
181        annotations.remove(section);
182    }
183    if annotations.is_empty() {
184        doc.remove("annotations");
185    }
186}
187fn prune_style(doc: &mut DocumentMut, config: &RepoConfig, name: &ArtifactName) {
188    let Some(style) = doc
189        .get_mut("annotations")
190        .and_then(|annotations| annotations.get_mut("style"))
191        .and_then(Item::as_table_like_mut)
192    else {
193        return;
194    };
195    if !top_level(config, name) {
196        style.remove("at");
197    }
198    if let Some(parts) = style.get_mut("parts").and_then(Item::as_table_like_mut) {
199        let stale = parts
200            .iter()
201            .filter(|(part, _)| {
202                !config.artifacts[name]
203                    .parts
204                    .iter()
205                    .any(|name| name.as_str() == *part)
206            })
207            .map(|(part, _)| part.to_owned())
208            .collect::<Vec<_>>();
209        for part in stale {
210            parts.remove(&part);
211        }
212        parts.sort_values();
213        if parts.is_empty() {
214            style.remove("parts");
215        }
216    }
217    cleanup(doc, "style");
218}
219pub(super) fn validate_style(
220    doc: &DocumentMut,
221    file: &Path,
222    config: &RepoConfig,
223    name: &ArtifactName,
224) -> Result<(), Refusal> {
225    style(doc, config, name)
226        .map(|_| ())
227        .map_err(|error| invalid(doc, file, "style", error))
228}
229pub(super) fn set_at(
230    doc: &mut DocumentMut,
231    file: &Path,
232    config: &RepoConfig,
233    name: &ArtifactName,
234    at: Option<Point>,
235) -> Result<(), Refusal> {
236    style(doc, config, name).map_err(|error| invalid(doc, file, "style", error))?;
237    if let Some(at) = at {
238        if at.iter().any(|number| !number.is_finite()) {
239            return Err(forbidden("Places must be finite coordinates."));
240        }
241        if top_level(config, name) {
242            replace(section_mut(doc, "style"), "at", point_value(at));
243        }
244    } else if let Some(style) = doc
245        .get_mut("annotations")
246        .and_then(|annotations| annotations.get_mut("style"))
247        .and_then(Item::as_table_like_mut)
248    {
249        style.remove("at");
250    }
251    prune_style(doc, config, name);
252    Ok(())
253}
254pub(super) fn set_parts(
255    doc: &mut DocumentMut,
256    file: &Path,
257    config: &RepoConfig,
258    name: &ArtifactName,
259    places: &BTreeMap<ArtifactName, Point>,
260    reset: bool,
261) -> Result<(), Refusal> {
262    style(doc, config, name).map_err(|error| invalid(doc, file, "style", error))?;
263    if places.values().flatten().any(|number| !number.is_finite()) {
264        return Err(forbidden("Places must be finite coordinates."));
265    }
266    if reset {
267        if let Some(style) = doc
268            .get_mut("annotations")
269            .and_then(|annotations| annotations.get_mut("style"))
270            .and_then(Item::as_table_like_mut)
271        {
272            style.remove("parts");
273        }
274    } else if !places.is_empty() {
275        let style = section_mut(doc, "style");
276        if style.get("parts").is_none() {
277            style.insert("parts", Item::Table(Table::new()));
278        }
279        let parts = style
280            .get_mut("parts")
281            .expect("inserted parts")
282            .as_table_like_mut()
283            .expect("validated parts");
284        for (part, place) in places {
285            if config.artifacts[name].parts.contains(part) {
286                replace(parts, part, point_value(*place));
287            }
288        }
289    }
290    prune_style(doc, config, name);
291    Ok(())
292}
293pub(super) fn set_comment(doc: &mut DocumentMut, file: &Path, text: &str) -> Result<(), Refusal> {
294    comment(doc).map_err(|error| invalid(doc, file, "comment", error))?;
295    if text.is_empty() {
296        if let Some(comment) = doc
297            .get_mut("annotations")
298            .and_then(|annotations| annotations.get_mut("comment"))
299            .and_then(Item::as_table_like_mut)
300        {
301            comment.remove("text");
302        }
303    } else {
304        replace(section_mut(doc, "comment"), "text", toml_edit::value(text));
305    }
306    cleanup(doc, "comment");
307    Ok(())
308}
309pub(super) fn take_comment(doc: &DocumentMut, file: &Path) -> Result<Option<String>, Refusal> {
310    comment(doc).map_err(|error| invalid(doc, file, "comment", error))
311}
312pub(super) fn rename_part(
313    doc: &mut DocumentMut,
314    file: &Path,
315    before: &RepoConfig,
316    owner: &ArtifactName,
317    old: &ArtifactName,
318    new: &ArtifactName,
319) -> Result<(), Refusal> {
320    let has_place = doc
321        .get("annotations")
322        .and_then(|annotations| annotations.get("style"))
323        .and_then(|style| style.get("parts"))
324        .and_then(Item::as_table_like)
325        .is_some_and(|parts| parts.contains_key(old));
326    if !has_place {
327        return Ok(());
328    }
329    style(doc, before, owner).map_err(|error| invalid(doc, file, "style", error))?;
330    let parts = section_mut(doc, "style")
331        .get_mut("parts")
332        .expect("placed part")
333        .as_table_like_mut()
334        .expect("validated parts");
335    let decoration = parts.key(old).map(|key| key.leaf_decor().clone());
336    let item = parts.remove(old).expect("placed part");
337    parts.insert(new, item);
338    if let Some(decoration) = decoration {
339        *parts.key_mut(new).expect("new key").leaf_decor_mut() = decoration;
340    }
341    parts.sort_values();
342    Ok(())
343}