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 --write, 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 body = refs::rewrite_relative_links(&body, file, &d.path, &new_main);
82 if let Some(bundle) = &d.dir {
83 let new_dir = new_main.rsplit_once('/').map(|x| x.0).unwrap_or("");
84 body = refs::rewrite_bundle_links(&body, file, bundle, new_dir);
85 }
86 for cite in other.path_cites.iter().filter(|p| &p.path == file) {
88 if refs::same_path(&cite.item, &d.path) {
89 body = body.replace(&cite.item, &format!("[[{new_s}]]"));
90 }
91 }
92 }
93 let is_main = file == &other.path;
94 if is_main {
95 body = edit::rewrite(&body, |m| {
96 refs::rewrite_rel(m, &old_s, &new_s);
97 if j == idx {
98 m.insert("id".into(), Value::String(new_s.clone()));
99 m.insert("updated".into(), Value::String(stamp::now_value()));
100 }
101 })?;
102 }
103 if body != text {
105 references += usize::from(j != idx);
106 let target = if j != idx {
107 file.clone()
108 } else if is_main {
109 new_main.clone()
110 } else {
111 let base = d.dir.as_deref().unwrap_or("");
112 let new_base = new_main.rsplit_once('/').map(|x| x.0).unwrap_or("");
113 file.replacen(base, new_base, 1)
114 };
115 plan.write(target, body, false);
116 }
117 }
118 }
119 if let Some(file) = &c.aliases.file
120 && let Ok(text) = std::fs::read_to_string(c.cfg.root.join(file))
121 {
122 let new_text: String = text
123 .lines()
124 .map(|l| match l.split_once('\t') {
125 Some((o, n)) if n.trim() == old_s => format!("{o}\t{new_s}\n"),
126 _ => format!("{l}\n"),
127 })
128 .collect();
129 if new_text != text {
130 plan.write(file.clone(), new_text, false);
131 }
132 }
133 Ok((Moved { from: old_s, to: new_s, path: new_main, references }, plan))
134}