use serde_json::Value;
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RenameOutcome {
pub rewritten: usize,
pub referencing_features: Vec<String>,
pub blocks: Vec<String>,
}
const NAMED_BLOCKS: &[&str] = &["features", "assembly", "pmi", "sheets", "cam", "simulation", "instructions", "exploded"];
const PORT_NAME_KEYS: &[&str] = &["pointRef", "directionRef", "contactBody"];
const TEXT_KEYS: &[&str] = &[
"type",
"partName",
"text",
"label",
"description",
"notes",
"note",
"title",
"comment",
"prefix",
"suffix",
];
const RESERVED: &[&str] = &["XY", "XZ", "YZ", "ORIGIN", "Math", "configurator"];
pub const MAX_NAME_LEN: usize = 64;
pub fn validate_name(name: &str) -> Result<(), String> {
if name.is_empty() {
return Err("the new name is empty".into());
}
if name.len() > MAX_NAME_LEN {
return Err(format!("the new name is longer than {MAX_NAME_LEN} characters"));
}
let mut chars = name.chars();
if !chars.next().is_some_and(|c| c.is_ascii_alphabetic()) {
return Err(format!("`{name}` must start with a letter"));
}
if let Some(bad) = name.chars().find(|c| !(c.is_ascii_alphanumeric() || *c == '-')) {
return Err(format!(
"`{name}` has `{bad}`: a name may hold only letters, digits and `-` (`_ : | . @ #` and spaces separate the names built from it)"
));
}
if RESERVED.contains(&name) {
return Err(format!("`{name}` is reserved"));
}
if crate::is_component_reference(name) || name.starts_with("APAT") {
return Err(format!("`{name}` has the form of a component id (ACOMP<n>, APAT<n>)"));
}
Ok(())
}
pub fn rename_name(name: &str, old: &str, new: &str) -> Option<String> {
rename_name_in(name, old, new, &crate::ComponentNamespace::new())
}
pub fn rename_name_in(name: &str, old: &str, new: &str, namespace: &crate::ComponentNamespace) -> Option<String> {
if old.is_empty() || !name.contains(old) {
return None;
}
let mut out = String::with_capacity(name.len() + new.len());
let mut changed = false;
let mut segment_start = 0;
let bytes = name.as_bytes();
for index in 0..=bytes.len() {
if index == bytes.len() || bytes[index] == b'|' || bytes[index] == b'#' {
let (segment, hit) = rename_segment(&name[segment_start..index], old, new, namespace);
changed |= hit;
out.push_str(&segment);
if index < bytes.len() {
out.push(bytes[index] as char);
}
segment_start = index + 1;
}
}
changed.then_some(out)
}
fn rename_segment(segment: &str, old: &str, new: &str, namespace: &crate::ComponentNamespace) -> (String, bool) {
let tokens: Vec<&str> = segment.split(':').collect();
let mut out = Vec::with_capacity(tokens.len());
let mut changed = false;
let mut foreign = false;
for (index, token) in tokens.iter().enumerate() {
if foreign {
out.push(token.to_string());
continue;
}
let renamed = rename_token(token, old, new);
changed |= renamed.is_some();
if index + 1 < tokens.len() && namespace.is_component(token) {
foreign = true;
}
out.push(renamed.unwrap_or_else(|| token.to_string()));
}
(out.join(":"), changed)
}
fn rename_token(token: &str, old: &str, new: &str) -> Option<String> {
if token.starts_with("APAT") {
let parts: Vec<&str> = token.split('.').collect();
if parts.len() >= 3 && parts[1..parts.len() - 1].join(".") == old && parts[parts.len() - 1].starts_with('i') {
return Some(format!("{}.{new}.{}", parts[0], parts[parts.len() - 1]));
}
}
let rest = token.strip_prefix(old)?;
if rest.is_empty() || rest.starts_with(['_', '@', '[', '.', '#']) {
Some(format!("{new}{rest}"))
} else {
None
}
}
fn walk(value: &mut Value, path: &mut Vec<String>, r: &Rename<'_>, apply: bool, hits: &mut Vec<String>) {
let (old, new) = (r.old, r.new);
match value {
Value::String(text) => {
if let Some(renamed) = rename_name_in(text, old, new, r.namespace) {
hits.push(path.join("/"));
if apply {
*text = renamed;
}
}
}
Value::Array(items) => {
for (index, item) in items.iter_mut().enumerate() {
path.push(index.to_string());
walk(item, path, r, apply, hits);
path.pop();
}
}
Value::Object(map) => {
let keys: Vec<String> = map.keys().cloned().collect();
for key in keys {
if TEXT_KEYS.contains(&key.as_str()) {
continue;
}
let renamed_key = rename_name_in(&key, old, new, r.namespace);
path.push(key.clone());
if renamed_key.is_some() {
hits.push(path.join("/"));
}
if let Some(child) = map.get_mut(&key) {
walk(child, path, r, apply, hits);
}
path.pop();
if let (true, Some(renamed)) = (apply, renamed_key) {
if let Some(child) = map.remove(&key) {
map.insert(renamed, child);
}
}
}
}
_ => {}
}
}
pub fn name_uses(document: &Value, name: &str) -> Vec<String> {
let mut probe = document.clone();
let mut hits = Vec::new();
let namespace = crate::component_namespace(document);
let r = Rename { old: name, new: name, namespace: &namespace, component: namespace.inner(name).is_some() };
walk_document(&mut probe, &r, false, &mut hits);
hits
}
struct Rename<'a> {
old: &'a str,
new: &'a str,
namespace: &'a crate::ComponentNamespace,
component: bool,
}
const OCCURRENCE_KEYS: &[&str] = &["instance", "occurrence"];
fn walk_document(document: &mut Value, r: &Rename<'_>, apply: bool, hits: &mut Vec<String>) {
let Some(map) = document.as_object_mut() else {
return;
};
for (key, value) in map.iter_mut() {
let mut path = vec![key.clone()];
if NAMED_BLOCKS.contains(&key.as_str()) {
walk(value, &mut path, r, apply, hits);
} else if key == "ports" {
walk_keys(value, &mut path, PORT_NAME_KEYS, r, apply, hits);
} else if r.component && ["pcb", "diagram", "symbol", "pads"].contains(&key.as_str()) {
walk_keys(value, &mut path, OCCURRENCE_KEYS, r, apply, hits);
}
}
}
fn walk_keys(value: &mut Value, path: &mut Vec<String>, keys: &[&str], r: &Rename<'_>, apply: bool, hits: &mut Vec<String>) {
match value {
Value::Array(items) => {
for (index, item) in items.iter_mut().enumerate() {
path.push(index.to_string());
walk_keys(item, path, keys, r, apply, hits);
path.pop();
}
}
Value::Object(map) => {
for (key, child) in map.iter_mut() {
path.push(key.clone());
if keys.contains(&key.as_str()) {
walk(child, path, r, apply, hits);
} else {
walk_keys(child, path, keys, r, apply, hits);
}
path.pop();
}
}
_ => {}
}
}
fn expression_names_word(document: &Value, name: &str) -> bool {
let word = |text: &str| {
text.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_')).any(|w| w == name)
};
document.get("expressions").and_then(Value::as_str).is_some_and(word)
|| document.get("configurator").and_then(Value::as_object).is_some_and(|m| m.keys().any(|k| word(k)))
}
fn feature_id(feature: &Value) -> Option<&str> {
let params = feature.get("inputParams")?;
["id", "featureID"]
.iter()
.find_map(|key| params.get(*key).and_then(Value::as_str).filter(|id| !id.is_empty()))
}
pub fn rename_feature_in_document(document: &mut Value, old: &str, new: &str) -> Result<RenameOutcome, String> {
if old == new {
return Err(format!("`{old}` already has that name"));
}
validate_name(new)?;
let features = document.get("features").and_then(Value::as_array).cloned().unwrap_or_default();
let ids: Vec<&str> = features.iter().filter_map(feature_id).collect();
if !ids.contains(&old) {
return Err(format!("no feature is named `{old}`"));
}
if crate::feature_pipeline::is_pattern_component_id(old) {
return Err(format!(
"`{old}` is a pattern of components: its instances are named `{old}.<seed>.i<n>`, so a pattern keeps its APAT<n> id"
));
}
let mut namespace = crate::component_namespace(document);
let component = namespace.inner(old).cloned();
if let Some(inner) = component.clone() {
namespace.insert(new, inner);
}
let r = Rename { old, new, namespace: &namespace, component: component.is_some() };
if let Some(other) = ids.iter().find(|id| **id != old && rename_name_in(id, old, new, &namespace).is_some()) {
return Err(format!(
"feature `{other}` has a name that starts with `{old}`: their references could not be told apart; rename `{other}` first"
));
}
for name in [old, new] {
if expression_names_word(document, name) {
return Err(format!(
"`{name}` is also an expression or configurator variable: params that use it could not be told from references; rename the variable first"
));
}
}
let taken = name_uses(document, new);
if let Some(first) = taken.first() {
return Err(format!("`{new}` is already a name in this document (at {first})"));
}
let mut hits = Vec::new();
walk_document(document, &r, true, &mut hits);
let mut outcome = RenameOutcome { rewritten: hits.len(), ..RenameOutcome::default() };
for hit in &hits {
let mut parts = hit.split('/');
match (parts.next(), parts.next()) {
(Some("features"), Some(index)) => {
let id = index.parse::<usize>().ok().and_then(|i| features.get(i)).and_then(feature_id);
if let Some(id) = id.filter(|id| *id != old) {
if !outcome.referencing_features.iter().any(|f| f == id) {
outcome.referencing_features.push(id.to_string());
}
}
}
(Some(block), _) if block != "features" => {
if !outcome.blocks.iter().any(|b| b == block) {
outcome.blocks.push(block.to_string());
}
}
_ => {}
}
}
Ok(outcome)
}