Files
worklane/src/util.rs
T
Ansho ReiandClaude Opus 5 5b0bac9c2d (7bfb9fc) Add campaigns, a ticket container assigned through worklane assign, and bump to 0.12.0
There was no way to group the tickets that have to be finished together. A
goal such as a v1 release was either one ticket that could not describe its
parts, or a set of tickets with the goal restated in every description and
nothing tying them together.

A campaign is a file of its own under `.worklane/campaigns/`, with a title, a
description and metadata, and it sits in no status directory. Its state is
derived instead: open until every member is done. Deriving it means there is
no such thing as a done campaign holding an open ticket, and no second
forward-only ruleset beside `mv`'s. An empty campaign is neither open nor
done, since calling it done would make a container nothing has been filed
against the most complete thing on the board.

Membership is one field on the *member*, Campaign in the ticket Metadata,
written only by `assign`. The member list is deliberately not on the campaign:
that would put membership in two places and make one file that every
assignment edits, contended the moment two agents share a board. So `add`
gains no `--campaign` and neither does `set`.

`add` does not write the field either. Every ticket written before campaigns
existed has none, so the insertion path has to exist regardless, and leaving
it out of `add` means one path that is always exercised rather than two. That
is the Relations argument from 4179958, applied to a field instead of a
section. `set_or_insert_metadata_field` is the upsert and `METADATA_ORDER` is
its anchor list, the way `SECTION_ORDER` is `ensure_section`'s, so Campaign
lands beside Status rather than at the end and Status stays last. A file with
no Metadata heading is an error rather than an insertion, per 641e3d5.

The three tiers came out of `resolve_ticket` into `resolve_in`, shared by both
kinds. 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. Two
things fell out of that. `Found.dir` is the status for a ticket and empty for
a campaign, which is what drops the bracket from the ambiguity listing for
one. And `resolve_ticket` can now explain a search that names a campaign, so
`mv`, `show`, `chown` and everything else that takes a ticket give the same
reason instead of a bare "no ticket found" — one place rather than a check per
command. Only on the zero-match path, so an ambiguous ticket error is never
replaced by a complaint about a directory the caller never mentioned.

The stored value is the full uuid, per the same rule the Relations section
follows, and the title is resolved for display. `reference_cell` is now shared
between the two, so a dangling campaign and a dangling relation target are
both `_missing_` rather than each inventing a spelling. `Resolved` carries
what `content_trim` cannot render from the file alone: a struct rather than
two more parameters, so the next such field is one entry instead of an edit at
every call site.

`campaign show` lists done members, unlike `ls`, which leaves the done column
out of its listing. What is finished against what is left is the whole
question a campaign asks. `ls --campaign` is the other way round and keeps
every rule `ls` already has.

Deliberately out of scope. The derived progress figure is 1cb999f, now
recorded as blocked by this, since nothing here can compute it yet.
Unassigning needs a field cleared back to unset, which is 74904dc. And the
board gets neither a campaign tab nor a card marker: the detail view resolves
the field because it renders the body, and that is all. A marker would want a
read per reload and the four corners are already spent, which is the b8ce18c
reasoning; filed as 61879a4.

Twenty-four integration tests and eleven unit tests, covering assign,
reassign, the no-op, a dangling campaign, the ls filter, `mv` refusing a
campaign, insertion placement, and a handwritten section and unknown metadata
field surviving an assignment verbatim.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-22 00:52:57 +02:00

3047 lines
113 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";
/// 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,
}
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",
}
}
/// Every colour in the palette, so a test can walk them without listing them.
pub const ALL: [Color; 7] = [
Color::Red,
Color::Cyan,
Color::Orange,
Color::Green,
Color::Grey,
Color::Magenta,
Color::BrightRed,
];
}
/// 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,
}
}
}
/// `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())
}
pub fn find_worklane_dir(start: &Path) -> Result<std::path::PathBuf> {
let mut current = start.canonicalize()?;
loop {
let worklane_dir = current.join(".worklane");
if worklane_dir.exists() {
return Ok(worklane_dir);
}
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 three-tier search, run over `dirs`, returning the first tier that matched
/// anything.
///
/// Three 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.
///
/// 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_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("");
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 !(by_prefix || in_title || in_filename) {
continue;
}
let found = Found {
dir: name.clone(),
title,
content,
uuid: uuid.to_string(),
};
if by_prefix {
by_id.push(found);
} else if in_title {
by_title.push(found);
} else {
by_filename.push(found);
}
}
}
Ok(match (by_id.is_empty(), by_title.is_empty()) {
(false, _) => by_id,
(true, false) => by_title,
(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 block [`render_relations`] built, or empty for a ticket with no relations.
pub relations: String,
/// 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 String, 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.
pub fn content_trim(content: &str, colored: bool, resolved: &Resolved) -> String {
let relations = resolved.relations.as_str();
let lines: Vec<&str> = content.trim().lines().collect();
let mut result = String::new();
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_str(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_str(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_str(relations);
}
result
}
/// 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);
}
value.to_string()
}
/// 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
}
pub fn is_unknown_value(value: &str) -> bool {
let trimmed = value.trim();
trimmed == "_None_" || trimmed == "_Not set_" || 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 }
}
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 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 metadata fields in the order `add` writes them, with `Campaign` in its place
/// 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.
const METADATA_ORDER: [&str; 8] = [
"ID",
"Priority",
"Tags",
"Due",
"Owner",
"Created At",
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))
}
/// 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,
}
pub const DESCRIPTION: Section = Section {
heading: "## Description",
label: "description",
placeholder: "_No description provided._",
kind: SectionKind::Prose,
};
pub const ACCEPTANCE: Section = Section {
heading: "## Acceptance Criteria",
label: "acceptance criteria",
placeholder: "_No acceptance criteria provided._",
kind: SectionKind::Checklist,
};
pub const PLAN: Section = Section {
heading: "## Implementation Plan",
label: "implementation plan",
placeholder: "_No implementation plan provided._",
kind: SectionKind::Numbered,
};
/// 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,
};
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(),
}
}
}
/// 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))
}
/// 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> {
let lines: Vec<&str> = content.lines().collect();
let body = section_body(&lines, section.heading)
.ok_or_else(|| anyhow!("Ticket has no {} section", section.label))?;
let mut out: Vec<String> = lines[..body.start].iter().map(|l| l.to_string()).collect();
out.extend(section.render(items, 1));
// 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!("Ticket has no {} section", 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 {
let id = paint(short_id(uuid), Color::Red, colored);
match name {
Some(name) => format!("({}) {}", id, name),
None => format!("({}) {}", id, paint("_missing_", Color::Grey, colored)),
}
}
/// A relation's target as it reads.
fn target_cell(target: Option<&RelatedTicket>, uuid: &str, colored: bool) -> String {
reference_cell(uuid, target.map(|ticket| ticket.title.as_str()), colored)
}
/// The Relations section as it is shown, or empty when there is nothing to show.
///
/// Both directions, stored first: the relations the ticket holds, then the ones held
/// against it, named from this end. Rendered from the index rather than from the body
/// alone, because a bare uuid says nothing and half the relations are not in the file.
pub fn render_relations(
stored: &[Relation],
index: &RelationIndex,
uuid: &str,
colored: bool,
) -> String {
let mut rows: Vec<(&'static str, String)> = stored
.iter()
.map(|relation| {
(
relation.kind.label(),
target_cell(index.get(&relation.target), &relation.target, colored),
)
})
.collect();
rows.extend(index.inbound(uuid).into_iter().map(|(kind, holder)| {
(
kind.inverse_label(),
target_cell(Some(holder), &holder.uuid, colored),
)
}));
if rows.is_empty() {
return String::new();
}
// Measured on the labels, which carry no colour, and padded before the target cell
// is joined on, for the reason the metadata table is: an escape sequence counted
// towards a width tilts the column the moment colour is on.
let width = rows
.iter()
.map(|(label, _)| label.chars().count())
.max()
.unwrap_or(0);
let mut out = String::new();
for (label, cell) in &rows {
out.push_str(label);
out.push_str(&" ".repeat(width - label.chars().count()));
out.push_str(COLUMN_GUTTER);
out.push_str(cell);
out.push('\n');
}
out
}
/// The rendered Relations block for one ticket, reading the board for the rest of it.
///
/// The colour decision is passed in rather than asked for, like everything else the
/// body renders: the board draws the same text with colour off.
pub fn relations_block(content: &str, worklane_dir: &Path, colored: bool) -> Result<String> {
let title = heading_title(content);
let stored = parse_relations(content, &title)?;
let index = RelationIndex::load(worklane_dir)?;
Ok(render_relations(
&stored,
&index,
&parse_ticket_field(content, "ID"),
colored,
))
}
/// 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()
}
/// 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 criterion on `line`, 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.
pub fn set_criterion(content: &str, line: 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 (index == line, 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]
}
}
}
pub fn status_dirs() -> Vec<&'static str> {
vec!["backlog", "committed", "reviewing", DONE]
}
/// 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 = "done";
/// 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 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 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
);
}
}
}
pub fn collect_ticket_items(status_path: impl AsRef<Path>) -> Result<Vec<TicketItem>> {
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");
// 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,
}),
};
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),
path: e.path(),
})
})
.collect();
items.sort_by(by_priority_then_title);
Ok(items)
}
/// The order a status column is read in: priority first, title as the tiebreak.
///
/// Named and exported because the board's All tab merges several boards' columns into
/// one and has to land in the order the listing uses. A merge sorted a second way
/// would put a p1 below a p5 depending on which project it came from.
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()))
}
#[cfg(test)]
mod tests {
use super::*;
#[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);
}
}
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 = std::env::temp_dir().join(format!("worklane-count-{}", uuid::Uuid::new_v4()));
fs::create_dir_all(&dir).unwrap();
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:?}");
fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn collect_ticket_items_lists_only_md_files() {
let dir = std::env::temp_dir().join(format!("worklane-stray-{}", uuid::Uuid::new_v4()));
fs::create_dir_all(&dir).unwrap();
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:?}");
fs::remove_dir_all(&dir).unwrap();
}
/// 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}");
}
#[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());
}
/// 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 --
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"));
}
#[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)];
assert_eq!(
render_relations(&stored, &index, SELF, false),
"regression of (b1b2c3d) The blocker\n\
blocks (ccccccc) The other one\n\
relates to (ccccccc) The other one\n"
);
}
/// 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)];
assert_eq!(
render_relations(&stored, &RelationIndex::new(Vec::new()), SELF, false),
"blocked by (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(&[], &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: "blocked by (b1b2c3d) The blocker\n".to_string(), ..Default::default() });
assert!(
rendered.contains("Relations\n─────────\n\nblocked by (b1b2c3d) The blocker\n\nMetadata"),
"{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: "blocks (641e3d5) The gated one\n".to_string(), ..Default::default() });
assert!(
rendered.contains("Body.\n\nRelations\n─────────\n\nblocks (641e3d5) The gated one\n\nMetadata"),
"{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: "blocks (641e3d5) X\n".to_string(), ..Default::default() });
assert!(rendered.ends_with("Relations\n─────────\n\nblocks (641e3d5) X\n"), "{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:?}");
}
}