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