1use serde::{Deserialize, Serialize};
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
25#[serde(rename_all = "snake_case")]
26pub enum Status {
27 Pending,
28 InProgress,
29 Done,
30 Cancelled,
31}
32
33impl Status {
34 pub fn as_str(self) -> &'static str {
35 match self {
36 Self::Pending => "pending",
37 Self::InProgress => "in_progress",
38 Self::Done => "done",
39 Self::Cancelled => "cancelled",
40 }
41 }
42
43 pub fn parse(word: &str) -> Option<Self> {
46 match word.trim().to_ascii_lowercase().as_str() {
47 "pending" | "todo" => Some(Self::Pending),
48 "in_progress" | "in-progress" | "inprogress" | "doing" | "active" => {
49 Some(Self::InProgress)
50 }
51 "done" | "completed" | "complete" => Some(Self::Done),
52 "cancelled" | "canceled" | "dropped" | "skipped" => Some(Self::Cancelled),
53 _ => None,
54 }
55 }
56
57 pub fn mark(self) -> &'static str {
59 match self {
60 Self::Pending => "[ ]",
61 Self::InProgress => "[~]",
62 Self::Done => "[x]",
63 Self::Cancelled => "[-]",
64 }
65 }
66
67 pub fn is_finished(self) -> bool {
69 matches!(self, Self::Done | Self::Cancelled)
70 }
71}
72
73#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
80pub struct Item {
81 pub id: String,
82 pub content: String,
83 pub status: Status,
84 #[serde(skip_serializing_if = "Option::is_none")]
85 pub parent: Option<String>,
86}
87
88impl Item {
89 pub fn new(id: &str, content: &str, status: Status) -> Self {
90 Self {
91 id: id.to_string(),
92 content: content.to_string(),
93 status,
94 parent: None,
95 }
96 }
97}
98
99#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
105pub struct Plan {
106 pub revision: u64,
107 pub items: Vec<Item>,
108}
109
110#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
112pub struct Counts {
113 pub pending: usize,
114 pub in_progress: usize,
115 pub done: usize,
116 pub cancelled: usize,
117}
118
119impl Plan {
120 pub fn new(items: Vec<Item>) -> Self {
121 Self { revision: 0, items }
122 }
123
124 pub fn counts(&self) -> Counts {
125 let mut counts = Counts::default();
126 for item in &self.items {
127 match item.status {
128 Status::Pending => counts.pending += 1,
129 Status::InProgress => counts.in_progress += 1,
130 Status::Done => counts.done += 1,
131 Status::Cancelled => counts.cancelled += 1,
132 }
133 }
134 counts
135 }
136
137 pub fn active(&self) -> impl Iterator<Item = &Item> {
141 self.items.iter().filter(|i| !i.status.is_finished())
142 }
143
144 pub fn current(&self) -> Option<&Item> {
146 self.items.iter().find(|i| i.status == Status::InProgress)
147 }
148
149 pub fn progress(&self) -> (usize, usize) {
151 let finished = self.items.iter().filter(|i| i.status.is_finished()).count();
152 (finished, self.items.len())
153 }
154}
155
156pub fn validate(items: &[Item]) -> Result<(), String> {
162 for (index, item) in items.iter().enumerate() {
163 let position = index + 1;
164 if item.id.trim().is_empty() {
165 return Err(format!(
166 "item {position} has no `id`; give each step a short unique id, because a merge \
167 patches by id"
168 ));
169 }
170 if item.content.trim().is_empty() {
171 return Err(format!(
172 "item {position} (`{}`) has no `content`; a step with nothing to do cannot be \
173 done or dropped",
174 item.id
175 ));
176 }
177 if let Some(earlier) = items[..index].iter().position(|i| i.id == item.id) {
178 return Err(format!(
179 "items {} and {position} share the id `{}`; an id has to name one step",
180 earlier + 1,
181 item.id
182 ));
183 }
184 }
185 Ok(())
186}
187
188pub fn merge(existing: &[Item], incoming: &[Item]) -> Vec<Item> {
195 let mut out = existing.to_vec();
196 for item in incoming {
197 match out.iter_mut().find(|e| e.id == item.id) {
198 Some(existing) => {
201 existing.content = item.content.clone();
202 existing.status = item.status;
203 existing.parent = item.parent.clone();
204 }
205 None => out.push(item.clone()),
206 }
207 }
208 out
209}
210
211pub fn one_in_progress(items: &mut [Item]) -> Vec<String> {
217 let mut seen = false;
218 let mut demoted = Vec::new();
219 for item in items.iter_mut() {
220 if item.status != Status::InProgress {
221 continue;
222 }
223 if seen {
224 item.status = Status::Pending;
225 demoted.push(item.id.clone());
226 } else {
227 seen = true;
228 }
229 }
230 demoted
231}
232
233#[cfg(test)]
234mod tests {
235 use super::*;
236
237 fn item(id: &str, status: Status) -> Item {
238 Item::new(id, &format!("step {id}"), status)
239 }
240
241 #[test]
242 fn a_merge_patches_in_place_and_appends_what_is_new() {
243 let existing = vec![
244 item("a", Status::Pending),
245 item("b", Status::Pending),
246 item("c", Status::Pending),
247 ];
248 let mut done = item("b", Status::Done);
249 done.content = "step b, finished".to_string();
250 let out = merge(&existing, &[done, item("d", Status::Pending)]);
251
252 assert_eq!(
253 out.iter().map(|i| i.id.as_str()).collect::<Vec<_>>(),
254 ["a", "b", "c", "d"],
255 "b is still second: a merge does not reorder the work that is left"
256 );
257 assert_eq!(out[1].status, Status::Done);
258 assert_eq!(out[1].content, "step b, finished");
259 assert_eq!(out[0].status, Status::Pending, "an unmentioned step stays");
260 }
261
262 #[test]
263 fn a_merge_keeps_what_it_does_not_mention() {
264 let existing = vec![item("a", Status::Done), item("b", Status::Pending)];
265 let out = merge(&existing, &[]);
266 assert_eq!(out, existing);
267 }
268
269 #[test]
270 fn one_in_progress_keeps_the_first_and_names_what_it_demoted() {
271 let mut items = vec![
272 item("a", Status::InProgress),
273 item("b", Status::InProgress),
274 item("c", Status::InProgress),
275 item("d", Status::Pending),
276 ];
277 let demoted = one_in_progress(&mut items);
278 assert_eq!(demoted, ["b", "c"]);
279 assert_eq!(items[0].status, Status::InProgress);
280 assert_eq!(items[1].status, Status::Pending);
281 assert_eq!(items[2].status, Status::Pending);
282 assert_eq!(items[3].status, Status::Pending);
283 }
284
285 #[test]
286 fn one_in_progress_leaves_a_single_marked_step_alone() {
287 let mut items = vec![item("a", Status::Pending), item("b", Status::InProgress)];
288 assert!(one_in_progress(&mut items).is_empty());
289 assert_eq!(items[1].status, Status::InProgress);
290 }
291
292 #[test]
293 fn counts_and_progress_are_the_four_numbers_and_finished_over_total() {
294 let plan = Plan::new(vec![
295 item("a", Status::Done),
296 item("b", Status::InProgress),
297 item("c", Status::Pending),
298 item("d", Status::Cancelled),
299 item("e", Status::Pending),
300 ]);
301 assert_eq!(
302 plan.counts(),
303 Counts {
304 pending: 2,
305 in_progress: 1,
306 done: 1,
307 cancelled: 1,
308 }
309 );
310 assert_eq!(plan.progress(), (2, 5));
311 assert_eq!(plan.current().map(|i| i.id.as_str()), Some("b"));
312 assert_eq!(
313 plan.active().map(|i| i.id.as_str()).collect::<Vec<_>>(),
314 ["b", "c", "e"],
315 "a handoff carries what is left, in order"
316 );
317 }
318
319 #[test]
320 fn validation_names_the_item_that_is_wrong() {
321 assert_eq!(
322 validate(&[
323 item("a", Status::Pending),
324 Item::new("b", " ", Status::Pending)
325 ])
326 .unwrap_err(),
327 "item 2 (`b`) has no `content`; a step with nothing to do cannot be done or dropped"
328 );
329 assert_eq!(
330 validate(&[
331 item("a", Status::Pending),
332 Item::new("", "x", Status::Pending)
333 ])
334 .unwrap_err(),
335 "item 2 has no `id`; give each step a short unique id, because a merge patches by id"
336 );
337 assert_eq!(
338 validate(&[
339 item("a", Status::Pending),
340 item("b", Status::Pending),
341 item("a", Status::Pending)
342 ])
343 .unwrap_err(),
344 "items 1 and 3 share the id `a`; an id has to name one step"
345 );
346 assert!(validate(&[]).is_ok(), "clearing a plan is legitimate");
347 }
348
349 #[test]
350 fn a_status_round_trips_and_accepts_the_spellings_a_model_writes() {
351 for status in [
352 Status::Pending,
353 Status::InProgress,
354 Status::Done,
355 Status::Cancelled,
356 ] {
357 assert_eq!(Status::parse(status.as_str()), Some(status));
358 }
359 assert_eq!(Status::parse("in-progress"), Some(Status::InProgress));
360 assert_eq!(Status::parse("Doing"), Some(Status::InProgress));
361 assert_eq!(Status::parse("completed"), Some(Status::Done));
362 assert_eq!(Status::parse("nonsense"), None);
363 }
364
365 #[test]
366 fn a_parent_groups_steps_without_a_second_shape() {
367 let mut phase = Item::new("p1", "The writer cluster", Status::InProgress);
368 phase.parent = None;
369 let mut step = Item::new("s1", "#535 array header", Status::Pending);
370 step.parent = Some("p1".to_string());
371 let plan = Plan::new(vec![phase, step]);
372 let nested: Vec<&Item> = plan
373 .items
374 .iter()
375 .filter(|i| i.parent.as_deref() == Some("p1"))
376 .collect();
377 assert_eq!(nested.len(), 1);
378 assert_eq!(nested[0].id, "s1");
379 }
380}