use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Status {
Pending,
InProgress,
Done,
Cancelled,
}
impl Status {
pub fn as_str(self) -> &'static str {
match self {
Self::Pending => "pending",
Self::InProgress => "in_progress",
Self::Done => "done",
Self::Cancelled => "cancelled",
}
}
pub fn parse(word: &str) -> Option<Self> {
match word.trim().to_ascii_lowercase().as_str() {
"pending" | "todo" => Some(Self::Pending),
"in_progress" | "in-progress" | "inprogress" | "doing" | "active" => {
Some(Self::InProgress)
}
"done" | "completed" | "complete" => Some(Self::Done),
"cancelled" | "canceled" | "dropped" | "skipped" => Some(Self::Cancelled),
_ => None,
}
}
pub fn mark(self) -> &'static str {
match self {
Self::Pending => "[ ]",
Self::InProgress => "[~]",
Self::Done => "[x]",
Self::Cancelled => "[-]",
}
}
pub fn is_finished(self) -> bool {
matches!(self, Self::Done | Self::Cancelled)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Item {
pub id: String,
pub content: String,
pub status: Status,
#[serde(skip_serializing_if = "Option::is_none")]
pub parent: Option<String>,
}
impl Item {
pub fn new(id: &str, content: &str, status: Status) -> Self {
Self {
id: id.to_string(),
content: content.to_string(),
status,
parent: None,
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Plan {
pub revision: u64,
pub items: Vec<Item>,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Counts {
pub pending: usize,
pub in_progress: usize,
pub done: usize,
pub cancelled: usize,
}
impl Plan {
pub fn new(items: Vec<Item>) -> Self {
Self { revision: 0, items }
}
pub fn counts(&self) -> Counts {
let mut counts = Counts::default();
for item in &self.items {
match item.status {
Status::Pending => counts.pending += 1,
Status::InProgress => counts.in_progress += 1,
Status::Done => counts.done += 1,
Status::Cancelled => counts.cancelled += 1,
}
}
counts
}
pub fn active(&self) -> impl Iterator<Item = &Item> {
self.items.iter().filter(|i| !i.status.is_finished())
}
pub fn current(&self) -> Option<&Item> {
self.items.iter().find(|i| i.status == Status::InProgress)
}
pub fn progress(&self) -> (usize, usize) {
let finished = self.items.iter().filter(|i| i.status.is_finished()).count();
(finished, self.items.len())
}
}
pub fn validate(items: &[Item]) -> Result<(), String> {
for (index, item) in items.iter().enumerate() {
let position = index + 1;
if item.id.trim().is_empty() {
return Err(format!(
"item {position} has no `id`; give each step a short unique id, because a merge \
patches by id"
));
}
if item.content.trim().is_empty() {
return Err(format!(
"item {position} (`{}`) has no `content`; a step with nothing to do cannot be \
done or dropped",
item.id
));
}
if let Some(earlier) = items[..index].iter().position(|i| i.id == item.id) {
return Err(format!(
"items {} and {position} share the id `{}`; an id has to name one step",
earlier + 1,
item.id
));
}
}
Ok(())
}
pub fn merge(existing: &[Item], incoming: &[Item]) -> Vec<Item> {
let mut out = existing.to_vec();
for item in incoming {
match out.iter_mut().find(|e| e.id == item.id) {
Some(existing) => {
existing.content = item.content.clone();
existing.status = item.status;
existing.parent = item.parent.clone();
}
None => out.push(item.clone()),
}
}
out
}
pub fn one_in_progress(items: &mut [Item]) -> Vec<String> {
let mut seen = false;
let mut demoted = Vec::new();
for item in items.iter_mut() {
if item.status != Status::InProgress {
continue;
}
if seen {
item.status = Status::Pending;
demoted.push(item.id.clone());
} else {
seen = true;
}
}
demoted
}
#[cfg(test)]
mod tests {
use super::*;
fn item(id: &str, status: Status) -> Item {
Item::new(id, &format!("step {id}"), status)
}
#[test]
fn a_merge_patches_in_place_and_appends_what_is_new() {
let existing = vec![
item("a", Status::Pending),
item("b", Status::Pending),
item("c", Status::Pending),
];
let mut done = item("b", Status::Done);
done.content = "step b, finished".to_string();
let out = merge(&existing, &[done, item("d", Status::Pending)]);
assert_eq!(
out.iter().map(|i| i.id.as_str()).collect::<Vec<_>>(),
["a", "b", "c", "d"],
"b is still second: a merge does not reorder the work that is left"
);
assert_eq!(out[1].status, Status::Done);
assert_eq!(out[1].content, "step b, finished");
assert_eq!(out[0].status, Status::Pending, "an unmentioned step stays");
}
#[test]
fn a_merge_keeps_what_it_does_not_mention() {
let existing = vec![item("a", Status::Done), item("b", Status::Pending)];
let out = merge(&existing, &[]);
assert_eq!(out, existing);
}
#[test]
fn one_in_progress_keeps_the_first_and_names_what_it_demoted() {
let mut items = vec![
item("a", Status::InProgress),
item("b", Status::InProgress),
item("c", Status::InProgress),
item("d", Status::Pending),
];
let demoted = one_in_progress(&mut items);
assert_eq!(demoted, ["b", "c"]);
assert_eq!(items[0].status, Status::InProgress);
assert_eq!(items[1].status, Status::Pending);
assert_eq!(items[2].status, Status::Pending);
assert_eq!(items[3].status, Status::Pending);
}
#[test]
fn one_in_progress_leaves_a_single_marked_step_alone() {
let mut items = vec![item("a", Status::Pending), item("b", Status::InProgress)];
assert!(one_in_progress(&mut items).is_empty());
assert_eq!(items[1].status, Status::InProgress);
}
#[test]
fn counts_and_progress_are_the_four_numbers_and_finished_over_total() {
let plan = Plan::new(vec![
item("a", Status::Done),
item("b", Status::InProgress),
item("c", Status::Pending),
item("d", Status::Cancelled),
item("e", Status::Pending),
]);
assert_eq!(
plan.counts(),
Counts {
pending: 2,
in_progress: 1,
done: 1,
cancelled: 1,
}
);
assert_eq!(plan.progress(), (2, 5));
assert_eq!(plan.current().map(|i| i.id.as_str()), Some("b"));
assert_eq!(
plan.active().map(|i| i.id.as_str()).collect::<Vec<_>>(),
["b", "c", "e"],
"a handoff carries what is left, in order"
);
}
#[test]
fn validation_names_the_item_that_is_wrong() {
assert_eq!(
validate(&[
item("a", Status::Pending),
Item::new("b", " ", Status::Pending)
])
.unwrap_err(),
"item 2 (`b`) has no `content`; a step with nothing to do cannot be done or dropped"
);
assert_eq!(
validate(&[
item("a", Status::Pending),
Item::new("", "x", Status::Pending)
])
.unwrap_err(),
"item 2 has no `id`; give each step a short unique id, because a merge patches by id"
);
assert_eq!(
validate(&[
item("a", Status::Pending),
item("b", Status::Pending),
item("a", Status::Pending)
])
.unwrap_err(),
"items 1 and 3 share the id `a`; an id has to name one step"
);
assert!(validate(&[]).is_ok(), "clearing a plan is legitimate");
}
#[test]
fn a_status_round_trips_and_accepts_the_spellings_a_model_writes() {
for status in [
Status::Pending,
Status::InProgress,
Status::Done,
Status::Cancelled,
] {
assert_eq!(Status::parse(status.as_str()), Some(status));
}
assert_eq!(Status::parse("in-progress"), Some(Status::InProgress));
assert_eq!(Status::parse("Doing"), Some(Status::InProgress));
assert_eq!(Status::parse("completed"), Some(Status::Done));
assert_eq!(Status::parse("nonsense"), None);
}
#[test]
fn a_parent_groups_steps_without_a_second_shape() {
let mut phase = Item::new("p1", "The writer cluster", Status::InProgress);
phase.parent = None;
let mut step = Item::new("s1", "#535 array header", Status::Pending);
step.parent = Some("p1".to_string());
let plan = Plan::new(vec![phase, step]);
let nested: Vec<&Item> = plan
.items
.iter()
.filter(|i| i.parent.as_deref() == Some("p1"))
.collect();
assert_eq!(nested.len(), 1);
assert_eq!(nested[0].id, "s1");
}
}