1use 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 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
56const SCALAR_KEYS: &[&str] = &["id", "title", "status", "owner", "created", "updated", "source_rev"];
58
59fn apply_one(map: &mut Map<String, Value>, a: &Assign) {
60 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 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 let items = bracketed
93 .and_then(|_| json_strings(a.value.trim()))
94 .unwrap_or_else(|| value.split(',').map(|s| s.trim().to_string()).collect());
95 m.insert(k, Value::Array(items.into_iter().filter(|s| !s.is_empty()).map(Value::String).collect()));
96 }
97 (Op::Set, false) => {
98 m.insert(k, Value::String(value));
99 }
100 (Op::Add, _) => {
101 let list = m.entry(k).or_insert_with(|| Value::Array(vec![]));
102 if let Value::Array(items) = list
103 && !items.iter().any(|x| x.as_str() == Some(value.as_str()))
104 {
105 items.push(Value::String(value));
106 }
107 }
108 (Op::Remove, _) => match m.get_mut(&k) {
109 Some(Value::Array(items)) => items.retain(|x| x.as_str() != Some(value.as_str())),
110 Some(Value::Object(entries)) => {
111 entries.remove(&value);
112 if entries.is_empty() {
113 m.remove(&k);
114 }
115 }
116 _ => {}
117 },
118 }
119}
120
121fn json_strings(list: &str) -> Option<Vec<String>> {
124 let items: Vec<Value> = serde_json::from_str(list).ok()?;
125 if !items.iter().any(Value::is_string) {
126 return None;
127 }
128 Some(
129 items
130 .into_iter()
131 .map(|v| match v {
132 Value::String(s) => s.trim().to_string(),
133 other => other.to_string(),
134 })
135 .collect(),
136 )
137}
138
139fn move_hint(ty: &crate::model::doctype::TypeDef, from: &str, to: &str, id: &str) -> String {
141 let next: Vec<&str> =
142 ty.statuses.iter().map(String::as_str).filter(|s| *s != from && ty.transition_allowed(from, s)).collect();
143 if to == "superseded" && from == "draft" {
144 return format!(
145 "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`",
146 crate::suggest::shell::word(id),
147 ty.name,
148 crate::suggest::shell::word(id),
149 crate::suggest::shell::word(id)
150 );
151 }
152 if to == "superseded" && ty.transition_allowed("active", "superseded") && from != "active" {
153 return format!("only an active {} can be superseded, and this one is {from}", ty.name);
154 }
155 if next.is_empty() {
156 format!("'{from}' is final")
157 } else {
158 format!("from '{from}' it can move to: {}", next.join(", "))
159 }
160}
161
162fn finishing_status<'a>(asked: &str, reachable: &[&'a String]) -> Option<&'a str> {
165 const FINISHED: &[&str] = &["done", "complete", "completed", "finished", "closed", "resolved", "archived"];
166 if !FINISHED.contains(&asked.to_lowercase().as_str()) {
167 return None;
168 }
169 FINISHED.iter().find_map(|f| reachable.iter().find(|s| s.as_str() == *f).map(|s| s.as_str()))
170}
171
172pub fn plan(c: &Corpus, idx: usize, assigns: &[Assign]) -> Result<Plan> {
173 plan_with(c, idx, assigns, false)
174}
175
176pub fn plan_superseded_by_new(c: &Corpus, idx: usize) -> Result<Plan> {
178 plan_with(c, idx, &[Assign::parse("status=superseded")?], true)
179}
180
181fn plan_with(c: &Corpus, idx: usize, assigns: &[Assign], successor_pending: bool) -> Result<Plan> {
182 let d = &c.docs[idx];
183 let ty = c.cfg.registry.get(&d.id.ty).ok_or_else(|| anyhow!("unknown type {}", d.id.ty))?;
184 for a in assigns {
185 refuse(c, idx, ty, a, successor_pending)?;
186 }
187 let pinned: Vec<Assign>;
189 let assigns = if assigns.iter().any(|a| a.key == "verified_at" && a.value == "HEAD") {
190 let head = crate::workspace::vcs::head(&c.cfg.spec_home)
191 .ok_or_else(|| anyhow!("verified_at=HEAD needs a git repository with a commit"))?;
192 pinned = assigns
193 .iter()
194 .map(|a| {
195 let mut a = a.clone();
196 if a.key == "verified_at" && a.value == "HEAD" {
197 a.value = head.chars().take(12).collect();
198 }
199 a
200 })
201 .collect();
202 &pinned[..]
203 } else {
204 assigns
205 };
206 let text = crate::corpus::overlay::read(&c.cfg.spec_home.join(&d.path))?;
207 let order = |m: &mut Map<String, Value>| {
209 let ordered = edit::ordered(std::mem::take(m));
210 *m = ordered;
211 };
212 let same = edit::rewrite(&text, |m| {
213 for a in assigns {
214 apply_one(m, a);
215 }
216 order(m);
217 })? == edit::rewrite(&text, order)?;
218 if same {
219 return Ok(Plan::default());
220 }
221 let mut after = Map::new();
222 let new = edit::rewrite(&text, |m| {
223 for a in assigns {
224 apply_one(m, a);
225 }
226 if !assigns.iter().any(|a| a.key == "updated") {
227 m.insert("updated".into(), Value::String(stamp::now_value()));
228 }
229 let ordered = edit::ordered(std::mem::take(m));
230 *m = ordered;
231 after = m.clone();
232 })?;
233 let mut p = Plan::default();
234 p.write(&d.path, new, false);
235 let Some(status) = assigns.iter().rev().find(|a| a.key == "status" && matches!(a.op, Op::Set)) else {
236 return Ok(p);
237 };
238 let before = d.status().unwrap_or_else(|| ty.initial.clone());
239 if status.value != before {
240 refuse_missing(d, ty, &status.value, &after, assigns)?;
241 }
242 if !successor_pending && ty.in_force(&status.value) && !ty.in_force(&before) {
244 let olds = super::takes_effect::still_in_force(c, &d.id.ty, &after);
245 p.changes.extend(super::takes_effect::supersede(c, &olds)?.changes);
246 }
247 Ok(p)
248}
249
250fn refuse_missing(
253 d: &crate::model::Doc,
254 ty: &crate::model::TypeDef,
255 status: &str,
256 after: &Map<String, Value>,
257 assigns: &[Assign],
258) -> Result<()> {
259 let Some(required) = ty.require_when.get(status) else { return Ok(()) };
260 let missing: Vec<&str> =
261 required.iter().map(String::as_str).filter(|k| !crate::check::rules::has_value(after, k)).collect();
262 if missing.is_empty() {
263 return Ok(());
264 }
265 let given = assigns.iter().filter(|a| !missing.contains(&a.key.as_str())).map(|a| {
266 let op = match a.op {
267 Op::Set => "=",
268 Op::Add => "+=",
269 Op::Remove => "-=",
270 };
271 crate::suggest::shell::word(format!("{}{op}{}", a.key, a.value))
272 });
273 let fill = missing.iter().map(|k| format!("{k}=…"));
274 bail!(
275 "status '{status}' requires {}, which {} does not have; set them in the same command; next: spec set {} {} --write",
276 missing.join(", "),
277 d.id,
278 crate::suggest::shell::word(&d.id),
279 given.chain(fill).collect::<Vec<_>>().join(" ")
280 )
281}
282
283fn refuse(c: &Corpus, idx: usize, ty: &crate::model::TypeDef, a: &Assign, successor_pending: bool) -> Result<()> {
286 let d = &c.docs[idx];
287 if PROTECTED.contains(&a.key.as_str()) {
288 bail!(
289 "{} cannot be set by hand: id comes from the path (spec mv), created is fixed, files is managed by spec attach",
290 a.key
291 );
292 }
293 if a.key == "title" && matches!(a.op, Op::Set) && a.value.trim().is_empty() {
295 bail!("title is required and cannot be emptied; give a new one: spec set {} title='…' --write", d.id);
296 }
297 if a.key == "updated" && matches!(a.op, Op::Set) && a.value.trim().is_empty() {
299 bail!("updated is required and cannot be emptied; give a date: spec set {} updated=today --write", d.id);
300 }
301 if a.key == "rel.supersedes" && !matches!(a.op, Op::Remove) {
302 for v in a.value.split(',').map(|v| v.trim().trim_matches(['[', ']', '"'])).filter(|v| !v.is_empty()) {
303 if let Some(old) = c.docs.iter().position(|o| o.id.to_string() == v && o.id.ty == d.id.ty) {
304 super::successor::refuse_second(c, old, Some(idx))?;
305 }
306 }
307 }
308 if a.key == "status" {
309 if !ty.statuses.contains(&a.value) {
310 let from = d.status().unwrap_or_else(|| ty.initial.clone());
311 let reachable: Vec<&String> =
312 ty.statuses.iter().filter(|s| **s != from && ty.transition_allowed(&from, s)).collect();
313 let pick = finishing_status(&a.value, &reachable);
314 let next = pick
315 .map(|s| format!("; next: spec set {} status={s} --write", crate::suggest::shell::word(&d.id)))
316 .unwrap_or_default();
317 bail!(
318 "status '{}' is not allowed for {} (allowed: {}; from '{from}': {}){next}",
319 a.value,
320 ty.name,
321 ty.statuses.join(", "),
322 reachable.iter().map(|s| s.as_str()).collect::<Vec<_>>().join(", ")
323 );
324 }
325 let from = d.status().unwrap_or_else(|| ty.initial.clone());
326 if !ty.transition_allowed(&from, &a.value) {
327 bail!(
328 "status cannot move from '{from}' to '{}'; {}",
329 a.value,
330 move_hint(ty, &from, &a.value, &d.id.to_string())
331 );
332 }
333 let me = d.id.to_string();
335 let succeeded = c
336 .docs
337 .iter()
338 .filter(|o| o.id.ty == d.id.ty) .any(|o| o.rel().get("supersedes").is_some_and(|l| l.iter().any(|x| x.trim_matches(['[', ']']) == me)));
340 if a.value == "superseded" && !succeeded && !successor_pending {
341 let title = d.title.clone().unwrap_or_else(|| d.slug.replace('-', " ")).replace('\'', "");
342 let w = crate::suggest::shell::word(&me);
343 bail!(
344 "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",
345 ty.name
346 );
347 }
348 }
349 Ok(())
350}
351
352#[cfg(test)]
353mod tests {
354 use super::*;
355
356 #[test]
357 fn parses_and_applies() {
358 let mut m = Map::new();
359 apply_one(&mut m, &Assign::parse("rel.implements+=sot:a/b").unwrap());
360 apply_one(&mut m, &Assign::parse("rel.implements+=sot:a/b").unwrap());
361 apply_one(&mut m, &Assign::parse("approvers=[kim, lee]").unwrap());
362 assert_eq!(m["approvers"], serde_json::json!(["kim", "lee"]), "C109");
363 apply_one(&mut m, &Assign::parse("tags=x, y").unwrap());
364 apply_one(&mut m, &Assign::parse("phase=P3").unwrap());
365 assert_eq!(m["rel"]["implements"], serde_json::json!(["sot:a/b"]));
366 assert_eq!(m["tags"], serde_json::json!(["x", "y"]));
367 apply_one(&mut m, &Assign::parse("tags-=x").unwrap());
368 apply_one(&mut m, &Assign::parse("rel.affects=a").unwrap());
369 apply_one(&mut m, &Assign::parse("rel.affects=").unwrap());
370 assert!(m["rel"].get("affects").is_none());
371 assert_eq!(m["tags"], serde_json::json!(["y"]));
372 assert!(Assign::parse("=x").is_err());
373 }
374}