parse_ticket_field searched every line of the file with contains, and set_status_field rewrote the first line starting with the Status marker wherever it sat. Tickets in this repo quote field markers in their descriptions, so a description list shaped like metadata was read in place of the real value and rewritten by mv, leaving the metadata stale. Both now scan only the lines under the Metadata heading and match on a line prefix rather than a substring. A file with no Metadata heading has no fields, so mv reports the missing Status field instead of editing prose. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
1068 lines
36 KiB
Rust
1068 lines
36 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",
|
|
_ => "",
|
|
}
|
|
}
|
|
|
|
pub fn color_text(text: &str, color: &str) -> String {
|
|
if should_use_colors() {
|
|
format!("{}{}{}", get_color(color), text, "\x1b[0m")
|
|
} else {
|
|
text.to_string()
|
|
}
|
|
}
|
|
|
|
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 mut result = String::new();
|
|
let mut current_section = "";
|
|
|
|
for line in &lines {
|
|
// Track current section
|
|
if line.starts_with("## ") {
|
|
current_section = line;
|
|
let section_name = &line[3..];
|
|
result.push_str(&color_text(section_name, "orange"));
|
|
result.push('\n');
|
|
result.push_str(&"─".repeat(line.len()));
|
|
result.push('\n');
|
|
result.push('\n');
|
|
continue;
|
|
}
|
|
|
|
// First line is the title header - color it in green
|
|
if line.starts_with("# ") && current_section.is_empty() {
|
|
let header = &line[2..]; // Remove "# "
|
|
result.push_str(&color_text(header, "green"));
|
|
result.push('\n');
|
|
continue;
|
|
}
|
|
|
|
// Implementation Plan - color numbers in cyan
|
|
if current_section == "## Implementation Plan" {
|
|
result.push_str(&colorize_ordered(line));
|
|
result.push('\n');
|
|
continue;
|
|
}
|
|
|
|
// Metadata - color field names in RED
|
|
if current_section == "## Metadata" {
|
|
result.push_str(&colorize_metadata(line));
|
|
result.push('\n');
|
|
continue;
|
|
}
|
|
|
|
// Acceptance Criteria checkboxes
|
|
if line.starts_with("- [ ]") {
|
|
result.push_str(&color_text("- [ ]", "grey"));
|
|
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()
|
|
}
|
|
|
|
pub fn colorize_metadata(line: &str) -> String {
|
|
if !line.contains("**") {
|
|
return line.to_string();
|
|
}
|
|
|
|
// Priority reads as a glyph here too, while the file keeps storing the number.
|
|
if let Some(value) = line.split("**Priority**:").nth(1) {
|
|
let priority = match value.trim().parse::<u8>() {
|
|
Ok(level) if PRIORITY_RANGE.contains(&level) => Priority::Level(level),
|
|
_ if is_unknown_value(value.trim()) => Priority::Unset,
|
|
_ => Priority::Invalid,
|
|
};
|
|
return format!(
|
|
"- {}: {} {}",
|
|
color_text("Priority", "red"),
|
|
show_priority(priority),
|
|
value.trim()
|
|
);
|
|
}
|
|
|
|
let content = line;
|
|
let open_pos = match content.find("**") {
|
|
Some(p) => p,
|
|
None => return content.to_string(),
|
|
};
|
|
|
|
let after_open = open_pos + 2;
|
|
let remaining = &content[after_open..];
|
|
let close_pos = match remaining.find("**") {
|
|
Some(p) => p,
|
|
None => return content.to_string(),
|
|
};
|
|
|
|
let field_name = &content[after_open..after_open + close_pos];
|
|
let after_field = &content[after_open + close_pos + 2..];
|
|
|
|
let colored_field = color_text(field_name, "red");
|
|
let value_text = after_field.strip_prefix(": ").map(|s| s.trim()).unwrap_or(after_field);
|
|
let after_field_colored = if is_unknown_value(value_text) {
|
|
color_text(after_field, "grey")
|
|
} else {
|
|
after_field.to_string()
|
|
};
|
|
|
|
format!(
|
|
"{}{}{}",
|
|
&content[..open_pos],
|
|
colored_field,
|
|
after_field_colored
|
|
)
|
|
}
|
|
|
|
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,
|
|
}
|
|
}
|
|
}
|
|
|
|
pub fn parse_priority(content: &str) -> Priority {
|
|
let raw = parse_ticket_field(content, "Priority");
|
|
|
|
if is_unknown_value(&raw) {
|
|
return Priority::Unset;
|
|
}
|
|
|
|
match raw.trim().parse::<u8>() {
|
|
Ok(level) if PRIORITY_RANGE.contains(&level) => Priority::Level(level),
|
|
_ => Priority::Invalid,
|
|
}
|
|
}
|
|
|
|
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 through `colorize_metadata`, so the listing was the
|
|
/// one place that ignored the rule.
|
|
fn dim_if_unset(value: &str) -> String {
|
|
if is_unknown_value(value) {
|
|
color_text(value, "grey")
|
|
} 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) -> String {
|
|
let (glyph, colour) = priority_mark(priority);
|
|
color_text(glyph, colour)
|
|
}
|
|
|
|
pub fn display_ticket_items(items: &[TicketItem]) {
|
|
for item in items {
|
|
let id = color_text(&item.id, "red");
|
|
let owner = dim_if_unset(&item.owner);
|
|
let due = dim_if_unset(&item.due);
|
|
let priority = show_priority(item.priority);
|
|
|
|
if item.created.is_empty() {
|
|
println!(
|
|
" {} ({}) {} | Owner: {} | Due: {}",
|
|
priority, id, item.title, owner, due
|
|
);
|
|
} else {
|
|
let created = color_text(&item.created, "cyan");
|
|
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() {
|
|
// Colour is off in a test process, so this asserts the decision, not the escape
|
|
for unset in ["_Not set_", "_None_"] {
|
|
assert!(is_unknown_value(unset), "{unset} should count as unset");
|
|
assert_eq!(dim_if_unset(unset), unset);
|
|
}
|
|
|
|
for set in ["alice", "2026-12-31", "bug,frontend"] {
|
|
assert!(!is_unknown_value(set));
|
|
assert_eq!(dim_if_unset(set), 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());
|
|
}
|
|
|
|
#[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:?}");
|
|
}
|
|
}
|
|
}
|