Skip to main content

specfold_core/authoring/
new.rs

1//! Creating a document: compute its owner and path, assign its key, write its frontmatter and
2//! body skeleton.
3
4use super::plan::Plan;
5use super::set;
6use crate::corpus::Corpus;
7use crate::graph::{Graph, Resolution};
8use crate::markdown::frontmatter::{edit, render};
9use crate::model::doctype::KeyKind;
10use crate::model::{DocId, Tier, stamp};
11use crate::placement::{self, paths};
12use anyhow::{Result, anyhow, bail};
13use serde::Serialize;
14use serde_json::{Map, Value, json};
15
16#[derive(Debug, Clone, Default)]
17pub struct NewDoc {
18    pub ty: String,
19    pub title: String,
20    pub governs: Vec<String>,
21    /// Overrides the computed owner (refused if it breaks placement, unless local).
22    pub owner: Option<String>,
23    /// For slug types; defaults to the slugified title.
24    pub slug: Option<String>,
25    /// Supersede this document.
26    pub from: Option<String>,
27    pub local: bool,
28    /// Force a bundle directory even for a single-file type.
29    pub bundle: bool,
30    /// Fixed key, for imports; otherwise now.
31    pub key: Option<String>,
32    /// Body to write instead of the type's template (audit records, generated documents).
33    pub body: Option<String>,
34    /// Documents this one depends on (`rel.depends_on`), e.g. what a change note updates.
35    pub depends_on: Vec<String>,
36    /// The repository-relative directory the command runs in (`-C`); the owner containing it is
37    /// the document's owner when its governs decide none. `None` is the repository root.
38    pub here: Option<String>,
39}
40
41#[derive(Debug, Clone, Serialize)]
42pub struct Created {
43    pub id: String,
44    pub path: String,
45    pub owner_reason: String,
46    /// Why the slug is not what the title reads as, when it drops most of a non-ASCII title.
47    pub slug_note: Option<String>,
48}
49
50/// A slug from the title. Titles in other scripts lose their words to slugify, so when less than
51/// half the title's letters survive, the governed path's last segment names the slug instead,
52/// and the caller is told; with neither, --slug is required.
53fn derive_slug(title: &str, governs: &[String]) -> Result<(String, Option<String>)> {
54    let from_title = stamp::slugify(title);
55    let letters = title.chars().filter(|c| c.is_alphanumeric()).count();
56    let kept = title.chars().filter(|c| c.is_ascii_alphanumeric()).count();
57    if letters == 0 || kept * 2 >= letters {
58        if !stamp::is_slug(&from_title) {
59            bail!("cannot derive a slug from the title; pass --slug <kebab-case>");
60        }
61        // Mostly ASCII, but words in another script still vanish from the slug: say which.
62        let dropped: Vec<&str> =
63            title.split_whitespace().filter(|w| w.chars().any(|c| c.is_alphanumeric() && !c.is_ascii())).collect();
64        let note = (!dropped.is_empty())
65            .then(|| format!("the slug '{from_title}' leaves out '{}'; pass --slug to name it", dropped.join(" ")));
66        return Ok((from_title, note));
67    }
68    let from_path = governs
69        .iter()
70        .filter_map(|g| g.trim_end_matches('/').rsplit('/').next())
71        .map(|seg| stamp::slugify(seg.split('.').next().unwrap_or(seg)))
72        .find(|s| stamp::is_slug(s));
73    match (from_path, stamp::is_slug(&from_title)) {
74        (Some(p), _) => {
75            let note = format!(
76                "the title is mostly non-ASCII, so the slug '{p}' comes from the governed path; pass --slug to name it"
77            );
78            Ok((p, Some(note)))
79        }
80        (None, true) => {
81            let note =
82                format!("the title is mostly non-ASCII, so the slug keeps only '{from_title}'; pass --slug to name it");
83            Ok((from_title, Some(note)))
84        }
85        (None, false) => bail!(
86            "the title has no ASCII words to make a slug from; give an English kebab-case --slug (replace my-slug); rerun with --slug my-slug"
87        ),
88    }
89}
90
91/// A2: the owner a new document starts with: the one containing the directory the command runs
92/// in, so `spec -C services/shop new plan` is the shop's plan. A retired owner's go to the root.
93fn current_owner<'a>(c: &'a Corpus, req: &NewDoc) -> &'a crate::workspace::Owner {
94    let o = req.here.as_deref().map(|h| c.owners.containing(h)).unwrap_or(c.owners.root());
95    if o.retired { c.owners.root() } else { o }
96}
97
98pub fn plan(c: &Corpus, g: &Graph, req: &NewDoc) -> Result<(Created, Plan)> {
99    let ty = c
100        .cfg
101        .registry
102        .get(&req.ty)
103        .ok_or_else(|| anyhow!("unknown type '{}' (have: {})", req.ty, c.cfg.registry.names().join(", ")))?;
104    if req.title.trim().is_empty() {
105        bail!("--title is required");
106    }
107    // C185: a governs value naming an existing path that holds glob characters is that path, so
108    // it is written escaped; read as a glob it would name other files or none.
109    let mut owned = req.clone();
110    for g in &mut owned.governs {
111        if g.contains(['[', '*', '?', '{']) && c.cfg.root.join(g.as_str()).exists() {
112            *g = crate::workspace::escape_glob(g);
113        }
114    }
115    let req = &owned;
116    let decision = placement::decide_local(&c.cfg, &c.owners, &req.governs, current_owner(c, req));
117    let (owner, reason) = match &req.owner {
118        Some(o) => {
119            let ow = c.owners.by_id(o).or_else(|| c.owners.by_path(o)).ok_or_else(|| anyhow!("no owner '{o}'"))?;
120            if !req.local && !req.governs.is_empty() && ow.id != decision.owner.id {
121                bail!(
122                    "--owner {} contradicts governs: the document belongs to {} ({})",
123                    ow.id,
124                    decision.owner.id,
125                    decision.reason
126                );
127            }
128            (ow, format!("owner given as {}", ow.id))
129        }
130        None => (decision.owner, decision.reason.clone()),
131    };
132    let (slug, slug_note) = match &req.slug {
133        Some(s) => (s.clone(), None),
134        None => derive_slug(&req.title, &req.governs)?,
135    };
136    if !stamp::is_slug(&slug) {
137        bail!("'{slug}' is not a kebab-case slug; pass --slug in lowercase words joined by '-'");
138    }
139    let mut key = match ty.key {
140        KeyKind::Slug => slug.clone(),
141        KeyKind::Stamp => req.key.clone().unwrap_or_else(stamp::now_stamp),
142    };
143    while g.by_id.contains_key(&DocId::new(&ty.name, &owner.id, &key).to_string()) {
144        match ty.key {
145            KeyKind::Slug => bail!("{}:{}/{key} already exists; choose another --slug", ty.name, owner.id),
146            KeyKind::Stamp => key = stamp::next_stamp(&key).ok_or_else(|| anyhow!("bad stamp {key}"))?,
147        }
148    }
149    let id = DocId::new(&ty.name, &owner.id, &key);
150    let tier = if req.local { Tier::Local } else { Tier::Committed };
151    let dir = paths::type_dir(&c.cfg, &c.owners, owner, tier, ty);
152    let path = paths::main_file(&dir, ty, &paths::stem(ty, &key, &slug), req.bundle);
153    let hint = if req.local { "change [forbid] paths or the type's directory" } else { "rerun with --local" };
154    super::forbid::refuse(c, &path, hint)?;
155    let today = stamp::now_value();
156    let mut fm = Map::new();
157    fm.insert("id".into(), Value::String(id.to_string()));
158    fm.insert("title".into(), Value::String(req.title.trim().to_string()));
159    fm.insert("status".into(), Value::String(ty.initial.clone()));
160    fm.insert("created".into(), Value::String(today.clone()));
161    fm.insert("updated".into(), Value::String(today));
162    let mut rel = Map::new();
163    if !req.governs.is_empty() {
164        rel.insert("governs".into(), json!(req.governs));
165    }
166    if !req.depends_on.is_empty() {
167        let mut ids = vec![];
168        for r in &req.depends_on {
169            let Resolution::Doc { idx, .. } = g.resolve(r) else { bail!("--depends-on {r} names no single document") };
170            ids.push(c.docs[idx].id.to_string());
171        }
172        rel.insert("depends_on".into(), json!(ids));
173    }
174    let mut plan = Plan::default();
175    if let Some(from) = &req.from {
176        let Resolution::Doc { idx, .. } = g.resolve(from) else { bail!("--from {from} names no single document") };
177        let old = &c.docs[idx];
178        if old.id.ty != ty.name {
179            bail!("--from {} is a {}, not a {}", old.id, old.id.ty, ty.name);
180        }
181        super::successor::refuse_second(c, idx, None)?;
182        rel.insert("supersedes".into(), json!([old.id.to_string()]));
183        let old_plan = set::plan_superseded_by_new(c, idx)?;
184        plan.changes.extend(old_plan.changes);
185    }
186    if !rel.is_empty() {
187        fm.insert("rel".into(), Value::Object(rel));
188    }
189    let template = with_required_sections(&ty.template, &ty.sections);
190    let body = format!("\n# {}\n\n{}", req.title.trim(), req.body.as_deref().unwrap_or(&template));
191    plan.write(&path, format!("{}{body}", render(&edit::ordered(fm))), true);
192    Ok((Created { id: id.to_string(), path, owner_reason: reason, slug_note }, plan))
193}
194
195/// `spec new --translation <lang> --from <source>`: a draft with its own key where `[translations]`
196/// pairs it (`<slug>-<lang>` beside the source, or under the `<lang>` owner for `layout = "dir"`),
197/// with the source's body and chapters copied and lang, rel.translation_of, source_rev recorded.
198pub fn translation(c: &Corpus, g: &Graph, from: &str, lang: &str, title: Option<&str>) -> Result<(Created, Plan)> {
199    use crate::config::types::TranslationLayout as L;
200    if let Some((name, rest)) = crate::remotes::split(&c.cfg, from) {
201        bail!(
202            "--from {from} is in the remote {name}, which specfold reads but never copies from; copy {rest} into this repository first (or translate it in that repository), then: spec new --translation {lang} --from <the local id> --write. A local translation may still name a remote source in rel.translation_of; R1 tracks it"
203        );
204    }
205    let Resolution::Doc { idx, .. } = g.resolve(from) else { bail!("--from {from} names no single document") };
206    if let Some(orig) = crate::translation::source_ref(c, idx) {
207        bail!(
208            "--from {} is itself a translation of {orig}; translate the original instead: spec new --translation {lang} --from {orig} --write",
209            c.docs[idx].id
210        );
211    }
212    if crate::translation::lang_problem(lang).is_some() {
213        bail!("--translation '{lang}' is not a language tag like ko or pt-br");
214    }
215    let src = &c.docs[idx];
216    let ty = c.cfg.registry.get(&src.id.ty).ok_or_else(|| anyhow!("unknown type '{}'", src.id.ty))?;
217    let t = &c.cfg.raw.translations;
218    if !t.languages.is_empty() && !t.languages.iter().any(|l| l == lang) {
219        bail!("'{lang}' is not in [translations] languages ({}); add it there first", t.languages.join(", "));
220    }
221    let src_owner = c.owners.by_id(&src.id.owner).ok_or_else(|| anyhow!("no owner '{}'", src.id.owner))?;
222    let (owner, slug) = match t.layout {
223        L::Dir => {
224            let want = if src_owner.path.is_empty() { lang.to_string() } else { format!("{}/{lang}", src_owner.path) };
225            let o = c.owners.by_path(&want).ok_or_else(|| {
226                anyhow!(
227                    "layout = \"dir\" puts the '{lang}' translation in {want}/, which is not an owner: create the directory {want}/ and add [[owners.kinds]] pattern = \"{want}\" to spec.toml"
228                )
229            })?;
230            (o, src.slug.clone())
231        }
232        // The tag keeps its BCP 47 case in `lang`; in a slug it is lower case (`setup-pt-br`).
233        _ => (src_owner, format!("{}-{}", src.slug, lang.to_ascii_lowercase())),
234    };
235    let mut key = match ty.key {
236        KeyKind::Slug => slug.clone(),
237        KeyKind::Stamp => stamp::now_stamp(),
238    };
239    while g.by_id.contains_key(&DocId::new(&ty.name, &owner.id, &key).to_string()) {
240        match ty.key {
241            KeyKind::Slug => bail!("{}:{}/{key} already exists: the '{lang}' translation is there", ty.name, owner.id),
242            KeyKind::Stamp => key = stamp::next_stamp(&key).ok_or_else(|| anyhow!("bad stamp {key}"))?,
243        }
244    }
245    let id = DocId::new(&ty.name, &owner.id, &key);
246    let bundle = src.dir.is_some();
247    let dir = paths::type_dir(&c.cfg, &c.owners, owner, src.tier, ty);
248    let stem = paths::stem(ty, &key, &slug);
249    let path = paths::main_file(&dir, ty, &stem, bundle);
250    super::forbid::refuse(c, &path, "change [forbid] paths or translate in another place")?;
251    let read = |p: &str| std::fs::read_to_string(c.cfg.root.join(p)).map_err(|e| anyhow!("cannot read {p}: {e}"));
252    let rev = crate::translation::rev_of(c, idx).ok_or_else(|| anyhow!("cannot read {}", src.path))?;
253    let today = stamp::now_value();
254    let mut fm = Map::new();
255    fm.insert("id".into(), Value::String(id.to_string()));
256    let title = title.map(str::to_string).or_else(|| src.title.clone()).unwrap_or_else(|| src.slug.replace('-', " "));
257    fm.insert("title".into(), Value::String(title.trim().to_string()));
258    // A translation starts as a draft where the type has one, whatever the source's status.
259    let status = if ty.statuses.iter().any(|s| s == "draft") { "draft".to_string() } else { ty.initial.clone() };
260    fm.insert("status".into(), Value::String(status));
261    fm.insert("created".into(), Value::String(today.clone()));
262    fm.insert("updated".into(), Value::String(today));
263    fm.insert("lang".into(), Value::String(lang.to_string()));
264    fm.insert(crate::translation::KEY.into(), Value::String(rev));
265    fm.insert("rel".into(), json!({ crate::translation::RELATION: [src.id.to_string()] }));
266    let mut plan = Plan::default();
267    let body = crate::markdown::frontmatter::split(&read(&src.path)?).body.to_string();
268    plan.write(&path, format!("{}{body}", render(&edit::ordered(fm))), true);
269    if let Some(src_dir) = &src.dir {
270        let new_dir = path.rsplit_once('/').map(|x| x.0).unwrap_or("").to_string();
271        for ch in &src.chapters {
272            let rest = ch.strip_prefix(&format!("{src_dir}/")).unwrap_or(ch);
273            plan.write(format!("{new_dir}/{rest}"), read(ch)?, true);
274        }
275        for f in &src.bundle_files {
276            let rest = f.strip_prefix(&format!("{src_dir}/")).unwrap_or(f);
277            plan.copy(f.clone(), format!("{new_dir}/{rest}"));
278        }
279    }
280    let reason = format!("the '{lang}' translation of {}", src.id);
281    Ok((Created { id: id.to_string(), path, owner_reason: reason, slug_note: None }, plan))
282}
283
284/// The type's template plus a heading for each required section it lacks, so a new document
285/// passes S7 from the start.
286fn with_required_sections(template: &str, required: &[String]) -> String {
287    let have: Vec<String> = template
288        .lines()
289        .filter(|l| l.starts_with('#'))
290        .map(|l| l.trim_start_matches('#').trim().to_lowercase())
291        .collect();
292    let mut out = template.to_string();
293    for s in required {
294        let s = s.trim();
295        if s.is_empty() || have.contains(&s.to_lowercase()) {
296            continue;
297        }
298        if !out.is_empty() && !out.ends_with("\n\n") {
299            out.push_str(if out.ends_with('\n') { "\n" } else { "\n\n" });
300        }
301        out.push_str(&format!("## {s}\n"));
302    }
303    out
304}
305
306#[cfg(test)]
307mod required_sections_tests {
308    #[test]
309    fn missing_required_sections_are_appended_once() {
310        let req = vec!["Decision".to_string(), "Risks".to_string()];
311        assert_eq!(
312            super::with_required_sections("## Context\n\n## Decision\n", &req),
313            "## Context\n\n## Decision\n\n## Risks\n"
314        );
315        assert_eq!(super::with_required_sections("", &req), "## Decision\n\n## Risks\n");
316    }
317}