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::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    *l = l.replacen(from, to, 1);
29    Some(lines.concat())
30}
31
32/// Fills id, title, status, created and updated where they are missing.
33fn fill_frontmatter(c: &Corpus, idx: usize, text: &str) -> Result<String> {
34    let d = &c.docs[idx];
35    let initial = c.cfg.registry.get(&d.id.ty).map(|t| t.initial.clone()).unwrap_or_else(|| "draft".into());
36    let created = vcs::first_commit_stamp(&c.cfg.root, &d.path)
37        .and_then(|s| stamp::normalize_date(&s))
38        .unwrap_or_else(stamp::today);
39    let title = d.title.clone().unwrap_or_else(|| d.slug.replace('-', " "));
40    edit::rewrite(text, |m| {
41        m.entry("id").or_insert_with(|| Value::String(d.id.to_string()));
42        m.entry("title").or_insert_with(|| Value::String(title));
43        m.entry("status").or_insert_with(|| Value::String(initial));
44        m.entry("created").or_insert_with(|| Value::String(created));
45        m.entry("updated").or_insert_with(|| Value::String(stamp::today()));
46        let ordered = edit::ordered(std::mem::take(m));
47        *m = ordered;
48    })
49}
50
51pub fn plan(c: &Corpus, findings: &[Finding], pick: Option<&Pick>) -> Result<(Plan, usize)> {
52    let mut texts: BTreeMap<String, String> = BTreeMap::new();
53    let mut applied = 0;
54    let read = |texts: &mut BTreeMap<String, String>, p: &str| -> Option<String> {
55        if let Some(t) = texts.get(p) {
56            return Some(t.clone());
57        }
58        std::fs::read_to_string(c.cfg.root.join(p)).ok()
59    };
60    for f in findings {
61        match (&f.fix, f.rule.as_str()) {
62            (Some(Fix::Replace { path, line, from, to }), _) => {
63                let Some(t) = read(&mut texts, path) else { continue };
64                if let Some(n) = replace_on_line(&t, *line, from, to) {
65                    texts.insert(path.clone(), n);
66                    applied += 1;
67                }
68            }
69            (_, "S1") if f.message.starts_with("missing") || f.message == "no frontmatter block" => {
70                let Some(idx) = c.docs.iter().position(|d| d.path == f.path) else { continue };
71                let Some(t) = read(&mut texts, &f.path) else { continue };
72                texts.insert(f.path.clone(), fill_frontmatter(c, idx, &t)?);
73                applied += 1;
74            }
75            (_, "L1") if !f.candidates.is_empty() => {
76                let Some(p) = pick.filter(|p| p.path == f.path && p.line == f.line && f.candidates.contains(&p.id))
77                else {
78                    continue;
79                };
80                let Some(t) = read(&mut texts, &f.path) else { continue };
81                let Some(target) = f.message.split("]]").next().and_then(|s| s.strip_prefix("[[")) else { continue };
82                let target_base = target.split('#').next().unwrap_or(target);
83                if let Some(n) = replace_on_line(&t, f.line, &format!("[[{target_base}"), &format!("[[{}", p.id)) {
84                    texts.insert(f.path.clone(), n);
85                    applied += 1;
86                }
87            }
88            _ => {}
89        }
90    }
91    let mut plan = Plan::default();
92    for (path, content) in texts {
93        plan.write(path, content, false);
94    }
95    Ok((plan, applied))
96}