Files
worklane/src/util.rs
T
Ansho ReiandClaude Opus 5 3592584747 Edit a campaign's description, and bump to 0.27.0
`campaign set` reached the title and the codename, so the description a
campaign was filed with was the description it kept: fixing a typo in the
one field nothing could edit meant a hand edit of the file, or refiling the
campaign and reassigning every member.

Both halves arrive together, which is why d637288 left this out rather than
adding the flag. `campaign set --description` replaces the section and
`campaign append --description` adds a paragraph to it, because a `set` with
no `append` is the half that is easy to reach for and wrong: replacing a
description to add a sentence is how the rest of it gets lost.

`append` is a campaign's own subcommand rather than the top-level one, which
resolves a ticket. `resolve_in`'s tiers are the same over both directories,
so one positional naming either object could resolve in each with nothing
but a flag to say which was meant, and it would make a liar of the
explanation `resolve_ticket` gives a ticket search that names a campaign.

The section is the `DESCRIPTION` entry and the surgery is
`set_section_body`, `append_section_body` and `Section::normalise`, not a
copy scoped to campaigns. `SECTION_ORDER` needs no campaign variant: a
campaign holds one section where a ticket holds four, and the followers a
campaign does not have are simply not in the file, so its description
anchors against `## Metadata`, where `campaign_body` writes it.

Still no `--clear`, and that is now a decision rather than a deferral: a
campaign's description has no cleared form, so an empty `--description ""`
is a paragraph break here as it is everywhere else, and the refusal for an
all-blank value says there is nowhere to go back to instead of naming a flag
that does not exist. `replaced_items` and `appended_items` hold that check
once for both objects, with the way out as the caller's argument.

The section refusal no longer says "Ticket", since a campaign reaches it
too.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-24 04:53:49 +02:00

5247 lines
208 KiB
Rust

use anyhow::{Result, anyhow};
use chrono::NaiveDateTime;
use std::fs;
use std::io::IsTerminal;
use std::path::Path;
use std::sync::OnceLock;
/// How timestamps are written into tickets and comments, and therefore how they
/// are read back. Shared so the writer and the reader cannot drift apart.
pub const TIMESTAMP_FORMAT: &str = "%Y-%m-%d %H:%M:%S";
/// How a comment filename is stamped.
///
/// Microseconds, not seconds: at second resolution two comments in the same
/// second produced the same name and the second silently truncated the first.
/// Fixed width, so the lexicographic sort in `read_comments` stays chronological.
pub const COMMENT_FILE_FORMAT: &str = "%Y%m%d_%H%M%S_%6f";
/// Where a ticket's comments live, under the board.
///
/// Beside the status directories rather than among them, the way `campaigns_dir` is: a
/// comment has no status of its own. Spelled once here, so the writer, the reader and the
/// card's counter cannot disagree about the path.
pub const COMMENTS_DIR: &str = "comments";
/// The comments directory for one ticket, named by its full uuid.
pub fn comments_dir(board: &Path, uuid: &str) -> std::path::PathBuf {
board.join(COMMENTS_DIR).join(uuid)
}
/// The mark a card puts after its comment count.
///
/// A closing quotation ornament, so `2\u{275e}` reads as two things somebody said rather
/// than as a second bracketed counter beside the criteria.
///
/// Deliberately neither U+1F4AC SPEECH BALLOON nor U+1F5E8 LEFT SPEECH BUBBLE. The first
/// has emoji presentation and East Asian Width Wide, so it draws two cells where
/// `spans_width` counts one character and every corner on the card would be a cell out.
/// The second is text presentation and Neutral, but sits in a pictograph block most
/// terminal fonts leave as tofu. This one is a Dingbat, with the coverage the priority
/// meter's Geometric Shapes have, and Neutral, so it is one cell wherever `BLOCKED_MARK`
/// already is.
pub const COMMENT_MARK: &str = "\u{275e}";
/// Whether colour is wanted, from the three inputs that decide it.
///
/// Split out from the caching wrapper so it can be tested without a pty and
/// without touching the process environment.
///
/// `NO_COLOR` follows the no-color.org convention: set and non-empty disables,
/// whatever the value. An empty value is treated as unset, which is what lets a
/// wrapper script clear an inherited one.
fn colors_wanted(is_terminal: bool, no_color: Option<&str>, term: Option<&str>) -> bool {
if no_color.is_some_and(|value| !value.is_empty()) {
return false;
}
if matches!(term, Some("dumb") | Some("")) {
return false;
}
is_terminal
}
pub fn should_use_colors() -> bool {
// Decided once: it cannot change mid-run, and color_text asks on every call.
static ENABLED: OnceLock<bool> = OnceLock::new();
*ENABLED.get_or_init(|| {
let no_color = std::env::var("NO_COLOR").ok();
let term = std::env::var("TERM").ok();
colors_wanted(std::io::stdout().is_terminal(), no_color.as_deref(), term.as_deref())
})
}
/// The palette, as a type rather than a set of strings.
///
/// One definition for both renderers. The CLI needs an escape sequence and the TUI
/// needs a `ratatui::style::Color`, and an enum makes a colour that exists for one and
/// not the other a compile error instead of something a test has to go looking for.
/// The stringly-typed version needed exactly such a test, and a missing entry silently
/// produced an empty prefix, which is how `magenta` came to be undefined.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Color {
Red,
Cyan,
Orange,
Green,
Grey,
Magenta,
BrightRed,
// The eight the tag palette draws from. Named as colours rather than as `TagBlue`,
// because the enum is the palette and `TAG_COLORS` is what reserves them: a use
// belongs to the list that claims it, not to the name of the colour it claims.
Blue,
Sky,
Violet,
Pink,
Turquoise,
Olive,
Tan,
Steel,
}
impl Color {
/// The SGR sequence the CLI writes.
pub fn ansi(self) -> &'static str {
match self {
Color::Red => "\x1b[31m",
Color::Cyan => "\x1b[36m",
Color::Orange => "\x1b[33m",
Color::Green => "\x1b[32m",
// Indexed colour 8 in the 256-colour form, which is byte for byte what
// crossterm emits for ratatui's Color::DarkGray, the grey frig and pantop
// use for dimmed rows. Neither SGR 90 nor 37 renders as grey on every
// palette: 90 leans on the bright-black slot and 37 can sit right on top
// of the default foreground.
Color::Grey => "\x1b[38;5;8m",
// Bold, per the guideline in AGENTS.md.
Color::Magenta => "\x1b[1;35m",
// Indexed, for the same reason grey is: this is the spelling that renders.
Color::BrightRed => "\x1b[38;5;9m",
// The tag palette, indexed throughout. The basic slots are themed by the
// terminal and drift towards each other on a real palette, which is fine
// for seven colours that each mean something and useless for six that have
// to stay apart from those seven and from one another.
Color::Blue => "\x1b[38;5;33m",
Color::Sky => "\x1b[38;5;117m",
Color::Violet => "\x1b[38;5;99m",
Color::Pink => "\x1b[38;5;205m",
Color::Turquoise => "\x1b[38;5;43m",
Color::Olive => "\x1b[38;5;106m",
Color::Tan => "\x1b[38;5;137m",
Color::Steel => "\x1b[38;5;67m",
}
}
/// Every colour in the palette, so a test can walk them without listing them.
pub const ALL: [Color; 15] = [
Color::Red,
Color::Cyan,
Color::Orange,
Color::Green,
Color::Grey,
Color::Magenta,
Color::BrightRed,
Color::Blue,
Color::Sky,
Color::Violet,
Color::Pink,
Color::Turquoise,
Color::Olive,
Color::Tan,
Color::Steel,
];
}
/// The colours a tag may be drawn in.
///
/// Deliberately disjoint from the seven that already carry a meaning, per the guideline
/// in AGENTS.md: a tag in red reads as a uuid, in green as a title, in grey as an unset
/// value. Reserving slots here rather than picking at the call site is what keeps the
/// next colour someone assigns from landing on top of the tags.
///
/// Eight, and a real board carries more tags than that, so two tags will share a
/// colour. That is accepted rather than designed around: the colour groups one tag
/// across cards, it does not identify it, and the tag is written out beside it either
/// way. Nothing pure can do better, since a function of the tag alone cannot know what
/// else sits on the card.
///
/// Eight rather than six because two tags on one card collide at roughly `1 / n`, so
/// the only lever is the size of the list. It stops here because these are the slots
/// the assigned meanings leave: red, orange, green, cyan, magenta and grey are spoken
/// for, and a ninth would have to be a shade of one of the eight. Two colours nobody
/// can tell apart are a collision by another name.
///
/// At eight, about a fifth of the cards on this board show two tags in one colour. That
/// is the arithmetic, not a fault to fix: the colour groups one tag *across* cards, so
/// a repeat within a card costs nothing that the tag text beside it does not answer.
///
/// Do not tune this against the tags on one board. The count of collisions on any given
/// board swings either side of the average on the luck of the hash, and picking the
/// length that flatters today's vocabulary would be fitting to noise. An earlier draft
/// scored two collisions in sixty-four here, which looked like a good palette and was
/// really a broken index folding the whole vocabulary into a handful of slots.
pub const TAG_COLORS: [Color; 8] = [
Color::Blue,
Color::Sky,
Color::Violet,
Color::Pink,
Color::Turquoise,
Color::Olive,
Color::Tan,
Color::Steel,
];
/// FNV-1a, 64 bit, over the bytes of the tag.
///
/// Written out rather than taken from `std`: `DefaultHasher` is explicitly not promised
/// to keep its output stable across releases, and a board that repaints itself on a
/// toolchain upgrade has lost the one property this is for. Nine lines and no
/// dependency buys a mapping that is the same on every machine and every version.
fn fnv1a(bytes: &[u8]) -> u64 {
const OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
const PRIME: u64 = 0x0000_0100_0000_01b3;
let mut hash = OFFSET;
for byte in bytes {
hash ^= u64::from(*byte);
hash = hash.wrapping_mul(PRIME);
}
hash
}
/// The colour a tag is drawn in, derived from the tag itself.
///
/// A pure function of the string, so the same tag is the same colour on every card, in
/// every view and on every board, with nothing stored and nothing to keep in step. Two
/// boards that have never met agree about `bug`.
///
/// Case sensitive, because `Bug` and `bug` are two different tags everywhere else in
/// worklane. Colouring them alike would be the display claiming a sameness the filter
/// and the field do not have.
pub fn tag_color(tag: &str) -> Color {
// Multiply-shift, not `% len`. The palette length is a power of two, so a modulus
// would keep the low three bits of the hash, and FNV-1a's low bits carry only the
// low bits of the input bytes: the multiply cannot move information downwards and
// the xor never does. `bug` and `BUG` differ in bit 5 of every letter, so under a
// modulus they landed in the same slot no matter what else the strings held, as did
// every other pair differing only above bit 2. Taking the top bits of the product
// uses the whole hash, which is where the avalanche is.
let index = (u128::from(fnv1a(tag.as_bytes())) * TAG_COLORS.len() as u128) >> 64;
TAG_COLORS[index as usize]
}
/// The same palette as ratatui sees it.
///
/// Chosen to match what crossterm emits for the escape above, so a card in the TUI and
/// a row in the listing are the same colour rather than two guesses at it.
impl From<Color> for ratatui::style::Color {
fn from(color: Color) -> Self {
use ratatui::style::Color as Tui;
match color {
Color::Red => Tui::Red,
Color::Cyan => Tui::Cyan,
Color::Orange => Tui::Yellow,
Color::Green => Tui::Green,
Color::Grey => Tui::DarkGray,
Color::Magenta => Tui::Magenta,
Color::BrightRed => Tui::LightRed,
// Indexed on both sides, so the card and the listing are the same colour
// by construction rather than by two guesses that happen to agree.
Color::Blue => Tui::Indexed(33),
Color::Sky => Tui::Indexed(117),
Color::Violet => Tui::Indexed(99),
Color::Pink => Tui::Indexed(205),
Color::Turquoise => Tui::Indexed(43),
Color::Olive => Tui::Indexed(106),
Color::Tan => Tui::Indexed(137),
Color::Steel => Tui::Indexed(67),
}
}
}
/// `color_text` with the decision passed in rather than asked for.
///
/// The seam matters for anything that aligns columns: a caller has to be able to
/// render both ways in one process to prove the padding does not depend on it.
pub fn paint(text: &str, color: Color, enabled: bool) -> String {
if enabled {
format!("{}{}{}", color.ansi(), text, "\x1b[0m")
} else {
text.to_string()
}
}
pub fn color_text(text: &str, color: Color) -> String {
paint(text, color, should_use_colors())
}
/// What sits at a candidate `.worklane` path.
///
/// The distinction the walk turns on is between nothing there and something
/// unusable there. `exists()` follows a link, so a dangling one answered the same
/// as an empty parent and the walk carried on upward until it met a board above
/// the project, which then became the board every write went to. Silently. With
/// the boards kept outside the project a dangling link is an ordinary state
/// rather than a corrupted tree: it is what you have before the boards repo is
/// cloned, and after a board directory is renamed.
#[derive(Debug, PartialEq)]
enum Candidate {
/// Nothing at that path, which is the one answer the walk carries on from.
Absent,
/// A directory, or a link that resolves to one.
Board,
/// A link that resolves to nothing, carrying the target it names.
Dangling(std::path::PathBuf),
/// There, and not a directory: a regular file, or a link to one.
NotADirectory,
}
/// Which of the four a `.worklane` path is.
///
/// `symlink_metadata` first, so the answer is about the entry itself and absence
/// cannot be confused with a target that is gone. Only then is the link followed,
/// which is what makes a resolvable one indistinguishable from a real directory.
fn classify(path: &Path) -> Result<Candidate> {
let entry = match fs::symlink_metadata(path) {
Ok(entry) => entry,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Candidate::Absent),
// Anything other than absence is a filesystem that could not answer, and
// reading that as absence is how the walk-past worked in the first place.
Err(error) => return Err(anyhow!("Could not read {}: {error}", path.display())),
};
if !entry.is_symlink() {
return Ok(match entry.is_dir() {
true => Candidate::Board,
false => Candidate::NotADirectory,
});
}
// Read whether or not it resolves: the target is the only part of the failure
// that says what to go and fix.
let target = fs::read_link(path).unwrap_or_else(|_| path.to_path_buf());
Ok(match fs::metadata(path) {
Ok(resolved) if resolved.is_dir() => Candidate::Board,
Ok(_) => Candidate::NotADirectory,
Err(_) => Candidate::Dangling(target),
})
}
/// The first `.worklane` at or above `start`.
///
/// The symlink stays unresolved in what is returned, so a board reached through a
/// link is the same path to everything downstream as one sitting in the project.
pub fn find_worklane_dir(start: &Path) -> Result<std::path::PathBuf> {
let mut current = start.canonicalize()?;
loop {
let worklane_dir = current.join(".worklane");
match classify(&worklane_dir)? {
Candidate::Board => return Ok(worklane_dir),
// The only answer that hands the search upward. A `.worklane` that is
// there but unusable is this project's board and is reported here,
// rather than quietly becoming a write to whatever sits above it.
Candidate::Absent => {}
Candidate::Dangling(target) => {
return Err(anyhow!(
"{} is a symlink to {}, which does not exist. The boards repo may not be cloned on this machine.",
worklane_dir.display(),
target.display()
));
}
Candidate::NotADirectory => {
return Err(anyhow!(
"{} is not a directory. A board is a directory of ticket files.",
worklane_dir.display()
));
}
}
if !current.pop() {
break;
}
}
Err(anyhow!("No .worklane directory found. Run `worklane init` first."))
}
/// Width of the abbreviated id shown by `ls` and by the disambiguation list.
pub const SHORT_ID_WIDTH: usize = 7;
/// The leading characters of `text`, counted in characters rather than bytes.
///
/// Byte slicing panics twice over here: on text shorter than the width, and on a
/// multibyte character straddling the cut. Both reach this code from a filename,
/// which nothing validates.
pub fn truncate_chars(text: &str, width: usize) -> &str {
match text.char_indices().nth(width) {
Some((byte, _)) => &text[..byte],
None => text,
}
}
/// A ticket id abbreviated for display.
pub fn short_id(id: &str) -> &str {
truncate_chars(id, SHORT_ID_WIDTH)
}
pub fn slug(title: &str) -> String {
title
.to_lowercase()
.chars()
.filter(|c| c.is_alphanumeric() || *c == ' ' || *c == '-' || *c == '_')
.map(|c| if c == ' ' { '-' } else { c })
.collect()
}
pub fn get_git_user() -> Option<String> {
std::process::Command::new("git")
.args(["config", "user.name"])
.output()
.ok()
.and_then(|out| {
if out.status.success() {
String::from_utf8(out.stdout)
.ok()
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
} else {
None
}
})
}
/// One file a search matched, and where it was found.
pub struct Found {
/// The name the match is reported under: the status directory for a ticket, and
/// empty for a campaign, which has no status of its own.
pub dir: String,
pub title: String,
pub content: String,
/// The uuid from the filename, which is what the first tier matches a prefix
/// against.
pub uuid: String,
}
/// The candidate list for an ambiguous search, as an error rather than a print
/// followed by `exit(1)`.
///
/// An error reaches the user on stderr and leaves the exit code non-zero, which
/// is the only combination the opencode wrapper can relay: it throws on the exit
/// code and keeps stderr, so the list printed to stdout was thrown away and the
/// agent saw nothing but a bare exit code.
///
/// `noun` names what was searched, since campaigns resolve through the same tiers and
/// "multiple tickets found" would be a lie for one.
pub fn ambiguous(noun: &str, search: &str, matches: &[Found]) -> anyhow::Error {
let mut message = format!("Multiple {}s found matching '{}':\n", noun, search);
for (i, found) in matches.iter().enumerate() {
// A campaign is in no status directory, so there is no bracket to print for it.
let status = match found.dir.is_empty() {
true => String::new(),
false => format!(" [{}]", color_text(&found.dir, Color::Orange)),
};
message.push_str(&format!(
" {}. ({}) {}{}\n",
i + 1,
color_text(short_id(&found.uuid), Color::Red),
found.title,
status,
));
}
message.push_str("\nUse the displayed ID or a more specific search term to select.");
anyhow!(message)
}
/// Shortest search tried as a UUID prefix. Below it the search is text, so a one or
/// two character term is a title search rather than a prefix matching half the board.
///
/// Four, not eight. The guard this replaces read `short_id.len() >= 8`, and `short_id`
/// there was always the full 36 character uuid, so it was always true and any length
/// already worked. Requiring eight would have broken the id the tool prints itself:
/// `ls` shows [`SHORT_ID_WIDTH`] characters, and pasting that back has to resolve.
pub const MIN_ID_SEARCH: usize = 4;
/// The ticket's title, from the first `# ` heading, or empty when it has none.
///
/// Public for the campaign index, whose files carry their title the same way.
pub fn heading_title(content: &str) -> String {
content
.lines()
.find(|line| line.starts_with("# "))
.map(|line| line[2..].trim().to_string())
.unwrap_or_default()
}
/// The status directories as [`resolve_in`] takes them.
fn status_paths(worklane_dir: &Path) -> Vec<(String, std::path::PathBuf)> {
status_dirs()
.into_iter()
.map(|status| (status.to_string(), worklane_dir.join(status)))
.collect()
}
/// The four-tier search, run over `dirs`, returning the first tier that matched
/// anything.
///
/// Four tiers, filled in one pass and consulted in order. A uuid prefix has to win
/// outright rather than join a flat list: ticket titles reference other tickets by id,
/// so an exact prefix match was reported as ambiguous against whichever title happened
/// to mention it.
///
/// **An exact codename wins over all three.** It is the one tier that is an exact match on
/// a field written for the purpose, so it cannot be a coincidence the way a substring can,
/// and a codename of `v1` is too short to be tried as an id at all. Only campaigns carry
/// the field, so for a ticket the tier is always empty and resolution is exactly what it
/// was. It lives here rather than in a campaign-only path for the reason the rest of this
/// function is shared: that would be a second copy of the precedence rules and a second
/// ambiguity message.
///
/// Shared by tickets and campaigns rather than written twice. A campaign is addressed
/// exactly the way a ticket is, and a second resolver would be a second copy of the
/// precedence rules to keep in step. Each entry pairs the name a match is reported
/// under with the directory to read, so what a location means is the caller's to say.
pub fn resolve_in(search: &str, dirs: &[(String, std::path::PathBuf)]) -> Result<Vec<Found>> {
let search_lower = search.to_lowercase();
let long_enough_for_an_id = search.chars().count() >= MIN_ID_SEARCH;
let mut by_codename: Vec<Found> = Vec::new();
let mut by_id: Vec<Found> = Vec::new();
let mut by_title: Vec<Found> = Vec::new();
let mut by_filename: Vec<Found> = Vec::new();
for (name, path) in dirs {
if !path.exists() {
continue;
}
for entry in fs::read_dir(path)?.filter_map(|e| e.ok()) {
let path = entry.path();
if !path.extension().is_some_and(|e| e == "md") {
continue;
}
let content = match fs::read_to_string(&path) {
Ok(c) => c,
Err(_) => continue,
};
let title = heading_title(&content);
let filename = path
.file_stem()
.map(|s| s.to_string_lossy().to_string())
.unwrap_or_default();
let uuid = filename.split('_').next().unwrap_or("");
// Case insensitive like the other three: a codename typed back off a listing
// has to resolve whatever case it was read in, which is the bargain the id
// tier already takes.
let is_codename = parse_codename(&content)
.is_some_and(|codename| codename.to_lowercase() == search_lower);
let by_prefix = long_enough_for_an_id && uuid.to_lowercase().starts_with(&search_lower);
let in_title = title.to_lowercase().contains(&search_lower);
// Still reaches the middle of a uuid, which the prefix tier cannot.
let in_filename = filename.to_lowercase().contains(&search_lower);
if !(is_codename || by_prefix || in_title || in_filename) {
continue;
}
let found = Found {
dir: name.clone(),
title,
content,
uuid: uuid.to_string(),
};
if is_codename {
by_codename.push(found);
} else if by_prefix {
by_id.push(found);
} else if in_title {
by_title.push(found);
} else {
by_filename.push(found);
}
}
}
Ok(match (by_codename.is_empty(), by_id.is_empty(), by_title.is_empty()) {
(false, _, _) => by_codename,
(true, false, _) => by_id,
(true, true, false) => by_title,
(true, true, true) => by_filename,
})
}
pub fn resolve_ticket(search: &str, worklane_dir: &Path) -> Result<(String, String, String)> {
let mut matches = resolve_in(search, &status_paths(worklane_dir))?;
if matches.is_empty() {
// A campaign is the other thing a search can name, and it is on no status
// directory, so it never reaches the tiers above. Explained here rather than in
// each command, so every argument that takes a ticket says the same thing and
// `mv <campaign>` refuses with a reason instead of a hunt for a typo.
if let Some(title) = crate::campaign::campaign_named(search, worklane_dir) {
return Err(anyhow!(
"'{}' is a campaign, not a ticket. A campaign sits in no status \
directory: its state is derived from its members. \
Try `worklane campaign show {}`.",
title,
search
));
}
return Err(anyhow!("No ticket found matching '{}'", search));
}
if matches.len() > 1 {
return Err(ambiguous("ticket", search, &matches));
}
let found = matches.remove(0);
Ok((found.dir, found.title, found.content))
}
pub fn format_comments(comments: &[(String, String, String, String)]) -> String {
format_comments_with(comments, should_use_colors())
}
/// As above, with the colour decision passed in for the TUI.
pub fn format_comments_with(
comments: &[(String, String, String, String)],
colored: bool,
) -> String {
if comments.is_empty() {
return paint("No comments yet.", Color::Grey, colored);
}
let mut result = String::new();
result.push('\n');
result.push_str(&paint("COMMENTS", Color::Orange, colored));
result.push_str(&format!("\n{}\n", "─".repeat(20)));
for (_filename, author, time, body) in comments {
result.push('\n');
result.push_str(&paint(&format!("From {} ({})", author, time), Color::Cyan, colored));
result.push('\n');
if !body.is_empty() {
result.push_str(" ");
result.push_str(body);
}
result.push('\n');
}
result
}
/// The parts of a ticket's body that cannot be rendered from the file alone.
///
/// Both are resolved against the rest of the board. The Relations section stores one
/// side of each edge and a bare uuid for each target, so the body alone cannot say what
/// a relation points at nor that anything points back. The Campaign field stores a uuid
/// whose title lives in another file entirely.
///
/// Passed in rather than derived in [`content_trim`], which has only the body, and so
/// the board can render the same text with colour off. A struct rather than two more
/// parameters, so the next thing resolved from the board is one field here instead of
/// an edit at every call site.
#[derive(Default)]
pub struct Resolved {
/// The relations of the ticket, both directions, from [`relations_for`]. Empty for a
/// ticket with none at either end.
///
/// Rows rather than the rendered block: the CLI paints them into escapes and the
/// board styles the same rows itself, since a paragraph is no place for an escape.
pub relations: Vec<RelationRow>,
/// The Campaign value as it reads, from [`reference_cell`]. Empty leaves the stored
/// value to render as it sits, which is what a ticket in no campaign wants.
pub campaign: String,
}
pub fn content_trim_colored(content: &str, resolved: &Resolved) -> String {
content_trim(content, should_use_colors(), resolved)
}
/// A section heading, its rule, and the blank line the body opens under.
///
/// The rule is measured on the name as displayed, in characters. It used to span the
/// raw line, so it ran three past the heading for the `## `, and byte length over-drew
/// anything non-ASCII.
fn push_heading(out: &mut Body, heading: &str, colored: bool) {
let name = heading.strip_prefix("## ").unwrap_or(heading);
out.push_str(&paint(name, Color::Orange, colored));
out.push('\n');
out.push_str(&"─".repeat(name.chars().count()));
out.push('\n');
out.push('\n');
}
/// The ticket body rendered for display, with the colour decision passed in.
///
/// The TUI needs the plain form: ratatui draws styled spans, and an escape sequence
/// embedded in a paragraph would be printed as literal bytes.
///
/// [`Resolved`] carries the parts that come from elsewhere on the board, since the
/// body alone cannot render them.
/// One piece of the rendered body: text as it prints, or relations still as rows.
///
/// The body is one string to the CLI and a run of styled lines to the board, and the
/// only part that differs is the relations block. Splitting the body here rather than
/// building it twice is what keeps the two views from drifting: everything outside the
/// block is rendered once, by [`content_parts`], and the rows are handed on unpainted.
pub enum BodyPart {
Text(String),
Relations(Vec<RelationRow>),
}
/// The body under construction. Text accumulates into the trailing run, and a relations
/// block closes it, so a caller pushes text and rows without tracking which it pushed
/// last.
#[derive(Default)]
struct Body {
parts: Vec<BodyPart>,
}
impl Body {
fn push_str(&mut self, text: &str) {
match self.parts.last_mut() {
Some(BodyPart::Text(run)) => run.push_str(text),
_ => self.parts.push(BodyPart::Text(text.to_string())),
}
}
fn push(&mut self, c: char) {
match self.parts.last_mut() {
Some(BodyPart::Text(run)) => run.push(c),
_ => self.parts.push(BodyPart::Text(c.to_string())),
}
}
fn push_relations(&mut self, rows: &[RelationRow]) {
self.parts.push(BodyPart::Relations(rows.to_vec()));
}
/// Whether the text written so far ends with `suffix`. A relations block never does,
/// since it is not text yet.
fn ends_with(&self, suffix: &str) -> bool {
match self.parts.last() {
Some(BodyPart::Text(run)) => run.ends_with(suffix),
_ => false,
}
}
}
pub fn content_trim(content: &str, colored: bool, resolved: &Resolved) -> String {
content_parts(content, colored, resolved)
.iter()
.map(|part| match part {
BodyPart::Text(text) => text.clone(),
BodyPart::Relations(rows) => render_relations(rows, colored),
})
.collect()
}
/// The body rendered into its parts, with the colour decision already applied to the
/// text and deliberately not to the relations.
pub fn content_parts(content: &str, colored: bool, resolved: &Resolved) -> Vec<BodyPart> {
let relations = resolved.relations.as_slice();
let lines: Vec<&str> = content.trim().lines().collect();
let mut result = Body::default();
let mut current_section = "";
let mut criterion = 0;
let mut i = 0;
// Whether the file keeps the section, which decides whether the block is spliced
// into it or injected ahead of the metadata.
let stores_relations = section_body(&lines, RELATIONS.heading).is_some();
let mut shown_relations = false;
while i < lines.len() {
let line = lines[i];
// Track current section
if let Some(section_name) = line.strip_prefix("## ") {
current_section = line;
// Only one side of a relation is stored, so a ticket nothing points at has
// no Relations section and still has relations to show. Injected where the
// file would have kept it, ahead of the metadata, rather than tacked on
// after everything.
if is_metadata_heading(line) && !stores_relations && !relations.is_empty() {
push_heading(&mut result, RELATIONS.heading, colored);
result.push_relations(relations);
result.push('\n');
shown_relations = true;
}
push_heading(&mut result, section_name, colored);
i += 1;
// Metadata is rendered as a block, so it is consumed here rather than
// falling through to the line-at-a-time cases below.
if is_metadata_heading(line) {
let end = section_end(&lines, i);
result.push_str(&render_metadata_table(
&lines[i..end],
colored,
&resolved.campaign,
));
i = end;
}
// As is Relations, whose stored lines carry a bare uuid each. The block
// holds the same edges resolved to a title, and the inverses with them.
if line.trim_end() == RELATIONS.heading && !relations.is_empty() {
let end = section_end(&lines, i);
result.push_relations(relations);
// The blank line the skipped body ended with, before the next heading.
if end < lines.len() {
result.push('\n');
}
i = end;
shown_relations = true;
}
continue;
}
// The title belongs to cmd_show, which prints it with its rule. Printing it
// again from the file content is what repeated it in every show output.
if line.starts_with("# ") && current_section.is_empty() {
i += 1;
// Along with the blank line the template puts under it, so dropping the
// title does not leave a gap where it used to be.
while i < lines.len() && lines[i].trim().is_empty() {
i += 1;
}
continue;
}
i += 1;
// Implementation Plan - color numbers in cyan
if current_section == "## Implementation Plan" {
result.push_str(&colorize_ordered(line, colored));
result.push('\n');
continue;
}
// Acceptance Criteria checkboxes, numbered so the index `check` takes is
// visible where the ticket is read. The number replaces the list marker
// rather than joining it, and is cyan like the numbers in the plan section.
if current_section == ACCEPTANCE.heading
&& let Some((checked, text)) = checkbox(line)
{
criterion += 1;
result.push_str(&paint(&format!("{}.", criterion), Color::Cyan, colored));
result.push(' ');
result.push_str(&paint(if checked { "[x]" } else { "[ ]" }, Color::Grey, colored));
result.push(' ');
result.push_str(&colorize_bold(text, colored));
result.push('\n');
continue;
}
// Standard markdown link colorization in cyan
if line.contains("[")
&& line.contains("(")
&& line.contains("]")
&& let Some(start) = line.find("[")
{
let bracket_text = &line[start..];
if let Some(end_bracket) = bracket_text.find("](") {
let link_start = start + end_bracket + 1;
if let Some(end) = line[link_start..].find(']') {
let absolute_end = link_start + end + 1;
result.push_str(&paint(&line[start..absolute_end], Color::Cyan, colored));
result.push('\n');
continue;
}
}
}
// Regular content - colorize **bold** in magenta
result.push_str(&colorize_bold(line, colored));
result.push('\n');
}
// A ticket with neither a Relations section nor a Metadata heading has nothing for
// the block to be injected ahead of, so it goes at the end rather than being lost.
if !relations.is_empty() && !shown_relations {
if !result.ends_with("\n\n") {
result.push('\n');
}
push_heading(&mut result, RELATIONS.heading, colored);
result.push_relations(relations);
}
result.parts
}
/// Colour the `1.` at the head of a numbered line, leaving the rest alone.
///
/// Takes the decision rather than asking for it. Asking is what put `\x1b[36m` and
/// `\x1b[0m` around every Implementation Plan number in the board's detail view,
/// which renders with colour off precisely because a paragraph is not a place an
/// escape sequence can go.
fn colorize_ordered(line: &str, colored: bool) -> String {
if line.chars().next().is_none_or(|c| !c.is_ascii_digit()) {
return line.to_string();
}
// Match "1. " pattern and color the number in cyan
let mut result = String::new();
let chars: Vec<char> = line.chars().collect();
for (i, c) in chars.iter().enumerate() {
if c.is_ascii_digit() {
// still scanning digits
} else if *c == '.' && i + 1 < chars.len() && chars[i + 1] == ' ' {
let number = &line[..i + 1];
result.push_str(&paint(number, Color::Cyan, colored));
result.push_str(&line[i + 1..]);
return result;
} else {
break;
}
}
line.to_string()
}
/// Space between a label column and the value beside it, in the metadata table and in
/// the relations block.
const COLUMN_GUTTER: &str = " ";
/// One line of the Metadata section, as the table sees it.
enum MetadataRow<'a> {
/// A `- **Name**: value` line, the shape the file stores fields in.
Field { name: &'a str, value: &'a str },
/// Anything else, carried through verbatim so a hand-written note in the
/// section is not dropped on the way to the screen.
Other(&'a str),
}
/// Split a metadata line into a field and its value, sharing the anchoring rules
/// `parse_ticket_field` uses: list marker optional, name matched at the start.
fn metadata_row(line: &str) -> MetadataRow<'_> {
let body = metadata_field_body(line);
let Some(rest) = body.strip_prefix("**") else {
return MetadataRow::Other(line);
};
let Some(close) = rest.find("**:") else {
return MetadataRow::Other(line);
};
MetadataRow::Field {
name: &rest[..close],
value: rest[close + "**:".len()..].trim(),
}
}
/// The value cell for a field, styled per the colour guideline.
///
/// `campaign` is the resolved cell for the Campaign field, empty when there is none.
/// The file stores the full uuid, per the rule the Relations section already follows,
/// so a bare value here would be thirty-six characters saying nothing.
fn metadata_value_cell(name: &str, value: &str, colored: bool, campaign: &str) -> String {
if name == CAMPAIGN_FIELD && !campaign.is_empty() {
return campaign.to_string();
}
if name == "Priority" {
// Reads as a glyph, while the file keeps storing the number.
let (glyph, colour) = priority_mark(priority_from_value(value));
return format!("{} {}", paint(glyph, colour, colored), value);
}
if is_unknown_value(value) {
return paint(value, Color::Grey, colored);
}
// The same word in the same colour as the label a card draws, since `tag_color` is a
// pure function of it. No mark here: the field name has already said what this is,
// and the mark is what tells a campaign from a tag on a row that holds both.
if name == CODENAME_FIELD {
return paint(value, tag_color(value), colored);
}
if name == "Tags" {
return paint_tags(value, colored);
}
value.to_string()
}
/// The stored tag list with each tag in its own colour.
///
/// Painted in place rather than split and rejoined, so whatever separators the file
/// holds come back unchanged. `bug, cli` and `bug,cli` are both written by hand at some
/// point, and a cell that normalised them would be the display quietly disagreeing with
/// the file it is showing.
fn paint_tags(value: &str, colored: bool) -> String {
value
.split(',')
.map(|piece| {
let tag = piece.trim();
if tag.is_empty() {
return piece.to_string();
}
let lead = piece.len() - piece.trim_start().len();
format!(
"{}{}{}",
&piece[..lead],
paint(tag, tag_color(tag), colored),
&piece[lead + tag.len()..]
)
})
.collect::<Vec<_>>()
.join(",")
}
/// Render the Metadata section as two aligned columns.
///
/// Taken as a block rather than a line at a time because the field column cannot be
/// sized until every name has been seen. The file is untouched by this: it goes on
/// storing the markdown list, and this is only how the list is shown.
fn render_metadata_table(lines: &[&str], colored: bool, campaign: &str) -> String {
// The heading already emits its own blank separator, so the one the template
// puts under it would otherwise open the section with a gap.
let start = lines
.iter()
.position(|line| !line.trim().is_empty())
.unwrap_or(lines.len());
let rows: Vec<MetadataRow> = lines[start..].iter().map(|line| metadata_row(line)).collect();
// Measured on the raw names, in characters, and padded before anything is
// styled. Measuring a coloured name counts its escape sequences towards its
// width, which is what tilts a table when colour is on and not when it is off.
let field_width = rows
.iter()
.filter_map(|row| match row {
MetadataRow::Field { name, .. } => Some(name.chars().count()),
MetadataRow::Other(_) => None,
})
.max()
.unwrap_or(0);
let mut result = String::new();
for row in &rows {
match row {
MetadataRow::Field { name, value } => {
result.push_str(&paint(name, Color::Red, colored));
result.push_str(&" ".repeat(field_width - name.chars().count()));
result.push_str(COLUMN_GUTTER);
result.push_str(&metadata_value_cell(name, value, colored, campaign));
}
// The decision this row is rendered under, not the one the terminal
// would give: `colorize_line` asked `should_use_colors()` here, which is
// how escapes reached the board's detail view.
MetadataRow::Other(text) => result.push_str(&colorize_bold(text, colored)),
}
result.push('\n');
}
result
}
/// What a scalar metadata field holds when it holds nothing.
///
/// A constant rather than a literal per site, because it is now written on purpose:
/// clearing a field puts it back, and the value it goes back to has to be the one `add`
/// wrote, or a cleared ticket and a never-set one would differ in the file.
pub const NOT_SET: &str = "_Not set_";
/// The same for Tags, which is a list.
///
/// A list that holds nothing reads as none rather than as not set, which is the
/// distinction `add` already makes and clearing has to keep.
pub const NONE: &str = "_None_";
/// Whether a field holds one of the two markers that mean it holds nothing.
///
/// The two constants and nothing else. `-None-` and `-Not set-` were accepted here from
/// the day the function was written, by analogy with the `**-Status**` field name the
/// `mv` splicing bug really did produce, c230d2c. But no version of this tool ever wrote
/// a hyphenated *value*: `git log -S` finds the two spellings in exactly one commit, the
/// one that added them to this line. They were dead from birth, and a ticket that somehow
/// holds one now reads as the text it is rather than being quietly taken for unset, which
/// is the right way round for corruption nobody can produce.
pub fn is_unknown_value(value: &str) -> bool {
let trimmed = value.trim();
trimmed == NONE || trimmed == NOT_SET
}
/// Replace `**bold**` with colour, or leave the line exactly as it is.
///
/// Taking `enabled` rather than asking makes both paths testable, and the
/// disabled path matters: stripping the markers when there is no colour to
/// replace them with loses the emphasis altogether, which is what happens to
/// every piped `show` and to everything the opencode tools read.
fn colorize_bold(line: &str, enabled: bool) -> String {
if !enabled {
return line.to_string();
}
let chars: Vec<char> = line.chars().collect();
let mut result = String::new();
let mut i = 0;
while i < chars.len() {
if !is_delimiter(&chars, i) {
result.push(chars[i]);
i += 1;
continue;
}
match (i + 2..chars.len()).find(|&at| is_delimiter(&chars, at)) {
Some(close) => {
let bold: String = chars[i + 2..close].iter().collect();
// `enabled`, not `should_use_colors()`. Asking again here made the
// flag a lie: the early return above respected it and this did not.
result.push_str(&paint(&bold, Color::Magenta, enabled));
i = close + 2;
}
// Unterminated: the rest is literal. The old scan walked off the end
// here and dropped the final character.
None => {
result.extend(&chars[i..]);
return result;
}
}
}
result
}
fn is_delimiter(chars: &[char], at: usize) -> bool {
chars.get(at) == Some(&'*') && chars.get(at + 1) == Some(&'*')
}
pub const METADATA_HEADING: &str = "## Metadata";
fn is_metadata_heading(line: &str) -> bool {
line.trim_end() == METADATA_HEADING
}
/// The lines of the Metadata section, or nothing when the heading is absent.
///
/// Field lookup has to be anchored here. Prose above the section is free text, so a
/// description quoting a field marker would otherwise shadow the real value below it.
fn metadata_lines(content: &str) -> impl Iterator<Item = &str> {
content
.lines()
.skip_while(|line| !is_metadata_heading(line))
.skip(1)
.take_while(|line| !line.starts_with("## "))
}
/// A metadata line without its list marker, so lookup can match on a prefix rather
/// than searching the whole line.
fn metadata_field_body(line: &str) -> &str {
let line = line.trim_start();
line.strip_prefix("- ").unwrap_or(line)
}
pub fn parse_ticket_field(content: &str, field: &str) -> String {
let prefix = format!("**{}**:", field);
metadata_lines(content)
.find_map(|line| metadata_field_body(line).strip_prefix(&prefix))
.map(|value| value.trim().to_string())
.unwrap_or_else(|| NOT_SET.to_string())
}
fn is_status_line(line: &str) -> bool {
let body = metadata_field_body(line);
// The second spelling is what earlier versions wrote, repair it on the way through.
body.starts_with("**Status**:") || body.starts_with("**-Status**:")
}
/// Rewrite one field in the Metadata section, leaving every other line untouched.
///
/// Scoped to the section for the same reason as `parse_ticket_field`: a description
/// line shaped like a metadata field would otherwise be rewritten in its place,
/// corrupting the prose and leaving the real metadata stale.
///
/// The matcher is a parameter because Status has a legacy spelling to repair, which no
/// other field has.
fn set_metadata_line(
content: &str,
field: &str,
value: &str,
matches: impl Fn(&str) -> bool,
) -> Option<String> {
let mut updated = String::with_capacity(content.len());
let mut in_metadata = false;
let mut found = false;
for line in content.lines() {
if line.starts_with("## ") {
in_metadata = is_metadata_heading(line);
}
if in_metadata && !found && matches(line) {
updated.push_str("- **");
updated.push_str(field);
updated.push_str("**: ");
updated.push_str(value);
found = true;
} else {
updated.push_str(line);
}
updated.push('\n');
}
if found { Some(updated) } else { None }
}
/// Drop one field from the Metadata section, leaving every other line untouched.
///
/// Scoped to the section for the same reason as [`set_metadata_line`], and shaped like
/// it: nothing means there was no such field, so a caller that removes a field a ticket
/// never carried leaves the content exactly as it found it rather than rewriting it
/// into an identical string.
fn remove_metadata_line(content: &str, field: &str) -> Option<String> {
let prefix = format!("**{}**:", field);
let mut updated = String::with_capacity(content.len());
let mut in_metadata = false;
let mut found = false;
for line in content.lines() {
if line.starts_with("## ") {
in_metadata = is_metadata_heading(line);
}
if in_metadata && !found && metadata_field_body(line).starts_with(&prefix) {
found = true;
continue;
}
updated.push_str(line);
updated.push('\n');
}
if found { Some(updated) } else { None }
}
pub fn set_status_field(content: &str, target_status: &str, title: &str) -> Result<String> {
set_metadata_line(content, "Status", target_status, is_status_line)
.ok_or_else(|| anyhow!("Ticket '{}' has no Status field in its Metadata section", title))
}
/// Rewrite a metadata field other than Status.
///
/// A field that is not already in the file is an error rather than an insertion. Every
/// ticket `add` writes carries the full set in a fixed order, and nothing else writes
/// these files, so a missing field means a hand-made ticket and guessing where the line
/// belongs would be inventing a format.
pub fn set_metadata_field(content: &str, field: &str, value: &str, title: &str) -> Result<String> {
let prefix = format!("**{}**:", field);
set_metadata_line(content, field, value, |line| {
metadata_field_body(line).starts_with(&prefix)
})
.ok_or_else(|| anyhow!("Ticket '{}' has no {} field in its Metadata section", title, field))
}
/// The metadata field naming the campaign a ticket belongs to.
///
/// Written only by `assign`, the way Owner is written only by `chown`. Storing the
/// member list on the campaign instead would put membership in two places and make one
/// file that every assignment edits, which is contended the moment two agents share a
/// board.
pub const CAMPAIGN_FIELD: &str = "Campaign";
/// The metadata field naming a campaign in a word, beside the uuid that addresses it.
///
/// A campaign is filed for a release or a migration, and those have names people already
/// use: `v1`, `beaver`. The uuid is what everything stores and the title is a sentence, so
/// neither is what a card has room to print. This is the short form, written by
/// `campaign add --codename` and nothing else.
///
/// Optional, and a campaign without one is not a lesser campaign: every campaign filed
/// before this existed has no field at all, which reads as unset the way an absent
/// Campaign field does.
pub const CODENAME_FIELD: &str = "Codename";
/// The mark a campaign carries where it is drawn as a label.
///
/// Not `#`, which is the tag marker: the two sit on the same row of a card and the row
/// would read as one list of tags with a stranger in it. A tilde is ASCII, so it renders
/// wherever `#` does, and it is not `@`, which reads as a person on every board anyone
/// has used.
///
/// One glyph, so the campaign on a card and the campaign in the picker are the same
/// thing said the same way.
pub const CAMPAIGN_MARK: &str = "~";
/// The campaign codename a file names, or nothing when it names none.
///
/// Absent, unset and empty are one answer, the bargain [`parse_campaign`] and
/// [`parse_tags`] both take: a campaign filed before the field existed carries no line at
/// all, and one whose line reads `_Not set_` has no codename either.
pub fn parse_codename(content: &str) -> Option<String> {
let value = parse_ticket_field(content, CODENAME_FIELD);
match is_unknown_value(&value) || value.trim().is_empty() {
true => None,
false => Some(value.trim().to_string()),
}
}
/// A campaign as a label: the mark, then the codename, or the short id when it has none.
///
/// The id is the fallback rather than the title, which is a sentence and would not fit the
/// row this is drawn on. It says little, which is the whole reason the codename field
/// exists, but it is addressable: `campaign show` takes it.
///
/// **A codename takes its own colour from [`tag_color`] and the fallback takes grey.** The
/// colour is what groups a campaign across the cards that carry it, and one word is one
/// colour in every view for the same reason a tag is. Grey on the id, rather than the red
/// a uuid is drawn in everywhere else, keeps a reserved meaning off a `TAG_COLORS` slot in
/// the one case where the label is an id: grey already means what a reader skips, which is
/// what a campaign with no codename has to say for itself.
///
/// A `Cell`, not a string, so the CLI paints it and the board makes a span of it, the way
/// a relation row already works. The bold is the board's: it is there to win a row against
/// the tags, and nothing in the CLI shares a line with them.
pub fn campaign_label(uuid: &str, codename: Option<&str>) -> Cell {
match codename {
Some(codename) => Cell::colored(format!("{CAMPAIGN_MARK}{codename}"), tag_color(codename)),
None => Cell::colored(format!("{CAMPAIGN_MARK}{}", short_id(uuid)), Color::Grey),
}
}
/// The campaign uuid a ticket names, or nothing when it names none.
///
/// Absent and unset are the same answer: a ticket that has never been assigned has no
/// field at all, since `add` does not write one, and a ticket whose field reads
/// `_Not set_` is in no campaign either.
pub fn parse_campaign(content: &str) -> Option<String> {
let value = parse_ticket_field(content, CAMPAIGN_FIELD);
match is_unknown_value(&value) || value.trim().is_empty() {
true => None,
false => Some(value),
}
}
/// The tags a ticket carries, from the comma-separated field.
///
/// Whole values, trimmed: the field is written as `bug, frontend` by `add` and as
/// `bug,frontend` by hand, and a caller asking whether a ticket is tagged `bug` must
/// not be answered by a ticket tagged `bugfix`. Absent, unset and empty are one
/// answer, as they are for [`parse_campaign`]: no tags.
pub fn parse_tags(content: &str) -> Vec<String> {
let value = parse_ticket_field(content, "Tags");
if is_unknown_value(&value) {
return Vec::new();
}
value
.split(',')
.map(str::trim)
.filter(|tag| !tag.is_empty())
.map(str::to_string)
.collect()
}
/// The metadata fields in the order `add` writes them, with the fields no ticket is
/// born with in their places among them.
///
/// The anchor list for inserting a field the file does not have yet, exactly as
/// [`SECTION_ORDER`] is for a missing section. Campaign sits beside Status because the
/// two answer the same kind of question, where the ticket belongs rather than what it
/// is, and Status stays last, which is where every file already keeps it. The three
/// stamps follow `Created At`, since they answer the same question it does about a
/// later moment, and they are in flow order for a reader who sees one after another
/// across a board.
///
/// `Codename` is a *campaign's* field and sits here for the same reason Campaign does: this
/// is the one list that decides where an inserted field lands, and a campaign filed before
/// the field existed is precisely the file `campaign set --codename` has to insert into.
/// Directly after ID, because that is where `campaign_body` writes it, so a campaign given
/// a codename later ends up with the same file as one filed with it. Nothing ever upserts
/// it on a ticket, so its place in a ticket's order costs nothing.
const METADATA_ORDER: [&str; 12] = [
"ID",
CODENAME_FIELD,
"Priority",
"Tags",
"Due",
"Owner",
"Created At",
COMMITTED_ON_FIELD,
SUBMITTED_ON_FIELD,
COMPLETED_ON_FIELD,
CAMPAIGN_FIELD,
"Status",
];
/// Rewrite a metadata field, adding the line when the file has no such field yet.
///
/// [`set_metadata_field`] refuses a field that is not already there, which is right for
/// the fields `add` writes: a missing one means a hand-made ticket. Campaign is
/// different, because no ticket written before campaigns existed carries it and `add`
/// deliberately does not write one. The insertion path therefore has to exist for every
/// such ticket, which is the same reasoning that keeps the Relations section out of
/// `add`: one path that is always exercised beats two.
pub fn set_or_insert_metadata_field(
content: &str,
field: &str,
value: &str,
title: &str,
) -> Result<String> {
let prefix = format!("**{}**:", field);
match set_metadata_line(content, field, value, |line| {
metadata_field_body(line).starts_with(&prefix)
}) {
Some(updated) => Ok(updated),
None => insert_metadata_field(content, field, value, title),
}
}
/// Add a metadata line the file does not have, in its place among the fields it does.
///
/// A file with no Metadata section is an error rather than an insertion. There is no
/// format to guess at there, and per 641e3d5 such a file has no fields at all, so
/// writing one above the prose would be inventing a shape nothing else reads.
fn insert_metadata_field(content: &str, field: &str, value: &str, title: &str) -> Result<String> {
let lines: Vec<&str> = content.lines().collect();
let heading = lines
.iter()
.position(|line| is_metadata_heading(line))
.ok_or_else(|| {
anyhow!(
"Ticket '{}' has no Metadata section, so its {} field cannot be written",
title,
field
)
})?;
let body = (heading + 1)..section_end(&lines, heading + 1);
// Before the first field that follows this one in the order and is actually in the
// file, the way `ensure_section` goes against `SECTION_ORDER`. A ticket written
// before the field existed therefore gains it in its place rather than at the end.
let following = METADATA_ORDER
.iter()
.skip_while(|name| **name != field)
.skip(1)
.filter_map(|name| {
let prefix = format!("**{}**:", name);
lines[body.clone()]
.iter()
.position(|line| metadata_field_body(line).starts_with(&prefix))
.map(|offset| body.start + offset)
})
.min();
let at = match following {
Some(at) => at,
// Nothing in the file follows it, so after the last line that holds anything:
// the blank line before the next section has to stay where it is.
None => body_content_end(&lines, &body),
};
let mut out: Vec<String> = lines[..at].iter().map(|l| l.to_string()).collect();
out.push(format!("- **{}**: {}", field, value));
out.extend(lines[at..].iter().map(|l| l.to_string()));
Ok(join_lines(&out))
}
// The metadata fields `mv` stamps with the time a ticket entered a status. Backlog has
// none: a ticket is filed there, and `Created At` already records when, so a fourth
// field would say the same thing for every ticket that has never moved.
pub const COMMITTED_ON_FIELD: &str = "Committed On";
pub const SUBMITTED_ON_FIELD: &str = "Submitted On";
pub const COMPLETED_ON_FIELD: &str = "Completed On";
/// Stamp the field of the status being entered and drop the ones after it.
///
/// The stamps accumulate down the flow rather than being mutually exclusive, so a
/// ticket that has walked the whole way carries `Created At`, `Committed On`,
/// `Submitted On` and `Completed On` side by side and the journey behind it is legible.
/// Presence therefore means the ticket got that far and has not been sent back past it,
/// not that it is sitting there now; `Status` is what says where it is.
///
/// One arrival rule covers both directions. A backward move truncates the journey at
/// the target, so `done` back to `reviewing` drops `Completed On` and keeps the two
/// before it, and anything back to `backlog` drops all three. A forward skip under `-f`
/// has nothing after it to clear, so `backlog` straight to `done` stamps `Completed On`
/// alone and leaves the stages it jumped over unwritten rather than fabricated.
/// Re-entering restamps rather than keeping the earlier value.
///
/// This is still not d4ce964's history log. These fields answer how far and when, once
/// per stage; every status change, every owner and every tag along the way is the log's
/// job and must not be grown here. `backlog` has no stamp, `Created At` answers for it.
///
/// The time comes in as a string rather than being read here, so the caller stamps the
/// same moment it reports and a test can pin the value.
pub fn set_status_stamp(content: &str, target: Status, now: &str, title: &str) -> Result<String> {
let mut content = content.to_string();
// Every status after the target, off the flow order `Status::ALL` already holds
// rather than a case per move, so arrival alone decides what is cleared and a
// backward move and a skip are the same rule.
for status in Status::ALL
.iter()
.skip_while(|status| **status != target)
.skip(1)
{
let Some(field) = status.stamp_field() else {
continue;
};
if let Some(updated) = remove_metadata_line(&content, field) {
content = updated;
}
}
match target.stamp_field() {
// Inserted on demand, the way Campaign is: every ticket written before these
// fields existed carries none of them.
Some(field) => set_or_insert_metadata_field(&content, field, now, title),
None => Ok(content),
}
}
/// Rewrite the title heading, the first `# ` line in the file.
///
/// `## ` headings do not match: the second character has to be a space.
pub fn set_title(content: &str, title: &str) -> Result<String> {
let mut updated = String::with_capacity(content.len());
let mut found = false;
for line in content.lines() {
if !found && line.starts_with("# ") {
updated.push_str("# ");
updated.push_str(title);
found = true;
} else {
updated.push_str(line);
}
updated.push('\n');
}
if !found {
return Err(anyhow!("Ticket '{}' has no title heading", title));
}
Ok(updated)
}
// Format created_at for display: "YYYY-MM-DD HH:MM:SS" becomes "YY-MM-DD:HH".
//
// Parsed rather than sliced by byte offset: the value comes from a file nothing
// validates, and the old offsets panicked on any multibyte character before them.
// Anything unparseable yields an empty string, which drops the column.
pub fn format_created_at(created_at: &str) -> String {
match NaiveDateTime::parse_from_str(created_at, TIMESTAMP_FORMAT) {
Ok(created_at) => created_at.format("%y-%m-%d:%H").to_string(),
Err(_) => String::new(),
}
}
/// How a section stores the lines the tool owns.
pub enum SectionKind {
/// Lines as written, a blank one acting as a paragraph break.
Prose,
/// One `- [ ] ` item per line.
Checklist,
/// One `N. ` step per line.
Numbered,
/// One `- ` item per line, unnumbered, with no blank line between items.
Bullets,
}
/// A section of a ticket whose body `set` and `append` can rewrite.
///
/// A table rather than a match arm per section, so adding a section later is one entry
/// here instead of edits spread across both commands.
pub struct Section {
pub heading: &'static str,
/// How the section is named in output, lowercase so it reads the same way the
/// metadata field labels do.
pub label: &'static str,
/// What `add` writes when the section is left empty. Treated as no content, so
/// appending to an empty section replaces the placeholder rather than following it.
pub placeholder: &'static str,
pub kind: SectionKind,
/// The `--clear` value that empties this section, where `set` can reach it at all.
///
/// `None` for Relations, for the same reason it is absent from `section_args`: its
/// only writer is `relate`, so `set` has no way to fill it and no business emptying
/// it either.
pub clear: Option<Clearable>,
}
pub const DESCRIPTION: Section = Section {
heading: "## Description",
label: "description",
placeholder: "_No description provided._",
kind: SectionKind::Prose,
clear: Some(Clearable::Description),
};
pub const ACCEPTANCE: Section = Section {
heading: "## Acceptance Criteria",
label: "acceptance criteria",
placeholder: "_No acceptance criteria provided._",
kind: SectionKind::Checklist,
clear: Some(Clearable::Acceptance),
};
pub const PLAN: Section = Section {
heading: "## Implementation Plan",
label: "implementation plan",
placeholder: "_No implementation plan provided._",
kind: SectionKind::Numbered,
clear: Some(Clearable::Plan),
};
/// The edges to other tickets, one per line.
///
/// Deliberately absent from `section_args`, so `set` and `append` cannot write it: a
/// relation names a target that has to be resolved to a uuid first, and a prose flag
/// would let an unresolvable line into the one section that is read back by machine.
/// `relate` is its only writer, the way `chown` is the only writer of Owner.
pub const RELATIONS: Section = Section {
heading: "## Relations",
label: "relations",
placeholder: "_No relations._",
kind: SectionKind::Bullets,
clear: None,
};
impl Section {
/// The values a caller supplied, reduced to the lines that belong in the body.
///
/// Prose keeps interior blanks, since those are paragraph breaks. A list has one
/// item per value, so a blank there is nothing at all.
pub fn normalise(&self, values: &[String]) -> Vec<String> {
match self.kind {
SectionKind::Prose => trim_blank_ends(values).to_vec(),
SectionKind::Checklist | SectionKind::Numbered | SectionKind::Bullets => values
.iter()
.filter(|value| !value.trim().is_empty())
.cloned()
.collect(),
}
}
/// `items` as body lines, numbering from `first` where the section is numbered.
fn render(&self, items: &[String], first: usize) -> Vec<String> {
match self.kind {
SectionKind::Prose => items.to_vec(),
SectionKind::Checklist => items.iter().map(|i| format!("- [ ] {}", i)).collect(),
SectionKind::Bullets => items.iter().map(|i| format!("- {}", i)).collect(),
SectionKind::Numbered => items
.iter()
.enumerate()
.map(|(offset, step)| format!("{}. {}", first + offset, step))
.collect(),
}
}
}
/// A field `set --clear` can return to the state a new ticket is born in.
///
/// The names are the flags they undo, so `--clear due` reads as the opposite of
/// `--due`. Three fields a ticket carries are deliberately absent:
///
/// - **Title** has no unset state. It addresses the ticket, it names the file through
/// its slug, and `add` requires it, so there is nothing to go back to.
/// - **Owner** is `chown`'s, and clearing it through `set` would give the field a
/// second writer, which is the rule the missing `set --owner` exists to keep.
/// - **Status**, **Campaign** and the three stamps belong to `mv` and `assign` for the
/// same reason.
#[derive(Copy, Clone, Debug, PartialEq, Eq, clap::ValueEnum)]
pub enum Clearable {
Due,
Tags,
Priority,
Description,
Acceptance,
Plan,
}
/// What clearing a field writes back.
pub enum Unset {
/// A metadata line, back to the sentinel `add` writes when the flag is omitted.
Field {
field: &'static str,
sentinel: &'static str,
},
/// A section body, back to the placeholder `add` writes for an empty one.
Section(&'static Section),
}
impl Clearable {
/// Every field that can be cleared.
///
/// `#[cfg(test)]` because nothing in the binary walks the list: clap emits the
/// values for `--clear` from the `ValueEnum` itself, so the only caller is the suite
/// that checks each one against the ticket it empties.
#[cfg(test)]
pub const ALL: [Clearable; 6] = [
Clearable::Due,
Clearable::Tags,
Clearable::Priority,
Clearable::Description,
Clearable::Acceptance,
Clearable::Plan,
];
/// What clearing the field amounts to.
///
/// The sentinels are [`NOT_SET`] and [`NONE`] rather than strings written out here,
/// so a cleared field is byte-identical to one `add` left alone. That is the whole
/// promise of the command: a ticket that has been cleared and one that was never
/// given the field read the same.
pub fn unset(self) -> Unset {
match self {
Clearable::Due => Unset::Field {
field: "Due",
sentinel: NOT_SET,
},
Clearable::Tags => Unset::Field { field: "Tags", sentinel: NONE },
Clearable::Priority => Unset::Field {
field: "Priority",
sentinel: NOT_SET,
},
Clearable::Description => Unset::Section(&DESCRIPTION),
Clearable::Acceptance => Unset::Section(&ACCEPTANCE),
Clearable::Plan => Unset::Section(&PLAN),
}
}
/// The value the flag takes, as clap spells it.
///
/// Written out rather than read off `to_possible_value`, because it is used in error
/// messages that tell a caller what to type and a `&'static str` is what those want.
/// `the_clear_values_are_the_names_clap_accepts` keeps the two in step.
pub fn name(self) -> &'static str {
match self {
Clearable::Due => "due",
Clearable::Tags => "tags",
Clearable::Priority => "priority",
Clearable::Description => "description",
Clearable::Acceptance => "acceptance",
Clearable::Plan => "plan",
}
}
/// How the change is named in output.
///
/// The label `set` already prints when it *writes* the field, so a cleared field is
/// named the way a replaced one is rather than in the flag's own spelling.
pub fn label(self) -> &'static str {
match self.unset() {
Unset::Field { .. } => self.name(),
Unset::Section(section) => section.label,
}
}
}
/// Whether the line opens with `N. `, the shape a numbered step is stored in.
fn is_numbered_item(line: &str) -> bool {
let digits = line.chars().take_while(|c| c.is_ascii_digit()).count();
// ASCII digits are one byte each, so the count is also the byte offset.
digits > 0 && line[digits..].starts_with(". ")
}
/// Where the section whose body starts at `from` ends: the next `## ` heading, or the
/// end of the file.
fn section_end(lines: &[&str], from: usize) -> usize {
lines[from..]
.iter()
.position(|line| line.starts_with("## "))
.map_or(lines.len(), |offset| from + offset)
}
/// The lines of a section's body, excluding the heading, running to the next `## `
/// heading or the end of the file.
fn section_body(lines: &[&str], heading: &str) -> Option<std::ops::Range<usize>> {
let at = lines.iter().position(|line| line.trim_end() == heading)?;
let after = at + 1;
Some(after..section_end(lines, after))
}
/// A section's body as prose, or nothing when the section is absent or holds only its
/// placeholder.
///
/// The whole of it, the blank lines between paragraphs included, for a view that can page
/// through what it cannot fit: the board's campaign frame gives a description three rows
/// and scrolls the rest, and the one line the picker draws is the first line of this.
///
/// It replaced `section_opening`, which did the cut here. The cut belongs to the view that
/// wants one line, not to the read: the file is only in hand while the campaigns directory
/// is being read, so what that read has to carry is everything a view might want, and
/// `CampaignRow::summary` is where the one line comes off it again.
///
/// Through [`section_body`] rather than a scan of its own, so what counts as the section is
/// decided in one place, and the placeholder reads as nothing here the way it does to
/// `append`. Only the ends are trimmed: those blanks separate the body from its heading and
/// from whatever follows, and a view that kept them would open on empty rows and scroll
/// past empty ones at the end. Indentation inside a line survives, since a nested list is
/// part of the prose.
pub fn section_prose(content: &str, section: &Section) -> Option<String> {
let lines: Vec<&str> = content.lines().collect();
let body = section_body(&lines, section.heading)?;
let kept: Vec<&str> = lines[body]
.iter()
.map(|line| line.trim_end())
.filter(|line| *line != section.placeholder)
.collect();
let start = kept.iter().position(|line| !line.is_empty())?;
let end = kept.iter().rposition(|line| !line.is_empty())?;
Some(kept[start..=end].join("\n"))
}
/// Where the body's content ends, ignoring the blank lines that separate it from
/// whatever follows.
fn body_content_end(lines: &[&str], body: &std::ops::Range<usize>) -> usize {
let mut end = body.end;
while end > body.start && lines[end - 1].trim().is_empty() {
end -= 1;
}
end
}
fn join_lines(lines: &[String]) -> String {
let mut out = lines.join("\n");
out.push('\n');
out
}
/// Replace a section's body with `items`, leaving every line outside it untouched.
pub fn set_section_body(content: &str, section: &Section, items: &[String]) -> Result<String> {
replace_section_body(content, section, section.render(items, 1))
}
/// Return a section to the placeholder `add` writes for an empty one.
///
/// Not [`set_section_body`] with the placeholder as its one item: the placeholder is a
/// line of the format rather than content, and `render` would dress it as `- [ ] _No
/// acceptance criteria provided._` in every section but the description. It is the same
/// line `append` already treats as no content, so a cleared section can be appended to
/// without the placeholder being left above what follows it.
pub fn clear_section_body(content: &str, section: &Section) -> Result<String> {
replace_section_body(content, section, vec![section.placeholder.to_string()])
}
/// The line surgery both of the above are, given a body that is already rendered.
///
/// The refusal names the section and not the file it is missing from, because both a ticket
/// and a campaign reach here: `campaign set --description` writes a campaign's one prose
/// section through this, so "Ticket has no description section" would be wrong half the
/// time. `write_then_replace` carries the noun instead, where a message about a *file* is
/// worth spelling.
fn replace_section_body(
content: &str,
section: &Section,
body_lines: Vec<String>,
) -> Result<String> {
let lines: Vec<&str> = content.lines().collect();
let body = section_body(&lines, section.heading)
.ok_or_else(|| anyhow!("There is no {} section to write to", section.label))?;
let mut out: Vec<String> = lines[..body.start].iter().map(|l| l.to_string()).collect();
out.extend(body_lines);
// One blank line before whatever section follows, matching how `add` writes it.
if body.end < lines.len() {
out.push(String::new());
}
out.extend(lines[body.end..].iter().map(|l| l.to_string()));
Ok(join_lines(&out))
}
/// Add `items` to the end of a section's body.
///
/// Prose gains a blank line first, so the addition reads as a new paragraph. A numbered
/// section continues from the count of steps already there rather than renumbering what
/// is above it, which keeps any handwritten line in the section exactly as it was.
pub fn append_section_body(content: &str, section: &Section, items: &[String]) -> Result<String> {
let lines: Vec<&str> = content.lines().collect();
let body = section_body(&lines, section.heading)
.ok_or_else(|| anyhow!("There is no {} section to write to", section.label))?;
let at = body_content_end(&lines, &body);
let existing: Vec<&&str> = lines[body.start..at]
.iter()
.filter(|line| !line.trim().is_empty())
.collect();
// An empty section is a placeholder, and following it with a paragraph would leave
// "_No description provided._" above the description.
if existing.len() == 1 && existing[0].trim() == section.placeholder {
return set_section_body(content, section, items);
}
let first = match section.kind {
SectionKind::Numbered => 1 + existing.iter().filter(|l| is_numbered_item(l)).count(),
_ => 1,
};
let mut out: Vec<String> = lines[..at].iter().map(|l| l.to_string()).collect();
if matches!(section.kind, SectionKind::Prose) && at > body.start {
out.push(String::new());
}
out.extend(section.render(items, first));
out.extend(lines[at..].iter().map(|l| l.to_string()));
Ok(join_lines(&out))
}
/// The order the tool's own sections sit in a ticket file.
///
/// Relations goes between the plan and the metadata: it is reference data rather than
/// the prose a reader needs first. Metadata is in the list as the anchor a missing
/// section is inserted against, not as a section anything appends to.
const SECTION_ORDER: [&str; 5] = [
DESCRIPTION.heading,
ACCEPTANCE.heading,
PLAN.heading,
RELATIONS.heading,
METADATA_HEADING,
];
/// `content` with `section` present, empty, and in its place when it was absent.
///
/// Inserted before the first section that follows it in [`SECTION_ORDER`] and is
/// actually in the file, so a ticket written before the section existed gains it
/// without being regenerated: a handwritten `## Notes` in between keeps its place, and
/// so does every blank line already there.
pub fn ensure_section(content: &str, section: &Section) -> String {
let lines: Vec<&str> = content.lines().collect();
if section_body(&lines, section.heading).is_some() {
return content.to_string();
}
let at = SECTION_ORDER
.iter()
.skip_while(|heading| **heading != section.heading)
.skip(1)
.filter_map(|heading| lines.iter().position(|line| line.trim_end() == *heading))
.min()
.unwrap_or(lines.len());
let mut out: Vec<String> = lines[..at].iter().map(|l| l.to_string()).collect();
// The template separates sections with one blank line. Whatever is already there
// is left as it is, and the line is only added when there is none.
if out.last().is_some_and(|line| !line.trim().is_empty()) {
out.push(String::new());
}
out.push(section.heading.to_string());
out.push(section.placeholder.to_string());
if at < lines.len() {
out.push(String::new());
}
out.extend(lines[at..].iter().map(|l| l.to_string()));
join_lines(&out)
}
// ------------------------------------------------------------------- relations --
/// The kinds of edge one ticket can record to another.
///
/// Three, and none of them carries prose of its own: that is what separates a relation
/// from a campaign, 7bfb9fc, which is a container with a description and a definition
/// of done. No label is a prefix of another, so a stored line parses unambiguously.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RelationKind {
BlockedBy,
RegressionOf,
RelatesTo,
}
impl RelationKind {
/// How the kind is written into the file and printed back.
pub fn label(self) -> &'static str {
match self {
RelationKind::BlockedBy => "blocked by",
RelationKind::RegressionOf => "regression of",
RelationKind::RelatesTo => "relates to",
}
}
/// How the kind reads from the other end, where nothing is stored.
///
/// `relates to` is its own inverse: the relation is symmetric, and the only thing
/// that differs between the two ends is which file happens to hold the line.
pub fn inverse_label(self) -> &'static str {
match self {
RelationKind::BlockedBy => "blocks",
RelationKind::RegressionOf => "regressed by",
RelationKind::RelatesTo => "relates to",
}
}
/// Every kind, so a caller can walk them without listing them a second time.
pub const ALL: [RelationKind; 3] = [
RelationKind::BlockedBy,
RelationKind::RegressionOf,
RelationKind::RelatesTo,
];
}
/// One stored edge: a kind, and the full uuid of the ticket it points at.
///
/// The full uuid, not the seven characters `ls` prints. Longer to read in the file, but
/// it resolves without a scan and cannot turn ambiguous as the board grows.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Relation {
pub kind: RelationKind,
pub target: String,
}
impl Relation {
/// The body line as the section stores it, without the list marker.
pub fn item(&self) -> String {
format!("{} {}", self.kind.label(), self.target)
}
}
/// One relation from a body line, or an error naming what could not be read.
fn parse_relation(line: &str) -> Result<Relation> {
let body = line.trim();
let body = body.strip_prefix("- ").unwrap_or(body).trim();
for kind in RelationKind::ALL {
if let Some(target) = body.strip_prefix(kind.label()) {
let target = target.trim();
if target.is_empty() {
return Err(anyhow!("relation '{}' names no target", body));
}
return Ok(Relation {
kind,
target: target.to_string(),
});
}
}
Err(anyhow!(
"'{}' is not a relation. The kinds are {}",
body,
RelationKind::ALL
.iter()
.map(|kind| kind.label())
.collect::<Vec<_>>()
.join(", ")
))
}
/// The relations a ticket stores, in the order they are written.
///
/// A line in the section that is not a relation is an error, not a line quietly
/// dropped. The section is the one part of a ticket that is read back by machine, and
/// an edge nobody can read is worse than a refusal to read the ticket. Nothing but
/// `relate` writes it, so a bad line means the file was edited by hand.
pub fn parse_relations(content: &str, title: &str) -> Result<Vec<Relation>> {
let lines: Vec<&str> = content.lines().collect();
let Some(body) = section_body(&lines, RELATIONS.heading) else {
return Ok(Vec::new());
};
lines[body]
.iter()
.filter(|line| !line.trim().is_empty() && line.trim() != RELATIONS.placeholder)
.map(|line| parse_relation(line).map_err(|e| anyhow!("Ticket '{}': {}", title, e)))
.collect()
}
/// A ticket as the other end of a relation sees it.
pub struct RelatedTicket {
pub uuid: String,
pub title: String,
/// The directory it sits in, which is what decides whether a blocker is still open.
pub status: String,
/// The relations it stores, and therefore where an inverse is derived from.
pub relations: Vec<Relation>,
}
/// Every ticket on the board with the relations it stores, read in one pass.
///
/// One side of a relation is stored and the other is derived, so anything that shows or
/// checks one has to look at every ticket. Read once here rather than per edge: a
/// lookup per relation would walk the whole tree once for each line.
pub struct RelationIndex {
tickets: Vec<RelatedTicket>,
}
impl RelationIndex {
/// The index over a list of tickets already read, so a test can build one without
/// a tree and `load` has one place that decides what the type holds.
pub fn new(tickets: Vec<RelatedTicket>) -> Self {
Self { tickets }
}
pub fn load(worklane_dir: &Path) -> Result<Self> {
let mut tickets = Vec::new();
for status in status_dirs() {
let status_path = worklane_dir.join(status);
if !status_path.exists() {
continue;
}
for entry in fs::read_dir(&status_path)? {
let path = entry?.path();
if !path.extension().is_some_and(|e| e == "md") {
continue;
}
let Ok(content) = fs::read_to_string(&path) else {
continue;
};
let title = heading_title(&content);
tickets.push(RelatedTicket {
uuid: parse_ticket_field(&content, "ID"),
relations: parse_relations(&content, &title)?,
title,
status: status.to_string(),
});
}
}
Ok(Self::new(tickets))
}
/// The ticket carrying `uuid`, or nothing when the board no longer has it.
pub fn get(&self, uuid: &str) -> Option<&RelatedTicket> {
self.tickets.iter().find(|ticket| ticket.uuid == uuid)
}
/// The relations other tickets hold pointing at `uuid`, as the kind reads from
/// this end and the ticket that holds it.
///
/// A uuid the file does not carry matches nothing: without the guard every ticket
/// with no ID field would relate to every other one that has none either.
pub fn inbound(&self, uuid: &str) -> Vec<(RelationKind, &RelatedTicket)> {
if uuid.trim().is_empty() || is_unknown_value(uuid) {
return Vec::new();
}
self.tickets
.iter()
.filter(|holder| holder.uuid != uuid)
.flat_map(|holder| {
holder
.relations
.iter()
.filter(|relation| relation.target == uuid)
.map(move |relation| (relation.kind, holder))
})
.collect()
}
}
/// A cross reference as it reads: the short id, then the name it points at.
///
/// `_missing_` rather than a bare uuid for something the board no longer holds. The id
/// is kept either way, since it is the only thing left to go looking for. Shared by the
/// relations block and the Campaign field, so a dangling reference is spelled one way
/// wherever it is shown.
pub fn reference_cell(uuid: &str, name: Option<&str>, colored: bool) -> String {
paint_cells(&reference_cells(uuid, name), colored)
}
/// The same cross reference in cells, for a renderer that is not writing escapes.
///
/// The one spelling of a reference, so the relations block and the Campaign field cannot
/// come to say a dangling one differently, and the board draws the id in the colour the
/// guideline gives it rather than dropping every colour to stay safe.
pub fn reference_cells(uuid: &str, name: Option<&str>) -> Vec<Cell> {
let mut cells = vec![
Cell::plain("("),
Cell::colored(short_id(uuid), Color::Red),
Cell::plain(") "),
];
match name {
Some(name) => cells.push(Cell::plain(name)),
None => cells.push(Cell::colored("_missing_", Color::Grey)),
}
cells
}
/// Cells as the CLI prints them: each one painted, or carried through as it stands.
pub fn paint_cells(cells: &[Cell], colored: bool) -> String {
cells
.iter()
.map(|cell| match cell.color {
Some(color) => paint(&cell.text, color, colored),
None => cell.text.clone(),
})
.collect()
}
/// The mark a blocking relation carries, and a card waiting on one.
///
/// Not a fourth circle. The Geometric Shapes glyphs belong to the priority meter, and
/// another one two cells away from it would read as part of that ramp rather than as a
/// different fact. A multiplication sign is Latin-1, like the middle dot the unset
/// priority draws, so it renders wherever the meter already does. That is the same
/// safe-glyph rule that took the quadrant circles out of the ramp.
///
/// One glyph for both places, since both say the same word: on a card that this ticket
/// is held up, in the relations block that this edge is what holds one. The direction is
/// the label's to say.
pub const BLOCKED_MARK: &str = "\u{d7}";
/// The mark a `relates to` row carries: a plain pointer to somewhere else worth reading.
pub const RELATES_MARK: &str = "\u{2192}";
/// The mark a regression row carries, pointing back at the fix it undid.
pub const REGRESSION_MARK: &str = "\u{2190}";
/// The mark for the status of a relation's target, and the colour it is drawn in.
///
/// One circle where the priority meter is always two, which is what keeps the two apart:
/// the meter reads `\u{25cf}\u{25d0}` and a status reads `\u{25d0}`, and they never sit in the same column.
/// `the_status_mark_is_one_cell_where_the_meter_is_two` pins that, since it is the whole
/// reason a circle is safe here when it is not safe on a card.
///
/// `\u{25cb}` not started, `\u{25d0}` under way, `\u{25cf}` finished, so the shape carries how far the
/// target has got and the colour says which of the two middle stages it is in. A ramp
/// inside one column, the way the priority meter reuses the palette: grey for the pile
/// nobody has picked up, orange for work in hand, cyan for work waiting on a reader,
/// green for done. Green is the one the priority ramp deliberately leaves out because it
/// means a title, and it is safe on a one-cell mark that no title sits behind.
const STATUS_MARKS: [(&str, &str, Color); 4] = [
("backlog", "\u{25cb}", Color::Grey),
("committed", "\u{25d0}", Color::Orange),
("reviewing", "\u{25d0}", Color::Cyan),
("done", "\u{25cf}", Color::Green),
];
/// The mark for a status, or `?` for a target the board no longer holds.
///
/// A placeholder rather than a blank, so the id column does not move when one row's
/// target has gone, and grey rather than a stage of the flow: the `_missing_` beside it
/// is grey for the same reason. An unrecognised value reads the same way, since the
/// status comes from the directory the ticket was found in and guessing at a fifth stage
/// would mark a status nothing can act on. `every_status_has_a_mark` pins the pairing
/// against `status_dirs`.
pub fn status_mark(status: Option<&str>) -> (&'static str, Color) {
let found = status.and_then(|status| {
STATUS_MARKS
.iter()
.find(|(name, _, _)| *name == status)
.map(|(_, mark, colour)| (*mark, *colour))
});
found.unwrap_or(("?", Color::Grey))
}
/// The glyph and colour for a kind of relation.
///
/// The label already names the kind in words, and this is what makes the block scannable
/// without reading them: the rows that hold you up are the red crosses, whichever
/// direction they point. Arrows and a cross rather than shapes from the priority
/// vocabulary, and all three are in the ramp the footer's own `\u{2190}\u{2192}\u{2191}\u{2193}` already draws.
///
/// The colours reuse the palette the way the priority meter does, as a small ramp inside
/// one column rather than as new meanings: brightred is the cross a card already draws,
/// cyan the pointer, orange the way back. Nothing here is a colour standing in for a
/// uuid or a title, which are what sit beside it on the row.
pub fn relation_mark(kind: RelationKind) -> (&'static str, Color) {
match kind {
RelationKind::BlockedBy => (BLOCKED_MARK, Color::BrightRed),
RelationKind::RelatesTo => (RELATES_MARK, Color::Cyan),
RelationKind::RegressionOf => (REGRESSION_MARK, Color::Orange),
}
}
/// One row of the Relations block: which relation, and what it points at.
///
/// The target is `None` for a uuid the board no longer holds, which is the one case with
/// neither a name nor a status to show.
#[derive(Clone, Debug)]
pub struct RelationRow {
/// Which edge this is, which decides the mark. Kept beside the label rather than
/// derived from it: the label is the same word for both directions of `relates to`,
/// and reading a kind back out of prose is how a mark comes to disagree with a row.
pub kind: RelationKind,
/// The kind as it reads from this end, which is what the row is padded against.
pub label: &'static str,
pub uuid: String,
/// The ticket it names, once the board has been read for it.
pub target: Option<RelationTarget>,
}
/// What a relation points at: what to call it, and how far it has got.
///
/// One `Option` around both rather than two, because they come from the same lookup and
/// so are absent together. The status is here again after 5ae9c7f took it out: the mark
/// keyed on the kind alone for one commit, and a blocking row's state is the thing a
/// reader most wants without leaving the ticket.
#[derive(Clone, Debug)]
pub struct RelationTarget {
pub title: String,
pub status: String,
}
/// A run of text and the colour it is drawn in, or `None` for the default foreground.
///
/// The unit both renderers take: [`paint`] turns one into an escape sequence for the
/// CLI, and the board turns the same one into a ratatui `Span`. A block laid out once
/// and painted twice cannot draw two different blocks.
#[derive(Clone, Debug)]
pub struct Cell {
pub text: String,
pub color: Option<Color>,
}
impl Cell {
fn plain(text: impl Into<String>) -> Self {
Cell { text: text.into(), color: None }
}
fn colored(text: impl Into<String>, color: Color) -> Self {
Cell {
text: text.into(),
color: Some(color),
}
}
}
/// The relations of one ticket, both directions, in the order they are shown.
///
/// Stored first: the relations the ticket holds, then the ones held against it, named
/// from this end. Read from the index rather than from the body alone, because a bare
/// uuid says nothing and half the relations are not in the file.
///
/// The single builder. Everything that shows a relation goes through these rows, so the
/// CLI and the board cannot disagree about which edges there are, what they are called
/// or which direction comes first.
pub fn relation_rows(stored: &[Relation], index: &RelationIndex, uuid: &str) -> Vec<RelationRow> {
let target_of = |ticket: Option<&RelatedTicket>| {
ticket.map(|ticket| RelationTarget {
title: ticket.title.clone(),
status: ticket.status.clone(),
})
};
let mut rows: Vec<RelationRow> = stored
.iter()
.map(|relation| RelationRow {
kind: relation.kind,
label: relation.kind.label(),
uuid: relation.target.clone(),
target: target_of(index.get(&relation.target)),
})
.collect();
rows.extend(
index
.inbound(uuid)
.into_iter()
.map(|(kind, holder)| RelationRow {
kind,
label: kind.inverse_label(),
uuid: holder.uuid.clone(),
target: target_of(Some(holder)),
}),
);
rows
}
/// The Relations block laid out: one row of cells per relation, or nothing to show.
///
/// The layout lives here rather than in each renderer, so the mark, the padding and the
/// gutter are decided once. The labels are measured with no colour on them and padded
/// before the target is joined, for the reason the metadata table is: an escape sequence
/// counted towards a width tilts the column the moment colour is on.
pub fn relation_cells(rows: &[RelationRow]) -> Vec<Vec<Cell>> {
let width = rows
.iter()
.map(|row| row.label.chars().count())
.max()
.unwrap_or(0);
rows.iter()
.map(|row| {
let (kind, kind_colour) = relation_mark(row.kind);
let (status, status_colour) =
status_mark(row.target.as_ref().map(|target| target.status.as_str()));
let padding = " ".repeat(width - row.label.chars().count());
// Kind, then state, then who: what sort of edge this is, how far the ticket
// at the other end has got, and which ticket that is. Both marks go ahead of
// the id, where they describe the target rather than the row, and every row
// carries both, so nothing is pushed out of line the way the card's blocked
// mark would have been.
let mut cells = vec![
Cell::plain(format!("{}{}{}", row.label, padding, COLUMN_GUTTER)),
Cell::colored(kind, kind_colour),
Cell::plain(" "),
Cell::colored(status, status_colour),
Cell::plain(" "),
];
cells.extend(reference_cells(
&row.uuid,
row.target.as_ref().map(|target| target.title.as_str()),
));
cells
})
.collect()
}
/// The Relations section as the CLI prints it, or empty when there is nothing to show.
pub fn render_relations(rows: &[RelationRow], colored: bool) -> String {
let mut out = String::new();
for row in relation_cells(rows) {
out.push_str(&paint_cells(&row, colored));
out.push('\n');
}
out
}
/// The relations of the ticket in `content`, read against the board around it.
///
/// Rows rather than a rendered block: the board styles them itself, since an escape
/// sequence in a ratatui paragraph is drawn as literal bytes.
pub fn relations_for(content: &str, worklane_dir: &Path) -> Result<Vec<RelationRow>> {
let title = heading_title(content);
let stored = parse_relations(content, &title)?;
let index = RelationIndex::load(worklane_dir)?;
Ok(relation_rows(&stored, &index, &parse_ticket_field(content, "ID")))
}
/// One acceptance criterion as it sits in the file.
pub struct Criterion {
/// Index into `content.lines()`, so the one line can be rewritten in place.
pub line: usize,
pub checked: bool,
pub text: String,
}
/// A checkbox line's state and text, or `None` when the line is not one.
///
/// Both `[x]` and `[X]` count as ticked. Anything else between the brackets is not a
/// criterion, so a handwritten line in the section is left out of the numbering.
pub fn checkbox(line: &str) -> Option<(bool, &str)> {
let rest = line.trim_start().strip_prefix("- [")?;
let mut chars = rest.char_indices();
let (_, mark) = chars.next()?;
let (closes_at, close) = chars.next()?;
if close != ']' {
return None;
}
let checked = match mark {
' ' => false,
'x' | 'X' => true,
_ => return None,
};
Some((checked, rest[closes_at + 1..].trim()))
}
/// The acceptance criteria, numbered in the order they appear.
///
/// Scoped to the section, so a checkbox written into a description is not a criterion,
/// and non-checkbox lines inside the section are skipped rather than numbered.
pub fn criteria(content: &str) -> Vec<Criterion> {
let lines: Vec<&str> = content.lines().collect();
let Some(body) = section_body(&lines, ACCEPTANCE.heading) else {
return Vec::new();
};
lines[body.clone()]
.iter()
.enumerate()
.filter_map(|(offset, line)| {
checkbox(line).map(|(checked, text)| Criterion {
line: body.start + offset,
checked,
text: text.to_string(),
})
})
.collect()
}
/// The criteria at `shown`, numbered by their real position in the list.
///
/// The position matters: a subset renumbered from one would contradict the advice to
/// use the number, pointing at whichever criterion happens to sit there instead.
pub fn numbered_criteria(criteria: &[Criterion], shown: &[usize]) -> String {
let colored = should_use_colors();
shown
.iter()
.filter_map(|offset| criteria.get(*offset).map(|criterion| (offset, criterion)))
.map(|(offset, criterion)| {
format!(
" {} {} {}",
paint(&format!("{}.", offset + 1), Color::Cyan, colored),
paint(if criterion.checked { "[x]" } else { "[ ]" }, Color::Grey, colored),
criterion.text
)
})
.collect::<Vec<_>>()
.join("\n")
}
/// The whole list, numbered as `show` numbers it.
pub fn criteria_list(criteria: &[Criterion]) -> String {
numbered_criteria(criteria, &(0..criteria.len()).collect::<Vec<_>>())
}
/// Whether `search` is a number rather than a substring, so a value out of range can
/// be reported as a bad index instead of a fruitless text search.
pub fn is_index(search: &str) -> bool {
search.trim().parse::<usize>().is_ok()
}
/// Whether `search` is the keyword standing for every criterion.
///
/// Checked before `find_criteria`, the way the index is checked before the substring,
/// so a criterion whose text contains "all" is reachable only by its number or by a
/// different substring. The keyword wins because ticking every box is the reason the
/// word is typed, and a board where `all` sometimes means one criterion and sometimes
/// means the lot would be worse than one that can be addressed another way.
///
/// Case-insensitive, like the substring match it stands beside.
pub fn is_all_criteria(search: &str) -> bool {
search.trim().eq_ignore_ascii_case("all")
}
/// Which criterion `search` names: a one-based index as `show` prints, or a
/// case-insensitive substring of the text.
///
/// The index is tried first, so a criterion whose text is literally "2" is reachable
/// only by substring. Returns every match, leaving the caller to refuse more than one.
pub fn find_criteria(criteria: &[Criterion], search: &str) -> Vec<usize> {
if let Ok(index) = search.trim().parse::<usize>() {
if index >= 1 && index <= criteria.len() {
return vec![index - 1];
}
// A number outside the range is a bad index, not a substring to hunt for.
return Vec::new();
}
// Trimmed, like the index path: an answer typed at the prompt arrives with its
// newline attached, and no criterion text contains one.
let needle = search.trim().to_lowercase();
criteria
.iter()
.enumerate()
.filter(|(_, criterion)| criterion.text.to_lowercase().contains(&needle))
.map(|(offset, _)| offset)
.collect()
}
/// Tick or untick the criteria on `lines`, leaving every other byte alone.
///
/// Only the character between the brackets is spliced. Rebuilding the line would
/// normalise its indentation and whatever spacing it carried after the checkbox.
///
/// Every line in one pass, so a batch is one rewrite and one save rather than one of
/// each per criterion. `lines` is searched rather than indexed because a ticket holds
/// a handful of criteria, and a set would only move the cost somewhere else.
pub fn set_criteria(content: &str, lines: &[usize], checked: bool) -> String {
let mark = if checked { 'x' } else { ' ' };
let mut out = String::with_capacity(content.len());
for (index, current) in content.lines().enumerate() {
match (lines.contains(&index), current.find("- [")) {
(true, Some(at)) => {
let opens = at + "- [".len();
out.push_str(&current[..opens]);
out.push(mark);
// Past the one character the brackets hold. Nothing follows on a line
// that ends mid-checkbox, which is why this is not unconditional.
if let Some((offset, _)) = current[opens..].char_indices().nth(1) {
out.push_str(&current[opens + offset..]);
}
}
_ => out.push_str(current),
}
out.push('\n');
}
out
}
/// The slice with blank values trimmed from both ends, interior ones kept.
///
/// Description values are joined with a single newline, so an empty value is how a
/// caller spells a paragraph break. That makes the interior blanks content, while a
/// blank at either end would only open or close the section with a gap.
pub fn trim_blank_ends(values: &[String]) -> &[String] {
let first = values.iter().position(|v| !v.trim().is_empty());
match first {
None => &[],
Some(first) => {
// Guaranteed to find one, since `first` is itself non-blank.
let last = match values.iter().rposition(|v| !v.trim().is_empty()) {
Some(last) => last,
None => first,
};
&values[first..=last]
}
}
}
/// A status, as clap accepts it and as the directory is named.
///
/// An enum rather than the string it was, so an unknown status is a usage error at parse
/// time with the four listed, the way `priority_level` and `iso_date` refuse a bad level
/// or date. That is the bargain the scalars already take, see AGENTS.md: nothing is
/// written, the exit code is 2, and no handler has to check. It also gives every shell
/// that completes possible values the four names for free.
///
/// The variants are in flow order, which is the order `mv` reads to decide whether a
/// move goes forward, and the order [`status_dirs`] hands the two views.
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum Status {
Backlog,
Committed,
Reviewing,
Done,
}
impl Status {
/// Every status, in flow order. The one list, which [`status_dirs`], `mv` and every
/// caller of [`by_status_order`] read rather than spelling the four names again.
pub const ALL: [Status; 4] = [
Status::Backlog,
Status::Committed,
Status::Reviewing,
Status::Done,
];
/// The field `mv` stamps on entering this status, for the three that have one.
///
/// Derived from the status rather than spelled at the call site, so the mapping is
/// in one place and a fifth status either brings its own stamp or explicitly has
/// none.
pub const fn stamp_field(self) -> Option<&'static str> {
match self {
Status::Backlog => None,
Status::Committed => Some(COMMITTED_ON_FIELD),
Status::Reviewing => Some(SUBMITTED_ON_FIELD),
Status::Done => Some(COMPLETED_ON_FIELD),
}
}
/// The directory name, which is also what clap accepts and what the `Status` field
/// holds. A `const fn` so [`DONE`] can be defined from it.
pub const fn as_str(self) -> &'static str {
match self {
Status::Backlog => "backlog",
Status::Committed => "committed",
Status::Reviewing => "reviewing",
Status::Done => "done",
}
}
}
pub fn status_dirs() -> Vec<&'static str> {
Status::ALL.iter().map(|status| status.as_str()).collect()
}
/// The end of the flow, and the one status both views treat differently: `ls` counts it
/// in the summary and leaves it out of the listing, and the board hides its column until
/// asked. Named because that rule now has two readers.
///
/// It is deliberately last in `status_dirs()`. The board leans on that: hiding done drops
/// the final column, so the other three keep their indices and the selection only has to
/// be handled when it is sitting on done itself.
pub const DONE: &str = Status::Done.as_str();
/// Lowest and highest level a ticket can carry. 1 is the most urgent, which is
/// what the `p1` to `p3` tags this replaced already meant.
pub const PRIORITY_RANGE: std::ops::RangeInclusive<u8> = 1..=5;
/// A ticket's priority as it comes off disk.
///
/// Three states, not two: a value outside the range has to stay distinguishable
/// from no value at all, or a typo silently reads as "no priority".
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Priority {
Level(u8),
Unset,
Invalid,
}
impl Priority {
/// Sort weight. Levels first in order, then anything wrong, then anything
/// absent, so a typo surfaces above the long tail of unset tickets.
pub fn rank(&self) -> u8 {
match self {
Priority::Level(level) => *level,
Priority::Invalid => u8::MAX - 1,
Priority::Unset => u8::MAX,
}
}
}
/// A priority from the value alone, for callers that already have it in hand.
pub fn priority_from_value(raw: &str) -> Priority {
let raw = raw.trim();
if is_unknown_value(raw) {
return Priority::Unset;
}
match raw.parse::<u8>() {
Ok(level) if PRIORITY_RANGE.contains(&level) => Priority::Level(level),
_ => Priority::Invalid,
}
}
pub fn parse_priority(content: &str) -> Priority {
priority_from_value(&parse_ticket_field(content, "Priority"))
}
/// How far along a ticket is: criteria ticked against criteria written.
///
/// `total` is never zero. A ticket with no criteria has no progress to show, and a card
/// reading `[0/0]` says less than a card saying nothing, so the absence is `None`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Progress {
pub met: usize,
pub total: usize,
}
/// `Clone` because the board's All tab holds the same ticket twice: once under its
/// own project's tab and once in the merge across projects. Re-reading the file for
/// the second copy would scan every tree twice on every tick that changed anything.
#[derive(Clone)]
pub struct TicketItem {
pub title: String,
pub owner: String,
pub due: String,
pub id: String,
pub created: String,
pub priority: Priority,
/// Ticked against total, or `None` for a ticket with no criteria.
///
/// Counted where the file is already being read, so the board pays nothing for it
/// beyond the count itself: the alternative, counting per card, would re-read every
/// ticket body on every draw rather than on the tick that changed something. The
/// listing ignores it, as it ignores `path`.
pub criteria: Option<Progress>,
/// The campaign uuid the ticket names, or `None` for a ticket in none.
///
/// Read here for the reason `criteria` is: `ls --campaign` filters on what this
/// pass already produced, rather than reading every ticket a second time to ask.
pub campaign: Option<String>,
/// The tags the ticket carries, split out of the comma-separated field, or empty
/// for an untagged one.
///
/// Read here for the reason `criteria` is: the board draws them on every card, and
/// asking per card would re-read every ticket body on every draw rather than on the
/// tick that changed something.
pub tags: Vec<String>,
/// The full uuid from the ticket's own ID field, as a relation stores it.
///
/// `id` is the seven characters a listing prints; a relation names the whole uuid,
/// so pairing a stored blocker with the ticket it points at needs the whole thing.
/// Absent or unset reads as `_Not set_`, the way every other field does, and the
/// board guards for it rather than matching on it.
pub uuid: String,
/// The uuids of the tickets this one records a `blocked by` against, empty when it
/// records none.
///
/// Read here for the reason `criteria` is: the board marks every held-up card on
/// every tick, and asking per card would re-read every ticket body on every draw.
/// The uuids only, never the answer: whether a blocker is still open is a fact
/// about another ticket, so it belongs to whoever holds the whole board.
///
/// A Relations section that cannot be parsed reads as no blockers rather than as a
/// ticket that cannot be listed. `show` and `mv` still refuse it, which is where a
/// hand-edited file has to be reported; a board or a listing that stops on one
/// malformed ticket is the worse failure, and is the same exception `detail_of`
/// already makes.
pub blockers: Vec<String>,
/// How many comments the ticket carries, `0` for one with none.
///
/// Read here for the reason `criteria` is: the board draws it on every card, so
/// asking per card would mean a `read_dir` per ticket per frame. It is the one field
/// on this pass that costs a directory listing rather than coming off the content
/// already in hand, which is why it is counted and never read: the bodies are the
/// detail view's business, and a count needs none of them.
pub comments: usize,
/// The file this came from. The listing ignores it; the TUI opens it for the
/// detail view rather than resolving the ticket a second time.
pub path: std::path::PathBuf,
/// The time `mv` stamped on entering committed, or `None` for a ticket that has
/// never got that far.
///
/// Read here for the reason `criteria` is, and it is what its column is ordered by:
/// a comparator that read the file would re-read every ticket on every comparison,
/// where this pass reads each one once.
pub committed_on: Option<String>,
/// The same for reviewing.
pub submitted_on: Option<String>,
/// The same for done.
pub completed_on: Option<String>,
}
impl TicketItem {
/// The stamp the ticket entered a status with, which is what that column sorts on.
///
/// A slot per status rather than a lookup by field name, so a fifth status carrying
/// a stamp is a compile error here the way it is in [`Status::stamp_field`].
/// Backlog has none: nothing stamps it, and `Created At` is not an entry time, so
/// every ticket in that column answers `None` and the whole order is the fallback.
fn entry_stamp(&self, status: Status) -> Option<&str> {
match status {
Status::Backlog => None,
Status::Committed => self.committed_on.as_deref(),
Status::Reviewing => self.submitted_on.as_deref(),
Status::Done => self.completed_on.as_deref(),
}
}
}
/// The stamp a ticket carries for a status, or `None` for one it has not reached.
///
/// The field name comes off [`Status::stamp_field`], so what is read here cannot drift
/// from what `mv` writes. An absent field reads as `_Not set_` like every other, and a
/// stamp is machine-written so that spelling never appears as a value; both count as no
/// stamp rather than as a time.
fn parse_stamp(content: &str, status: Status) -> Option<String> {
let value = parse_ticket_field(content, status.stamp_field()?);
match is_unknown_value(&value) {
true => None,
false => Some(value),
}
}
/// The date part of a due value, for a view with only a corner to spend on it.
///
/// The field is not validated, see daa0e79, so it holds whatever a caller typed: a bare
/// date, a date and a time, or free text. Only a real `YYYY-MM-DD` prefix is cut back
/// to. Taking the first word regardless would turn a free-text due into its first word,
/// which is worse than showing what is stored and letting the column decide.
pub fn due_date(due: &str) -> &str {
let candidate = due.split([' ', 'T']).next().unwrap_or(due);
match is_ymd(candidate) {
true => candidate,
false => due,
}
}
fn is_ymd(value: &str) -> bool {
let bytes = value.as_bytes();
bytes.len() == 10
&& bytes[4] == b'-'
&& bytes[7] == b'-'
&& [0, 1, 2, 3, 5, 6, 8, 9]
.iter()
.all(|at| bytes[*at].is_ascii_digit())
}
/// Grey for a value that is not set, per the colour guideline.
///
/// `show` already did this in its metadata rendering, so the listing was the one
/// place that ignored the rule.
fn dim_if_unset(value: &str, colored: bool) -> String {
if is_unknown_value(value) {
paint(value, Color::Grey, colored)
} else {
value.to_string()
}
}
/// The mark and colour for a level, from one place.
///
/// A two-segment meter that empties as the level rises, so the level is legible
/// from shape alone: colour is off whenever output is piped, and NO_COLOR turns it
/// off in a terminal too, so colour accentuates and never encodes.
///
/// Only three glyphs, the ones frig uses for its status indicators and which are
/// therefore known to render here. The quadrant circles this first used are in a
/// quarter as many fonts, so terminals substituted them from a fallback font that
/// draws them oversized. Two cells of a three-level ramp gives five steps of ink,
/// 2, 1.5, 1, 0.5, 0, without leaving that safe set.
///
/// The number counts up while the mark empties out, because 1 is the most urgent.
/// That is the convention every tracker uses and what the p1 tags this replaced
/// already meant.
pub fn priority_mark(priority: Priority) -> (&'static str, Color) {
match priority {
Priority::Level(1) => ("\u{25cf}\u{25cf}", Color::BrightRed),
Priority::Level(2) => ("\u{25cf}\u{25d0}", Color::Red),
Priority::Level(3) => ("\u{25cf}\u{25cb}", Color::Orange),
Priority::Level(4) => ("\u{25d0}\u{25cb}", Color::Cyan),
Priority::Level(5) => ("\u{25cb}\u{25cb}", Color::Grey),
// Unreachable while Level is only built by parse_priority, which checks
// the range, but a level added later should not silently render blank.
Priority::Level(_) | Priority::Invalid => ("??", Color::BrightRed),
Priority::Unset => ("\u{b7}\u{b7}", Color::Grey),
}
}
/// The legend, for help text. Nothing else in a listing explains the glyphs.
pub fn priority_legend() -> String {
let levels = PRIORITY_RANGE
.map(|level| {
let (glyph, _) = priority_mark(Priority::Level(level));
format!("{} {}", glyph, level)
})
.collect::<Vec<_>>()
.join(" ");
let (unset, _) = priority_mark(Priority::Unset);
format!("Priority: {levels} {unset} unset 1 is most urgent")
}
fn show_priority(priority: Priority, colored: bool) -> String {
let (glyph, colour) = priority_mark(priority);
paint(glyph, colour, colored)
}
pub fn display_ticket_items(items: &[TicketItem]) {
let colored = should_use_colors();
for item in items {
let id = paint(&item.id, Color::Red, colored);
let owner = dim_if_unset(&item.owner, colored);
let due = dim_if_unset(&item.due, colored);
let priority = show_priority(item.priority, colored);
if item.created.is_empty() {
println!(" {} ({}) {} | Owner: {} | Due: {}", priority, id, item.title, owner, due);
} else {
let created = paint(&item.created, Color::Cyan, colored);
println!(
" {} {} ({}) {} | Owner: {} | Due: {}",
priority, created, id, item.title, owner, due
);
}
}
}
/// How many comments a ticket has, counted off the directory rather than read.
///
/// `.md` only, the filter `read_comments` applies, so a stray file dropped in there is
/// not counted as something somebody wrote. A missing directory is none, which is what a
/// ticket nobody has commented on has: no directory is created until the first comment.
fn count_comments(board: &Path, uuid: &str) -> usize {
let Ok(entries) = fs::read_dir(comments_dir(board, uuid)) else {
return 0;
};
entries
.filter_map(|entry| entry.ok())
.filter(|entry| entry.path().extension().is_some_and(|ext| ext == "md"))
.count()
}
pub fn collect_ticket_items(status_path: impl AsRef<Path>) -> Result<Vec<TicketItem>> {
let status_path = status_path.as_ref();
// The comments sit beside the status directories, so the board is this one's parent.
// Derived rather than taken as a second argument: every caller joins a status onto a
// board it already holds, and two arguments would let a status from one board arrive
// with the comments of another. `None` only for a bare relative path, which no caller
// passes and which counts nothing rather than failing.
let board = status_path.parent();
let entries: Vec<_> = fs::read_dir(status_path)?
.filter_map(|e| e.ok())
// A status directory is a plain directory, so anything can be dropped in it.
// Without the extension a stray notes.txt was listed as a titleless ticket and
// counted in the summary alongside the real ones.
.filter(|e| e.path().extension().is_some_and(|ext| ext == "md"))
.collect();
let mut items: Vec<TicketItem> = entries
.iter()
.filter_map(|e| {
let content = fs::read_to_string(e.path()).ok()?;
let title = match heading_title(&content) {
title if title.is_empty() => "_No title_".to_string(),
title => title,
};
let owner = parse_ticket_field(&content, "Owner");
let due = parse_ticket_field(&content, "Due");
let filename = e.path().file_stem()?.to_string_lossy().to_string();
let created_at = parse_ticket_field(&content, "Created At");
let blockers = parse_relations(&content, &title)
.unwrap_or_default()
.into_iter()
.filter(|relation| relation.kind == RelationKind::BlockedBy)
.map(|relation| relation.target)
.collect();
// Through `criteria()`, so the card and the numbers `show` prints cannot
// disagree: a checkbox written into a description is not a criterion there
// and is not counted here.
let counted = criteria(&content);
let progress = match counted.len() {
0 => None,
total => Some(Progress {
met: counted.iter().filter(|criterion| criterion.checked).count(),
total,
}),
};
// The ticket's own ID field, not the filename stem: a comment directory is
// named by the uuid the file records, which is what `comment` wrote it under.
let uuid = parse_ticket_field(&content, "ID");
let comments = board.map_or(0, |board| count_comments(board, &uuid));
Some(TicketItem {
title,
owner,
due,
id: short_id(&filename).to_string(),
created: format_created_at(&created_at),
priority: parse_priority(&content),
criteria: progress,
campaign: parse_campaign(&content),
tags: parse_tags(&content),
uuid,
blockers,
comments,
path: e.path(),
committed_on: parse_stamp(&content, Status::Committed),
submitted_on: parse_stamp(&content, Status::Reviewing),
completed_on: parse_stamp(&content, Status::Done),
})
})
.collect();
items.sort_by(by_priority_then_title);
Ok(items)
}
/// The order the backlog is read in, and the tiebreak every other column falls back to:
/// priority first, title second.
///
/// Named and exported because the board's All tab merges several boards' columns into
/// one and has to land in one order. A merge sorted a second way would put a p1 below a
/// p5 depending on which project it came from, and the merge spans statuses, so no
/// single stamp governs it.
pub fn by_priority_then_title(a: &TicketItem, b: &TicketItem) -> std::cmp::Ordering {
a.priority
.rank()
.cmp(&b.priority.rank())
.then_with(|| a.title.to_lowercase().cmp(&b.title.to_lowercase()))
}
/// The order one status column is read in, keyed on the status.
///
/// Priority is the clock in the backlog, and that column keeps exactly the order it has
/// always printed. Past the backlog the question changes: committed asks what has waited
/// longest, reviewing what was handed over first, done what just landed. The head of
/// every column is therefore what the reader acts on next, which is ascending by entry
/// stamp in committed and reviewing and descending in done, the way a changelog reads.
///
/// A ticket with no stamp sinks below every stamped one in its column. A missing time is
/// unknown, not ancient, and unknown must not claim the head of a queue ahead of a wait
/// somebody can point at. Reading absence as the epoch would come free from the string
/// comparison and put every legacy ticket first on data nothing verified.
///
/// The comparison is a string comparison. The stamp format is `%Y-%m-%d %H:%M:%S`, where
/// lexicographic order is chronological order, the same property `Due` already relies
/// on, so there is no date parsing at sort time. Equal stamps happen, `mv` writes whole
/// seconds, and they fall through to priority and title like everything else.
pub fn by_status_order(status: Status, a: &TicketItem, b: &TicketItem) -> std::cmp::Ordering {
let by_stamp = match (a.entry_stamp(status), b.entry_stamp(status)) {
(Some(left), Some(right)) => match status {
Status::Done => right.cmp(left),
_ => left.cmp(right),
},
(Some(_), None) => std::cmp::Ordering::Less,
(None, Some(_)) => std::cmp::Ordering::Greater,
// Both unstamped, which is every ticket in the backlog: the fallback is the
// whole order there rather than a tiebreak.
(None, None) => std::cmp::Ordering::Equal,
};
by_stamp.then_with(|| by_priority_then_title(a, b))
}
/// The environment variable that keeps a test's fixture directory on disk.
///
/// Opt-in rather than on-by-default-when-a-test-fails, because the assertions in this crate
/// carry the state they are about: a failing board test prints the rendered rows, a failing
/// listing test prints the listing. The path is what you want when you would rather poke at
/// the files than read the message, which is the less common of the two.
#[cfg(test)]
pub const KEEP_FIXTURES: &str = "WORKLANE_KEEP_FIXTURES";
/// A fixture directory under the system temp directory that removes itself.
///
/// Every unit test in this crate builds its board or its status directory by hand under
/// `std::env::temp_dir()`. The ones that remembered a `remove_dir_all` at the end of the
/// test only cleaned up when their assertions passed, and most had no such line at all, so
/// a full run left one directory per test behind. `/tmp` reached 18363 of them and filled
/// the disk, which failed a link step and then a `git add` with "No space left on device" —
/// an error that names neither the tests nor what they left behind. That is b74dc5a.
///
/// A `Drop` rather than a line at the end of each test, because that is the only shape that
/// runs when an assertion fails, which is exactly when a fixture is most likely to be
/// stranded: unwinding runs destructors, so the guard holds on the failing path without the
/// test having to say anything.
///
/// `assert_fs::TempDir` is a dev-dependency already and is what the integration tests use,
/// and it was still not the answer here. It names its directories `.tmpXXXXXX`, which says
/// nothing about whose they are for the one case that matters — the one left on disk on
/// purpose — and it has no opinion about naming the path when it keeps one. Wrapping it to
/// add both is more code than this.
///
/// `Deref` to `Path`, so a fixture reads as the path it stands for at the call sites that
/// already had one and nothing had to change but the type.
#[cfg(test)]
pub struct Fixture {
/// What is removed: the directory this fixture created at the top.
root: std::path::PathBuf,
/// What the test works with, at or below the root. The two differ only for a fixture
/// that needs a named directory inside a parent it can also throw away.
path: std::path::PathBuf,
/// Whether to leave the directory behind, read once here rather than at drop time.
///
/// At construction because the answer must not be able to change between a test
/// starting and ending, and because it is what [`Fixture::swept`] can then turn off for
/// the tests that are about the guard rather than about this flag.
keep: bool,
}
#[cfg(test)]
impl Fixture {
/// A fresh directory, named after the family of tests that asked for it.
///
/// The prefix earns its place on the kept path: `worklane-tui-` says which suite left it
/// where a random name would not, and the uuid is what makes two fixtures with one
/// prefix two directories, so no test can reach another's.
pub fn new(prefix: &str) -> Self {
let root = std::env::temp_dir().join(format!("{prefix}-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&root).unwrap();
Fixture {
path: root.clone(),
root,
keep: std::env::var_os(KEEP_FIXTURES).is_some(),
}
}
/// The same fixture, swept up whatever the environment says.
///
/// For the tests below, which assert that the directory goes: they are about the guard
/// and not about the flag, so `WORKLANE_KEEP_FIXTURES` in a reader's environment must
/// not be able to fail them.
pub fn swept(mut self) -> Self {
self.keep = false;
self
}
/// The same fixture, pointing at a directory inside it.
///
/// For the tree a project test needs: `<root>/<project>/.worklane`, where the path the
/// test hands to `projects` is the project and what has to be removed is the root above
/// it. Consuming, so one directory never has two guards and therefore never two attempts
/// to remove it.
pub fn child(mut self, name: &str) -> Self {
self.path = self.root.join(name);
self
}
}
#[cfg(test)]
impl AsRef<std::path::Path> for Fixture {
fn as_ref(&self) -> &std::path::Path {
&self.path
}
}
/// Beside `AsRef`, because the two reach different call sites: a parameter bound by
/// `impl AsRef<Path>` is not a coercion site, and a parameter typed `&Path` is.
#[cfg(test)]
impl std::ops::Deref for Fixture {
type Target = std::path::Path;
fn deref(&self) -> &std::path::Path {
&self.path
}
}
#[cfg(test)]
impl Drop for Fixture {
fn drop(&mut self) {
if self.keep {
// Named, since a fixture kept and not findable is a fixture kept for nothing.
eprintln!("kept fixture {}", self.root.display());
return;
}
// Best effort. A directory that will not go must not turn a passing test into a
// failing one, and must not panic a second time out of a drop that is already
// unwinding, which would lose the failure the test was reporting.
std::fs::remove_dir_all(&self.root).ok();
}
}
#[cfg(test)]
mod tests {
use super::*;
/// The guard removes the directory when it goes out of scope, which is what makes the
/// cleanup independent of the assertions passing: unwinding runs destructors, so a
/// failing test drops its fixture on the way out exactly as a passing one does.
#[test]
fn a_fixture_removes_itself_when_its_guard_goes() {
let path = {
let dir = Fixture::new("worklane-guard").swept();
fs::write(dir.join("a.md"), "body").unwrap();
assert!(dir.exists(), "the fixture was not created");
dir.to_path_buf()
};
assert!(!path.exists(), "the fixture outlived its guard: {}", path.display());
}
/// And on the failing path, which is the whole point: a line at the end of a test does
/// not run when an assertion above it does not pass.
#[test]
fn a_fixture_removes_itself_when_the_test_panics() {
// The default hook would print this deliberate panic and make a green run read as a
// red one. Swapped for the length of the call and put straight back, which is as
// narrow as a process-wide hook can be made.
let hook = std::panic::take_hook();
std::panic::set_hook(Box::new(|_| {}));
let caught = std::panic::catch_unwind(|| {
let dir = Fixture::new("worklane-guard").swept();
// Handed out through the payload, so the assertion below has a path to look at
// whether or not the guard did its job.
std::panic::panic_any(dir.to_path_buf());
});
std::panic::set_hook(hook);
let path = *caught
.expect_err("the closure did not panic")
.downcast::<std::path::PathBuf>()
.expect("the panic did not carry the fixture path");
assert!(!path.exists(), "the fixture survived a failing test: {}", path.display());
}
/// Two fixtures with one prefix are two directories, so no test can rely on one another
/// test built — which the shared temp directory is what made possible.
#[test]
fn two_fixtures_with_one_prefix_are_two_directories() {
let first = Fixture::new("worklane-guard");
let second = Fixture::new("worklane-guard");
assert_ne!(first.to_path_buf(), second.to_path_buf(), "one directory, two guards");
let kept = second.to_path_buf();
drop(first);
assert!(kept.exists(), "one fixture going took the other with it");
}
#[test]
fn no_color_disables_colour_on_a_terminal() {
assert!(!colors_wanted(true, Some("1"), Some("xterm-256color")));
// Any value at all, per the convention
assert!(!colors_wanted(true, Some("0"), Some("xterm-256color")));
assert!(!colors_wanted(true, Some("false"), Some("xterm-256color")));
}
/// An empty value counts as unset, so a wrapper script can clear one it
/// inherited.
#[test]
fn an_empty_no_color_is_ignored() {
assert!(colors_wanted(true, Some(""), Some("xterm-256color")));
}
#[test]
fn a_dumb_terminal_gets_no_colour() {
assert!(!colors_wanted(true, None, Some("dumb")));
assert!(!colors_wanted(true, None, Some("")));
}
#[test]
fn colour_needs_a_terminal() {
assert!(colors_wanted(true, None, Some("xterm-256color")));
assert!(!colors_wanted(false, None, Some("xterm-256color")));
// No TERM at all is fine as long as it is a terminal
assert!(colors_wanted(true, None, None));
}
#[test]
fn unset_values_are_dimmed_and_set_ones_are_not() {
// Both paths, now that the colour decision is a parameter: with colour off the
// text has to come back untouched, with it on only the unset values get wrapped
for unset in ["_Not set_", "_None_"] {
assert!(is_unknown_value(unset), "{unset} should count as unset");
assert_eq!(dim_if_unset(unset, false), unset);
assert_eq!(dim_if_unset(unset, true), paint(unset, Color::Grey, true));
}
for set in ["alice", "2026-12-31", "bug,frontend"] {
assert!(!is_unknown_value(set));
assert_eq!(dim_if_unset(set, false), set);
assert_eq!(dim_if_unset(set, true), set);
}
}
/// The hyphenated spellings are values like any other, and this is what says so.
///
/// They were accepted as unset for months without any version of the tool ever
/// writing one, so the risk this pins is somebody re-adding them by analogy with the
/// `**-Status**` repair in `is_status_line`, which guards a corruption that was real.
#[test]
fn a_hyphenated_marker_is_not_unset() {
for legacy in ["-None-", "-Not set-", "-Nothing-"] {
assert!(
!is_unknown_value(legacy),
"{legacy} is read as unset, so a corrupted field would pass for an empty one"
);
}
}
fn ticket_with_priority(raw: &str) -> String {
format!("# T\n\n## Metadata\n\n- **Priority**: {}\n", raw)
}
/// A ticket whose prose quotes the field markers it also carries as metadata,
/// as a list so the quoted lines start with the marker. This repo files tickets
/// about the metadata format, so it is the normal case here rather than a corner.
fn ticket_shadowing_its_own_metadata() -> String {
"# Shadow\n\
\n\
## Description\n\
The current format is:\n\
- **Owner**: nobody\n\
- **Status**: backlog\n\
\n\
## Metadata\n\
\n\
- **ID**: real-id\n\
- **Owner**: alice\n\
- **Status**: backlog\n"
.to_string()
}
#[test]
fn prose_quoting_a_field_marker_does_not_shadow_the_metadata() {
let content = ticket_shadowing_its_own_metadata();
assert_eq!(parse_ticket_field(&content, "Owner"), "alice");
assert_eq!(parse_ticket_field(&content, "ID"), "real-id");
assert_eq!(parse_ticket_field(&content, "Status"), "backlog");
}
#[test]
fn a_field_only_mentioned_in_prose_reads_as_unset() {
let content =
"# T\n\n## Description\n- **Due**: 2026-12-31\n\n## Metadata\n\n- **ID**: x\n";
assert_eq!(parse_ticket_field(content, "Due"), "_Not set_");
}
#[test]
fn a_field_lookup_needs_the_metadata_heading() {
// No section, no fields: there is nothing to anchor to.
assert_eq!(parse_ticket_field("# T\n\n- **Owner**: alice\n", "Owner"), "_Not set_");
}
#[test]
fn a_field_lookup_stops_at_the_next_section() {
let content = "# T\n\n## Metadata\n\n- **ID**: x\n\n## Notes\n\n- **Owner**: alice\n";
assert_eq!(parse_ticket_field(content, "Owner"), "_Not set_");
assert_eq!(parse_ticket_field(content, "ID"), "x");
}
/// Matching on a prefix, not a substring: a field name inside another field's
/// value is not that field.
#[test]
fn a_field_marker_inside_another_value_is_not_matched() {
let content = "# T\n\n## Metadata\n\n- **Tags**: mentions **Owner**: bob\n";
assert_eq!(parse_ticket_field(content, "Owner"), "_Not set_");
assert_eq!(parse_ticket_field(content, "Tags"), "mentions **Owner**: bob");
}
#[test]
fn setting_the_status_leaves_prose_that_looks_like_metadata_alone() {
let content = ticket_shadowing_its_own_metadata();
let updated = set_status_field(&content, "committed", "Shadow").unwrap();
assert!(
updated.contains("## Description\nThe current format is:\n- **Owner**: nobody\n- **Status**: backlog\n"),
"the description was rewritten:\n{updated}"
);
assert_eq!(parse_ticket_field(&updated, "Status"), "committed");
assert_eq!(updated.matches("**Status**: committed").count(), 1);
}
#[test]
fn setting_the_status_needs_the_field_in_the_metadata_section() {
// A Status line above the section is prose, so this is a ticket without the field.
let content =
"# T\n\n## Description\n- **Status**: backlog\n\n## Metadata\n\n- **ID**: x\n";
assert!(set_status_field(content, "committed", "T").is_err());
}
/// SGR escapes removed, so a rendered cell can be measured as it lands on screen.
/// Test-only: production never measures a styled string, which is the point.
fn unstyled(text: &str) -> String {
let mut out = String::new();
let mut chars = text.chars();
while let Some(c) = chars.next() {
if c != '\x1b' {
out.push(c);
continue;
}
// Drop everything up to and including the 'm' that closes the sequence.
for c in chars.by_ref() {
if c == 'm' {
break;
}
}
}
out
}
#[test]
fn the_metadata_table_aligns_values_in_one_column() {
// The leading blank line is what the ticket template writes under the heading.
let rendered = render_metadata_table(
&[
"",
"- **ID**: abc",
"- **Created At**: 2026-08-20",
"- **Owner**: alice",
],
false,
"",
);
assert_eq!(
rendered,
"ID abc\n\
Created At 2026-08-20\n\
Owner alice\n"
);
}
#[test]
fn a_long_field_name_widens_the_column_for_every_row() {
let rendered =
render_metadata_table(&["- **ID**: abc", "- **Handled By Team**: ops"], false, "");
assert_eq!(
rendered,
"ID abc\n\
Handled By Team ops\n"
);
}
/// The trap the ticket names: field names are coloured, unset values are greyed
/// and Priority carries a mark, so measuring the styled text would tilt the table
/// with colour on and not with it off.
#[test]
fn colour_does_not_change_the_alignment() {
let lines = [
"- **ID**: abc",
"- **Priority**: 2",
"- **Due**: _Not set_",
"- **Owner**: Ansho Rei",
];
let plain = render_metadata_table(&lines, false, "");
let coloured = render_metadata_table(&lines, true, "");
assert_ne!(coloured, plain, "colour produced no escapes at all");
assert_eq!(unstyled(&coloured), plain);
}
#[test]
fn a_non_ascii_field_name_is_measured_in_characters() {
// "Créé à" is 6 characters and 8 bytes, so a byte-width column pads it short
let rendered = render_metadata_table(&["- **Créé à**: oui", "- **ID**: abc"], false, "");
assert_eq!(
rendered,
"Créé à oui\n\
ID abc\n"
);
}
#[test]
fn a_non_ascii_value_leaves_the_column_alone() {
let lines = ["- **Owner**: 日本語", "- **ID**: abc"];
let rendered = render_metadata_table(&lines, false, "");
assert_eq!(
rendered,
"Owner 日本語\n\
ID abc\n"
);
}
#[test]
fn a_field_the_tool_does_not_know_still_gets_a_row() {
let rendered = render_metadata_table(&["- **ID**: abc", "- **Sprint**: 14"], false, "");
assert!(rendered.contains("Sprint 14"), "{rendered:?}");
}
#[test]
fn a_line_that_is_not_a_field_is_carried_through() {
let rendered = render_metadata_table(&["- **ID**: abc", "a hand written note"], false, "");
assert_eq!(
rendered,
"ID abc\n\
a hand written note\n"
);
}
#[test]
fn the_priority_cell_carries_the_mark_and_the_stored_number() {
let rendered = render_metadata_table(&["- **Priority**: 2"], false, "");
let (glyph, _) = priority_mark(Priority::Level(2));
assert_eq!(rendered, format!("Priority {glyph} 2\n"));
}
#[test]
fn an_unset_priority_reads_as_unset_in_the_table() {
let rendered = render_metadata_table(&["- **Priority**: _Not set_"], false, "");
let (glyph, _) = priority_mark(Priority::Unset);
assert_eq!(rendered, format!("Priority {glyph} _Not set_\n"));
}
/// A ticket with the two things that used to leak: a numbered plan, and a
/// hand-written line inside the Metadata section.
const BOTH_LEAKS: &str = "# T\n\n## Implementation Plan\n1. First step\n2. Second step\n\
\n## Metadata\n\n- **ID**: abc\nA **handwritten** note\n";
/// The bug: the board asks for `content_trim(content, false)` because a paragraph
/// is no place for an escape sequence, and two paths asked the terminal instead.
#[test]
fn the_body_carries_no_escape_when_the_colour_is_off() {
let rendered = content_trim(BOTH_LEAKS, false, &Resolved::default());
assert!(
!rendered.contains('\x1b'),
"an escape survived colour being off: {rendered:?}"
);
// And the content is all still there, in plain form.
assert!(rendered.contains("1. First step"), "{rendered:?}");
assert!(rendered.contains("**handwritten**"), "{rendered:?}");
}
/// The other half of the pair, and the one that makes the first mean something:
/// with the flag on, both paths still colour. Without this, the passing test above
/// could be a colouring path that was simply deleted.
#[test]
fn the_body_colours_the_plan_number_and_a_metadata_note_when_the_colour_is_on() {
let rendered = content_trim(BOTH_LEAKS, true, &Resolved::default());
assert!(
rendered.contains(&format!("{}1.", Color::Cyan.ansi())),
"the plan number lost its colour: {rendered:?}"
);
assert!(
rendered.contains(&format!("{}handwritten", Color::Magenta.ansi())),
"the bold run lost its colour: {rendered:?}"
);
}
/// The flag has to be the only thing that decides, or the disabled path is just
/// the terminal's answer in disguise — which is why the leak survived a test
/// asserting the detail view holds no escapes. In a test binary there is no tty,
/// so `should_use_colors()` is false and the leaking branch was never taken.
#[test]
fn nothing_the_body_renders_asks_the_terminal_for_the_colour_decision() {
let callers = callers_of_color_text(include_str!("util.rs"));
// `ambiguous` is the one that may: it builds the candidate list for a failed
// search, reaches the user on stderr, and is not reachable from `content_trim`.
assert_eq!(
callers,
vec!["ambiguous".to_string()],
"`color_text` asks `should_use_colors()`. Everything reachable from \
`content_trim` has to take the decision as an argument and pass it to \
`paint` instead, because the board renders with colour off and an escape \
in a ratatui paragraph is drawn as literal bytes. If the new caller really \
is CLI-only, add it here and say why."
);
}
/// Which functions in this file call `color_text`, by name, definitions and the
/// test module excluded.
fn callers_of_color_text(source: &str) -> Vec<String> {
let body = match source.find("\n#[cfg(test)]") {
Some(end) => &source[..end],
None => source,
};
let mut current = String::new();
let mut callers = Vec::new();
for line in body.lines() {
if let Some(rest) = line.strip_prefix("fn ").or_else(|| line.strip_prefix("pub fn ")) {
current = rest.split('(').next().unwrap_or_default().to_string();
continue;
}
if line.contains("color_text(") && !callers.contains(&current) {
callers.push(current.clone());
}
}
callers
}
/// The field is not validated, see daa0e79, so the card cannot trust it to be a
/// bare date. Only a real date prefix is cut back to: free text is left alone,
/// since turning "next friday" into "next" would be a worse answer than the width.
#[test]
fn a_due_value_is_cut_back_to_its_date_only_when_it_has_one() {
assert_eq!(due_date("2026-12-31"), "2026-12-31");
assert_eq!(due_date("2026-12-31 09:30:00"), "2026-12-31");
assert_eq!(due_date("2026-12-31T09:30:00Z"), "2026-12-31");
assert_eq!(due_date("_Not set_"), "_Not set_");
assert_eq!(due_date("next friday"), "next friday");
assert_eq!(due_date("2026-1-1 09:30"), "2026-1-1 09:30");
}
/// The count on a card comes from `criteria()`, the same function that numbers them
/// in `show`, so the two cannot disagree about what a criterion is.
#[test]
fn collect_ticket_items_counts_the_criteria_show_would_number() {
let dir = Fixture::new("worklane-count");
let write = |name: &str, body: &str| {
fs::write(
dir.join(format!("11111111-0000-4000-8000-00000000000{name}.md")),
format!("# T{name}\n\n{body}\n\n## Metadata\n\n- **Owner**: alice\n"),
)
.unwrap();
};
// A checkbox in the description is not a criterion, in either view.
write(
"1",
"## Description\n- [x] not a criterion\n\n## Acceptance Criteria\n- [x] One\n- [ ] Two",
);
write("2", "## Acceptance Criteria\n_No acceptance criteria provided._");
let items = collect_ticket_items(&dir).unwrap();
let counted: Vec<Option<Progress>> = items.iter().map(|item| item.criteria).collect();
assert!(counted.contains(&Some(Progress { met: 1, total: 2 })), "{counted:?}");
assert!(
counted.contains(&None),
"a ticket with no criteria got a count: {counted:?}"
);
}
/// The count is a directory listing rather than a read: nothing here parses a comment,
/// and the bodies are the detail view's business.
///
/// `.md` only, the filter `read_comments` applies, so a stray file dropped in there is
/// not counted as something somebody wrote. A ticket with no directory at all has
/// none, which is every ticket until the first comment creates one.
#[test]
fn collect_ticket_items_counts_the_comments_under_the_board() {
let board = tempfile::tempdir().unwrap();
let backlog = board.path().join("backlog");
fs::create_dir_all(&backlog).unwrap();
let write = |uuid: &str| {
fs::write(
backlog.join(format!("{uuid}.md")),
format!("# T{uuid}\n\n## Metadata\n\n- **ID**: {uuid}\n- **Owner**: alice\n"),
)
.unwrap();
};
let talked_about = "11111111-0000-4000-8000-000000000001";
let quiet = "11111111-0000-4000-8000-000000000002";
write(talked_about);
write(quiet);
let comments = comments_dir(board.path(), talked_about);
fs::create_dir_all(&comments).unwrap();
fs::write(comments.join("20260823_120000_000000.md"), "**Comment**\n").unwrap();
fs::write(comments.join("20260823_120001_000000.md"), "**Comment**\n").unwrap();
// Not a comment, and not counted as one.
fs::write(comments.join("notes.txt"), "scratch\n").unwrap();
let items = collect_ticket_items(&backlog).unwrap();
let counted = |uuid: &str| {
items
.iter()
.find(|item| item.uuid == uuid)
.unwrap_or_else(|| panic!("no item for {uuid}"))
.comments
};
assert_eq!(counted(talked_about), 2);
assert_eq!(counted(quiet), 0);
}
/// The blockers come off the read that builds the item, so the board pays no second
/// pass for them, and only the `blocked by` kind is one: the other two record no
/// dependency and gate nothing.
///
/// A section that cannot be parsed reads as no blockers rather than as a ticket that
/// cannot be listed. `show` and `mv` are where a hand-edited file is reported; a
/// listing that stops on one malformed ticket is the worse failure.
#[test]
fn collect_ticket_items_reads_the_uuid_and_the_blockers_it_records() {
let dir = Fixture::new("worklane-blocked");
let uuid = |tail: &str| format!("11111111-0000-4000-8000-00000000000{tail}");
let write = |name: &str, relations: &str| {
fs::write(
dir.join(format!("{}.md", uuid(name))),
format!(
"# T{name}\n\n## Relations\n{relations}\n## Metadata\n\n- **ID**: {}\n",
uuid(name)
),
)
.unwrap();
};
write("1", &format!("\n- blocked by {}\n- relates to {}\n", uuid("2"), uuid("3")));
write("2", "\n- regression of 99999999-0000-4000-8000-000000000000\n");
write("3", "\n- waits for the other one\n");
let items = collect_ticket_items(&dir).unwrap();
let of = |title: &str| items.iter().find(|item| item.title == title).unwrap();
assert_eq!(of("T1").uuid, uuid("1"));
assert_eq!(of("T1").blockers, vec![uuid("2")]);
assert!(of("T2").blockers.is_empty(), "a regression was read as a blocker");
assert!(of("T3").blockers.is_empty(), "an unreadable section was not survived");
}
/// Whole values, so a filter or a card cannot confuse two tags that share a prefix.
#[test]
fn parse_tags_splits_on_commas_and_keeps_whole_values() {
let content = "# T\n\n## Metadata\n\n- **Tags**: bug, frontend,bugfix\n";
assert_eq!(parse_tags(content), vec!["bug", "frontend", "bugfix"]);
}
/// Absent, unset and empty are one answer: no tags.
#[test]
fn parse_tags_reads_an_unset_or_missing_field_as_none() {
assert_eq!(
parse_tags("# T\n\n## Metadata\n\n- **Tags**: _None_\n"),
Vec::<String>::new()
);
assert_eq!(parse_tags("# T\n\n## Metadata\n\n- **Tags**:\n"), Vec::<String>::new());
assert_eq!(
parse_tags("# T\n\n## Metadata\n\n- **Owner**: alice\n"),
Vec::<String>::new()
);
assert_eq!(parse_tags("# T\n\n## Metadata\n\n- **Tags**: , ,\n"), Vec::<String>::new());
}
#[test]
fn collect_ticket_items_lists_only_md_files() {
let dir = Fixture::new("worklane-stray");
fs::write(
dir.join("11111111-0000-4000-8000-000000000001.md"),
"# Real\n\n## Metadata\n\n- **Owner**: alice\n",
)
.unwrap();
fs::write(dir.join("notes.txt"), "# Stray\n").unwrap();
// A directory read_to_string happened to reject, so it was already skipped by
// accident. Kept here so the extension filter is what keeps it out.
fs::create_dir_all(dir.join("subdir")).unwrap();
let items = collect_ticket_items(&dir).unwrap();
let titles: Vec<&str> = items.iter().map(|item| item.title.as_str()).collect();
assert_eq!(titles, vec!["Real"], "{titles:?}");
}
/// The template ticket, and the shape every insertion test measures against.
fn with_metadata(fields: &str) -> String {
format!("# T\n\n## Description\nBody.\n\n## Metadata\n\n{fields}")
}
#[test]
fn an_absent_metadata_field_is_inserted_in_its_place() {
let content = with_metadata("- **ID**: abc\n- **Owner**: alice\n- **Status**: backlog\n");
let updated =
set_or_insert_metadata_field(&content, CAMPAIGN_FIELD, "c-uuid", "T").unwrap();
// Against METADATA_ORDER, so Status stays last where every file keeps it.
assert!(
updated.contains("- **Owner**: alice\n- **Campaign**: c-uuid\n- **Status**: backlog\n"),
"{updated}"
);
}
/// Nothing in the order follows it in this file, so it goes after the last line that
/// holds anything rather than past the blank that separates the section from the
/// next one. The blank has to stay where it is.
#[test]
fn an_absent_field_with_nothing_after_it_lands_at_the_end_of_the_section() {
let content = with_metadata("- **ID**: abc\n- **Owner**: alice\n\n## Notes\nAfter.\n");
let updated =
set_or_insert_metadata_field(&content, CAMPAIGN_FIELD, "c-uuid", "T").unwrap();
assert!(
updated.contains("- **Owner**: alice\n- **Campaign**: c-uuid\n\n## Notes\nAfter.\n"),
"{updated}"
);
}
/// An existing field is rewritten, not doubled, which is what keeps a ticket in at
/// most one campaign.
#[test]
fn a_field_already_there_is_rewritten_rather_than_added() {
let content =
with_metadata("- **ID**: abc\n- **Campaign**: first\n- **Status**: backlog\n");
let updated =
set_or_insert_metadata_field(&content, CAMPAIGN_FIELD, "second", "T").unwrap();
assert_eq!(updated.matches("**Campaign**:").count(), 1, "{updated}");
assert!(updated.contains("- **Campaign**: second"), "{updated}");
}
/// Prose above the section is free text, and tickets in this repo quote field
/// markers constantly. An insertion must not be steered by one.
#[test]
fn a_marker_in_the_description_does_not_take_the_insertion() {
let content = "# T\n\n## Description\n- **Campaign**: not a field\n\n\
## Metadata\n\n- **ID**: abc\n- **Status**: backlog\n";
let updated = set_or_insert_metadata_field(content, CAMPAIGN_FIELD, "c-uuid", "T").unwrap();
assert!(updated.contains("- **Campaign**: not a field"), "{updated}");
assert!(
updated.contains("- **ID**: abc\n- **Campaign**: c-uuid\n- **Status**: backlog"),
"{updated}"
);
}
/// No Metadata heading means no fields at all, per 641e3d5, so there is no format to
/// guess at and writing one above the prose would invent a shape nothing reads.
#[test]
fn a_file_with_no_metadata_section_is_an_error_rather_than_an_insertion() {
let content = "# T\n\n## Description\nBody.\n";
let error = set_or_insert_metadata_field(content, CAMPAIGN_FIELD, "c-uuid", "T")
.expect_err("a file with no Metadata section gained a field");
assert!(error.to_string().contains("no Metadata section"), "{error}");
assert!(error.to_string().contains("Campaign"), "{error}");
}
/// The stamp of the status being entered, added to what the ticket already carries:
/// the fields accumulate down the flow, so the stages behind it stay readable.
#[test]
fn entering_a_status_stamps_its_field_and_keeps_the_ones_before_it() {
let content = with_metadata(
"- **ID**: abc\n- **Committed On**: 2026-08-01 09:00:00\n- **Status**: committed\n",
);
let updated =
set_status_stamp(&content, Status::Reviewing, "2026-08-22 10:11:12", "T").unwrap();
assert!(updated.contains("- **Submitted On**: 2026-08-22 10:11:12"), "{updated}");
assert!(updated.contains("- **Committed On**: 2026-08-01 09:00:00"), "{updated}");
}
/// Arrival truncates the journey at the target, so the stage the ticket has been
/// sent back out of is dropped and the ones it still got through are not.
#[test]
fn arriving_removes_the_stamps_of_the_statuses_after_the_target() {
let content = with_metadata(
"- **ID**: abc\n\
- **Committed On**: 2026-08-01 09:00:00\n\
- **Submitted On**: 2026-08-02 09:00:00\n\
- **Completed On**: 2026-08-03 09:00:00\n\
- **Status**: done\n",
);
let updated =
set_status_stamp(&content, Status::Reviewing, "2026-08-22 10:11:12", "T").unwrap();
assert!(!updated.contains("**Completed On**"), "{updated}");
assert!(updated.contains("- **Committed On**: 2026-08-01 09:00:00"), "{updated}");
assert!(updated.contains("- **Submitted On**: 2026-08-22 10:11:12"), "{updated}");
}
/// Backlog has no stamp of its own and every status follows it, so a ticket forced
/// all the way back carries none of the three rather than a trail it has undone.
#[test]
fn moving_back_to_backlog_leaves_no_stamp_behind() {
let content = with_metadata(
"- **ID**: abc\n\
- **Committed On**: 2026-08-01 09:00:00\n\
- **Submitted On**: 2026-08-02 09:00:00\n\
- **Completed On**: 2026-08-03 09:00:00\n\
- **Status**: done\n",
);
let updated =
set_status_stamp(&content, Status::Backlog, "2026-08-22 10:11:12", "T").unwrap();
for field in [COMMITTED_ON_FIELD, SUBMITTED_ON_FIELD, COMPLETED_ON_FIELD] {
assert!(!updated.contains(&format!("**{}**", field)), "{updated}");
}
assert!(!updated.contains("2026-08-22 10:11:12"), "{updated}");
assert!(updated.contains("- **ID**: abc\n- **Status**: done\n"), "{updated}");
}
/// A skip stamps the target and nothing else. The stages it jumped over are left
/// unwritten rather than given a time the ticket never spent there.
#[test]
fn a_forward_skip_stamps_only_the_status_it_lands_in() {
let content = with_metadata("- **ID**: abc\n- **Status**: backlog\n");
let updated = set_status_stamp(&content, Status::Done, "2026-08-22 10:11:12", "T").unwrap();
assert!(updated.contains("- **Completed On**: 2026-08-22 10:11:12"), "{updated}");
assert!(!updated.contains("**Committed On**"), "{updated}");
assert!(!updated.contains("**Submitted On**"), "{updated}");
}
/// Re-entry is the time of the move that brought it back, not the first one.
#[test]
fn re_entering_a_status_restamps_rather_than_keeping_the_earlier_value() {
let content = with_metadata(
"- **ID**: abc\n- **Committed On**: 2026-08-01 09:00:00\n- **Status**: backlog\n",
);
let updated =
set_status_stamp(&content, Status::Committed, "2026-08-22 10:11:12", "T").unwrap();
assert_eq!(updated.matches("**Committed On**:").count(), 1, "{updated}");
assert!(!updated.contains("2026-08-01 09:00:00"), "{updated}");
}
/// Against METADATA_ORDER, like Campaign: after Created At, which answers the same
/// kind of question, and never past Status, which every file keeps last.
#[test]
fn a_stamp_is_inserted_in_its_place_on_a_ticket_that_predates_the_field() {
let content = with_metadata(
"- **ID**: abc\n\
- **Created At**: 2026-08-01 09:00:00\n\
- **Campaign**: c-uuid\n\
- **Status**: reviewing\n",
);
let updated = set_status_stamp(&content, Status::Done, "2026-08-22 10:11:12", "T").unwrap();
assert!(
updated.contains(
"- **Created At**: 2026-08-01 09:00:00\n\
- **Completed On**: 2026-08-22 10:11:12\n\
- **Campaign**: c-uuid\n\
- **Status**: reviewing\n"
),
"{updated}"
);
}
/// A listed ticket with only the fields the column order reads: its title, its
/// priority and the stamp for the status being sorted.
fn listed(title: &str, level: u8, status: Status, stamp: Option<&str>) -> TicketItem {
let stamp = stamp.map(|value| value.to_string());
TicketItem {
title: title.to_string(),
owner: NOT_SET.to_string(),
due: NOT_SET.to_string(),
id: "0000000".to_string(),
created: String::new(),
priority: Priority::Level(level),
criteria: None,
campaign: None,
tags: Vec::new(),
uuid: NOT_SET.to_string(),
blockers: Vec::new(),
comments: 0,
path: std::path::PathBuf::new(),
committed_on: match status {
Status::Committed => stamp.clone(),
_ => None,
},
submitted_on: match status {
Status::Reviewing => stamp.clone(),
_ => None,
},
completed_on: match status {
Status::Done => stamp,
_ => None,
},
}
}
/// Sorted the way the column is read, titles out, so a case reads as the order it
/// asserts rather than as a pair of comparisons.
fn ordered(status: Status, mut items: Vec<TicketItem>) -> Vec<String> {
items.sort_by(|a, b| by_status_order(status, a, b));
items.into_iter().map(|item| item.title).collect()
}
/// The backlog is the one column priority still governs, and it prints exactly what
/// it always has: the stamps a ticket carries from an earlier trip through the flow
/// do not reach it, because backlog has no stamp of its own to sort on.
#[test]
fn the_backlog_keeps_priority_then_title() {
let items = vec![
listed("zebra", 5, Status::Backlog, None),
listed("alpha", 1, Status::Backlog, None),
listed("beta", 1, Status::Backlog, None),
];
assert_eq!(ordered(Status::Backlog, items), ["alpha", "beta", "zebra"]);
}
/// Committed and reviewing are queues: the head is what has waited longest, which is
/// where the reader picks next from.
#[test]
fn committed_and_reviewing_list_the_oldest_stamp_first() {
for status in [Status::Committed, Status::Reviewing] {
let items = vec![
listed("newest", 1, status, Some("2026-08-03 09:00:00")),
listed("oldest", 5, status, Some("2026-08-01 09:00:00")),
listed("middle", 1, status, Some("2026-08-02 09:00:00")),
];
assert_eq!(ordered(status, items), ["oldest", "middle", "newest"], "{status:?}");
}
}
/// Done reads like a changelog: what just landed is at the top, and priority no
/// longer decides anything about finished work.
#[test]
fn done_lists_the_newest_stamp_first() {
let items = vec![
listed("first", 1, Status::Done, Some("2026-08-01 09:00:00")),
listed("last", 5, Status::Done, Some("2026-08-03 09:00:00")),
listed("middle", 1, Status::Done, Some("2026-08-02 09:00:00")),
];
assert_eq!(ordered(Status::Done, items), ["last", "middle", "first"]);
}
/// A missing stamp is unknown, not ancient. Reading absence as the epoch would come
/// free from the string comparison and hand the head of the queue to every legacy
/// ticket, so it sinks instead, in both directions.
#[test]
fn a_ticket_with_no_stamp_sorts_below_every_stamped_one() {
for status in [Status::Committed, Status::Reviewing, Status::Done] {
let items = vec![
listed("unstamped", 1, status, None),
listed("stamped", 5, status, Some("2026-08-01 09:00:00")),
];
assert_eq!(ordered(status, items), ["stamped", "unstamped"], "{status:?}");
}
}
/// `mv` writes whole seconds, so two moves in the same second is a real tie rather
/// than a hypothetical one, and it falls through to the order the backlog uses.
#[test]
fn equal_stamps_fall_back_to_priority_then_title() {
let same = Some("2026-08-01 09:00:00");
let items = vec![
listed("zebra", 1, Status::Committed, same),
listed("beta", 3, Status::Committed, same),
listed("alpha", 3, Status::Committed, same),
];
assert_eq!(ordered(Status::Committed, items), ["zebra", "alpha", "beta"]);
}
/// Two unstamped tickets in one column are ordered among themselves the way the
/// backlog is, rather than left in whatever order the directory handed them back.
#[test]
fn unstamped_tickets_are_ordered_among_themselves_by_priority_then_title() {
let items = vec![
listed("zebra", 1, Status::Done, None),
listed("beta", 3, Status::Done, None),
listed("alpha", 3, Status::Done, None),
];
assert_eq!(ordered(Status::Done, items), ["zebra", "alpha", "beta"]);
}
/// The stamps come off the pass that builds the listing, not off a second read at
/// comparison time, which is what makes an ordered column cost one read per file.
#[test]
fn collect_ticket_items_reads_the_stamps_the_order_sorts_on() {
let dir = Fixture::new("worklane-stamps");
fs::write(
dir.join("aaaa_walked.md"),
"# Walked\n\n## Metadata\n\n\
- **ID**: aaaa\n\
- **Committed On**: 2026-08-01 09:00:00\n\
- **Submitted On**: 2026-08-02 09:00:00\n\
- **Completed On**: 2026-08-03 09:00:00\n\
- **Status**: done\n",
)
.unwrap();
fs::write(
dir.join("bbbb_fresh.md"),
"# Fresh\n\n## Metadata\n\n- **ID**: bbbb\n- **Status**: backlog\n",
)
.unwrap();
let items = collect_ticket_items(&dir).unwrap();
let walked = items.iter().find(|item| item.title == "Walked").unwrap();
assert_eq!(walked.committed_on.as_deref(), Some("2026-08-01 09:00:00"));
assert_eq!(walked.submitted_on.as_deref(), Some("2026-08-02 09:00:00"));
assert_eq!(walked.completed_on.as_deref(), Some("2026-08-03 09:00:00"));
// Absent reads as no stamp rather than as the `_Not set_` every other field
// falls back to, so the order sinks it instead of comparing that text.
let fresh = items.iter().find(|item| item.title == "Fresh").unwrap();
assert_eq!(fresh.committed_on, None);
assert_eq!(fresh.submitted_on, None);
assert_eq!(fresh.completed_on, None);
}
/// Removal is scoped to the section for the same reason the write is: a description
/// quoting a field marker is prose, and rewriting it would corrupt the ticket text
/// while leaving the real field in place.
#[test]
fn a_marker_in_the_description_is_not_the_field_being_removed() {
let content = "# T\n\n## Description\n- **Committed On**: not a field\n\n\
## Metadata\n\n- **ID**: abc\n- **Status**: backlog\n";
let updated =
set_status_stamp(content, Status::Backlog, "2026-08-22 10:11:12", "T").unwrap();
assert!(updated.contains("- **Committed On**: not a field"), "{updated}");
}
/// Nothing to remove is not a rewrite: the content comes back byte for byte, which
/// is what keeps a move that stamps nothing from touching the file's shape.
#[test]
fn removing_a_field_the_ticket_does_not_carry_leaves_the_content_alone() {
let content = with_metadata("- **ID**: abc\n- **Status**: backlog\n");
assert_eq!(remove_metadata_line(&content, COMPLETED_ON_FIELD), None);
assert_eq!(
set_status_stamp(&content, Status::Backlog, "2026-08-22 10:11:12", "T").unwrap(),
content
);
}
#[test]
fn a_campaign_field_that_is_unset_or_absent_reads_as_no_campaign() {
assert_eq!(parse_campaign(&with_metadata("- **ID**: abc\n")), None);
assert_eq!(parse_campaign(&with_metadata("- **Campaign**: _Not set_\n")), None);
assert_eq!(
parse_campaign(&with_metadata("- **Campaign**: c-uuid\n")),
Some("c-uuid".to_string())
);
}
/// The Campaign row shows the resolved cell, and every other row is untouched by it.
#[test]
fn the_campaign_row_shows_the_cell_it_was_given() {
let lines = ["- **Campaign**: c-uuid", "- **Owner**: alice"];
let rendered = render_metadata_table(&lines, false, "(c-uuid) v1 release");
assert!(rendered.contains("Campaign (c-uuid) v1 release"), "{rendered}");
assert!(rendered.contains("Owner alice"), "{rendered}");
}
/// With no cell to show, the stored value renders as it sits. That is what a ticket
/// in no campaign wants, and it keeps the field readable on a board whose campaigns
/// directory cannot be read.
#[test]
fn the_campaign_row_falls_back_to_the_stored_value() {
let rendered = render_metadata_table(&["- **Campaign**: c-uuid"], false, "");
assert!(rendered.contains("Campaign c-uuid"), "{rendered}");
}
#[test]
fn a_section_rule_matches_the_width_of_its_name() {
let rendered = content_trim_colored("# T\n\n## Description\nbody\n", &Resolved::default());
// Eleven characters, not fourteen: the rule used to span "## Description"
assert!(rendered.starts_with("Description\n───────────\n"), "{rendered:?}");
}
#[test]
fn a_non_ascii_section_name_is_not_over_drawn() {
let rendered = content_trim_colored("# T\n\n## Résumé\nbody\n", &Resolved::default());
assert!(rendered.starts_with("Résumé\n──────\n"), "{rendered:?}");
}
#[test]
fn the_body_leaves_the_title_to_cmd_show() {
let rendered =
content_trim_colored("# Only Once\n\n## Description\nbody\n", &Resolved::default());
assert!(!rendered.contains("Only Once"), "{rendered:?}");
// And no gap where it was
assert!(rendered.starts_with("Description"), "{rendered:?}");
}
#[test]
fn the_metadata_section_renders_as_a_table_inside_the_body() {
let content = "# T\n\n## Metadata\n\n- **ID**: abc\n- **Owner**: alice\n";
let rendered = content_trim_colored(content, &Resolved::default());
assert_eq!(rendered, "Metadata\n────────\n\nID abc\nOwner alice\n");
}
#[test]
fn a_section_after_metadata_still_renders() {
let content = "# T\n\n## Metadata\n\n- **ID**: abc\n\n## Notes\n\nafter\n";
let rendered = content_trim_colored(content, &Resolved::default());
assert!(rendered.contains("ID abc"), "{rendered:?}");
assert!(rendered.contains("Notes\n─────\n"), "{rendered:?}");
assert!(rendered.ends_with("after\n"), "{rendered:?}");
}
#[test]
fn blank_values_are_trimmed_from_the_ends_but_kept_inside() {
let owned =
|values: &[&str]| -> Vec<String> { values.iter().map(|v| v.to_string()).collect() };
// A break between paragraphs is content
let two_paragraphs = owned(&["First.", "", "Second."]);
assert_eq!(trim_blank_ends(&two_paragraphs), two_paragraphs.as_slice());
// A run of them is kept verbatim rather than collapsed
let wide = owned(&["A", "", "", "B"]);
assert_eq!(trim_blank_ends(&wide), wide.as_slice());
// The ends are not
assert_eq!(
trim_blank_ends(&owned(&["", " ", "Only.", "", ""])),
owned(&["Only."]).as_slice()
);
// Nothing but blanks is nothing at all
assert!(trim_blank_ends(&owned(&["", " ", ""])).is_empty());
assert!(trim_blank_ends(&[]).is_empty());
// A single value survives either way
assert_eq!(trim_blank_ends(&owned(&["One."])), owned(&["One."]).as_slice());
}
#[test]
fn a_level_in_range_parses() {
for level in 1..=5u8 {
let content = ticket_with_priority(&level.to_string());
assert_eq!(parse_priority(&content), Priority::Level(level));
}
}
#[test]
fn a_missing_or_unset_level_is_unset() {
assert_eq!(parse_priority("# T\n\n## Metadata\n"), Priority::Unset);
assert_eq!(parse_priority(&ticket_with_priority("_Not set_")), Priority::Unset);
assert_eq!(parse_priority(&ticket_with_priority("_None_")), Priority::Unset);
}
/// Distinct from unset on purpose: a typo must not read as "no priority".
#[test]
fn an_out_of_range_or_unparseable_level_is_invalid() {
for raw in ["0", "6", "42", "high", "-1", "1.5", "999999999999"] {
assert_eq!(
parse_priority(&ticket_with_priority(raw)),
Priority::Invalid,
"for {raw:?}"
);
}
}
#[test]
fn levels_sort_ahead_of_invalid_which_sorts_ahead_of_unset() {
let mut ranks = [
Priority::Unset,
Priority::Level(5),
Priority::Invalid,
Priority::Level(1),
]
.map(|p| p.rank());
ranks.sort();
assert_eq!(
ranks,
[
Priority::Level(1).rank(),
Priority::Level(5).rank(),
Priority::Invalid.rank(),
Priority::Unset.rank()
]
);
}
#[test]
fn each_level_gets_its_own_glyph_and_colour() {
let marks: Vec<_> = PRIORITY_RANGE
.map(|level| priority_mark(Priority::Level(level)))
.collect();
let glyphs: std::collections::HashSet<_> = marks.iter().map(|(g, _)| *g).collect();
assert_eq!(glyphs.len(), marks.len(), "two levels share a glyph");
let colours: std::collections::HashSet<_> = marks.iter().map(|(_, c)| *c).collect();
assert_eq!(colours.len(), marks.len(), "two levels share a colour");
}
/// The glyph has to carry the level with colour off, which is how every pipe
/// and every opencode tool reads it.
#[test]
fn the_glyph_alone_distinguishes_every_state() {
let mut seen = std::collections::HashSet::new();
for state in PRIORITY_RANGE
.map(Priority::Level)
.chain([Priority::Unset, Priority::Invalid])
{
let (glyph, _) = priority_mark(state);
assert!(seen.insert(glyph), "{glyph} is used for more than one state");
}
}
#[test]
fn the_fullest_mark_is_the_most_urgent() {
assert_eq!(priority_mark(Priority::Level(1)).0, "\u{25cf}\u{25cf}");
assert_eq!(priority_mark(Priority::Level(5)).0, "\u{25cb}\u{25cb}");
}
/// Every mark is the same width, or the column stops lining up.
#[test]
fn every_mark_is_the_same_width() {
let widths: std::collections::HashSet<usize> = PRIORITY_RANGE
.map(Priority::Level)
.chain([Priority::Unset, Priority::Invalid])
.map(|p| priority_mark(p).0.chars().count())
.collect();
assert_eq!(widths, std::collections::HashSet::from([2]));
}
/// The marks are built only from what frig already renders in this terminal:
/// the quadrant circles are in a quarter as many fonts and got substituted
/// from a fallback font that drew them oversized.
#[test]
fn marks_use_only_the_glyphs_known_to_render() {
let allowed = ['\u{25cf}', '\u{25d0}', '\u{25cb}', '\u{b7}', '?'];
for state in PRIORITY_RANGE
.map(Priority::Level)
.chain([Priority::Unset, Priority::Invalid])
{
for ch in priority_mark(state).0.chars() {
assert!(allowed.contains(&ch), "{ch:?} is outside the safe set");
}
}
}
#[test]
fn the_meter_empties_as_the_level_rises() {
let ink = |p: Priority| -> f32 {
priority_mark(p)
.0
.chars()
.map(|c| match c {
'\u{25cf}' => 1.0,
'\u{25d0}' => 0.5,
_ => 0.0,
})
.sum()
};
let mut previous = f32::MAX;
for level in PRIORITY_RANGE {
let current = ink(Priority::Level(level));
assert!(current < previous, "level {level} does not empty further");
previous = current;
}
}
#[test]
fn an_invalid_level_is_marked_wrong_not_unset() {
assert_eq!(priority_mark(Priority::Invalid).0, "??");
assert_ne!(priority_mark(Priority::Invalid), priority_mark(Priority::Unset));
}
#[test]
fn the_legend_covers_every_level_and_says_which_way_it_runs() {
let legend = priority_legend();
for level in PRIORITY_RANGE {
let (glyph, _) = priority_mark(Priority::Level(level));
assert!(legend.contains(glyph), "{glyph} missing from the legend");
assert!(legend.contains(&level.to_string()));
}
assert!(legend.contains("most urgent"), "direction not spelled out");
}
/// Green means title; a priority must not borrow it.
#[test]
fn the_ramp_avoids_green() {
for level in PRIORITY_RANGE {
assert_ne!(priority_mark(Priority::Level(level)).1, Color::Green);
}
}
#[test]
fn every_colour_has_an_escape_and_a_ratatui_equivalent() {
// The old version of this test guarded against a name with no entry, which the
// enum now makes a compile error. What is left worth asserting is that no
// variant renders as nothing, and that the two renderers agree on the set.
let mut seen = std::collections::HashSet::new();
for colour in Color::ALL {
assert!(!colour.ansi().is_empty(), "{colour:?} has no escape");
assert!(colour.ansi().starts_with("\x1b["), "{colour:?} is not an SGR sequence");
assert!(
seen.insert(ratatui::style::Color::from(colour)),
"{colour:?} shares its ratatui colour"
);
}
assert_eq!(seen.len(), Color::ALL.len());
}
/// The text a cell holds once its colour is taken off, so a test can assert the
/// separators survived without spelling out the escapes around them.
fn strip_escapes(text: &str) -> String {
let mut out = String::with_capacity(text.len());
let mut rest = text;
while let Some(at) = rest.find('\x1b') {
out.push_str(&rest[..at]);
match rest[at..].find('m') {
Some(end) => rest = &rest[at + end + 1..],
None => return out,
}
}
out.push_str(rest);
out
}
#[test]
fn a_tag_keeps_its_colour_and_different_tags_do_not_all_share_one() {
assert_eq!(tag_color("bug"), tag_color("bug"));
assert_eq!(tag_color("frontend"), tag_color("frontend"));
let spread: std::collections::HashSet<Color> = [
"bug", "feature", "cli", "tui", "docs", "chore", "output", "skills",
]
.iter()
.map(|tag| tag_color(tag))
.collect();
assert!(spread.len() > 3, "the mapping collapses the vocabulary: {spread:?}");
}
/// Case sensitive on purpose: `Bug` and `bug` are two different tags to the field
/// and to every search, so one colour for both would be the display claiming a
/// sameness nothing else has.
///
/// Over a set rather than one pair. Any single pair can land in the same slot by
/// luck, one time in `TAG_COLORS.len()`, and a test that reads that accident as
/// case folding would be asserting the hash rather than the rule.
#[test]
fn tag_colour_does_not_fold_case() {
let folded = ["bug", "cli", "tui", "docs", "chore"]
.iter()
.all(|tag| tag_color(tag) == tag_color(&tag.to_uppercase()));
assert!(!folded, "tag_color lowercases before hashing");
}
/// Pinned so that a change to the hash is a failing test rather than a board that
/// quietly repaints itself. If this fails, the mapping moved: decide whether that
/// was intended before rewriting the expectations.
#[test]
fn the_tag_mapping_is_pinned() {
assert_eq!(tag_color("bug"), Color::Blue);
assert_eq!(tag_color("feature"), Color::Blue);
assert_eq!(tag_color("cli"), Color::Steel);
assert_eq!(tag_color("tui"), Color::Violet);
assert_eq!(tag_color("docs"), Color::Tan);
assert_eq!(tag_color("chore"), Color::Sky);
assert_eq!(tag_color("skills"), Color::Tan);
assert_eq!(tag_color("output"), Color::Blue);
}
/// The whole reason the tag palette is a reserved list rather than a pick at the
/// call site: a tag drawn in red reads as a uuid, in green as a title, in grey as
/// an unset value.
#[test]
fn no_tag_colour_carries_another_meaning() {
for assigned in [
Color::Red,
Color::Orange,
Color::Cyan,
Color::Green,
Color::Grey,
Color::Magenta,
Color::BrightRed,
] {
assert!(
!TAG_COLORS.contains(&assigned),
"{assigned:?} means something else already"
);
}
// The priority ramp is the other list that claims colours, and it is built from
// the assigned seven rather than named here, so ask it directly.
for level in PRIORITY_RANGE {
let ramp = priority_mark(Priority::Level(level)).1;
assert!(!TAG_COLORS.contains(&ramp), "{ramp:?} is a priority colour");
}
}
#[test]
fn the_tags_cell_paints_each_tag_and_leaves_the_separators_alone() {
let plain = metadata_value_cell("Tags", "bug, cli", false, "");
assert_eq!(plain, "bug, cli", "colour off must be the stored value");
let painted = metadata_value_cell("Tags", "bug, cli", true, "");
assert!(painted.contains(&paint("bug", tag_color("bug"), true)));
assert!(painted.contains(&paint("cli", tag_color("cli"), true)));
// The separator the file holds comes back as it went in, spacing and all.
assert_eq!(strip_escapes(&painted), "bug, cli");
assert_eq!(strip_escapes(&metadata_value_cell("Tags", "bug,cli", true, "")), "bug,cli");
assert_eq!(
strip_escapes(&metadata_value_cell("Tags", " bug , cli ", true, "")),
" bug , cli "
);
}
/// An unset value stays grey, since the Tags branch sits behind the unknown check.
#[test]
fn an_unset_tags_cell_is_still_grey() {
assert_eq!(
metadata_value_cell("Tags", "_None_", true, ""),
paint("_None_", Color::Grey, true)
);
}
/// Pinned deliberately. Both SGR spellings of grey failed on a real palette,
/// 90 reading nearly as light as the foreground and 37 sitting on top of it.
/// This is the exact sequence crossterm emits for ratatui's Color::DarkGray,
/// so worklane's grey is the one frig and pantop already render.
#[test]
fn grey_matches_the_indexed_colour_frig_uses() {
assert_eq!(Color::Grey.ansi(), "\x1b[38;5;8m");
}
/// With no colour to carry the emphasis, the markers are the emphasis.
#[test]
fn bold_markers_survive_when_colour_is_off() {
let line = "Some **bold** text";
assert_eq!(colorize_bold(line, false), line);
}
#[test]
fn bold_markers_are_replaced_when_colour_is_on() {
let out = colorize_bold("Some **bold** text", true);
assert!(out.contains("bold"), "was {out:?}");
assert!(!out.contains("**"), "markers left behind in {out:?}");
}
/// The old scan ran past the end here and dropped the last character.
#[test]
fn an_unterminated_marker_keeps_the_whole_line() {
for line in ["a **bold", "**", "***", "trailing **"] {
assert_eq!(colorize_bold(line, true), line, "for {line:?}");
}
}
#[test]
fn several_bold_runs_on_one_line_all_survive() {
let out = colorize_bold("**one** and **two** and rest", true);
assert!(out.contains("one") && out.contains("two") && out.ends_with("and rest"));
assert!(!out.contains("**"), "was {out:?}");
}
#[test]
fn short_id_shortens_a_full_uuid() {
assert_eq!(short_id("c230d2c6-d78a-44a5-8f5f-88fb28f84493"), "c230d2c");
}
#[test]
fn short_id_leaves_anything_shorter_alone() {
assert_eq!(short_id("abc"), "abc");
assert_eq!(short_id(""), "");
assert_eq!(short_id("abcdefg"), "abcdefg");
}
/// The cut used to land inside a character and panic.
#[test]
fn short_id_counts_characters_not_bytes() {
assert_eq!(short_id("émigré-ticket"), "émigré-");
assert_eq!(short_id("日本語"), "日本語");
}
#[test]
fn created_at_is_shortened_for_display() {
assert_eq!(format_created_at("2026-08-20 13:06:34"), "26-08-20:13");
}
/// Every one of these reached the old byte offsets from an unvalidated file.
#[test]
fn unparseable_created_at_drops_the_column() {
for value in [
"_Not set_",
"",
"2026-08-20",
"日本語日本語日本語",
"not a date at all",
] {
assert_eq!(format_created_at(value), "", "for {value:?}");
}
}
// --------------------------------------------------------------- relations --
/// One row as the block shows it, for a test about where the block goes rather than
/// about how it was derived.
fn row(
kind: RelationKind,
label: &'static str,
uuid: &str,
title: &str,
status: &str,
) -> RelationRow {
RelationRow {
kind,
label,
uuid: uuid.to_string(),
target: Some(RelationTarget {
title: title.to_string(),
status: status.to_string(),
}),
}
}
/// The status mark as the block draws it, so a row assertion reads like the row.
/// The glyphs themselves are pinned literally by `the_status_marks_are_pinned`.
fn smark(status: &str) -> &'static str {
status_mark(Some(status)).0
}
const TARGET: &str = "b1b2c3d4-5e6f-4a7b-8c9d-0e1f2a3b4c5d";
const SELF: &str = "641e3d5c-1b0e-4d2f-9a7e-3c8b5f0a2d61";
fn related(uuid: &str, title: &str, status: &str, relations: Vec<Relation>) -> RelatedTicket {
RelatedTicket {
uuid: uuid.to_string(),
title: title.to_string(),
status: status.to_string(),
relations,
}
}
fn relation(kind: RelationKind, target: &str) -> Relation {
Relation {
kind,
target: target.to_string(),
}
}
#[test]
fn a_stored_line_parses_back_into_the_relation_that_wrote_it() {
for kind in RelationKind::ALL {
let stored = format!("- {}", relation(kind, TARGET).item());
assert_eq!(parse_relation(&stored).unwrap(), relation(kind, TARGET));
}
}
/// No label is a prefix of another, so the longer kind cannot be read as a shorter
/// one with a target that starts with the rest of its name.
#[test]
fn no_kind_label_is_a_prefix_of_another() {
for kind in RelationKind::ALL {
for other in RelationKind::ALL {
assert!(
kind == other || !other.label().starts_with(kind.label()),
"{} is a prefix of {}",
kind.label(),
other.label()
);
}
}
}
/// An unreadable line is an error naming the kinds, not a line quietly dropped:
/// the section is the one part of a ticket that is read back by machine.
#[test]
fn a_line_that_is_not_a_relation_is_refused() {
let error = parse_relation("- depends on abc").unwrap_err().to_string();
assert!(error.contains("is not a relation"), "{error}");
assert!(error.contains("blocked by"), "{error}");
assert!(
parse_relation("- blocked by")
.unwrap_err()
.to_string()
.contains("no target")
);
}
/// The two directions of the pairing have to agree, or `--clear acceptance` would
/// empty one section while the error message about an empty value named another.
#[test]
fn every_clearable_section_points_back_at_the_field_that_clears_it() {
for field in Clearable::ALL {
if let Unset::Section(section) = field.unset() {
assert_eq!(
section.clear,
Some(field),
"{} does not point back at --clear {}",
section.heading,
field.name()
);
}
}
assert_eq!(RELATIONS.clear, None, "set must not be able to empty Relations");
}
/// The names are written out for the error messages, so this is what keeps them the
/// names clap actually accepts.
#[test]
fn the_clear_values_are_the_names_clap_accepts() {
for field in Clearable::ALL {
let possible = clap::ValueEnum::to_possible_value(&field).expect("not hidden");
assert_eq!(possible.get_name(), field.name());
}
}
/// The sentinel a cleared field goes back to is the one `add` writes for a field it
/// was never given, which is the whole promise of the flag.
#[test]
fn a_cleared_scalar_holds_the_sentinel_add_writes() {
for field in Clearable::ALL {
let Unset::Field { field: name, sentinel } = field.unset() else {
continue;
};
let expected = match name {
"Tags" => NONE,
_ => NOT_SET,
};
assert_eq!(sentinel, expected, "{name}");
assert!(is_unknown_value(sentinel), "{name} clears to something readable as set");
}
}
/// The placeholder goes in as a line of the format, not as an item: dressed by
/// `render` it would read `- [ ] _No acceptance criteria provided._`.
#[test]
fn clearing_a_section_writes_the_bare_placeholder() {
let content =
"# T\n\n## Acceptance Criteria\n- [x] Done\n- [ ] Not\n\n## Metadata\n\n- **ID**: x\n";
let cleared = clear_section_body(content, &ACCEPTANCE).unwrap();
assert!(
cleared.contains(&format!("## Acceptance Criteria\n{}\n", ACCEPTANCE.placeholder)),
"{cleared}"
);
// Everything outside the section is where it was.
assert!(cleared.contains("- **ID**: x"), "{cleared}");
// And a second clear is the same string, which is what makes the no-op free.
assert_eq!(clear_section_body(&cleared, &ACCEPTANCE).unwrap(), cleared);
}
#[test]
fn the_placeholder_is_no_relations_rather_than_a_bad_line() {
let content = format!(
"# T\n\n## Relations\n{}\n\n## Metadata\n\n- **ID**: x\n",
RELATIONS.placeholder
);
assert_eq!(parse_relations(&content, "T").unwrap(), Vec::new());
}
#[test]
fn a_ticket_with_no_relations_section_has_none() {
assert_eq!(
parse_relations("# T\n\n## Metadata\n\n- **ID**: x\n", "T").unwrap(),
Vec::new()
);
}
/// Between the plan and the metadata, and only once: a second call is a no-op
/// rather than a second heading.
#[test]
fn the_section_is_inserted_before_the_metadata() {
let content = "# T\n\n## Implementation Plan\n1. Step\n\n## Metadata\n\n- **ID**: x\n";
let inserted = ensure_section(content, &RELATIONS);
assert_eq!(
inserted,
"# T\n\n## Implementation Plan\n1. Step\n\n## Relations\n_No relations._\n\n## Metadata\n\n- **ID**: x\n"
);
assert_eq!(ensure_section(&inserted, &RELATIONS), inserted);
}
/// The anchor is the metadata, not the plan, so a section the tool knows nothing
/// about keeps its place instead of being pushed down.
#[test]
fn an_unknown_section_between_the_two_keeps_its_place() {
let content = "# T\n\n## Implementation Plan\n1. Step\n\n## Notes\nBy hand.\n\n## Metadata\n\n- **ID**: x\n";
let inserted = ensure_section(content, &RELATIONS);
assert!(
inserted.contains("## Notes\nBy hand.\n\n## Relations\n_No relations._\n\n## Metadata"),
"{inserted}"
);
}
/// Nothing to insert in front of, so it goes at the end rather than nowhere.
#[test]
fn the_section_lands_at_the_end_when_nothing_follows_it() {
assert_eq!(
ensure_section("# T\n\n## Description\nBody.\n", &RELATIONS),
"# T\n\n## Description\nBody.\n\n## Relations\n_No relations._\n"
);
}
/// Both directions in one block, the stored edges first, each padded to the widest
/// label. `relates to` is symmetric, so it reads the same from either end.
#[test]
fn the_block_renders_both_directions() {
let index = RelationIndex::new(vec![
related(TARGET, "The blocker", "backlog", Vec::new()),
related(
"cccccccc-1111-4222-8333-444444444444",
"The other one",
"reviewing",
vec![
relation(RelationKind::BlockedBy, SELF),
relation(RelationKind::RelatesTo, SELF),
],
),
]);
let stored = vec![relation(RelationKind::RegressionOf, TARGET)];
// Each row marked for its own kind: the way back for the regression, the cross
// for the block, the pointer for the neighbour.
assert_eq!(
render_relations(&relation_rows(&stored, &index, SELF), false),
format!(
"regression of {REGRESSION_MARK} {backlog} (b1b2c3d) The blocker\n\
blocks {BLOCKED_MARK} {reviewing} (ccccccc) The other one\n\
relates to {RELATES_MARK} {reviewing} (ccccccc) The other one\n",
backlog = smark("backlog"),
reviewing = smark("reviewing"),
)
);
}
/// The mapping itself, literally, so a change to a glyph or a colour is a decision
/// rather than a surprise. Every other assertion about a row interpolates these.
#[test]
fn the_status_marks_are_pinned() {
assert_eq!(status_mark(Some("backlog")), ("\u{25cb}", Color::Grey));
assert_eq!(status_mark(Some("committed")), ("\u{25d0}", Color::Orange));
assert_eq!(status_mark(Some("reviewing")), ("\u{25d0}", Color::Cyan));
assert_eq!(status_mark(Some("done")), ("\u{25cf}", Color::Green));
assert_eq!(status_mark(None), ("?", Color::Grey));
}
/// Every status the board holds is told apart from the other three. The shape does
/// not do it alone, since committed and reviewing are both half circles, so it is the
/// pair that has to be unique. Pinned against `status_dirs` rather than the four
/// names written out here, so a status added later fails this instead of silently
/// reading as `?`.
#[test]
fn every_status_has_a_mark() {
let mut seen = std::collections::HashSet::new();
for status in status_dirs() {
let (mark, colour) = status_mark(Some(status));
assert_ne!(mark, "?", "{status} has no mark of its own");
assert!(
seen.insert((mark, colour)),
"{status} is drawn exactly like another status"
);
}
assert_eq!(seen.len(), 4, "{seen:?}");
}
/// An unrecognised value reads as missing rather than as a fifth stage of the flow.
#[test]
fn a_status_the_board_does_not_use_reads_as_missing() {
assert_eq!(status_mark(Some("elsewhere")), ("?", Color::Grey));
assert_eq!(status_mark(Some("")), ("?", Color::Grey));
}
/// The circles are the priority meter's glyphs, and this is what keeps a status from
/// being read as a level: the meter is always two cells and a status mark is one.
/// A card carries the meter and never a status mark; the block carries the status
/// mark and never a meter.
#[test]
fn the_status_mark_is_one_cell_where_the_meter_is_two() {
for status in status_dirs() {
assert_eq!(
status_mark(Some(status)).0.chars().count(),
1,
"{status} is drawn wide enough to read as a priority meter"
);
}
for priority in [
Priority::Level(1),
Priority::Level(3),
Priority::Level(5),
Priority::Unset,
] {
assert_eq!(
priority_mark(priority).0.chars().count(),
2,
"{priority:?} is drawn narrow enough to read as a status mark"
);
}
}
/// The mark on each row is the status of the ticket that row names, not of the ticket
/// being read, so four relations in four statuses read four ways.
#[test]
fn the_block_marks_each_target_with_its_own_status() {
let rows: Vec<RelationRow> = status_dirs()
.into_iter()
.map(|status| row(RelationKind::RelatesTo, "relates to", TARGET, status, status))
.collect();
let rendered = render_relations(&rows, false);
for status in status_dirs() {
assert!(
rendered.contains(&format!("{} (b1b2c3d) {status}", smark(status))),
"no {status} row marked {:?}:\n{rendered}",
smark(status)
);
}
}
/// Every kind has a mark of its own, and no two share one: the mark is what makes the
/// block scannable without reading the labels, so two kinds drawn alike would defeat
/// it.
#[test]
fn every_relation_kind_has_a_mark_of_its_own() {
let kinds = [
RelationKind::BlockedBy,
RelationKind::RelatesTo,
RelationKind::RegressionOf,
];
let mut seen = std::collections::HashSet::new();
for kind in kinds {
let (mark, colour) = relation_mark(kind);
assert!(!mark.is_empty(), "{kind:?} has no mark");
assert!(seen.insert(mark), "{kind:?} shares its mark with another kind");
assert_ne!(colour, Color::Green, "{kind:?} is drawn in the colour that means a title");
}
assert_eq!(seen.len(), 3, "{seen:?}");
}
/// Both directions of one kind carry the same mark, since the kind is what the mark
/// says and the label is what says which way it points.
#[test]
fn both_directions_of_a_kind_carry_one_mark() {
let index = RelationIndex::new(vec![
related(TARGET, "The blocker", "backlog", Vec::new()),
related(
"cccccccc-1111-4222-8333-444444444444",
"The held one",
"backlog",
vec![relation(RelationKind::BlockedBy, SELF)],
),
]);
let stored = vec![relation(RelationKind::BlockedBy, TARGET)];
let rendered = render_relations(&relation_rows(&stored, &index, SELF), false);
let backlog = smark("backlog");
assert!(
rendered.contains(&format!("blocked by {BLOCKED_MARK} {backlog} (b1b2c3d)")),
"{rendered}"
);
assert!(
rendered.contains(&format!("blocks {BLOCKED_MARK} {backlog} (ccccccc)")),
"{rendered}"
);
}
/// The cards spend the circles on priority, two cells away from nothing at all, so a
/// relation drawn as one would be read as a level.
#[test]
fn no_relation_mark_is_a_priority_glyph() {
let levels = [1, 2, 3, 4, 5].map(|level| priority_mark(Priority::Level(level)).0);
let priority: String = levels
.iter()
.copied()
.chain([priority_mark(Priority::Unset).0])
.collect();
for kind in [
RelationKind::BlockedBy,
RelationKind::RelatesTo,
RelationKind::RegressionOf,
] {
let (mark, _) = relation_mark(kind);
assert!(
!priority.contains(mark),
"{kind:?} is drawn with {mark:?}, which the priority meter uses"
);
}
}
/// The id is kept, since it is the only thing left to go looking for, and the title
/// is `_missing_` rather than a bare uuid pretending to be one.
#[test]
fn a_target_the_board_does_not_have_renders_as_missing() {
let stored = vec![relation(RelationKind::BlockedBy, TARGET)];
// The kind mark survives, since it is read from this ticket's own file, and the
// status mark cannot: `?` holds the column so the id does not move, and
// `_missing_` is what says the target is gone.
assert_eq!(
render_relations(&relation_rows(&stored, &RelationIndex::new(Vec::new()), SELF), false),
format!("blocked by {BLOCKED_MARK} ? (b1b2c3d) _missing_\n")
);
}
#[test]
fn a_ticket_with_no_relations_at_either_end_renders_no_block() {
let index = RelationIndex::new(vec![related(TARGET, "Elsewhere", "backlog", Vec::new())]);
assert_eq!(render_relations(&relation_rows(&[], &index, SELF), false), "");
}
/// Without the guard every ticket with no ID field relates to every other one that
/// has none either, since `_Not set_` matches `_Not set_`.
#[test]
fn a_ticket_with_no_id_derives_no_inverse() {
let index = RelationIndex::new(vec![related(
TARGET,
"The holder",
"backlog",
vec![relation(RelationKind::BlockedBy, "_Not set_")],
)]);
assert!(index.inbound("_Not set_").is_empty());
assert!(index.inbound("").is_empty());
}
/// The stored lines carry a bare uuid, so the block replaces the body rather than
/// being printed beside it.
#[test]
fn the_body_shows_the_block_in_place_of_the_stored_lines() {
let content = format!(
"# T\n\n## Relations\n- blocked by {}\n\n## Metadata\n\n- **ID**: {}\n",
TARGET, SELF
);
let rendered = content_trim(
&content,
false,
&Resolved {
relations: vec![row(
RelationKind::BlockedBy,
"blocked by",
TARGET,
"The blocker",
"backlog",
)],
..Default::default()
},
);
assert!(
rendered.contains(&format!("Relations\n─────────\n\nblocked by {BLOCKED_MARK} {} (b1b2c3d) The blocker\n\nMetadata", smark("backlog"))),
"{rendered:?}"
);
assert!(!rendered.contains(TARGET), "the bare uuid was printed: {rendered:?}");
}
/// Only one side of a relation is stored, so the ticket at the other end has no
/// section at all and still has something to show. It goes where the file would
/// have kept it, ahead of the metadata.
#[test]
fn the_body_injects_the_block_when_the_file_has_no_section() {
let content =
format!("# T\n\n## Description\nBody.\n\n## Metadata\n\n- **ID**: {}\n", SELF);
let rendered = content_trim(
&content,
false,
&Resolved {
relations: vec![row(
RelationKind::BlockedBy,
"blocks",
SELF,
"The gated one",
"committed",
)],
..Default::default()
},
);
assert!(
rendered.contains(&format!("Body.\n\nRelations\n─────────\n\nblocks {BLOCKED_MARK} {} (641e3d5) The gated one\n\nMetadata", smark("committed"))),
"{rendered:?}"
);
}
/// A file with no metadata heading has nothing to inject ahead of, and the block is
/// worth more at the end than dropped.
#[test]
fn the_body_appends_the_block_when_there_is_no_metadata() {
let rendered = content_trim(
"# T\n\n## Description\nBody.\n",
false,
&Resolved {
relations: vec![row(RelationKind::BlockedBy, "blocks", SELF, "X", "done")],
..Default::default()
},
);
assert!(
rendered.ends_with(&format!(
"Relations\n─────────\n\nblocks {BLOCKED_MARK} {} (641e3d5) X\n",
smark("done")
)),
"{rendered:?}"
);
}
/// No block and a section holding only its placeholder: the section renders as it
/// is written, the way every other empty section does.
#[test]
fn an_empty_block_leaves_the_section_as_written() {
let content = "# T\n\n## Relations\n_No relations._\n\n## Metadata\n\n- **ID**: x\n";
let rendered = content_trim(content, false, &Resolved::default());
assert!(
rendered.contains("Relations\n─────────\n\n_No relations._\n"),
"{rendered:?}"
);
}
// ----------------------------------------------------- finding the board --
/// A project directory under a temp root.
///
/// The root is canonicalized because `find_worklane_dir` canonicalizes its
/// start: on a system whose temp path runs through a link, the two spellings
/// of the same directory would not compare equal.
fn project_in(root: &tempfile::TempDir) -> std::path::PathBuf {
let dir = root.path().canonicalize().unwrap().join("project");
fs::create_dir_all(&dir).unwrap();
dir
}
/// The failure names the target, since the link is not the thing to fix, and it
/// does not say to run `init`: that answer belongs to an empty tree, and giving
/// it here points at the wrong problem.
#[test]
fn a_dangling_board_link_is_reported_with_its_target() {
let root = tempfile::tempdir().unwrap();
let project = project_in(&root);
let target = project.parent().unwrap().join("boards/2fed877-the-board");
std::os::unix::fs::symlink(&target, project.join(".worklane")).unwrap();
let error = find_worklane_dir(&project).unwrap_err().to_string();
assert!(error.contains(&target.display().to_string()), "{error}");
assert!(error.contains("boards repo"), "{error}");
assert!(!error.contains("worklane init"), "{error}");
}
/// The bug this was written for: `exists()` follows the link, so a dangling one
/// answered false, the walk carried on up the tree, and the board above the
/// project became the board every write landed in.
#[test]
fn a_dangling_board_link_does_not_reach_the_board_above_it() {
let root = tempfile::tempdir().unwrap();
let project = project_in(&root);
let above = project.parent().unwrap().join(".worklane");
fs::create_dir_all(&above).unwrap();
let link = project.join(".worklane");
std::os::unix::fs::symlink(project.parent().unwrap().join("gone"), &link).unwrap();
let error = find_worklane_dir(&project).unwrap_err().to_string();
assert!(error.contains(&link.display().to_string()), "{error}");
// And the walk really would have reached it, so the assertion above is
// about where the walk stopped rather than about an empty tree.
assert_eq!(find_worklane_dir(project.parent().unwrap()).unwrap(), above);
}
/// Nothing at that path is still the one answer the walk carries on from.
#[test]
fn no_worklane_at_all_lets_the_walk_carry_on_upward() {
let root = tempfile::tempdir().unwrap();
let project = project_in(&root);
let above = project.parent().unwrap().join(".worklane");
fs::create_dir_all(&above).unwrap();
assert_eq!(find_worklane_dir(&project).unwrap(), above);
}
/// A link that resolves is the board, and what comes back is the link rather
/// than its target: `.worklane/backlog` has to read the same either way.
#[test]
fn a_link_to_a_board_resolves_the_way_a_directory_does() {
let root = tempfile::tempdir().unwrap();
let project = project_in(&root);
let board = project.parent().unwrap().join("boards/2fed877-the-board");
fs::create_dir_all(&board).unwrap();
let link = project.join(".worklane");
std::os::unix::fs::symlink(&board, &link).unwrap();
assert_eq!(find_worklane_dir(&project).unwrap(), link);
}
/// A regular file is reported rather than stepped over, and a board above it
/// does not make it the walk's problem to solve.
#[test]
fn a_regular_file_where_the_board_goes_is_an_error() {
let root = tempfile::tempdir().unwrap();
let project = project_in(&root);
fs::write(project.join(".worklane"), "board = \"2fed877\"\n").unwrap();
fs::create_dir_all(project.parent().unwrap().join(".worklane")).unwrap();
let error = find_worklane_dir(&project).unwrap_err().to_string();
assert!(error.contains("not a directory"), "{error}");
}
/// A link that resolves to a file, which the follow catches and the entry check
/// on its own cannot: the entry is a symlink and the target is not a directory.
#[test]
fn a_link_to_a_file_is_not_a_board_either() {
let root = tempfile::tempdir().unwrap();
let project = project_in(&root);
let file = project.parent().unwrap().join("pointer.toml");
fs::write(&file, "board = \"2fed877\"\n").unwrap();
std::os::unix::fs::symlink(&file, project.join(".worklane")).unwrap();
let error = find_worklane_dir(&project).unwrap_err().to_string();
assert!(error.contains("not a directory"), "{error}");
}
}