use super::reference::{WorkRef, tokens};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Section {
Roots,
Doing,
Queued,
Notes,
Decisions,
}
impl Section {
const ALL: [Self; 5] = [
Self::Roots,
Self::Doing,
Self::Queued,
Self::Notes,
Self::Decisions,
];
#[must_use]
pub const fn heading(self) -> &'static str {
match self {
Self::Roots => "Roots",
Self::Doing => "Doing",
Self::Queued => "Queued",
Self::Notes => "Notes",
Self::Decisions => "Decisions",
}
}
const fn holds_rows(self) -> bool {
matches!(self, Self::Roots | Self::Doing | Self::Queued)
}
#[must_use]
pub const fn is_open_work(self) -> bool {
matches!(self, Self::Doing | Self::Queued)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Row {
section: Section,
line: usize,
text: String,
}
impl Row {
#[must_use]
pub const fn section(&self) -> Section {
self.section
}
#[must_use]
pub const fn line(&self) -> usize {
self.line
}
#[must_use]
pub fn text(&self) -> &str {
&self.text
}
#[must_use]
pub fn summary(&self) -> &str {
self.text.lines().next().unwrap_or_default()
}
#[must_use]
pub fn references(&self) -> Vec<WorkRef> {
WorkRef::parse_all(&self.text)
}
#[must_use]
pub fn names(&self, id: &str) -> bool {
tokens(&self.text).any(|token| token == id)
}
#[must_use]
pub fn blocking_mark(&self) -> Option<&str> {
let mut words = tokens(&self.text);
words.find(|word| *word == "BLOCKING")?;
words.next()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Violation {
OutsideSection,
UnknownSection(String),
RepeatedSection(Section),
NotARow,
Checkbox,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LineViolation {
pub line: usize,
pub violation: Violation,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct TasksFile {
rows: Vec<Row>,
violations: Vec<LineViolation>,
lines: usize,
}
impl TasksFile {
#[must_use]
pub fn parse(content: &str) -> Self {
let mut file = Self::default();
let mut section: Option<Section> = None;
let mut seen: Vec<Section> = Vec::new();
let mut in_unknown = false;
let mut titled = false;
let mut fence: Option<(char, usize)> = None;
for (index, line) in content.lines().enumerate() {
let number = index + 1;
file.lines = number;
let free_text = section.is_some_and(|current| !current.holds_rows());
if free_text {
match (fence, Fence::of(line)) {
(None, Some(opening)) => {
fence = Some((opening.marker, opening.length));
continue;
}
(Some((marker, length)), Some(closing)) if closing.closes(marker, length) => {
fence = None;
continue;
}
(Some(_), _) => continue,
(None, None) => {}
}
}
if line.trim().is_empty() {
continue;
}
if let Some(heading) = line.strip_prefix("## ") {
let heading = heading.trim();
let named = Section::ALL
.into_iter()
.find(|candidate| candidate.heading() == heading);
if free_text && named.is_none() {
continue;
}
section = named;
in_unknown = section.is_none();
if let Some(found) = section {
if seen.contains(&found) {
file.violate(number, Violation::RepeatedSection(found));
}
seen.push(found);
} else {
file.violate(number, Violation::UnknownSection(heading.to_string()));
}
continue;
}
if in_unknown {
continue;
}
match section {
None => {
if !titled && seen.is_empty() && line.starts_with("# ") {
titled = true;
} else {
file.violate(number, Violation::OutsideSection);
}
}
Some(current) if !current.holds_rows() => {}
Some(current) => file.row_line(current, number, line),
}
}
file
}
fn violate(&mut self, line: usize, violation: Violation) {
self.violations.push(LineViolation { line, violation });
}
fn row_line(&mut self, section: Section, number: usize, line: &str) {
if let Some(text) = line.strip_prefix("- ").or_else(|| line.strip_prefix("* ")) {
let text = text.trim();
if ["[ ]", "[x]", "[X]"]
.iter()
.any(|checkbox| text.starts_with(checkbox))
{
self.violate(number, Violation::Checkbox);
return;
}
self.rows.push(Row {
section,
line: number,
text: text.to_string(),
});
return;
}
let continues = line.starts_with([' ', '\t'])
&& self.rows.last().is_some_and(|row| row.section == section);
match self.rows.last_mut() {
Some(row) if continues => {
row.text.push('\n');
row.text.push_str(line.trim());
}
_ => self.violate(number, Violation::NotARow),
}
}
#[must_use]
pub fn rows(&self) -> &[Row] {
&self.rows
}
#[must_use]
pub fn violations(&self) -> &[LineViolation] {
&self.violations
}
#[must_use]
pub const fn lines(&self) -> usize {
self.lines
}
#[must_use]
pub fn roots(&self) -> Vec<WorkRef> {
let mut roots: Vec<WorkRef> = Vec::new();
for reference in self
.rows
.iter()
.filter(|row| row.section == Section::Roots)
.flat_map(Row::references)
{
if !roots.contains(&reference) {
roots.push(reference);
}
}
roots
}
pub fn rows_naming<'a>(&'a self, reference: &'a WorkRef) -> impl Iterator<Item = &'a Row> {
self.rows.iter().filter(move |row| {
row.references()
.iter()
.any(|named| named.matches(reference))
})
}
pub fn rows_naming_id<'a>(&'a self, id: &'a str) -> impl Iterator<Item = &'a Row> {
self.rows.iter().filter(move |row| row.names(id))
}
}
struct Fence<'a> {
marker: char,
length: usize,
rest: &'a str,
}
impl<'a> Fence<'a> {
fn of(line: &'a str) -> Option<Self> {
let unindented = line.trim_start_matches(' ');
if line.len() - unindented.len() > 3 {
return None;
}
let marker = unindented
.chars()
.next()
.filter(|c| matches!(c, '`' | '~'))?;
let rest = unindented.trim_start_matches(marker);
let length = unindented.len() - rest.len();
(length >= 3).then_some(Self {
marker,
length,
rest,
})
}
fn closes(&self, marker: char, length: usize) -> bool {
self.marker == marker && self.length >= length && self.rest.trim().is_empty()
}
}
#[cfg(test)]
mod tests {
use super::*;
const WELL_FORMED: &str = "# Ship search\n\n## Roots\n- #129 event-driven tasks.md\n\n## Doing\n- #130 wire the backend, PR #12 open\n next: answer review\n- #131 pick a db BLOCKING req-7\n\n## Queued\n- #132 docs\n\n## Notes\nfree text, - [ ] even this\n### a heading\n\n## Decisions\n> \"use sqlite\"\n";
#[test]
fn a_well_formed_document_has_rows_and_no_violations() {
let file = TasksFile::parse(WELL_FORMED);
assert_eq!(file.violations(), &[]);
let rows: Vec<_> = file
.rows()
.iter()
.map(|row| (row.section(), row.line(), row.summary()))
.collect();
assert_eq!(
rows,
vec![
(Section::Roots, 4, "#129 event-driven tasks.md"),
(Section::Doing, 7, "#130 wire the backend, PR #12 open"),
(Section::Doing, 9, "#131 pick a db BLOCKING req-7"),
(Section::Queued, 12, "#132 docs"),
]
);
assert!(file.rows()[1].text().ends_with("next: answer review"));
assert_eq!(file.rows()[2].blocking_mark(), Some("req-7"));
assert_eq!(file.roots(), vec![WorkRef::issue(129)]);
assert_eq!(file.lines(), 19);
}
#[test]
fn each_kind_of_violation_is_reported_with_its_line() {
let file = TasksFile::parse(
"stray\n## Doing\n- [ ] old style\nplain\n## Plans\n- hidden\n## Doing\n- ok\n",
);
assert_eq!(
file.violations(),
&[
LineViolation {
line: 1,
violation: Violation::OutsideSection,
},
LineViolation {
line: 3,
violation: Violation::Checkbox,
},
LineViolation {
line: 4,
violation: Violation::NotARow,
},
LineViolation {
line: 5,
violation: Violation::UnknownSection("Plans".to_string()),
},
LineViolation {
line: 7,
violation: Violation::RepeatedSection(Section::Doing),
},
]
);
}
#[test]
fn rows_are_found_by_reference_and_by_id() {
let file = TasksFile::parse(WELL_FORMED);
let merged = WorkRef::pull_request(12);
let naming: Vec<_> = file.rows_naming(&merged).map(Row::line).collect();
assert_eq!(naming, vec![7]);
let asking: Vec<_> = file.rows_naming_id("req-7").map(Row::line).collect();
assert_eq!(asking, vec![9]);
assert_eq!(file.rows_naming_id("req").count(), 0);
}
#[test]
fn a_mark_reads_through_markdown_and_punctuation_like_names() {
for text in [
"- pick a db `BLOCKING` `req-7`",
"- pick a db (BLOCKING: req-7)",
"- pick a db **BLOCKING** req-7.",
] {
let file = TasksFile::parse(&format!("## Doing\n{text}\n"));
let row = &file.rows()[0];
assert_eq!(row.blocking_mark(), Some("req-7"), "{text}");
assert!(row.names("req-7"), "{text}");
}
let trailing = TasksFile::parse("## Doing\n- pick a db `BLOCKING`\n");
assert_eq!(trailing.rows()[0].blocking_mark(), None);
}
#[test]
fn free_text_holds_headings_and_fences_of_its_own() {
let file = TasksFile::parse(
"## Notes\n## Findings\n```md\n## Doing\n- not a row\n```\n~~~~\n## Roots\n~~~\n~~~~\n## Decisions\n> \"## Queued is fine\"\n## Doing\n- #4 real row\n",
);
assert_eq!(file.violations(), &[]);
let rows: Vec<_> = file
.rows()
.iter()
.map(|row| (row.section(), row.summary()))
.collect();
assert_eq!(rows, vec![(Section::Doing, "#4 real row")]);
}
#[test]
fn a_known_heading_outside_a_fence_still_ends_free_text() {
let file = TasksFile::parse("## Notes\ntext\n## Notes\n");
assert_eq!(
file.violations(),
&[LineViolation {
line: 3,
violation: Violation::RepeatedSection(Section::Notes),
}]
);
}
}