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::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().unwrap(), child.to_string())
51        }
52        None => (map, key.to_string()),
53    }
54}
55
56fn apply_one(map: &mut Map<String, Value>, a: &Assign) {
57    let is_list = a.key.starts_with("rel.") || LIST_KEYS.contains(&a.key.as_str());
58    let value = if a.key == "updated" && a.value == "today" { stamp::now_value() } else { a.value.clone() };
59    let (m, k) = target(map, &a.key);
60    match (&a.op, is_list) {
61        (Op::Set, true) => {
62            m.insert(
63                k,
64                Value::Array(
65                    value
66                        .split(',')
67                        .map(|s| Value::String(s.trim().into()))
68                        .filter(|v| v.as_str() != Some(""))
69                        .collect(),
70                ),
71            );
72        }
73        (Op::Set, false) => {
74            m.insert(k, Value::String(value));
75        }
76        (Op::Add, _) => {
77            let list = m.entry(k).or_insert_with(|| Value::Array(vec![]));
78            if let Value::Array(items) = list
79                && !items.iter().any(|x| x.as_str() == Some(value.as_str()))
80            {
81                items.push(Value::String(value));
82            }
83        }
84        (Op::Remove, _) => match m.get_mut(&k) {
85            Some(Value::Array(items)) => items.retain(|x| x.as_str() != Some(value.as_str())),
86            Some(Value::Object(entries)) => {
87                entries.remove(&value);
88                if entries.is_empty() {
89                    m.remove(&k);
90                }
91            }
92            _ => {}
93        },
94    }
95}
96
97/// What to run instead of a refused status move: never the command that was just refused.
98fn move_hint(ty: &crate::model::doctype::TypeDef, from: &str, to: &str, id: &str) -> String {
99    let next: Vec<&str> =
100        ty.statuses.iter().map(String::as_str).filter(|s| *s != from && ty.transition_allowed(from, s)).collect();
101    if to == "superseded" && from == "draft" {
102        return format!(
103            "a draft has not taken effect, so nothing supersedes it: make it active first with `spec set {id} status=active`, then run `spec new {} --from {id}`; or change the draft itself with `spec edit {id}`",
104            ty.name
105        );
106    }
107    if to == "superseded" && ty.transition_allowed("active", "superseded") && from != "active" {
108        return format!("only an active {} can be superseded, and this one is {from}", ty.name);
109    }
110    if next.is_empty() {
111        format!("'{from}' is final")
112    } else {
113        format!("from '{from}' it can move to: {}", next.join(", "))
114    }
115}
116
117/// The status a word for "finished" most likely means: types name the end of their work
118/// differently (`archived`, `done`, `closed`), so a near miss gets the real one suggested.
119fn finishing_status<'a>(asked: &str, reachable: &[&'a String]) -> Option<&'a str> {
120    const FINISHED: &[&str] = &["done", "complete", "completed", "finished", "closed", "resolved", "archived"];
121    if !FINISHED.contains(&asked.to_lowercase().as_str()) {
122        return None;
123    }
124    FINISHED.iter().find_map(|f| reachable.iter().find(|s| s.as_str() == *f).map(|s| s.as_str()))
125}
126
127pub fn plan(c: &Corpus, idx: usize, assigns: &[Assign]) -> Result<Plan> {
128    plan_with(c, idx, assigns, false)
129}
130
131/// The old document's half of `spec new --from`: its successor is written in the same change.
132pub fn plan_superseded_by_new(c: &Corpus, idx: usize) -> Result<Plan> {
133    plan_with(c, idx, &[Assign::parse("status=superseded")?], true)
134}
135
136fn plan_with(c: &Corpus, idx: usize, assigns: &[Assign], successor_pending: bool) -> Result<Plan> {
137    let d = &c.docs[idx];
138    let ty = c.cfg.registry.get(&d.id.ty).ok_or_else(|| anyhow!("unknown type {}", d.id.ty))?;
139    for a in assigns {
140        if PROTECTED.contains(&a.key.as_str()) {
141            bail!(
142                "{} cannot be set by hand: id comes from the path (spec mv), created is fixed, files is managed by spec attach",
143                a.key
144            );
145        }
146        if a.key == "status" {
147            if !ty.statuses.contains(&a.value) {
148                let from = d.status().unwrap_or_else(|| ty.initial.clone());
149                let reachable: Vec<&String> =
150                    ty.statuses.iter().filter(|s| **s != from && ty.transition_allowed(&from, s)).collect();
151                let pick = finishing_status(&a.value, &reachable);
152                let next = pick.map(|s| format!("; next: spec set {} status={s}", d.id)).unwrap_or_default();
153                bail!(
154                    "status '{}' is not allowed for {} (allowed: {}; from '{from}': {}){next}",
155                    a.value,
156                    ty.name,
157                    ty.statuses.join(", "),
158                    reachable.iter().map(|s| s.as_str()).collect::<Vec<_>>().join(", ")
159                );
160            }
161            let from = d.status().unwrap_or_else(|| ty.initial.clone());
162            if !ty.transition_allowed(&from, &a.value) {
163                bail!(
164                    "status cannot move from '{from}' to '{}'; {}",
165                    a.value,
166                    move_hint(ty, &from, &a.value, &d.id.to_string())
167                );
168            }
169            // superseded without a successor is a T1 error the moment it is written.
170            let me = d.id.to_string();
171            let succeeded = c
172                .docs
173                .iter()
174                .any(|o| o.rel().get("supersedes").is_some_and(|l| l.iter().any(|x| x.trim_matches(['[', ']']) == me)));
175            if a.value == "superseded" && !succeeded && !successor_pending {
176                let title = d.title.clone().unwrap_or_else(|| d.slug.replace('-', " ")).replace('\'', "");
177                bail!(
178                    "nothing supersedes {me} yet, so status=superseded would fail T1; write the successor, which marks this one superseded (edit the title); next: spec new {} --from {me} --title '{title}'",
179                    ty.name
180                );
181            }
182        }
183    }
184    // A pin names a commit; HEAD is resolved now, since HEAD moves.
185    let pinned: Vec<Assign>;
186    let assigns = if assigns.iter().any(|a| a.key == "verified_at" && a.value == "HEAD") {
187        let head = crate::workspace::vcs::head(&c.cfg.root)
188            .ok_or_else(|| anyhow!("verified_at=HEAD needs a git repository with a commit"))?;
189        pinned = assigns
190            .iter()
191            .map(|a| {
192                let mut a = a.clone();
193                if a.key == "verified_at" && a.value == "HEAD" {
194                    a.value = head.chars().take(12).collect();
195                }
196                a
197            })
198            .collect();
199        &pinned[..]
200    } else {
201        assigns
202    };
203    let text = std::fs::read_to_string(c.cfg.root.join(&d.path))?;
204    let new = edit::rewrite(&text, |m| {
205        for a in assigns {
206            apply_one(m, a);
207        }
208        if !assigns.iter().any(|a| a.key == "updated") {
209            m.insert("updated".into(), Value::String(stamp::now_value()));
210        }
211        let ordered = edit::ordered(std::mem::take(m));
212        *m = ordered;
213    })?;
214    let mut p = Plan::default();
215    p.write(&d.path, new, false);
216    Ok(p)
217}
218
219#[cfg(test)]
220mod tests {
221    use super::*;
222
223    #[test]
224    fn parses_and_applies() {
225        let mut m = Map::new();
226        apply_one(&mut m, &Assign::parse("rel.implements+=sot:a/b").unwrap());
227        apply_one(&mut m, &Assign::parse("rel.implements+=sot:a/b").unwrap());
228        apply_one(&mut m, &Assign::parse("tags=x, y").unwrap());
229        apply_one(&mut m, &Assign::parse("phase=P3").unwrap());
230        assert_eq!(m["rel"]["implements"], serde_json::json!(["sot:a/b"]));
231        assert_eq!(m["tags"], serde_json::json!(["x", "y"]));
232        apply_one(&mut m, &Assign::parse("tags-=x").unwrap());
233        assert_eq!(m["tags"], serde_json::json!(["y"]));
234        assert!(Assign::parse("=x").is_err());
235    }
236}