Skip to main content

specfold_core/authoring/
fix.rs

1//! Applying the fixes that need no judgement: exact replacements reported by rules, missing
2//! frontmatter keys, and a chosen target for an ambiguous reference.
3
4use super::plan::Plan;
5use crate::check::finding::{Finding, Fix};
6use crate::corpus::Corpus;
7use crate::model::markdown::frontmatter::edit;
8use crate::model::stamp;
9use crate::workspace::vcs;
10use anyhow::Result;
11use serde_json::Value;
12use std::collections::BTreeMap;
13
14#[derive(Debug, Clone, Default)]
15pub struct Pick {
16    /// The id to use instead of an ambiguous reference.
17    pub id: String,
18    pub path: String,
19    pub line: usize,
20}
21
22fn replace_on_line(text: &str, line: usize, from: &str, to: &str) -> Option<String> {
23    let mut lines: Vec<String> = text.split_inclusive('\n').map(str::to_string).collect();
24    let l = lines.get_mut(line.checked_sub(1)?)?;
25    if !l.contains(from) {
26        return None;
27    }
28    // C261: findings on one line are one finding, so every occurrence is fixed at once.
29    *l = l.replace(from, to);
30    Some(lines.concat())
31}
32
33/// Fills id, title, status, created and updated where they are missing.
34fn fill_frontmatter(c: &Corpus, idx: usize, text: &str) -> Result<String> {
35    let d = &c.docs[idx];
36    let initial = c.cfg.registry.get(&d.id.ty).map(|t| t.initial.clone()).unwrap_or_else(|| "draft".into());
37    let created = vcs::first_commit_stamp(&c.cfg.spec_home, &d.path)
38        .and_then(|s| stamp::normalize_date(&s))
39        .unwrap_or_else(stamp::today);
40    let title = d.title.clone().unwrap_or_else(|| d.slug.replace('-', " "));
41    edit::rewrite(text, |m| {
42        m.entry("id").or_insert_with(|| Value::String(d.id.to_string()));
43        m.entry("title").or_insert_with(|| Value::String(title));
44        m.entry("status").or_insert_with(|| Value::String(initial));
45        m.entry("created").or_insert_with(|| Value::String(created));
46        m.entry("updated").or_insert_with(|| Value::String(stamp::now_value()));
47        let ordered = edit::ordered(std::mem::take(m));
48        *m = ordered;
49    })
50}
51
52/// Keeps `alias` on the document `keep` and removes it from every other document that carries
53/// it, in frontmatter `aliases` and in the alias table. Returns the number of files changed.
54/// Removes `alias` from the other documents among `among` (one owner's candidates), so another
55/// owner's own alias of the same name stays.
56fn drop_alias(
57    c: &Corpus,
58    texts: &mut BTreeMap<String, String>,
59    alias: &str,
60    keep: &str,
61    among: &[String],
62) -> Result<usize> {
63    let mut changed = 0;
64    let drops = |id: &str| id != keep && among.iter().any(|x| x == id);
65    for d in &c.docs {
66        if !drops(&d.id.to_string()) || !d.list_field("aliases").iter().any(|a| a == alias) {
67            continue;
68        }
69        let Some(t) =
70            texts.get(&d.path).cloned().or_else(|| std::fs::read_to_string(c.cfg.spec_home.join(&d.path)).ok())
71        else {
72            continue;
73        };
74        let n = edit::rewrite(&t, |m| {
75            if let Some(Value::Array(list)) = m.get_mut("aliases") {
76                list.retain(|v| v.as_str() != Some(alias));
77                if list.is_empty() {
78                    m.remove("aliases");
79                }
80            }
81        })?;
82        if n != t {
83            texts.insert(d.path.clone(), n);
84            changed += 1;
85        }
86    }
87    if let Some(file) = &c.aliases.file {
88        let t = texts.get(file).cloned().or_else(|| std::fs::read_to_string(c.cfg.spec_home.join(file)).ok());
89        if let Some(t) = t {
90            let n: String = t
91                .split_inclusive('\n')
92                .filter(|l| match l.trim_end().split_once('\t') {
93                    Some((old, new)) => old != alias || !drops(new.trim()),
94                    None => true,
95                })
96                .collect();
97            if n != t {
98                texts.insert(file.clone(), n);
99                changed += 1;
100            }
101        }
102    }
103    Ok(changed)
104}
105
106pub fn plan(c: &Corpus, findings: &[Finding], pick: Option<&Pick>) -> Result<(Plan, usize)> {
107    let mut texts: BTreeMap<String, String> = BTreeMap::new();
108    let mut applied = 0;
109    let read = |texts: &mut BTreeMap<String, String>, p: &str| -> Option<String> {
110        if let Some(t) = texts.get(p) {
111            return Some(t.clone());
112        }
113        std::fs::read_to_string(c.cfg.spec_home.join(p)).ok()
114    };
115    for f in findings {
116        match (&f.fix, f.rule.as_str()) {
117            (Some(Fix::Replace { path, line, from, to }), _) => {
118                let Some(t) = read(&mut texts, path) else { continue };
119                // C257: a path inside `[[...]]` takes the id alone, keeping the brackets and label.
120                let wiki = to.strip_suffix("]]").filter(|open| open.starts_with("[["));
121                let n = wiki.and_then(|open| replace_on_line(&t, *line, &format!("[[{from}"), open));
122                // C264: the same path also written bare on that line is one finding, so it goes too.
123                let n = match n {
124                    Some(n) => Some(replace_on_line(&n, *line, from, to).unwrap_or(n)),
125                    None => replace_on_line(&t, *line, from, to),
126                };
127                if let Some(n) = n {
128                    texts.insert(path.clone(), n);
129                    applied += 1;
130                }
131            }
132            (_, "S1") if f.message.starts_with("missing") || f.message == "no frontmatter block" => {
133                let Some(idx) = c.docs.iter().position(|d| d.path == f.path) else { continue };
134                let Some(t) = read(&mut texts, &f.path) else { continue };
135                texts.insert(f.path.clone(), fill_frontmatter(c, idx, &t)?);
136                applied += 1;
137            }
138            (_, "L1") if !f.candidates.is_empty() => {
139                let Some(p) = pick.filter(|p| p.path == f.path && p.line == f.line && f.candidates.contains(&p.id))
140                else {
141                    continue;
142                };
143                let Some(t) = read(&mut texts, &f.path) else { continue };
144                let Some(target) = f.message.split("]]").next().and_then(|s| s.strip_prefix("[[")) else { continue };
145                let target_base = target.split('#').next().unwrap_or(target);
146                if let Some(n) = replace_on_line(&t, f.line, &format!("[[{target_base}"), &format!("[[{}", p.id)) {
147                    texts.insert(f.path.clone(), n);
148                    applied += 1;
149                }
150            }
151            (_, "I2") if f.candidates.len() > 1 => {
152                let Some(p) = pick.filter(|p| p.path == f.path && f.candidates.contains(&p.id)) else { continue };
153                let Some(alias) = f.message.strip_prefix("alias '").and_then(|m| m.split_once("' names")).map(|x| x.0)
154                else {
155                    continue;
156                };
157                applied += drop_alias(c, &mut texts, alias, &p.id, &f.candidates)?;
158            }
159            _ => {}
160        }
161    }
162    let mut plan = Plan::default();
163    for (path, content) in texts {
164        plan.write(path, content, false);
165    }
166    Ok((plan, applied))
167}
168
169/// Writes `rel.translation_of` and `lang` into every translation the `[translations]` layout
170/// pairs by name alone, so the pair survives a rename or a layout change.
171pub fn translation_pairs(c: &Corpus) -> Result<(Plan, usize)> {
172    let mut plan = Plan::default();
173    let mut n = 0;
174    for (i, d) in c.docs.iter().enumerate() {
175        if crate::corpus::translation::source_ref(c, i).is_some() {
176            continue;
177        }
178        let Some(inf) = crate::corpus::translation::inferred(c, i) else { continue };
179        let Some(src) = inf.source else { continue };
180        let Ok(t) = std::fs::read_to_string(c.cfg.spec_home.join(&d.path)) else { continue };
181        let source = c.docs[src].id.to_string();
182        let new = edit::rewrite(&t, |m| {
183            m.entry("lang").or_insert_with(|| Value::String(inf.lang.clone()));
184            let rel = m.entry("rel").or_insert_with(|| Value::Object(Default::default()));
185            if let Value::Object(r) = rel {
186                r.insert(
187                    crate::corpus::translation::RELATION.into(),
188                    Value::Array(vec![Value::String(source.clone())]),
189                );
190            }
191            let ordered = edit::ordered(std::mem::take(m));
192            *m = ordered;
193        })?;
194        if new != t {
195            plan.write(d.path.clone(), new, false);
196            n += 1;
197        }
198    }
199    Ok((plan, n))
200}