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) = parse_document(source);
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(source: &str, file: &Path, section: &str, message: String) -> Refusal {
136    ConfigError::new(
137        file,
138        location::error_at(source, &["annotations", section], &message),
139    )
140    .into()
141}
142fn section_mut<'a>(doc: &'a mut DocumentMut, key: &str) -> &'a mut dyn TableLike {
143    if doc.get("annotations").is_none() {
144        let mut table = Table::new();
145        table.set_implicit(true);
146        doc["annotations"] = Item::Table(table);
147    }
148    let annotations = doc["annotations"]
149        .as_table_like_mut()
150        .expect("validated annotation table");
151    if annotations.get(key).is_none() {
152        annotations.insert(key, Item::Table(Table::new()));
153    }
154    annotations
155        .get_mut(key)
156        .expect("section inserted")
157        .as_table_like_mut()
158        .expect("validated section")
159}
160fn replace(table: &mut dyn TableLike, key: &str, mut item: Item) {
161    if let Some(old) = table.get(key).and_then(Item::as_value)
162        && let Some(value) = item.as_value_mut()
163    {
164        *value.decor_mut() = old.decor().clone();
165    }
166    table.insert(key, item);
167}
168fn point_value(point: Point) -> Item {
169    toml_edit::value(point.into_iter().collect::<toml_edit::Array>())
170}
171fn cleanup(doc: &mut DocumentMut, section: &str) {
172    let Some(annotations) = doc.get_mut("annotations").and_then(Item::as_table_like_mut) else {
173        return;
174    };
175    if annotations
176        .get(section)
177        .and_then(Item::as_table_like)
178        .is_some_and(|table| table.is_empty())
179    {
180        annotations.remove(section);
181    }
182    if annotations.is_empty() {
183        doc.remove("annotations");
184    }
185}
186fn prune_style(doc: &mut DocumentMut, config: &RepoConfig, name: &ArtifactName) {
187    let Some(style) = doc
188        .get_mut("annotations")
189        .and_then(|annotations| annotations.get_mut("style"))
190        .and_then(Item::as_table_like_mut)
191    else {
192        return;
193    };
194    if !top_level(config, name) {
195        style.remove("at");
196    }
197    if let Some(parts) = style.get_mut("parts").and_then(Item::as_table_like_mut) {
198        let stale = parts
199            .iter()
200            .filter(|(part, _)| {
201                !config.artifacts[name]
202                    .parts
203                    .iter()
204                    .any(|name| name.as_str() == *part)
205            })
206            .map(|(part, _)| part.to_owned())
207            .collect::<Vec<_>>();
208        for part in stale {
209            parts.remove(&part);
210        }
211        parts.sort_values();
212        if parts.is_empty() {
213            style.remove("parts");
214        }
215    }
216    cleanup(doc, "style");
217}
218pub(super) fn validate_style(
219    doc: &DocumentMut,
220    file: &Path,
221    source: &str,
222    config: &RepoConfig,
223    name: &ArtifactName,
224) -> Result<(), Refusal> {
225    style(doc, config, name)
226        .map(|_| ())
227        .map_err(|error| invalid(source, file, "style", error))
228}
229pub(super) fn set_at(
230    doc: &mut DocumentMut,
231    file: &Path,
232    source: &str,
233    config: &RepoConfig,
234    name: &ArtifactName,
235    at: Option<Point>,
236) -> Result<(), Refusal> {
237    style(doc, config, name).map_err(|error| invalid(source, file, "style", error))?;
238    if let Some(at) = at {
239        if at.iter().any(|number| !number.is_finite()) {
240            return Err(forbidden("Places must be finite coordinates."));
241        }
242        if top_level(config, name) {
243            replace(section_mut(doc, "style"), "at", point_value(at));
244        }
245    } else if let Some(style) = doc
246        .get_mut("annotations")
247        .and_then(|annotations| annotations.get_mut("style"))
248        .and_then(Item::as_table_like_mut)
249    {
250        style.remove("at");
251    }
252    prune_style(doc, config, name);
253    Ok(())
254}
255pub(super) fn set_parts(
256    doc: &mut DocumentMut,
257    file: &Path,
258    source: &str,
259    config: &RepoConfig,
260    name: &ArtifactName,
261    places: &BTreeMap<ArtifactName, Point>,
262    reset: bool,
263) -> Result<(), Refusal> {
264    style(doc, config, name).map_err(|error| invalid(source, file, "style", error))?;
265    if places.values().flatten().any(|number| !number.is_finite()) {
266        return Err(forbidden("Places must be finite coordinates."));
267    }
268    if reset {
269        if let Some(style) = doc
270            .get_mut("annotations")
271            .and_then(|annotations| annotations.get_mut("style"))
272            .and_then(Item::as_table_like_mut)
273        {
274            style.remove("parts");
275        }
276    } else if !places.is_empty() {
277        let style = section_mut(doc, "style");
278        if style.get("parts").is_none() {
279            style.insert("parts", Item::Table(Table::new()));
280        }
281        let parts = style
282            .get_mut("parts")
283            .expect("inserted parts")
284            .as_table_like_mut()
285            .expect("validated parts");
286        for (part, place) in places {
287            if config.artifacts[name].parts.contains(part) {
288                replace(parts, part, point_value(*place));
289            }
290        }
291    }
292    prune_style(doc, config, name);
293    Ok(())
294}
295pub(super) fn set_comment(
296    doc: &mut DocumentMut,
297    file: &Path,
298    source: &str,
299    text: &str,
300) -> Result<(), Refusal> {
301    comment(doc).map_err(|error| invalid(source, file, "comment", error))?;
302    if text.is_empty() {
303        if let Some(comment) = doc
304            .get_mut("annotations")
305            .and_then(|annotations| annotations.get_mut("comment"))
306            .and_then(Item::as_table_like_mut)
307        {
308            comment.remove("text");
309        }
310    } else {
311        replace(section_mut(doc, "comment"), "text", toml_edit::value(text));
312    }
313    cleanup(doc, "comment");
314    Ok(())
315}
316pub(super) fn take_comment(
317    doc: &DocumentMut,
318    file: &Path,
319    source: &str,
320) -> Result<Option<String>, Refusal> {
321    comment(doc).map_err(|error| invalid(source, file, "comment", error))
322}
323pub(super) fn rename_part(
324    doc: &mut DocumentMut,
325    file: &Path,
326    source: &str,
327    before: &RepoConfig,
328    owner: &ArtifactName,
329    old: &ArtifactName,
330    new: &ArtifactName,
331) -> Result<(), Refusal> {
332    let has_place = doc
333        .get("annotations")
334        .and_then(|annotations| annotations.get("style"))
335        .and_then(|style| style.get("parts"))
336        .and_then(Item::as_table_like)
337        .is_some_and(|parts| parts.contains_key(old));
338    if !has_place {
339        return Ok(());
340    }
341    style(doc, before, owner).map_err(|error| invalid(source, file, "style", error))?;
342    let parts = section_mut(doc, "style")
343        .get_mut("parts")
344        .expect("placed part")
345        .as_table_like_mut()
346        .expect("validated parts");
347    let decoration = parts.key(old).map(|key| key.leaf_decor().clone());
348    let item = parts.remove(old).expect("placed part");
349    parts.insert(new, item);
350    if let Some(decoration) = decoration {
351        *parts.key_mut(new).expect("new key").leaf_decor_mut() = decoration;
352    }
353    parts.sort_values();
354    Ok(())
355}