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.
54fn drop_alias(c: &Corpus, texts: &mut BTreeMap<String, String>, alias: &str, keep: &str) -> Result<usize> {
55    let mut changed = 0;
56    for d in &c.docs {
57        if d.id.to_string() == keep || !d.list_field("aliases").iter().any(|a| a == alias) {
58            continue;
59        }
60        let Some(t) =
61            texts.get(&d.path).cloned().or_else(|| std::fs::read_to_string(c.cfg.spec_home.join(&d.path)).ok())
62        else {
63            continue;
64        };
65        let n = edit::rewrite(&t, |m| {
66            if let Some(Value::Array(list)) = m.get_mut("aliases") {
67                list.retain(|v| v.as_str() != Some(alias));
68                if list.is_empty() {
69                    m.remove("aliases");
70                }
71            }
72        })?;
73        if n != t {
74            texts.insert(d.path.clone(), n);
75            changed += 1;
76        }
77    }
78    if let Some(file) = &c.aliases.file {
79        let t = texts.get(file).cloned().or_else(|| std::fs::read_to_string(c.cfg.spec_home.join(file)).ok());
80        if let Some(t) = t {
81            let n: String = t
82                .split_inclusive('\n')
83                .filter(|l| match l.trim_end().split_once('\t') {
84                    Some((old, new)) => old != alias || new.trim() == keep,
85                    None => true,
86                })
87                .collect();
88            if n != t {
89                texts.insert(file.clone(), n);
90                changed += 1;
91            }
92        }
93    }
94    Ok(changed)
95}
96
97pub fn plan(c: &Corpus, findings: &[Finding], pick: Option<&Pick>) -> Result<(Plan, usize)> {
98    let mut texts: BTreeMap<String, String> = BTreeMap::new();
99    let mut applied = 0;
100    let read = |texts: &mut BTreeMap<String, String>, p: &str| -> Option<String> {
101        if let Some(t) = texts.get(p) {
102            return Some(t.clone());
103        }
104        std::fs::read_to_string(c.cfg.spec_home.join(p)).ok()
105    };
106    for f in findings {
107        match (&f.fix, f.rule.as_str()) {
108            (Some(Fix::Replace { path, line, from, to }), _) => {
109                let Some(t) = read(&mut texts, path) else { continue };
110                // C257: a path inside `[[...]]` takes the id alone, keeping the brackets and label.
111                let wiki = to.strip_suffix("]]").filter(|open| open.starts_with("[["));
112                let n = wiki.and_then(|open| replace_on_line(&t, *line, &format!("[[{from}"), open));
113                // C264: the same path also written bare on that line is one finding, so it goes too.
114                let n = match n {
115                    Some(n) => Some(replace_on_line(&n, *line, from, to).unwrap_or(n)),
116                    None => replace_on_line(&t, *line, from, to),
117                };
118                if let Some(n) = n {
119                    texts.insert(path.clone(), n);
120                    applied += 1;
121                }
122            }
123            (_, "S1") if f.message.starts_with("missing") || f.message == "no frontmatter block" => {
124                let Some(idx) = c.docs.iter().position(|d| d.path == f.path) else { continue };
125                let Some(t) = read(&mut texts, &f.path) else { continue };
126                texts.insert(f.path.clone(), fill_frontmatter(c, idx, &t)?);
127                applied += 1;
128            }
129            (_, "L1") if !f.candidates.is_empty() => {
130                let Some(p) = pick.filter(|p| p.path == f.path && p.line == f.line && f.candidates.contains(&p.id))
131                else {
132                    continue;
133                };
134                let Some(t) = read(&mut texts, &f.path) else { continue };
135                let Some(target) = f.message.split("]]").next().and_then(|s| s.strip_prefix("[[")) else { continue };
136                let target_base = target.split('#').next().unwrap_or(target);
137                if let Some(n) = replace_on_line(&t, f.line, &format!("[[{target_base}"), &format!("[[{}", p.id)) {
138                    texts.insert(f.path.clone(), n);
139                    applied += 1;
140                }
141            }
142            (_, "I2") if f.candidates.len() > 1 => {
143                let Some(p) = pick.filter(|p| p.path == f.path && f.candidates.contains(&p.id)) else { continue };
144                let Some(alias) = f.message.strip_prefix("alias '").and_then(|m| m.split_once("' names")).map(|x| x.0)
145                else {
146                    continue;
147                };
148                applied += drop_alias(c, &mut texts, alias, &p.id)?;
149            }
150            _ => {}
151        }
152    }
153    let mut plan = Plan::default();
154    for (path, content) in texts {
155        plan.write(path, content, false);
156    }
157    Ok((plan, applied))
158}
159
160/// Writes `rel.translation_of` and `lang` into every translation the `[translations]` layout
161/// pairs by name alone, so the pair survives a rename or a layout change.
162pub fn translation_pairs(c: &Corpus) -> Result<(Plan, usize)> {
163    let mut plan = Plan::default();
164    let mut n = 0;
165    for (i, d) in c.docs.iter().enumerate() {
166        if crate::corpus::translation::source_ref(c, i).is_some() {
167            continue;
168        }
169        let Some(inf) = crate::corpus::translation::inferred(c, i) else { continue };
170        let Some(src) = inf.source else { continue };
171        let Ok(t) = std::fs::read_to_string(c.cfg.spec_home.join(&d.path)) else { continue };
172        let source = c.docs[src].id.to_string();
173        let new = edit::rewrite(&t, |m| {
174            m.entry("lang").or_insert_with(|| Value::String(inf.lang.clone()));
175            let rel = m.entry("rel").or_insert_with(|| Value::Object(Default::default()));
176            if let Value::Object(r) = rel {
177                r.insert(
178                    crate::corpus::translation::RELATION.into(),
179                    Value::Array(vec![Value::String(source.clone())]),
180                );
181            }
182            let ordered = edit::ordered(std::mem::take(m));
183            *m = ordered;
184        })?;
185        if new != t {
186            plan.write(d.path.clone(), new, false);
187            n += 1;
188        }
189    }
190    Ok((plan, n))
191}