specfold_core/authoring/
mv.rs1use super::plan::Plan;
4use super::refs;
5use crate::corpus::Corpus;
6use crate::markdown::frontmatter::edit;
7use crate::model::doctype::KeyKind;
8use crate::model::{DocId, Tier, stamp};
9use crate::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 pub owner: Option<String>,
18 pub slug: Option<String>,
20 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 => placement::decide(&c.owners, &d.rel().remove("governs").unwrap_or_default(), current).owner,
39 };
40 let slug = req.slug.clone().unwrap_or_else(|| d.slug.clone());
41 if !stamp::is_slug(&slug) {
42 bail!("'{slug}' is not a kebab-case slug");
43 }
44 let key = if ty.key == KeyKind::Slug { slug.clone() } else { d.id.key.clone() };
45 let new_id = DocId::new(&ty.name, &owner.id, &key);
46 let tier = req.tier.unwrap_or(d.tier);
47 let dir = paths::type_dir(&c.cfg, &c.owners, owner, tier, ty);
48 let stem = paths::stem(ty, &key, &slug);
49 let new_main = paths::main_file(&dir, ty, &stem, d.dir.is_some());
50 if new_main == d.path {
51 return Ok((
52 Moved { from: d.id.to_string(), to: new_id.to_string(), path: new_main, references: 0 },
53 Plan::default(),
54 ));
55 }
56 let hint = if tier == Tier::Local {
57 "change [forbid] paths or the type's directory"
58 } else {
59 "choose another --owner, or keep it local: spec new --local, then move the body"
60 };
61 super::forbid::refuse(c, &new_main, hint)?;
62 if c.docs.iter().enumerate().any(|(j, x)| j != idx && x.id == new_id) {
63 bail!("{new_id} already exists");
64 }
65 let mut plan = Plan::default();
66 match &d.dir {
67 Some(bundle) => plan.mv(bundle.clone(), new_main.rsplit_once('/').map(|x| x.0.to_string()).unwrap_or_default()),
68 None => plan.mv(d.path.clone(), new_main.clone()),
69 }
70 let (old_s, new_s) = (d.id.to_string(), new_id.to_string());
71 let mut references = 0;
72 for (j, other) in c.docs.iter().enumerate() {
73 if other.tier == Tier::Committed && tier == Tier::Local && j != idx {
74 continue;
75 }
76 for file in std::iter::once(&other.path).chain(&other.chapters) {
77 let text = std::fs::read_to_string(c.cfg.root.join(file))?;
78 let mut body = refs::rewrite_body(&text, &old_s, &new_s);
79 if j != idx {
80 for cite in other.path_cites.iter().filter(|p| &p.path == file) {
82 if refs::same_path(&cite.item, &d.path) {
83 body = body.replace(&cite.item, &format!("[[{new_s}]]"));
84 }
85 }
86 }
87 let is_main = file == &other.path;
88 if is_main {
89 let mut rel_changed = false;
90 body = edit::rewrite(&body, |m| {
91 rel_changed = refs::rewrite_rel(m, &old_s, &new_s);
92 if j == idx {
93 m.insert("id".into(), Value::String(new_s.clone()));
94 m.insert("updated".into(), Value::String(stamp::now_value()));
95 }
96 })?;
97 references += usize::from(rel_changed);
98 }
99 if body != text {
100 references += usize::from(j != idx);
101 let target = if j != idx {
102 file.clone()
103 } else if is_main {
104 new_main.clone()
105 } else {
106 let base = d.dir.as_deref().unwrap_or("");
107 let new_base = new_main.rsplit_once('/').map(|x| x.0).unwrap_or("");
108 file.replacen(base, new_base, 1)
109 };
110 plan.write(target, body, false);
111 }
112 }
113 }
114 if let Some(file) = &c.aliases.file
115 && let Ok(text) = std::fs::read_to_string(c.cfg.root.join(file))
116 {
117 let new_text: String = text
118 .lines()
119 .map(|l| match l.split_once('\t') {
120 Some((o, n)) if n.trim() == old_s => format!("{o}\t{new_s}\n"),
121 _ => format!("{l}\n"),
122 })
123 .collect();
124 if new_text != text {
125 plan.write(file.clone(), new_text, false);
126 }
127 }
128 Ok((Moved { from: old_s, to: new_s, path: new_main, references }, plan))
129}