Skip to main content
← Back to kicad-monkey Rust Docs kicad-monkey Rust Crate API Reference

kicad_monkey_core/
library_edits.rs

1//! Parameterized, source-preserving edits for reusable KiCad library items.
2//!
3//! Applications choose property, font, layer and resource policies. These
4//! operations neither discover files nor select a preferred model format.
5
6mod artwork;
7mod footprints;
8mod models;
9mod properties;
10mod symbols;
11
12pub use artwork::{
13    FootprintArtwork, FootprintFieldText, FootprintFieldTextKind, append_footprint_artwork,
14};
15pub use footprints::{
16    FootprintEdits, edit_footprint, normalize_nonpositive_direct_pad_sizes,
17    remove_footprint_layer_forms,
18};
19pub use models::{EmbeddedModelEdits, KeptEmbeddedModel, edit_footprint_embedded_models};
20pub use properties::{PropertyFont, SymbolLibraryEdits, edit_symbol_library};
21pub use symbols::{
22    SymbolPropertyUpdate, SymbolPropertyValue, materialize_symbol_unit, symbol_property_values,
23    upsert_symbol_properties,
24};
25
26use crate::sexpr::{
27    Error, ErrorKind, Patch, Sexp, apply_patches_with_limit, build_with_limit, parse,
28};
29use crate::sexpr_projection::{FormSpan, Selector, scan_form_spans};
30
31/// The actual output and the number of changed Source forms, not a fidelity
32/// receipt, model count or permission to publish a file.
33#[derive(Clone, Debug, Eq, PartialEq)]
34pub struct LibraryEdit {
35    pub source: String,
36    pub changed_forms: usize,
37}
38
39fn invalid(message: impl Into<std::borrow::Cow<'static, str>>) -> Error {
40    Error::build(ErrorKind::InvalidBuildValue, message)
41}
42
43fn scalar(value: &Sexp) -> Option<&str> {
44    match value {
45        Sexp::Atom(value) | Sexp::Quoted(value) => Some(value),
46        _ => None,
47    }
48}
49
50fn children(value: &Sexp) -> Result<&[Sexp], Error> {
51    match value {
52        Sexp::List(values) => Ok(values),
53        _ => Err(invalid("Expected a Source list")),
54    }
55}
56
57fn children_mut(value: &mut Sexp) -> Result<&mut Vec<Sexp>, Error> {
58    match value {
59        Sexp::List(values) => Ok(values),
60        _ => Err(invalid("Expected a Source list")),
61    }
62}
63
64fn head(value: &Sexp) -> Option<&str> {
65    match value {
66        Sexp::List(values) => values.first().and_then(scalar),
67        _ => None,
68    }
69}
70
71fn named_child<'a>(values: &'a [Sexp], name: &str) -> Option<&'a Sexp> {
72    values.iter().find(|value| head(value) == Some(name))
73}
74
75fn root_and_spans(source: &str, permitted: &[&str]) -> Result<(FormSpan, Vec<FormSpan>), Error> {
76    let spans = scan_form_spans(source, &Selector::default())?;
77    let mut roots = spans.iter().filter(|span| span.depth == 0);
78    let root = roots
79        .next()
80        .ok_or_else(|| invalid("Expected one library item root"))?;
81    if roots.next().is_some()
82        || !root
83            .head
84            .as_deref()
85            .is_some_and(|head| permitted.contains(&head))
86    {
87        return Err(invalid("Unexpected library item root"));
88    }
89    Ok((root.clone(), spans))
90}
91
92fn replacement<'a>(
93    source: &'a str,
94    span: &FormSpan,
95    value: &Sexp,
96    maximum: usize,
97) -> Result<Option<Patch<'a>>, Error> {
98    if parse(span.text(source)?)? == *value {
99        return Ok(None);
100    }
101    Ok(Some(Patch::new(
102        span.range.start,
103        span.range.end,
104        build_with_limit(value, maximum)?,
105    )))
106}
107
108fn finish(source: &str, patches: &[Patch<'_>], maximum: usize) -> Result<LibraryEdit, Error> {
109    if patches.is_empty() && source.len() > maximum {
110        return Err(Error::build(
111            ErrorKind::ResourceLimit,
112            "Library output exceeds max_output_bytes",
113        ));
114    }
115    let mut ordered = patches.to_vec();
116    ordered.sort_by_key(|patch| patch.start_offset);
117    Ok(LibraryEdit {
118        source: apply_patches_with_limit(source, &ordered, maximum)?,
119        changed_forms: patches.len(),
120    })
121}