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