Skip to main content

specfold_core/authoring/
refs.rs

1//! Rewriting references to a document when its id changes.
2
3use crate::paths::{normalize, relative_from_file as relative};
4use regex::Regex;
5use serde_json::{Map, Value};
6
7/// Replaces `[[old]]` and `[[old#anchor]]` (and `[[old|label]]`) with the new id in Markdown text.
8pub fn rewrite_body(text: &str, old: &str, new: &str) -> String {
9    let re = Regex::new(&format!(r"\[\[{}(#[^\]|]*)?(\|[^\]]*)?\]\]", regex::escape(old)))
10        .expect("an escaped id always forms a valid regex");
11    re.replace_all(text, |c: &regex::Captures| {
12        format!("[[{new}{}{}]]", c.get(1).map_or("", |m| m.as_str()), c.get(2).map_or("", |m| m.as_str()))
13    })
14    .into_owned()
15}
16
17/// Cites `id` where `text` names `path`: a path already written as a reference, `[[path]]` or
18/// `[[path|label]]`, keeps its brackets and label instead of gaining a second pair (C257).
19pub fn cite_path_as_id(text: &str, path: &str, id: &str) -> String {
20    text.replace(&format!("[[{path}"), &format!("[[{id}")).replace(path, &format!("[[{id}]]"))
21}
22
23/// Whether a cited path names `path` (root-relative), ignoring leading `./` and `../`.
24pub fn same_path(cited: &str, path: &str) -> bool {
25    let mut t = cited.trim_end_matches('/');
26    while let Some(rest) = t.strip_prefix("../").or_else(|| t.strip_prefix("./")) {
27        t = rest;
28    }
29    t == path
30}
31
32/// Replaces the id inside `rel.*` lists, keeping anchors.
33pub fn rewrite_rel(map: &mut Map<String, Value>, old: &str, new: &str) -> bool {
34    let Some(Value::Object(rel)) = map.get_mut("rel") else { return false };
35    let mut changed = false;
36    for v in rel.values_mut() {
37        let Value::Array(items) = v else { continue };
38        for item in items.iter_mut() {
39            let Some(s) = item.as_str() else { continue };
40            let (target, anchor) = s.split_once('#').map(|(t, a)| (t, Some(a))).unwrap_or((s, None));
41            if target == old {
42                *item = Value::String(match anchor {
43                    Some(a) => format!("{new}#{a}"),
44                    None => new.to_string(),
45                });
46                changed = true;
47            }
48        }
49    }
50    changed
51}
52
53/// Rewrites local Markdown links in `file` that point at `old` so they point at `new`:
54/// inline, angle-bracket, percent-encoded and reference-definition forms, outside code.
55pub fn rewrite_relative_links(body: &str, file: &str, old: &str, new: &str) -> String {
56    let dir = file.rsplit_once('/').map(|x| x.0).unwrap_or("");
57    crate::model::markdown::link_dest::rewrite(body, |target| {
58        let local = !target.is_empty() && !target.contains("://") && !target.starts_with('/');
59        let joined = if dir.is_empty() { target.to_string() } else { format!("{dir}/{target}") };
60        (local && normalize(&joined).as_deref() == Some(old)).then(|| relative(file, new))
61    })
62    .0
63}
64
65/// C234: relative links to anything under a moved bundle directory (its attachments, its
66/// chapters) follow the directory to its new place.
67pub fn rewrite_bundle_links(body: &str, file: &str, old_dir: &str, new_dir: &str) -> String {
68    let dir = file.rsplit_once('/').map(|x| x.0).unwrap_or("");
69    let prefix = format!("{old_dir}/");
70    crate::model::markdown::link_dest::rewrite(body, |target| {
71        let local = !target.is_empty() && !target.contains("://") && !target.starts_with('/');
72        let joined = if dir.is_empty() { target.to_string() } else { format!("{dir}/{target}") };
73        let rest = normalize(&joined).filter(|_| local)?.strip_prefix(&prefix)?.to_string();
74        Some(relative(file, &format!("{new_dir}/{rest}")))
75    })
76    .0
77}
78
79#[cfg(test)]
80mod tests {
81    use super::*;
82
83    #[test]
84    fn rewrites() {
85        let t = "a [[adr:x/1]] b [[adr:x/1#K-1|see]] c [[adr:x/10]]";
86        assert_eq!(rewrite_body(t, "adr:x/1", "adr:y/1"), "a [[adr:y/1]] b [[adr:y/1#K-1|see]] c [[adr:x/10]]");
87        let mut m: Map<String, Value> =
88            serde_json::from_str(r#"{"rel":{"implements":["adr:x/1#A","sot:z/q"]}}"#).unwrap();
89        assert!(rewrite_rel(&mut m, "adr:x/1", "adr:y/1"));
90        assert_eq!(m["rel"]["implements"][0], "adr:y/1#A");
91    }
92}