Skip to main content

specfold_core/authoring/
set.rs

1//! Changing frontmatter through assignments (`key=value`, `key+=value`, `key-=value`), with the
2//! lifecycle enforced and `updated` kept current.
3
4use super::plan::Plan;
5use crate::corpus::Corpus;
6use crate::model::markdown::frontmatter::edit;
7use crate::model::stamp;
8use anyhow::{Result, anyhow, bail};
9use serde_json::{Map, Value};
10use shape::Shape;
11
12mod shape;
13
14#[derive(Debug, Clone, PartialEq, Eq)]
15pub enum Op {
16    Set,
17    Add,
18    Remove,
19}
20
21#[derive(Debug, Clone)]
22pub struct Assign {
23    /// `status`, `phase`, `tags`, `rel.implements` …
24    pub key: String,
25    pub op: Op,
26    pub value: String,
27}
28
29impl Assign {
30    pub fn parse(s: &str) -> Result<Self> {
31        for (token, op) in [("+=", Op::Add), ("-=", Op::Remove), ("=", Op::Set)] {
32            if let Some((k, v)) = s.split_once(token) {
33                if k.is_empty() {
34                    break;
35                }
36                return Ok(Assign { key: k.trim().to_string(), op, value: v.trim().to_string() });
37            }
38        }
39        bail!("'{s}' is not key=value, key+=value or key-=value")
40    }
41}
42
43const PROTECTED: &[&str] = &["id", "created", "files"];
44const LIST_KEYS: &[&str] = &["tags", "owners", "aliases", "verify", "check_skip", "screens"];
45
46fn target<'a>(map: &'a mut Map<String, Value>, key: &str) -> (&'a mut Map<String, Value>, String) {
47    match key.split_once('.') {
48        Some((parent, child)) => {
49            let entry = map.entry(parent.to_string()).or_insert_with(|| Value::Object(Map::new()));
50            if !entry.is_object() {
51                *entry = Value::Object(Map::new());
52            }
53            (entry.as_object_mut().expect("entry was just made an object"), child.to_string())
54        }
55        None => (map, key.to_string()),
56    }
57}
58
59/// Frontmatter keys that hold one value.
60const SCALAR_KEYS: &[&str] = &["id", "title", "status", "owner", "created", "updated", "source_rev"];
61
62fn apply_one(map: &mut Map<String, Value>, a: &Assign, shape: Shape) {
63    // C109: `key=[a, b]` is a list, written the way YAML writes one.
64    // C200: a single-value key keeps `[x, y]` as text (the writer quotes it), not a list.
65    let scalar = SCALAR_KEYS.contains(&a.key.as_str());
66    let bracketed = a.value.trim().strip_prefix('[').and_then(|v| v.strip_suffix(']')).filter(|_| !scalar);
67    let is_list = bracketed.is_some() || a.key.starts_with("rel.") || LIST_KEYS.contains(&a.key.as_str());
68    let value = if let (Op::Set, Some(inner)) = (&a.op, bracketed) {
69        if inner.trim().is_empty() {
70            let (m, k) = target(map, &a.key);
71            m.insert(k, Value::Array(vec![]));
72            return;
73        }
74        inner.to_string()
75    } else if a.key == "updated" && a.value == "today" {
76        stamp::now_value()
77    } else {
78        a.value.clone()
79    };
80    let nested = a.key.contains('.');
81    let (m, k) = target(map, &a.key);
82    // `key=` with nothing after it deletes the key, so an unknown relation can be taken out.
83    if matches!(a.op, Op::Set) && value.is_empty() {
84        m.remove(&k);
85        if nested {
86            let parent = a.key.split('.').next().unwrap_or_default();
87            if map.get(parent).is_some_and(|v| v.as_object().is_some_and(|o| o.is_empty())) {
88                map.remove(parent);
89            }
90        }
91        return;
92    }
93    match (&a.op, is_list) {
94        (Op::Set, true) => {
95            let items = bracketed
96                .and_then(|_| json_strings(a.value.trim()))
97                .unwrap_or_else(|| value.split(',').map(|s| s.trim().to_string()).collect());
98            m.insert(k, Value::Array(items.into_iter().filter(|s| !s.is_empty()).map(Value::String).collect()));
99        }
100        (Op::Set, false) => {
101            let v = shape::value(shape, value, m.get(&k));
102            m.insert(k, v);
103        }
104        (Op::Add, _) => {
105            let list = m.entry(k).or_insert_with(|| Value::Array(vec![]));
106            if let Value::Array(items) = list
107                && !items.iter().any(|x| x.as_str() == Some(value.as_str()))
108            {
109                items.push(Value::String(value));
110            }
111        }
112        (Op::Remove, _) => match m.get_mut(&k) {
113            Some(Value::Array(items)) => items.retain(|x| x.as_str() != Some(value.as_str())),
114            Some(Value::Object(entries)) => {
115                entries.remove(&value);
116                if entries.is_empty() {
117                    m.remove(&k);
118                }
119            }
120            _ => {}
121        },
122    }
123}
124
125/// The items of a JSON array holding a string (`["7.3", "x, y"]`), quotes and escapes read as
126/// JSON; None for anything else, which is split on commas as typed, so `[7.30, 10.2]` keeps `7.30`.
127fn json_strings(list: &str) -> Option<Vec<String>> {
128    let items: Vec<Value> = serde_json::from_str(list).ok()?;
129    if !items.iter().any(Value::is_string) {
130        return None;
131    }
132    Some(
133        items
134            .into_iter()
135            .map(|v| match v {
136                Value::String(s) => s.trim().to_string(),
137                other => other.to_string(),
138            })
139            .collect(),
140    )
141}
142
143/// What to run instead of a refused status move: never the command that was just refused.
144fn move_hint(ty: &crate::model::doctype::TypeDef, from: &str, to: &str, id: &str) -> String {
145    let next: Vec<&str> =
146        ty.statuses.iter().map(String::as_str).filter(|s| *s != from && ty.transition_allowed(from, s)).collect();
147    if to == "superseded" && from == "draft" {
148        return format!(
149            "a draft has not taken effect, so nothing supersedes it: make it active first with `spec set {} status=active --write`, then run `spec new {} --title '…' --from {} --write`; or change the draft itself with `spec edit {} --text '…' --write`",
150            crate::suggest::shell::word(id),
151            ty.name,
152            crate::suggest::shell::word(id),
153            crate::suggest::shell::word(id)
154        );
155    }
156    if to == "superseded" && ty.transition_allowed("active", "superseded") && from != "active" {
157        return format!("only an active {} can be superseded, and this one is {from}", ty.name);
158    }
159    if next.is_empty() {
160        format!("'{from}' is final")
161    } else {
162        format!("from '{from}' it can move to: {}", next.join(", "))
163    }
164}
165
166/// The status a word for "finished" most likely means: types name the end of their work
167/// differently (`archived`, `done`, `closed`), so a near miss gets the real one suggested.
168fn finishing_status<'a>(asked: &str, reachable: &[&'a String]) -> Option<&'a str> {
169    const FINISHED: &[&str] = &["done", "complete", "completed", "finished", "closed", "resolved", "archived"];
170    if !FINISHED.contains(&asked.to_lowercase().as_str()) {
171        return None;
172    }
173    FINISHED.iter().find_map(|f| reachable.iter().find(|s| s.as_str() == *f).map(|s| s.as_str()))
174}
175
176pub fn plan(c: &Corpus, idx: usize, assigns: &[Assign]) -> Result<Plan> {
177    plan_with(c, idx, assigns, false)
178}
179
180/// The old document's half of `spec new --from`: its successor is written in the same change.
181pub fn plan_superseded_by_new(c: &Corpus, idx: usize) -> Result<Plan> {
182    plan_with(c, idx, &[Assign::parse("status=superseded")?], true)
183}
184
185fn plan_with(c: &Corpus, idx: usize, assigns: &[Assign], successor_pending: bool) -> Result<Plan> {
186    let d = &c.docs[idx];
187    let ty = c.cfg.registry.get(&d.id.ty).ok_or_else(|| anyhow!("unknown type {}", d.id.ty))?;
188    for a in assigns {
189        refuse(c, idx, ty, a, successor_pending)?;
190    }
191    // A pin names a commit; HEAD is resolved now, since HEAD moves.
192    let pinned: Vec<Assign>;
193    let assigns = if assigns.iter().any(|a| a.key == "verified_at" && a.value == "HEAD") {
194        let head = crate::workspace::vcs::head(&c.cfg.spec_home)
195            .ok_or_else(|| anyhow!("verified_at=HEAD needs a git repository with a commit"))?;
196        pinned = assigns
197            .iter()
198            .map(|a| {
199                let mut a = a.clone();
200                if a.key == "verified_at" && a.value == "HEAD" {
201                    a.value = head.chars().take(12).collect();
202                }
203                a
204            })
205            .collect();
206        &pinned[..]
207    } else {
208        assigns
209    };
210    let text = crate::corpus::overlay::read(&c.cfg.spec_home.join(&d.path))?;
211    // C117: values that are already there change nothing, so nothing is written and `updated` stays.
212    let apply_all = |m: &mut Map<String, Value>| {
213        for a in assigns {
214            apply_one(m, a, shape::of(ty, &a.key));
215        }
216    };
217    if edit::rewrite_keeping(&text, &[], apply_all)? == text {
218        return Ok(Plan::default());
219    }
220    // Values change where they stand and new keys go last, so a one-value change is a one-line diff.
221    let mut after = Map::new();
222    let new = edit::rewrite_keeping(&text, &[], |m| {
223        apply_all(m);
224        if !assigns.iter().any(|a| a.key == "updated") {
225            m.insert("updated".into(), Value::String(stamp::now_value()));
226        }
227        after = m.clone();
228    })?;
229    let mut p = Plan::default();
230    p.write(&d.path, new, false);
231    let Some(status) = assigns.iter().rev().find(|a| a.key == "status" && matches!(a.op, Op::Set)) else {
232        return Ok(p);
233    };
234    let before = d.status().unwrap_or_else(|| ty.initial.clone());
235    if status.value != before {
236        refuse_missing(d, ty, &status.value, &after, assigns)?;
237    }
238    // A successor that starts pending supersedes what it names only once it holds.
239    if !successor_pending && ty.in_force(&status.value) && !ty.in_force(&before) {
240        let olds = super::takes_effect::still_in_force(c, &d.id.ty, &after);
241        p.changes.extend(super::takes_effect::supersede(c, &olds)?.changes);
242    }
243    Ok(p)
244}
245
246/// Refuses a status whose required fields (`require_when`) the document would not have, with the
247/// command that sets them together.
248fn refuse_missing(
249    d: &crate::model::Doc,
250    ty: &crate::model::TypeDef,
251    status: &str,
252    after: &Map<String, Value>,
253    assigns: &[Assign],
254) -> Result<()> {
255    let Some(required) = ty.require_when.get(status) else { return Ok(()) };
256    let missing: Vec<&str> =
257        required.iter().map(String::as_str).filter(|k| !crate::check::rules::has_value(after, k)).collect();
258    if missing.is_empty() {
259        return Ok(());
260    }
261    let given = assigns.iter().filter(|a| !missing.contains(&a.key.as_str())).map(|a| {
262        let op = match a.op {
263            Op::Set => "=",
264            Op::Add => "+=",
265            Op::Remove => "-=",
266        };
267        crate::suggest::shell::word(format!("{}{op}{}", a.key, a.value))
268    });
269    let fill = missing.iter().map(|k| format!("{k}=…"));
270    bail!(
271        "status '{status}' requires {}, which {} does not have; set them in the same command; next: spec set {} {} --write",
272        missing.join(", "),
273        d.id,
274        crate::suggest::shell::word(&d.id),
275        given.chain(fill).collect::<Vec<_>>().join(" ")
276    )
277}
278
279/// Why `a` cannot be written to document `idx`, if it cannot: a protected key, an emptied required
280/// key, a second successor, or a status the type does not allow or reach from here.
281fn refuse(c: &Corpus, idx: usize, ty: &crate::model::TypeDef, a: &Assign, successor_pending: bool) -> Result<()> {
282    let d = &c.docs[idx];
283    if PROTECTED.contains(&a.key.as_str()) {
284        bail!(
285            "{} cannot be set by hand: id comes from the path (spec mv), created is fixed, files is managed by spec attach",
286            a.key
287        );
288    }
289    // C128: title is required (S1), so it can be changed but not emptied.
290    if a.key == "title" && matches!(a.op, Op::Set) && a.value.trim().is_empty() {
291        bail!("title is required and cannot be emptied; give a new one: spec set {} title='…' --write", d.id);
292    }
293    // C223: updated is required (S1) as well; `updated=` would delete it.
294    if a.key == "updated" && matches!(a.op, Op::Set) && a.value.trim().is_empty() {
295        bail!("updated is required and cannot be emptied; give a date: spec set {} updated=today --write", d.id);
296    }
297    let blank = a.value.trim().is_empty();
298    if shape::of(ty, &a.key) == Shape::Integer && matches!(a.op, Op::Set) && !blank && a.value.parse::<u64>().is_err() {
299        let w = crate::suggest::shell::word(&d.id);
300        bail!(
301            "{} takes a whole number, and '{}' is not one; next: spec set {w} {}=<number> --write",
302            a.key,
303            a.value,
304            a.key
305        );
306    }
307    if a.key == "rel.supersedes" && !matches!(a.op, Op::Remove) {
308        for v in a.value.split(',').map(|v| v.trim().trim_matches(['[', ']', '"'])).filter(|v| !v.is_empty()) {
309            if let Some(old) = c.docs.iter().position(|o| o.id.to_string() == v && o.id.ty == d.id.ty) {
310                super::successor::refuse_second(c, old, Some(idx))?;
311            }
312        }
313    }
314    if a.key == "status" {
315        if !ty.statuses.contains(&a.value) {
316            let from = d.status().unwrap_or_else(|| ty.initial.clone());
317            let reachable: Vec<&String> =
318                ty.statuses.iter().filter(|s| **s != from && ty.transition_allowed(&from, s)).collect();
319            let pick = finishing_status(&a.value, &reachable);
320            let next = pick
321                .map(|s| format!("; next: spec set {} status={s} --write", crate::suggest::shell::word(&d.id)))
322                .unwrap_or_default();
323            bail!(
324                "status '{}' is not allowed for {} (allowed: {}; from '{from}': {}){next}",
325                a.value,
326                ty.name,
327                ty.statuses.join(", "),
328                reachable.iter().map(|s| s.as_str()).collect::<Vec<_>>().join(", ")
329            );
330        }
331        let from = d.status().unwrap_or_else(|| ty.initial.clone());
332        if !ty.transition_allowed(&from, &a.value) {
333            bail!(
334                "status cannot move from '{from}' to '{}'; {}",
335                a.value,
336                move_hint(ty, &from, &a.value, &d.id.to_string())
337            );
338        }
339        // superseded without a successor is a T1 error the moment it is written.
340        let me = d.id.to_string();
341        let succeeded = c
342            .docs
343            .iter()
344            .filter(|o| o.id.ty == d.id.ty) // C204: L3 refuses a cross-type supersedes
345            .any(|o| o.rel().get("supersedes").is_some_and(|l| l.iter().any(|x| x.trim_matches(['[', ']']) == me)));
346        if a.value == "superseded" && !succeeded && !successor_pending {
347            let title = d.title.clone().unwrap_or_else(|| d.slug.replace('-', " ")).replace('\'', "");
348            let w = crate::suggest::shell::word(&me);
349            bail!(
350                "nothing supersedes {me} yet, so status=superseded would fail T1; when a newer document replaces it, record that on the newer one with `spec set <newer-id> rel.supersedes+={w} --write` and run this again; otherwise write the successor, which marks this one superseded (edit the title); next: spec new {} --from {w} --title '{title}' --write",
351                ty.name
352            );
353        }
354    }
355    Ok(())
356}
357
358#[cfg(test)]
359mod tests {
360    use super::*;
361
362    fn apply(m: &mut Map<String, Value>, s: &str) {
363        apply_one(m, &Assign::parse(s).unwrap(), Shape::Infer);
364    }
365
366    #[test]
367    fn parses_and_applies() {
368        let mut m = Map::new();
369        apply(&mut m, "rel.implements+=sot:a/b");
370        apply(&mut m, "rel.implements+=sot:a/b");
371        apply(&mut m, "approvers=[kim, lee]");
372        assert_eq!(m["approvers"], serde_json::json!(["kim", "lee"]), "C109");
373        apply(&mut m, "tags=x, y");
374        apply(&mut m, "phase=P3");
375        assert_eq!(m["rel"]["implements"], serde_json::json!(["sot:a/b"]));
376        assert_eq!(m["tags"], serde_json::json!(["x", "y"]));
377        apply(&mut m, "tags-=x");
378        apply(&mut m, "rel.affects=a");
379        apply(&mut m, "rel.affects=");
380        assert!(m["rel"].get("affects").is_none());
381        assert_eq!(m["tags"], serde_json::json!(["y"]));
382        assert!(Assign::parse("=x").is_err());
383    }
384}