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};
10
11#[derive(Debug, Clone, PartialEq, Eq)]
12pub enum Op {
13    Set,
14    Add,
15    Remove,
16}
17
18#[derive(Debug, Clone)]
19pub struct Assign {
20    /// `status`, `phase`, `tags`, `rel.implements` …
21    pub key: String,
22    pub op: Op,
23    pub value: String,
24}
25
26impl Assign {
27    pub fn parse(s: &str) -> Result<Self> {
28        for (token, op) in [("+=", Op::Add), ("-=", Op::Remove), ("=", Op::Set)] {
29            if let Some((k, v)) = s.split_once(token) {
30                if k.is_empty() {
31                    break;
32                }
33                return Ok(Assign { key: k.trim().to_string(), op, value: v.trim().to_string() });
34            }
35        }
36        bail!("'{s}' is not key=value, key+=value or key-=value")
37    }
38}
39
40const PROTECTED: &[&str] = &["id", "created", "files"];
41const LIST_KEYS: &[&str] = &["tags", "owners", "aliases", "verify", "check_skip", "screens"];
42
43fn target<'a>(map: &'a mut Map<String, Value>, key: &str) -> (&'a mut Map<String, Value>, String) {
44    match key.split_once('.') {
45        Some((parent, child)) => {
46            let entry = map.entry(parent.to_string()).or_insert_with(|| Value::Object(Map::new()));
47            if !entry.is_object() {
48                *entry = Value::Object(Map::new());
49            }
50            (entry.as_object_mut().expect("entry was just made an object"), child.to_string())
51        }
52        None => (map, key.to_string()),
53    }
54}
55
56/// Frontmatter keys that hold one value.
57const SCALAR_KEYS: &[&str] = &["id", "title", "status", "owner", "created", "updated", "source_rev"];
58
59fn apply_one(map: &mut Map<String, Value>, a: &Assign) {
60    // C109: `key=[a, b]` is a list, written the way YAML writes one.
61    // C200: a single-value key keeps `[x, y]` as text (the writer quotes it), not a list.
62    let scalar = SCALAR_KEYS.contains(&a.key.as_str());
63    let bracketed = a.value.trim().strip_prefix('[').and_then(|v| v.strip_suffix(']')).filter(|_| !scalar);
64    let is_list = bracketed.is_some() || a.key.starts_with("rel.") || LIST_KEYS.contains(&a.key.as_str());
65    let value = if let (Op::Set, Some(inner)) = (&a.op, bracketed) {
66        if inner.trim().is_empty() {
67            let (m, k) = target(map, &a.key);
68            m.insert(k, Value::Array(vec![]));
69            return;
70        }
71        inner.to_string()
72    } else if a.key == "updated" && a.value == "today" {
73        stamp::now_value()
74    } else {
75        a.value.clone()
76    };
77    let nested = a.key.contains('.');
78    let (m, k) = target(map, &a.key);
79    // `key=` with nothing after it deletes the key, so an unknown relation can be taken out.
80    if matches!(a.op, Op::Set) && value.is_empty() {
81        m.remove(&k);
82        if nested {
83            let parent = a.key.split('.').next().unwrap_or_default();
84            if map.get(parent).is_some_and(|v| v.as_object().is_some_and(|o| o.is_empty())) {
85                map.remove(parent);
86            }
87        }
88        return;
89    }
90    match (&a.op, is_list) {
91        (Op::Set, true) => {
92            m.insert(
93                k,
94                Value::Array(
95                    value
96                        .split(',')
97                        .map(|s| Value::String(s.trim().into()))
98                        .filter(|v| v.as_str() != Some(""))
99                        .collect(),
100                ),
101            );
102        }
103        (Op::Set, false) => {
104            m.insert(k, Value::String(value));
105        }
106        (Op::Add, _) => {
107            let list = m.entry(k).or_insert_with(|| Value::Array(vec![]));
108            if let Value::Array(items) = list
109                && !items.iter().any(|x| x.as_str() == Some(value.as_str()))
110            {
111                items.push(Value::String(value));
112            }
113        }
114        (Op::Remove, _) => match m.get_mut(&k) {
115            Some(Value::Array(items)) => items.retain(|x| x.as_str() != Some(value.as_str())),
116            Some(Value::Object(entries)) => {
117                entries.remove(&value);
118                if entries.is_empty() {
119                    m.remove(&k);
120                }
121            }
122            _ => {}
123        },
124    }
125}
126
127/// What to run instead of a refused status move: never the command that was just refused.
128fn move_hint(ty: &crate::model::doctype::TypeDef, from: &str, to: &str, id: &str) -> String {
129    let next: Vec<&str> =
130        ty.statuses.iter().map(String::as_str).filter(|s| *s != from && ty.transition_allowed(from, s)).collect();
131    if to == "superseded" && from == "draft" {
132        return format!(
133            "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`",
134            crate::suggest::shell::word(id),
135            ty.name,
136            crate::suggest::shell::word(id),
137            crate::suggest::shell::word(id)
138        );
139    }
140    if to == "superseded" && ty.transition_allowed("active", "superseded") && from != "active" {
141        return format!("only an active {} can be superseded, and this one is {from}", ty.name);
142    }
143    if next.is_empty() {
144        format!("'{from}' is final")
145    } else {
146        format!("from '{from}' it can move to: {}", next.join(", "))
147    }
148}
149
150/// The status a word for "finished" most likely means: types name the end of their work
151/// differently (`archived`, `done`, `closed`), so a near miss gets the real one suggested.
152fn finishing_status<'a>(asked: &str, reachable: &[&'a String]) -> Option<&'a str> {
153    const FINISHED: &[&str] = &["done", "complete", "completed", "finished", "closed", "resolved", "archived"];
154    if !FINISHED.contains(&asked.to_lowercase().as_str()) {
155        return None;
156    }
157    FINISHED.iter().find_map(|f| reachable.iter().find(|s| s.as_str() == *f).map(|s| s.as_str()))
158}
159
160pub fn plan(c: &Corpus, idx: usize, assigns: &[Assign]) -> Result<Plan> {
161    plan_with(c, idx, assigns, false)
162}
163
164/// The old document's half of `spec new --from`: its successor is written in the same change.
165pub fn plan_superseded_by_new(c: &Corpus, idx: usize) -> Result<Plan> {
166    plan_with(c, idx, &[Assign::parse("status=superseded")?], true)
167}
168
169fn plan_with(c: &Corpus, idx: usize, assigns: &[Assign], successor_pending: bool) -> Result<Plan> {
170    let d = &c.docs[idx];
171    let ty = c.cfg.registry.get(&d.id.ty).ok_or_else(|| anyhow!("unknown type {}", d.id.ty))?;
172    for a in assigns {
173        refuse(c, idx, ty, a, successor_pending)?;
174    }
175    // A pin names a commit; HEAD is resolved now, since HEAD moves.
176    let pinned: Vec<Assign>;
177    let assigns = if assigns.iter().any(|a| a.key == "verified_at" && a.value == "HEAD") {
178        let head = crate::workspace::vcs::head(&c.cfg.spec_home)
179            .ok_or_else(|| anyhow!("verified_at=HEAD needs a git repository with a commit"))?;
180        pinned = assigns
181            .iter()
182            .map(|a| {
183                let mut a = a.clone();
184                if a.key == "verified_at" && a.value == "HEAD" {
185                    a.value = head.chars().take(12).collect();
186                }
187                a
188            })
189            .collect();
190        &pinned[..]
191    } else {
192        assigns
193    };
194    let text = crate::corpus::overlay::read(&c.cfg.spec_home.join(&d.path))?;
195    // C117: values that are already there change nothing, so nothing is written and `updated` stays.
196    let order = |m: &mut Map<String, Value>| {
197        let ordered = edit::ordered(std::mem::take(m));
198        *m = ordered;
199    };
200    let same = edit::rewrite(&text, |m| {
201        for a in assigns {
202            apply_one(m, a);
203        }
204        order(m);
205    })? == edit::rewrite(&text, order)?;
206    if same {
207        return Ok(Plan::default());
208    }
209    let new = edit::rewrite(&text, |m| {
210        for a in assigns {
211            apply_one(m, a);
212        }
213        if !assigns.iter().any(|a| a.key == "updated") {
214            m.insert("updated".into(), Value::String(stamp::now_value()));
215        }
216        let ordered = edit::ordered(std::mem::take(m));
217        *m = ordered;
218    })?;
219    let mut p = Plan::default();
220    p.write(&d.path, new, false);
221    Ok(p)
222}
223
224/// Why `a` cannot be written to document `idx`, if it cannot: a protected key, an emptied required
225/// key, a second successor, or a status the type does not allow or reach from here.
226fn refuse(c: &Corpus, idx: usize, ty: &crate::model::TypeDef, a: &Assign, successor_pending: bool) -> Result<()> {
227    let d = &c.docs[idx];
228    if PROTECTED.contains(&a.key.as_str()) {
229        bail!(
230            "{} cannot be set by hand: id comes from the path (spec mv), created is fixed, files is managed by spec attach",
231            a.key
232        );
233    }
234    // C128: title is required (S1), so it can be changed but not emptied.
235    if a.key == "title" && matches!(a.op, Op::Set) && a.value.trim().is_empty() {
236        bail!("title is required and cannot be emptied; give a new one: spec set {} title='…' --write", d.id);
237    }
238    // C223: updated is required (S1) as well; `updated=` would delete it.
239    if a.key == "updated" && matches!(a.op, Op::Set) && a.value.trim().is_empty() {
240        bail!("updated is required and cannot be emptied; give a date: spec set {} updated=today --write", d.id);
241    }
242    if a.key == "rel.supersedes" && !matches!(a.op, Op::Remove) {
243        for v in a.value.split(',').map(|v| v.trim().trim_matches(['[', ']'])).filter(|v| !v.is_empty()) {
244            if let Some(old) = c.docs.iter().position(|o| o.id.to_string() == v && o.id.ty == d.id.ty) {
245                super::successor::refuse_second(c, old, Some(idx))?;
246            }
247        }
248    }
249    if a.key == "status" {
250        if !ty.statuses.contains(&a.value) {
251            let from = d.status().unwrap_or_else(|| ty.initial.clone());
252            let reachable: Vec<&String> =
253                ty.statuses.iter().filter(|s| **s != from && ty.transition_allowed(&from, s)).collect();
254            let pick = finishing_status(&a.value, &reachable);
255            let next = pick
256                .map(|s| format!("; next: spec set {} status={s} --write", crate::suggest::shell::word(&d.id)))
257                .unwrap_or_default();
258            bail!(
259                "status '{}' is not allowed for {} (allowed: {}; from '{from}': {}){next}",
260                a.value,
261                ty.name,
262                ty.statuses.join(", "),
263                reachable.iter().map(|s| s.as_str()).collect::<Vec<_>>().join(", ")
264            );
265        }
266        let from = d.status().unwrap_or_else(|| ty.initial.clone());
267        if !ty.transition_allowed(&from, &a.value) {
268            bail!(
269                "status cannot move from '{from}' to '{}'; {}",
270                a.value,
271                move_hint(ty, &from, &a.value, &d.id.to_string())
272            );
273        }
274        // superseded without a successor is a T1 error the moment it is written.
275        let me = d.id.to_string();
276        let succeeded = c
277            .docs
278            .iter()
279            .filter(|o| o.id.ty == d.id.ty) // C204: L3 refuses a cross-type supersedes
280            .any(|o| o.rel().get("supersedes").is_some_and(|l| l.iter().any(|x| x.trim_matches(['[', ']']) == me)));
281        if a.value == "superseded" && !succeeded && !successor_pending {
282            let title = d.title.clone().unwrap_or_else(|| d.slug.replace('-', " ")).replace('\'', "");
283            let w = crate::suggest::shell::word(&me);
284            bail!(
285                "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",
286                ty.name
287            );
288        }
289    }
290    Ok(())
291}
292
293#[cfg(test)]
294mod tests {
295    use super::*;
296
297    #[test]
298    fn parses_and_applies() {
299        let mut m = Map::new();
300        apply_one(&mut m, &Assign::parse("rel.implements+=sot:a/b").unwrap());
301        apply_one(&mut m, &Assign::parse("rel.implements+=sot:a/b").unwrap());
302        apply_one(&mut m, &Assign::parse("approvers=[kim, lee]").unwrap());
303        assert_eq!(m["approvers"], serde_json::json!(["kim", "lee"]), "C109");
304        apply_one(&mut m, &Assign::parse("tags=x, y").unwrap());
305        apply_one(&mut m, &Assign::parse("phase=P3").unwrap());
306        assert_eq!(m["rel"]["implements"], serde_json::json!(["sot:a/b"]));
307        assert_eq!(m["tags"], serde_json::json!(["x", "y"]));
308        apply_one(&mut m, &Assign::parse("tags-=x").unwrap());
309        apply_one(&mut m, &Assign::parse("rel.affects=a").unwrap());
310        apply_one(&mut m, &Assign::parse("rel.affects=").unwrap());
311        assert!(m["rel"].get("affects").is_none());
312        assert_eq!(m["tags"], serde_json::json!(["y"]));
313        assert!(Assign::parse("=x").is_err());
314    }
315}