Files
worklane/src/util.rs
T
Ansho ReiandClaude Opus 5 f557437f62 (277a527) Render the metadata section as an aligned table, and bump to 0.3.0
show printed the Metadata block as the markdown list the file stores, so with
seven fields the values did not line up and the block read as file contents
rather than as a summary. It now renders as two aligned columns: field names
left, values right. The file is untouched, this is display only.

content_trim_colored streamed one line at a time, so nothing ever saw the whole
section. The Metadata lines are now taken as a block, since the field column
cannot be sized until every name has been seen.

Column width is measured on the raw names, in characters, and padding is applied
before anything is styled. Measuring a coloured name counts its escape sequences
towards its width, which tilts the table with colour on and not with it off.
paint() is color_text() with the decision passed in, which is what lets a test
render both ways in one process and compare.

colorize_metadata is folded into the renderer, its only caller. A line in the
section that is not a field is carried through rather than dropped, so a hand
written note survives, and an unrecognised field still gets a row.

Plain columns, no border characters: nothing to degrade on a font that lacks
them, and the section rules already carry the only box drawing here.

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

1316 lines
45 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(),
)
})
}
pub fn get_color(color: &str) -> &'static str {
match color {
"red" => "\x1b[31m",
"cyan" => "\x1b[36m",
"orange" => "\x1b[33m",
"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.
"grey" => "\x1b[38;5;8m",
// Bold, per the guideline in AGENTS.md. Its absence meant colorize_line
// asked for a colour that did not exist and got an empty prefix.
"magenta" => "\x1b[1;35m",
// Indexed, for the same reason grey is: this is the spelling that renders.
"brightred" => "\x1b[38;5;9m",
_ => "",
}
}
/// `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: &str, enabled: bool) -> String {
if enabled {
format!("{}{}{}", get_color(color), text, "\x1b[0m")
} else {
text.to_string()
}
}
pub fn color_text(text: &str, color: &str) -> 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
}
})
}
/// 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.
fn ambiguous(search: &str, matches: &[(String, String, String, String)]) -> anyhow::Error {
let mut message = format!("Multiple tickets found matching '{}':\n", search);
for (i, (status, title, _, id)) in matches.iter().enumerate() {
message.push_str(&format!(
" {}. ({}) {} [{}]\n",
i + 1,
color_text(short_id(id), "red"),
title,
color_text(status, "orange"),
));
}
message.push_str("\nUse the displayed ID or a more specific search term to select.");
anyhow!(message)
}
pub fn resolve_ticket(search: &str, worklane_dir: &Path) -> Result<(String, String, String)> {
let statuses = status_dirs();
let mut matches: Vec<(String, String, String, String)> = Vec::new();
for status in &statuses {
let status_path = worklane_dir.join(status);
if !status_path.exists() {
continue;
}
let entries = fs::read_dir(&status_path)?;
for entry in entries.filter_map(|e| e.ok()) {
let path = entry.path();
if !path.extension().map_or(false, |e| e == "md") {
continue;
}
let content = match fs::read_to_string(&path) {
Ok(c) => c,
Err(_) => continue,
};
let title = content
.lines()
.find(|l| l.starts_with("# "))
.map(|l| l[2..].trim())
.unwrap_or("")
.to_string();
let filename = path
.file_stem()
.map(|s| s.to_string_lossy().to_string())
.unwrap_or_default();
let short_id = filename.split('_').next().unwrap_or("");
let search_lower = search.to_lowercase();
let title_lower = title.to_lowercase();
let filename_lower = filename.to_lowercase();
let id_match =
short_id.to_lowercase().starts_with(&search_lower) && short_id.len() >= 8;
let title_match = title_lower.contains(&search_lower);
let filename_match = filename_lower.contains(&search_lower);
if id_match || title_match || filename_match {
matches.push((status.to_string(), title, content, short_id.to_string()));
}
}
}
if matches.is_empty() {
return Err(anyhow!("No ticket found matching '{}'", search));
}
if matches.len() > 1 {
return Err(ambiguous(search, &matches));
}
let (status, title, content, _short_id) = matches.remove(0);
Ok((status, title, content))
}
pub fn format_comments(comments: &[(String, String, String, String)]) -> String {
if comments.is_empty() {
return color_text("No comments yet.", "grey");
}
let mut result = String::new();
result.push_str("\n");
result.push_str(&color_text("COMMENTS", "orange"));
result.push_str(&format!("\n{}\n", "─".repeat(20)));
for (_filename, author, time, body) in comments {
result.push_str("\n");
result.push_str(&color_text(&format!("From {} ({})", author, time), "cyan"));
result.push_str("\n");
if !body.is_empty() {
result.push_str(&" ".to_string());
result.push_str(body);
}
result.push('\n');
}
result
}
pub fn content_trim_colored(content: &str) -> String {
let lines: Vec<&str> = content.trim().lines().collect();
let colored = should_use_colors();
let mut result = String::new();
let mut current_section = "";
let mut i = 0;
while i < lines.len() {
let line = lines[i];
// Track current section
if let Some(section_name) = line.strip_prefix("## ") {
current_section = line;
result.push_str(&paint(section_name, "orange", colored));
result.push('\n');
// Measured on the name as displayed, in characters. The rule used to span
// the raw line, so it ran three past the heading for the "## ", and byte
// length over-drew for anything non-ASCII.
result.push_str(&"─".repeat(section_name.chars().count()));
result.push('\n');
result.push('\n');
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 = lines[i..]
.iter()
.position(|l| l.starts_with("## "))
.map_or(lines.len(), |offset| i + offset);
result.push_str(&render_metadata_table(&lines[i..end], colored));
i = end;
}
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));
result.push('\n');
continue;
}
// Acceptance Criteria checkboxes
if line.starts_with("- [ ]") {
result.push_str(&paint("- [ ]", "grey", colored));
result.push_str(&line[5..]);
result.push('\n');
continue;
}
// Standard markdown link colorization in cyan
if line.contains("[") && line.contains("(") && line.contains("]") {
if 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(&color_text(&line[start..absolute_end], "cyan"));
result.push('\n');
continue;
}
}
}
}
// Regular content - colorize **bold** in magenta
result.push_str(&colorize_line(line));
result.push('\n');
}
result
}
pub fn colorize_ordered(line: &str) -> String {
if line.chars().next().map_or(true, |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(&color_text(number, "cyan"));
result.push_str(&line[i + 1..]);
return result;
} else {
break;
}
}
line.to_string()
}
/// Space between the field column and the value column.
const METADATA_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.
fn metadata_value_cell(name: &str, value: &str, colored: bool) -> 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, "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) -> 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, "red", colored));
result.push_str(&" ".repeat(field_width - name.chars().count()));
result.push_str(METADATA_GUTTER);
result.push_str(&metadata_value_cell(name, value, colored));
}
MetadataRow::Other(text) => result.push_str(&colorize_line(text)),
}
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-"
}
pub fn colorize_line(line: &str) -> String {
colorize_bold(line, should_use_colors())
}
/// 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();
result.push_str(&color_text(&bold, "magenta"));
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(&'*')
}
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 the Status 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 the Status field would otherwise be rewritten in its place, corrupting
// the prose and leaving the real metadata stale.
pub fn set_status_field(content: &str, target_status: &str, title: &str) -> Result<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 && is_status_line(line) {
updated.push_str("- **Status**: ");
updated.push_str(target_status);
found = true;
} else {
updated.push_str(line);
}
updated.push('\n');
}
if !found {
return Err(anyhow!(
"Ticket '{}' has no Status field in its Metadata section",
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(),
}
}
pub fn status_dirs() -> Vec<&'static str> {
vec!["backlog", "committed", "reviewing", "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"))
}
pub struct TicketItem {
pub title: String,
pub owner: String,
pub due: String,
pub id: String,
pub created: String,
pub priority: Priority,
}
/// 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, "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, &'static str) {
match priority {
Priority::Level(1) => ("\u{25cf}\u{25cf}", "brightred"),
Priority::Level(2) => ("\u{25cf}\u{25d0}", "red"),
Priority::Level(3) => ("\u{25cf}\u{25cb}", "orange"),
Priority::Level(4) => ("\u{25d0}\u{25cb}", "cyan"),
Priority::Level(5) => ("\u{25cb}\u{25cb}", "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 => ("??", "brightred"),
Priority::Unset => ("\u{b7}\u{b7}", "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, "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, "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()).collect();
let mut items: Vec<TicketItem> = entries
.iter()
.filter_map(|e| {
let content = fs::read_to_string(e.path()).ok()?;
let title = content
.lines()
.find(|l| l.starts_with("# "))
.map(|l| l[2..].trim().to_string())
.unwrap_or_else(|| "_No title_".to_string());
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");
Some(TicketItem {
title,
owner,
due,
id: short_id(&filename).to_string(),
created: format_created_at(&created_at),
priority: parse_priority(&content),
})
})
.collect();
// Priority first, title as the tiebreak, which is what the sort used to be.
items.sort_by(|a, b| {
a.priority
.rank()
.cmp(&b.priority.rank())
.then_with(|| a.title.to_lowercase().cmp(&b.title.to_lowercase()))
});
Ok(items)
}
#[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, "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"));
}
#[test]
fn a_section_rule_matches_the_width_of_its_name() {
let rendered = content_trim_colored("# T\n\n## Description\nbody\n");
// 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");
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");
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);
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);
assert!(rendered.contains("ID abc"), "{rendered:?}");
assert!(rendered.contains("Notes\n─────\n"), "{rendered:?}");
assert!(rendered.ends_with("after\n"), "{rendered:?}");
}
#[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, "green");
}
}
#[test]
fn every_colour_the_code_asks_for_exists() {
for colour in ["red", "cyan", "orange", "green", "grey", "magenta", "brightred"] {
assert!(!get_color(colour).is_empty(), "{colour} is not defined");
}
}
/// 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!(get_color("grey"), "\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:?}");
}
}
}