1use 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 = refs::cite_path_as_id(&body, &cite.item, &new_s);
90 }
91 }
92 }
93 let is_main = file == &other.path;
94 if is_main {
95 body = edit::rewrite_keeping(&body, &[(old_s.as_str(), new_s.as_str())], |m| {
97 refs::rewrite_rel(m, &old_s, &new_s);
98 if j == idx {
99 m.insert("id".into(), Value::String(new_s.clone()));
100 m.insert("updated".into(), Value::String(stamp::now_value()));
101 }
102 })?;
103 }
104 if body != text {
106 references += usize::from(j != idx);
107 let target = if j != idx {
108 file.clone()
109 } else if is_main {
110 new_main.clone()
111 } else {
112 let base = d.dir.as_deref().unwrap_or("");
113 let new_base = new_main.rsplit_once('/').map(|x| x.0).unwrap_or("");
114 file.replacen(base, new_base, 1)
115 };
116 plan.write(target, body, false);
117 }
118 }
119 }
120 let (from_path, to_path) = match &d.dir {
122 Some(bundle) => (bundle.clone(), new_main.rsplit_once('/').map(|x| x.0.to_string()).unwrap_or_default()),
123 None => (d.path.clone(), new_main.clone()),
124 };
125 if let Some((rel, text)) = crate::check::baseline::follow_move(c, &from_path, &to_path)? {
126 plan.write(rel, text, false);
127 }
128 if let Some(file) = &c.aliases.file
129 && let Ok(text) = std::fs::read_to_string(c.cfg.root.join(file))
130 {
131 let new_text: String = text
132 .lines()
133 .map(|l| match l.split_once('\t') {
134 Some((o, n)) if n.trim() == old_s => format!("{o}\t{new_s}\n"),
135 _ => format!("{l}\n"),
136 })
137 .collect();
138 if new_text != text {
139 plan.write(file.clone(), new_text, false);
140 }
141 }
142 Ok((Moved { from: old_s, to: new_s, path: new_main, references }, plan))
143}