Skip to main content

specfold_core/authoring/
mv.rs

1//! Moving or renaming a document, and rewriting every reference to it.
2
3use super::plan::Plan;
4use super::refs;
5use crate::corpus::Corpus;
6use crate::model::doctype::KeyKind;
7use crate::model::markdown::frontmatter::edit;
8use crate::model::{DocId, Tier, stamp};
9use crate::workspace::placement::{self, paths};
10use anyhow::{Result, anyhow, bail};
11use serde::Serialize;
12use serde_json::Value;
13
14#[derive(Debug, Clone, Default)]
15pub struct Move {
16    /// Target owner; computed from governs when absent.
17    pub owner: Option<String>,
18    /// New slug.
19    pub slug: Option<String>,
20    /// Target tier: promote a local document into the committed tree, or the reverse.
21    pub tier: Option<Tier>,
22}
23
24#[derive(Debug, Clone, Serialize)]
25pub struct Moved {
26    pub from: String,
27    pub to: String,
28    pub path: String,
29    pub references: usize,
30}
31
32pub fn plan(c: &Corpus, idx: usize, req: &Move) -> Result<(Moved, Plan)> {
33    let d = &c.docs[idx];
34    let ty = c.cfg.registry.get(&d.id.ty).ok_or_else(|| anyhow!("unknown type {}", d.id.ty))?;
35    let current = c.owners.by_id(&d.id.owner).ok_or_else(|| anyhow!("owner {} no longer exists", d.id.owner))?;
36    let owner = match &req.owner {
37        Some(o) => c.owners.by_id(o).or_else(|| c.owners.by_path(o)).ok_or_else(|| anyhow!("no owner '{o}'"))?,
38        None => {
39            placement::decide_local(&c.cfg, &c.owners, &d.rel().remove("governs").unwrap_or_default(), current).owner
40        }
41    };
42    let slug = req.slug.clone().unwrap_or_else(|| d.slug.clone());
43    if !stamp::is_slug(&slug) {
44        bail!("'{slug}' is not a kebab-case slug");
45    }
46    let key = if ty.key == KeyKind::Slug { slug.clone() } else { d.id.key.clone() };
47    let new_id = DocId::new(&ty.name, &owner.id, &key);
48    let tier = req.tier.unwrap_or(d.tier);
49    let dir = paths::type_dir(&c.cfg, &c.owners, owner, tier, ty);
50    let stem = paths::stem(ty, &key, &slug);
51    let new_main = paths::main_file(&dir, ty, &stem, d.dir.is_some());
52    if new_main == d.path {
53        return Ok((
54            Moved { from: d.id.to_string(), to: new_id.to_string(), path: new_main, references: 0 },
55            Plan::default(),
56        ));
57    }
58    let hint = if tier == Tier::Local {
59        "change [forbid] paths or the type's directory"
60    } else {
61        "choose another --owner, or keep it local: spec new --local --write, then move the body"
62    };
63    super::forbid::refuse(c, &new_main, hint)?;
64    if c.docs.iter().enumerate().any(|(j, x)| j != idx && x.id == new_id) {
65        bail!("{new_id} already exists");
66    }
67    let mut plan = Plan::default();
68    match &d.dir {
69        Some(bundle) => plan.mv(bundle.clone(), new_main.rsplit_once('/').map(|x| x.0.to_string()).unwrap_or_default()),
70        None => plan.mv(d.path.clone(), new_main.clone()),
71    }
72    let (old_s, new_s) = (d.id.to_string(), new_id.to_string());
73    let references = rewrite_references(c, idx, (&old_s, &new_s), &new_main, tier, &mut plan)?;
74    follow_tables(c, idx, (&old_s, &new_s), &new_main, &mut plan)?;
75    Ok((Moved { from: old_s, to: new_s, path: new_main, references }, plan))
76}
77
78/// Every file whose text names the moved document, rewritten: ids, relations, relative links and
79/// path citations. Returns how many other files changed.
80fn rewrite_references(
81    c: &Corpus,
82    idx: usize,
83    (old_s, new_s): (&str, &str),
84    new_main: &str,
85    tier: Tier,
86    plan: &mut Plan,
87) -> Result<usize> {
88    let d = &c.docs[idx];
89    let mut references = 0;
90    for (j, other) in c.docs.iter().enumerate() {
91        if other.tier == Tier::Committed && tier == Tier::Local && j != idx {
92            continue;
93        }
94        for file in std::iter::once(&other.path).chain(&other.chapters) {
95            let text = std::fs::read_to_string(c.cfg.spec_home.join(file))?;
96            let mut body = refs::rewrite_body(&text, old_s, new_s);
97            if j != idx {
98                // C137: relative Markdown links to the moved file follow it, fragment kept.
99                body = refs::rewrite_relative_links(&body, file, &d.path, new_main);
100                if let Some(bundle) = &d.dir {
101                    let new_dir = new_main.rsplit_once('/').map(|x| x.0).unwrap_or("");
102                    body = refs::rewrite_bundle_links(&body, file, bundle, new_dir);
103                }
104                // Plain paths to the moved file break with the move; cite the new id instead (L2).
105                for cite in other.path_cites.iter().filter(|p| &p.path == file) {
106                    if refs::same_path(&cite.item, &d.path) {
107                        body = refs::cite_path_as_id(&body, &cite.item, new_s);
108                    }
109                }
110            }
111            let is_main = file == &other.path;
112            if is_main {
113                // E3: only the fields that change are written; quoting elsewhere stays.
114                body = edit::rewrite_keeping(&body, &[(old_s, new_s)], |m| {
115                    refs::rewrite_rel(m, old_s, new_s);
116                    if j == idx {
117                        m.insert("id".into(), Value::String(new_s.to_string()));
118                        m.insert("updated".into(), Value::String(stamp::now_value()));
119                    }
120                })?;
121            }
122            // C224: a referring file counts once, whether its links, its rel lines, or both changed.
123            if body != text {
124                references += usize::from(j != idx);
125                let target = if j != idx {
126                    file.clone()
127                } else if is_main {
128                    new_main.to_string()
129                } else {
130                    let base = d.dir.as_deref().unwrap_or("");
131                    let new_base = new_main.rsplit_once('/').map(|x| x.0).unwrap_or("");
132                    file.replacen(base, new_base, 1)
133                };
134                plan.write(target, body, false);
135            }
136        }
137    }
138    Ok(references)
139}
140
141/// The baseline and the alias table follow the move.
142fn follow_tables(c: &Corpus, idx: usize, (old_s, new_s): (&str, &str), new_main: &str, plan: &mut Plan) -> Result<()> {
143    let d = &c.docs[idx];
144    // D2: baseline entries follow the moved file or bundle, so its known errors stay held.
145    let (from_path, to_path) = match &d.dir {
146        Some(bundle) => (bundle.clone(), new_main.rsplit_once('/').map(|x| x.0.to_string()).unwrap_or_default()),
147        None => (d.path.clone(), new_main.to_string()),
148    };
149    if let Some((rel, text)) = crate::check::baseline::follow_move(c, &from_path, &to_path)? {
150        plan.write(rel, text, false);
151    }
152    if let Some(file) = &c.aliases.file
153        && let Ok(text) = std::fs::read_to_string(c.cfg.spec_home.join(file))
154    {
155        let new_text: String = text
156            .lines()
157            .map(|l| match l.split_once('\t') {
158                Some((o, n)) if n.trim() == old_s => format!("{o}\t{new_s}\n"),
159                _ => format!("{l}\n"),
160            })
161            .collect();
162        if new_text != text {
163            plan.write(file.clone(), new_text, false);
164        }
165    }
166    Ok(())
167}