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};
10use shape::Shape;
11
12mod relation;
13mod shape;
14
15#[derive(Debug, Clone, PartialEq, Eq)]
16pub enum Op {
17 Set,
18 Add,
19 Remove,
20}
21
22#[derive(Debug, Clone)]
23pub struct Assign {
24 pub key: String,
26 pub op: Op,
27 pub value: String,
28}
29
30impl Assign {
31 pub fn parse(s: &str) -> Result<Self> {
32 for (token, op) in [("+=", Op::Add), ("-=", Op::Remove), ("=", Op::Set)] {
33 if let Some((k, v)) = s.split_once(token) {
34 if k.is_empty() {
35 break;
36 }
37 return Ok(Assign { key: k.trim().to_string(), op, value: v.trim().to_string() });
38 }
39 }
40 bail!("'{s}' is not key=value, key+=value or key-=value")
41 }
42}
43
44const PROTECTED: &[&str] = &["id", "created", "files"];
45const LIST_KEYS: &[&str] = &["tags", "owners", "aliases", "verify", "check_skip", "screens"];
46
47fn target<'a>(map: &'a mut Map<String, Value>, key: &str) -> (&'a mut Map<String, Value>, String) {
48 match key.split_once('.') {
49 Some((parent, child)) => {
50 let entry = map.entry(parent.to_string()).or_insert_with(|| Value::Object(Map::new()));
51 if !entry.is_object() {
52 *entry = Value::Object(Map::new());
53 }
54 (entry.as_object_mut().expect("entry was just made an object"), child.to_string())
55 }
56 None => (map, key.to_string()),
57 }
58}
59
60const SCALAR_KEYS: &[&str] = &["id", "title", "status", "owner", "created", "updated", "source_rev"];
62
63fn apply_one(map: &mut Map<String, Value>, a: &Assign, shape: Shape) {
64 let scalar = SCALAR_KEYS.contains(&a.key.as_str());
67 let bracketed = a.value.trim().strip_prefix('[').and_then(|v| v.strip_suffix(']')).filter(|_| !scalar);
68 let is_list = bracketed.is_some() || a.key.starts_with("rel.") || LIST_KEYS.contains(&a.key.as_str());
69 let value = if let (Op::Set, Some(inner)) = (&a.op, bracketed) {
70 if inner.trim().is_empty() {
71 let (m, k) = target(map, &a.key);
72 m.insert(k, Value::Array(vec![]));
73 return;
74 }
75 inner.to_string()
76 } else if a.key == "updated" && a.value == "today" {
77 stamp::now_value()
78 } else {
79 a.value.clone()
80 };
81 let nested = a.key.contains('.');
82 let (m, k) = target(map, &a.key);
83 if matches!(a.op, Op::Set) && value.is_empty() {
85 m.remove(&k);
86 if nested {
87 let parent = a.key.split('.').next().unwrap_or_default();
88 if map.get(parent).is_some_and(|v| v.as_object().is_some_and(|o| o.is_empty())) {
89 map.remove(parent);
90 }
91 }
92 return;
93 }
94 match (&a.op, is_list) {
95 (Op::Set, true) => {
96 let items = bracketed
97 .and_then(|_| json_strings(a.value.trim()))
98 .unwrap_or_else(|| value.split(',').map(|s| s.trim().to_string()).collect());
99 m.insert(k, Value::Array(items.into_iter().filter(|s| !s.is_empty()).map(Value::String).collect()));
100 }
101 (Op::Set, false) => {
102 let v = shape::value(shape, value, m.get(&k));
103 m.insert(k, v);
104 }
105 (Op::Add, _) => {
106 let list = m.entry(k).or_insert_with(|| Value::Array(vec![]));
107 if let Value::Array(items) = list
108 && !items.iter().any(|x| x.as_str() == Some(value.as_str()))
109 {
110 items.push(Value::String(value));
111 }
112 }
113 (Op::Remove, _) => match m.get_mut(&k) {
114 Some(Value::Array(items)) => items.retain(|x| x.as_str() != Some(value.as_str())),
115 Some(Value::Object(entries)) => {
116 entries.remove(&value);
117 if entries.is_empty() {
118 m.remove(&k);
119 }
120 }
121 _ => {}
122 },
123 }
124}
125
126fn json_strings(list: &str) -> Option<Vec<String>> {
129 let items: Vec<Value> = serde_json::from_str(list).ok()?;
130 if !items.iter().any(Value::is_string) {
131 return None;
132 }
133 Some(
134 items
135 .into_iter()
136 .map(|v| match v {
137 Value::String(s) => s.trim().to_string(),
138 other => other.to_string(),
139 })
140 .collect(),
141 )
142}
143
144fn move_hint(ty: &crate::model::doctype::TypeDef, from: &str, to: &str, id: &str) -> String {
146 let next: Vec<&str> =
147 ty.statuses.iter().map(String::as_str).filter(|s| *s != from && ty.transition_allowed(from, s)).collect();
148 if to == "superseded" && from == "draft" {
149 return format!(
150 "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`",
151 crate::suggest::shell::word(id),
152 ty.name,
153 crate::suggest::shell::word(id),
154 crate::suggest::shell::word(id)
155 );
156 }
157 if to == "superseded" && ty.transition_allowed("active", "superseded") && from != "active" {
158 return format!("only an active {} can be superseded, and this one is {from}", ty.name);
159 }
160 if next.is_empty() {
161 format!("'{from}' is final")
162 } else {
163 format!("from '{from}' it can move to: {}", next.join(", "))
164 }
165}
166
167fn finishing_status<'a>(asked: &str, reachable: &[&'a String]) -> Option<&'a str> {
170 const FINISHED: &[&str] = &["done", "complete", "completed", "finished", "closed", "resolved", "archived"];
171 if !FINISHED.contains(&asked.to_lowercase().as_str()) {
172 return None;
173 }
174 FINISHED.iter().find_map(|f| reachable.iter().find(|s| s.as_str() == *f).map(|s| s.as_str()))
175}
176
177pub fn qualify(c: &Corpus, idx: usize, assigns: &[Assign]) -> Vec<Assign> {
179 match c.cfg.registry.get(&c.docs[idx].id.ty) {
180 Some(ty) => assigns.iter().map(|a| relation::qualified(ty, a)).collect(),
181 None => assigns.to_vec(),
182 }
183}
184
185pub fn plan(c: &Corpus, idx: usize, assigns: &[Assign]) -> Result<Plan> {
186 plan_with(c, idx, assigns, false)
187}
188
189pub fn plan_superseded_by_new(c: &Corpus, idx: usize) -> Result<Plan> {
191 plan_with(c, idx, &[Assign::parse("status=superseded")?], true)
192}
193
194fn plan_with(c: &Corpus, idx: usize, assigns: &[Assign], successor_pending: bool) -> Result<Plan> {
195 let d = &c.docs[idx];
196 let ty = c.cfg.registry.get(&d.id.ty).ok_or_else(|| anyhow!("unknown type {}", d.id.ty))?;
197 let qualified = qualify(c, idx, assigns);
198 let assigns = &qualified[..];
199 for a in assigns {
200 refuse(c, idx, ty, a, successor_pending)?;
201 }
202 let pinned: Vec<Assign>;
204 let assigns = if assigns.iter().any(|a| a.key == "verified_at" && a.value == "HEAD") {
205 let head = crate::workspace::vcs::head(&c.cfg.spec_home)
206 .ok_or_else(|| anyhow!("verified_at=HEAD needs a git repository with a commit"))?;
207 pinned = assigns
208 .iter()
209 .map(|a| {
210 let mut a = a.clone();
211 if a.key == "verified_at" && a.value == "HEAD" {
212 a.value = head.chars().take(12).collect();
213 }
214 a
215 })
216 .collect();
217 &pinned[..]
218 } else {
219 assigns
220 };
221 let text = crate::corpus::overlay::read(&c.cfg.spec_home.join(&d.path))?;
222 let apply_all = |m: &mut Map<String, Value>| {
224 for a in assigns {
225 relation::fold_top_level(m, &a.key);
226 apply_one(m, a, shape::of(ty, &a.key));
227 }
228 };
229 if edit::rewrite_keeping(&text, &[], apply_all)? == text {
230 return Ok(Plan::default());
231 }
232 let mut after = Map::new();
234 let new = edit::rewrite_keeping(&text, &[], |m| {
235 apply_all(m);
236 if !assigns.iter().any(|a| a.key == "updated") {
237 m.insert("updated".into(), Value::String(stamp::now_value()));
238 }
239 after = m.clone();
240 })?;
241 let mut p = Plan::default();
242 p.write(&d.path, new, false);
243 let Some(status) = assigns.iter().rev().find(|a| a.key == "status" && matches!(a.op, Op::Set)) else {
244 return Ok(p);
245 };
246 let before = d.status().unwrap_or_else(|| ty.initial.clone());
247 if status.value != before {
248 refuse_missing(d, ty, &status.value, &after, assigns)?;
249 }
250 if !successor_pending && ty.in_force(&status.value) && !ty.in_force(&before) {
252 let olds = super::takes_effect::still_in_force(c, &d.id.ty, &after);
253 p.changes.extend(super::takes_effect::supersede(c, &olds)?.changes);
254 }
255 Ok(p)
256}
257
258fn refuse_missing(
261 d: &crate::model::Doc,
262 ty: &crate::model::TypeDef,
263 status: &str,
264 after: &Map<String, Value>,
265 assigns: &[Assign],
266) -> Result<()> {
267 let Some(required) = ty.require_when.get(status) else { return Ok(()) };
268 let missing: Vec<&str> =
269 required.iter().map(String::as_str).filter(|k| !crate::check::rules::has_value(after, k)).collect();
270 if missing.is_empty() {
271 return Ok(());
272 }
273 let given = assigns.iter().filter(|a| !missing.contains(&a.key.as_str())).map(|a| {
274 let op = match a.op {
275 Op::Set => "=",
276 Op::Add => "+=",
277 Op::Remove => "-=",
278 };
279 crate::suggest::shell::word(format!("{}{op}{}", a.key, a.value))
280 });
281 let fill = missing.iter().map(|k| format!("{k}=…"));
282 bail!(
283 "status '{status}' requires {}, which {} does not have; set them in the same command; next: spec set {} {} --write",
284 missing.join(", "),
285 d.id,
286 crate::suggest::shell::word(&d.id),
287 given.chain(fill).collect::<Vec<_>>().join(" ")
288 )
289}
290
291fn refuse(c: &Corpus, idx: usize, ty: &crate::model::TypeDef, a: &Assign, successor_pending: bool) -> Result<()> {
294 let d = &c.docs[idx];
295 if PROTECTED.contains(&a.key.as_str()) {
296 bail!(
297 "{} cannot be set by hand: id comes from the path (spec mv), created is fixed, files is managed by spec attach",
298 a.key
299 );
300 }
301 if a.key == "title" && matches!(a.op, Op::Set) && a.value.trim().is_empty() {
303 bail!("title is required and cannot be emptied; give a new one: spec set {} title='…' --write", d.id);
304 }
305 if a.key == "updated" && matches!(a.op, Op::Set) && a.value.trim().is_empty() {
307 bail!("updated is required and cannot be emptied; give a date: spec set {} updated=today --write", d.id);
308 }
309 let blank = a.value.trim().is_empty();
310 if shape::of(ty, &a.key) == Shape::Integer && matches!(a.op, Op::Set) && !blank && a.value.parse::<u64>().is_err() {
311 let w = crate::suggest::shell::word(&d.id);
312 bail!(
313 "{} takes a whole number, and '{}' is not one; next: spec set {w} {}=<number> --write",
314 a.key,
315 a.value,
316 a.key
317 );
318 }
319 if a.key == "rel.supersedes" && !matches!(a.op, Op::Remove) {
320 for v in a.value.split(',').map(|v| v.trim().trim_matches(['[', ']', '"'])).filter(|v| !v.is_empty()) {
321 if let Some(old) = c.docs.iter().position(|o| o.id.to_string() == v && o.id.ty == d.id.ty) {
322 super::successor::refuse_second(c, old, Some(idx))?;
323 }
324 }
325 }
326 if a.key == "status" {
327 if !ty.statuses.contains(&a.value) {
328 let from = d.status().unwrap_or_else(|| ty.initial.clone());
329 let reachable: Vec<&String> =
330 ty.statuses.iter().filter(|s| **s != from && ty.transition_allowed(&from, s)).collect();
331 let pick = finishing_status(&a.value, &reachable);
332 let next = pick
333 .map(|s| format!("; next: spec set {} status={s} --write", crate::suggest::shell::word(&d.id)))
334 .unwrap_or_default();
335 bail!(
336 "status '{}' is not allowed for {} (allowed: {}; from '{from}': {}){next}",
337 a.value,
338 ty.name,
339 ty.statuses.join(", "),
340 reachable.iter().map(|s| s.as_str()).collect::<Vec<_>>().join(", ")
341 );
342 }
343 let from = d.status().unwrap_or_else(|| ty.initial.clone());
344 if !ty.transition_allowed(&from, &a.value) {
345 bail!(
346 "status cannot move from '{from}' to '{}'; {}",
347 a.value,
348 move_hint(ty, &from, &a.value, &d.id.to_string())
349 );
350 }
351 let me = d.id.to_string();
353 let succeeded = c
354 .docs
355 .iter()
356 .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)));
358 if a.value == "superseded" && !succeeded && !successor_pending {
359 let title = d.title.clone().unwrap_or_else(|| d.slug.replace('-', " ")).replace('\'', "");
360 let w = crate::suggest::shell::word(&me);
361 bail!(
362 "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",
363 ty.name
364 );
365 }
366 }
367 Ok(())
368}
369
370#[cfg(test)]
371mod tests {
372 use super::*;
373
374 fn apply(m: &mut Map<String, Value>, s: &str) {
375 apply_one(m, &Assign::parse(s).unwrap(), Shape::Infer);
376 }
377
378 #[test]
379 fn parses_and_applies() {
380 let mut m = Map::new();
381 apply(&mut m, "rel.implements+=sot:a/b");
382 apply(&mut m, "rel.implements+=sot:a/b");
383 apply(&mut m, "approvers=[kim, lee]");
384 assert_eq!(m["approvers"], serde_json::json!(["kim", "lee"]), "C109");
385 apply(&mut m, "tags=x, y");
386 apply(&mut m, "phase=P3");
387 assert_eq!(m["rel"]["implements"], serde_json::json!(["sot:a/b"]));
388 assert_eq!(m["tags"], serde_json::json!(["x", "y"]));
389 apply(&mut m, "tags-=x");
390 apply(&mut m, "rel.affects=a");
391 apply(&mut m, "rel.affects=");
392 assert!(m["rel"].get("affects").is_none());
393 assert_eq!(m["tags"], serde_json::json!(["y"]));
394 assert!(Assign::parse("=x").is_err());
395 }
396}