From f515d699308383dc50867e6673aab483eb6794f5 Mon Sep 17 00:00:00 2001 From: Ansho Rei Date: Sun, 23 Aug 2026 15:47:05 +0200 Subject: [PATCH] (1db02e5) Give the board a tags file, and bump to 0.25.0 The board carried twenty-four tags and defined none of them. `campaign` and `campaigns` were both on it, one ticket each side, and nothing on disk could have caught that. `.worklane/tags.md` is the vocabulary: one level-two heading per tag, its annotation as the prose under it, alphabetical by byte so a near-duplicate lands next to what it duplicates. `worklane tags add --annotation` writes it, `init` creates it empty, and `tags add` creates it on demand for a board that predates it. Declaring a tag tags no ticket, and tagging a ticket declares nothing. The counts stay derived from the status directories, so the file and the board can disagree; reporting that disagreement is 9564ac9. `tags` becomes a group with an optional subcommand. The bare form is still the listing, byte for byte, because the shipped fish completion calls it that way to fill in `ls --tag`; `tags ls` is the same arm. Every write re-renders the whole file from the parsed vocabulary rather than splicing one section, which is why an unreadable file is an error in `TagIndex::load` where an unreadable campaigns directory is an empty index: empty here would mean erased. `no_tag_taking_option_is_missing` used to panic on any tag positional. It now allows what `TAG_NEW_COMMANDS` records, which is `tags add` alone: the tag it takes does not exist yet, so completing it from `worklane tags` would offer exactly the values it refuses. Co-Authored-By: Claude Opus 5 (1M context) --- Cargo.lock | 2 +- Cargo.toml | 2 +- src/command.rs | 95 +++++++++++++- src/completions.rs | 34 ++++- src/handlers.rs | 59 ++++++++- src/main.rs | 15 ++- src/tag.rs | 312 +++++++++++++++++++++++++++++++++++++++++++++ tests/cmd_tags.rs | 236 ++++++++++++++++++++++++++++++++++ 8 files changed, 739 insertions(+), 16 deletions(-) create mode 100644 src/tag.rs diff --git a/Cargo.lock b/Cargo.lock index 16175b3..a13eca7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1503,7 +1503,7 @@ dependencies = [ [[package]] name = "worklane" -version = "0.24.2" +version = "0.25.0" dependencies = [ "anyhow", "assert_cmd", diff --git a/Cargo.toml b/Cargo.toml index f5e6c2b..9252b98 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "worklane" -version = "0.24.2" +version = "0.25.0" edition = "2024" [dependencies] diff --git a/src/command.rs b/src/command.rs index bc8a41a..a53bad2 100644 --- a/src/command.rs +++ b/src/command.rs @@ -130,6 +130,56 @@ fn codename(raw: &str) -> Result { Ok(value) } +/// Reject a tag value that `ls --tag` could never match. +/// +/// `--tag` matches a whole value of the comma-separated Tags field, so a value carrying a +/// comma is two tags and would be declared under a name nothing can be filtered by. A line +/// break is refused for the file's sake rather than the filter's: a tag is a heading in +/// `tags.md`, and a heading is one line. +/// +/// Trimmed rather than refused for surrounding space, because `parse_tags` trims every +/// value it reads off a ticket and [`TagIndex::parse`] trims every heading it reads off the +/// vocabulary. Refusing here would refuse a value that both of those accept. +/// +/// [`TagIndex::parse`]: crate::tag::TagIndex::parse +fn tag_value(raw: &str) -> Result { + let value = raw.trim(); + + if value.is_empty() { + return Err("tag cannot be empty".to_string()); + } + + if value.contains(',') { + return Err( + "tag cannot contain a comma, which is what separates one tag from the next".to_string() + ); + } + + if value.contains(['\n', '\r']) { + return Err("tag must be a single line".to_string()); + } + + Ok(value.to_string()) +} + +/// Reject an annotation line that would be read back as a tag of its own. +/// +/// The vocabulary is one heading per tag with its prose under it, so a line of prose +/// starting with the section marker would split the annotation and declare whatever +/// followed. Refused at parse time, where nothing has been written, rather than escaped on +/// the way in: an annotation is prose, and quietly rewriting prose is worse than asking for +/// a different line. +fn annotation_line(raw: &str) -> Result { + match raw.lines().any(|line| line.starts_with(crate::tag::SECTION)) { + true => Err(format!( + "an annotation line cannot start with '{}', which is how the vocabulary file \ + starts a tag", + crate::tag::SECTION + )), + false => Ok(raw.to_string()), + } +} + /// Arguments that carry prose, and therefore have to accept a value starting with /// a hyphen. /// @@ -244,15 +294,18 @@ pub enum Command { ticket: String, }, - /// List the tags the board carries, and how many tickets carry each + /// The tag vocabulary: what the board carries, and what each tag means /// /// A command rather than a mode on `ls`, for two reasons. `ls --tag ` answers /// "what is tagged bug" and cannot answer "what tags exist", which is the question a /// grooming sweep starts from; and a `--tags` beside a `--tag` is one letter away from /// a filter that means something else. /// - /// The output is machine-readable, like `ls --ids`: the tag, a tab, the count. - Tags, + /// The listing is machine-readable, like `ls --ids`: the tag, a tab, the count. + Tags { + #[command(subcommand)] + command: Option, + }, /// Print a shell completion script /// @@ -429,6 +482,42 @@ pub struct CampaignAddArgs { pub owner: Option, } +/// What the tag vocabulary can be asked for. +/// +/// Optional, unlike [`CampaignCommand`], and that is the whole shape of the compatibility +/// here: `worklane tags` was the listing before it was a group, the shipped fish completion +/// calls it that way to fill in `ls --tag`, and a bare call turning into a usage error would +/// break a script for the sake of symmetry. So the bare form stays the listing, and `tags +/// ls` is the same thing spelled the way `campaign ls` is. +/// +/// No `set`: changing an annotation is 9688d34, and a half of `add`/`set` that only ever +/// declares is the honest half to ship first. +#[derive(clap::Subcommand)] +pub enum TagCommand { + /// Declare a tag, and what it means + Add(TagAddArgs), + + /// List the tags the board carries, and how many tickets carry each + Ls, +} + +/// What declaring a tag takes: the tag, and what it is for. +/// +/// No owner and no timestamp, which every other file under `.worklane/` carries. A tag is +/// not an object with a history, it is a word the board agrees on, and `git log` over +/// `tags.md` answers who wrote which line better than a field would. +#[derive(clap::Args)] +pub struct TagAddArgs { + /// The tag to declare, spelled the way `ls --tag` matches it + #[arg(value_parser = tag_value)] + pub tag: String, + + /// What the tag means and when it is appropriate. Use multiple flags for multiline + /// annotations + #[arg(short, long, allow_hyphen_values = PROSE, value_parser = annotation_line)] + pub annotation: Vec, +} + /// `ls` holds four filters, an output mode and nothing else, which is the boundary the /// Rust Style rule in AGENTS.md names: two of the filters are adjacent `Option` /// values that a caller can swap silently, so the mode that joined them came as a diff --git a/src/completions.rs b/src/completions.rs index b3c7619..c40613c 100644 --- a/src/completions.rs +++ b/src/completions.rs @@ -351,6 +351,18 @@ mod tests { assert_eq!(seen, 4, "expected assign, campaign show, campaign set and ls --campaign"); } + /// Commands whose tag positional names a tag that does not exist yet. + /// + /// `tags add` declares a word the board has never carried, so completing it from + /// `worklane tags` would offer exactly the values the command refuses. Recorded rather + /// than skipped, so the *next* tag positional has to say which it is: `tags set` takes + /// a tag that is already declared and wants a rule in the fish block, and the test + /// below fails until it gets one or lands here. + /// + /// In the test module because nothing outside it reads the list; the rule it encodes is + /// about what the fish block is missing, which is a test's question. + const TAG_NEW_COMMANDS: [(&str, &str); 1] = [("tags", "add")]; + /// Tags have their own list because their values come from `worklane tags` rather than /// from a listing of objects, so a second tag-taking option would need that rule and /// not the campaign one. @@ -363,19 +375,29 @@ mod tests { } seen += 1; let name = path.join(" "); - let long = arg.get_long().unwrap_or_else(|| { - panic!( + + let Some(long) = arg.get_long() else { + let nested = match path.as_slice() { + [parent, child] => { + TAG_NEW_COMMANDS.contains(&(parent.as_str(), child.as_str())) + } + _ => false, + }; + assert!( + nested, "`worklane {name}` takes a tag as a positional, \ - which the fish block has no rule for" - ) - }); + which the fish block has no rule for" + ); + continue; + }; + assert!( TAG_FLAGS.contains(&long), "`worklane {name} --{long}` takes a tag but is not in TAG_FLAGS" ); } - assert_eq!(seen, 1, "expected ls --tag"); + assert_eq!(seen, 2, "expected ls --tag and tags add"); } /// **Every rule naming an option has to say which command it belongs to.** A bare diff --git a/src/handlers.rs b/src/handlers.rs index 249a352..ab126dc 100644 --- a/src/handlers.rs +++ b/src/handlers.rs @@ -8,9 +8,10 @@ use std::path::Path; use crate::campaign::*; use crate::command::{ AddArgs, AppendArgs, CampaignAddArgs, CampaignSetArgs, CheckArgs, ChownArgs, LsArgs, - RelateArgs, SetArgs, + RelateArgs, SetArgs, TagAddArgs, }; use crate::install; +use crate::tag::{TAGS_FILE, TagIndex, tags_path}; use crate::util::*; pub fn cmd_init(start: &Path) -> Result<()> { @@ -33,6 +34,13 @@ pub fn cmd_init(start: &Path) -> Result<()> { // campaigns, which is why `status_dirs()` is untouched. fs::create_dir_all(campaigns_dir(&worklane_dir))?; + // The tag vocabulary, beside both for the same reason, and written empty rather than + // left for the first `tags add` to make. An empty file explains itself when it is + // opened, which is the point of the preamble, and a board that has one from the start + // has one file shape rather than two. `fs::write` and not `write_then_replace`: the + // directory was made three lines ago, so there is nothing here to truncate. + fs::write(tags_path(&worklane_dir), TagIndex::default().render())?; + println!("Initialized worklane in: {}", worklane_dir.display()); Ok(()) } @@ -462,6 +470,7 @@ pub fn cmd_show(search: &str, worklane_dir: &Path) -> Result<()> { /// mid-sentence so there is no capital to case. const TICKET: &str = "ticket"; const CAMPAIGN: &str = "campaign"; +const TAG: &str = "tag"; /// Write `content` over `path`, without ever leaving half a file behind. /// @@ -1239,6 +1248,54 @@ pub fn cmd_tags(worklane_dir: &Path) -> Result<()> { Ok(()) } +/// Declare a tag, and what it means. +/// +/// The counterpart of `cmd_tags`, which reports the vocabulary the tickets *carry*. This +/// writes the one the board *intends*, and the two are deliberately not kept in step: a +/// declaration tags nothing, so the file cannot be used to work out what is in use, and +/// `tags add` on a word no ticket carries is the normal case rather than a mistake. +/// +/// **A tag already declared is refused rather than overwritten**, the way `add` refuses +/// nothing and `campaign set --codename` refuses a replacement without `--force`. An +/// annotation is the sentence a whole team files tickets against, so replacing one by +/// typing `add` twice is not something to do by accident. The refusal names the command +/// that does replace it, since that is the next thing the caller wants. +/// +/// The whole file is re-rendered from the parsed vocabulary, so declaring a tag also +/// re-sorts the file and rewrites its preamble. That is why an unreadable file is an error +/// in `TagIndex::load` rather than an empty vocabulary: here, empty would mean erased. +pub fn cmd_tag_add(args: &TagAddArgs, start: &Path) -> Result<()> { + let worklane_dir = find_worklane_dir(start)?; + let mut index = TagIndex::load(&worklane_dir)?; + + if index.declared(&args.tag) { + return Err(anyhow!( + "Tag '{}' is already declared, so nothing was written. \ + Use `worklane tags set` to change what it means", + args.tag + )); + } + + // Joined with a single newline, so an empty value is a paragraph break, exactly as it + // is for a description. + let annotation = trim_blank_ends(&args.annotation).join("\n"); + index.declare(&args.tag, &annotation); + + write_then_replace( + &worklane_dir, + &tags_path(&worklane_dir), + TAGS_FILE, + &index.render(), + TAG, + &args.tag, + )?; + + // The tag in its own colour, which is the colour it is drawn in on every card and in + // every listing: `tag_color` is a pure function of the word. + println!("Declared tag: {}", color_text(&args.tag, tag_color(&args.tag))); + Ok(()) +} + /// Replace fields on a campaign that is already filed. /// /// `cmd_set` for a campaign, and built out of the same parts: `set_title` for the heading, diff --git a/src/main.rs b/src/main.rs index 555f990..b3af4ab 100644 --- a/src/main.rs +++ b/src/main.rs @@ -7,6 +7,7 @@ mod command; mod completions; mod handlers; mod install; +mod tag; mod tui; mod util; @@ -78,10 +79,16 @@ fn main() -> Result<()> { } }, Some(Command::Assign { campaign, ticket }) => cmd_assign(&campaign, &ticket, &start), - Some(Command::Tags) => { - let worklane_dir = find_worklane_dir(&start)?; - cmd_tags(&worklane_dir) - } + // The bare form and `ls` are one arm: `worklane tags` was the listing before the + // group existed and the fish completion still calls it that way, so the two + // spellings cannot be allowed to drift into two behaviours. + Some(Command::Tags { command }) => match command { + None | Some(TagCommand::Ls) => { + let worklane_dir = find_worklane_dir(&start)?; + cmd_tags(&worklane_dir) + } + Some(TagCommand::Add(args)) => cmd_tag_add(&args, &start), + }, // No board either, for the reason `install-skill` has none: a completion script // is generated from the clap definition and is the same wherever it is run. Some(Command::Completions { shell }) => { diff --git a/src/tag.rs b/src/tag.rs new file mode 100644 index 0000000..0c065dd --- /dev/null +++ b/src/tag.rs @@ -0,0 +1,312 @@ +//! The tag vocabulary: which tags the board declares, and what each one means. +//! +//! One file, `.worklane/tags.md`, beside the status directories rather than among them, +//! for the reason the campaigns directory sits there: a tag has no status. One section +//! per tag, the tag as the heading and its annotation as the prose under it, so the file +//! reads as a document to whoever opens it and parses by heading to the CLI. +//! +//! **Declaring a tag tags no ticket, and tagging a ticket declares nothing.** This is a +//! vocabulary and not an index of what carries what: the counts stay derived from the +//! status directories, where `cmd_tags` already reads them. So the file and the board can +//! disagree, and that disagreement is the point — a tag carried but never declared is a +//! word nobody agreed to, which is what `campaign` and `campaigns` on this board were. +//! +//! Unlike a campaign, a tag has no uuid and no file of its own. It *is* its name, which is +//! what `ls --tag` matches whole and case sensitively, so the name is the key here and +//! there is nothing to resolve by prefix. + +use anyhow::{Result, anyhow}; +use std::collections::BTreeMap; +use std::fs; +use std::path::{Path, PathBuf}; + +use crate::util::trim_blank_ends; + +/// The vocabulary file, beside the status directories rather than among them. +pub const TAGS_FILE: &str = "tags.md"; + +pub fn tags_path(worklane_dir: &Path) -> PathBuf { + worklane_dir.join(TAGS_FILE) +} + +/// What one tag's heading looks like, and therefore what an annotation may not start a +/// line with. +/// +/// Public so the `--annotation` parser refuses the one line that would split a section, +/// rather than carrying its own copy of the spelling. Two places knowing what a heading +/// is, is how the file comes to be written in a shape it cannot be read back in. +pub const SECTION: &str = "## "; + +/// What a tag declared with nothing to say about it writes. +/// +/// A placeholder rather than an empty section, for the reason `add` writes one into an +/// empty Description: a heading with nothing under it reads as a file that failed to +/// write, and the round trip has nothing to be right about. +pub const NO_ANNOTATION: &str = "_No annotation provided._"; + +/// The heading the file opens with. Not a tag: [`tag_heading`] only reads level two. +const TITLE: &str = "# Tags"; + +/// What the file says for itself, for whoever opens it rather than for the parser. +/// +/// Re-rendered on every write, so it is present whether `init` made the file or +/// `tags add` did. It says what declaring does and does not do, because the file's one +/// real trap is reading it as the list of tags in use. +const PREAMBLE: &str = "\ +What each tag on this board means, and when it is appropriate to reach for it. Declaring a +tag here tags nothing: the counts come from the tickets themselves, and `worklane tags` is +what reports them. Written by `worklane tags`, not by hand."; + +/// The tag a level-two heading names, or nothing for any other line. +/// +/// Exactly two hashes. A `### ` line inside an annotation is prose about the tag it sits +/// under and not the start of another one, which a bare `strip_prefix` would read as a tag +/// called `# something`. +fn tag_heading(line: &str) -> Option<&str> { + let rest = line.strip_prefix(SECTION)?; + + match rest.starts_with('#') { + true => None, + false => Some(rest.trim()), + } +} + +/// The board's declared tags, each with what it means. +/// +/// A `BTreeMap` rather than a `Vec`: the order is alphabetical by byte, which is the order +/// `cmd_tags` already prints in, so `Bug` and `bug` stay two entries and land next to each +/// other. Near-duplicates being adjacent is the property the whole file is for. +/// +/// An annotation of `""` is a tag declared with nothing said about it, which is why the +/// placeholder is a rendering detail rather than a value anything holds. +#[derive(Default)] +pub struct TagIndex { + tags: BTreeMap, +} + +impl TagIndex { + /// The vocabulary as the file declares it. + /// + /// A missing file is an empty vocabulary and not an error: every board made before this + /// existed has none, and refusing there would mean a `worklane init` over a live board + /// just to get a file. + /// + /// An *unreadable* file is an error, which is the opposite of what [`CampaignIndex`] + /// does with its directory, and deliberately. The whole file is re-rendered on every + /// write, so treating one that is there as empty would erase every tag in it on the + /// next `tags add`. A campaign index that comes back empty loses a label on a card; + /// this one would lose the file. + /// + /// [`CampaignIndex`]: crate::campaign::CampaignIndex + pub fn load(worklane_dir: &Path) -> Result { + let path = tags_path(worklane_dir); + + if !path.exists() { + return Ok(Self::default()); + } + + let content = fs::read_to_string(&path).map_err(|e| { + anyhow!("Could not read the tag vocabulary at {}: {}", path.display(), e) + })?; + + Ok(Self::parse(&content)) + } + + /// The vocabulary out of the file's text. + /// + /// Everything above the first tag heading is prose for whoever opens the file and is + /// dropped: the title, the preamble, and anything else that ended up there. A heading + /// with no tag in it starts nothing, and the lines under it belong to no tag, so a + /// damaged file loses that section rather than attaching it to the tag above. + pub fn parse(content: &str) -> Self { + let mut tags = BTreeMap::new(); + let mut open: Option<(String, Vec)> = None; + + for line in content.lines() { + match tag_heading(line) { + Some(tag) => { + if let Some((held, body)) = open.take() { + tags.insert(held, annotation(&body)); + } + if !tag.is_empty() { + open = Some((tag.to_string(), Vec::new())); + } + } + None => { + if let Some((_, body)) = &mut open { + body.push(line.to_string()); + } + } + } + } + + if let Some((held, body)) = open { + tags.insert(held, annotation(&body)); + } + + Self { tags } + } + + /// Whether the file already declares this tag, matched whole and case sensitively, the + /// way `ls --tag` matches it. + pub fn declared(&self, tag: &str) -> bool { + self.tags.contains_key(tag) + } + + /// Declare `tag`, or replace what it means. + /// + /// One writer for both, because the file holds one section per tag either way and the + /// question of whether a caller may overwrite is the caller's: `tags add` refuses a tag + /// already declared, and `tags set` refuses one that is not. + pub fn declare(&mut self, tag: &str, annotation: &str) { + self.tags.insert(tag.to_string(), annotation.to_string()); + } + + /// The whole file, rendered from the whole vocabulary. + /// + /// Every write goes through here rather than splicing one section in place, which is + /// what keeps the file canonical: alphabetical, one blank line between sections, and + /// the preamble present however the file came to exist. The cost is that nothing + /// hand-written above the first heading survives a write, which is the bargain every + /// file under `.worklane/` already makes — the CLI is its only writer. + pub fn render(&self) -> String { + let mut out = format!("{TITLE}\n\n{PREAMBLE}\n"); + + for (tag, annotation) in &self.tags { + let body = match annotation.is_empty() { + true => NO_ANNOTATION, + false => annotation, + }; + out.push_str(&format!("\n{SECTION}{tag}\n{body}\n")); + } + + out + } +} + +/// One section's prose, with the blank lines around it dropped and the placeholder read +/// back as nothing. +/// +/// Through `trim_blank_ends`, the same function that decides where a ticket's description +/// starts and ends, so a blank line inside an annotation is kept and one at either end is +/// not. +fn annotation(body: &[String]) -> String { + let text = trim_blank_ends(body).join("\n"); + + match text == NO_ANNOTATION { + true => String::new(), + false => text, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// What a tag holds, read back out of the file it was written into. The round trip is + /// the property that matters: nothing else keeps the writer and the parser agreeing on + /// what a section is. + fn round_trip(tag: &str, annotation: &str) -> String { + let mut index = TagIndex::default(); + index.declare(tag, annotation); + + let read = TagIndex::parse(&index.render()); + read.tags + .get(tag) + .cloned() + .expect("the tag did not survive the round trip") + } + + #[test] + fn an_annotation_survives_the_round_trip() { + assert_eq!( + round_trip("bug", "Something the binary does wrong."), + "Something the binary does wrong." + ); + } + + /// A blank line inside an annotation is a paragraph break and is kept, which is what + /// `trim_blank_ends` is doing here rather than a blanket trim. + #[test] + fn a_paragraph_break_inside_an_annotation_is_kept() { + assert_eq!(round_trip("bug", "One.\n\nTwo."), "One.\n\nTwo."); + } + + /// A tag declared with nothing to say writes the placeholder and reads back as nothing, + /// so the file never holds a heading with a blank under it and nothing ever holds the + /// placeholder as if it were prose. + #[test] + fn a_tag_with_no_annotation_writes_the_placeholder_and_reads_back_empty() { + let mut index = TagIndex::default(); + index.declare("cli", ""); + + let rendered = index.render(); + assert!(rendered.contains(NO_ANNOTATION), "{rendered}"); + assert_eq!(TagIndex::parse(&rendered).tags["cli"], ""); + } + + /// Byte order, so `Bug` and `bug` are two tags and sit next to each other. The same + /// order `tags` prints in, and the reason the file is worth reading at all: a + /// near-duplicate is spotted by being adjacent to what it duplicates. + #[test] + fn the_file_is_alphabetical_and_keeps_case_apart() { + let mut index = TagIndex::default(); + for tag in ["tui", "bug", "Bug", "cli"] { + index.declare(tag, ""); + } + + let rendered = index.render(); + let headings: Vec<&str> = rendered.lines().filter_map(tag_heading).collect(); + assert_eq!(headings, vec!["Bug", "bug", "cli", "tui"]); + } + + /// Everything above the first heading is for whoever opens the file. The preamble says + /// `## ` nowhere, but a parser that took the title for a tag would declare one called + /// `Tags` on the next write. + #[test] + fn the_prose_above_the_first_heading_declares_nothing() { + let index = TagIndex::parse(&TagIndex::default().render()); + assert!(index.tags.is_empty(), "the preamble declared a tag"); + } + + /// A deeper heading is prose about the tag it sits under. `strip_prefix` alone read it + /// as a tag called `# whatever`, which then became a real section on the next write. + #[test] + fn a_deeper_heading_inside_an_annotation_is_not_a_tag() { + let index = TagIndex::parse("# Tags\n\n## bug\nProse.\n\n### An aside\nMore prose.\n"); + + assert_eq!(index.tags.len(), 1, "a sub-heading was read as a tag"); + assert_eq!(index.tags["bug"], "Prose.\n\n### An aside\nMore prose."); + } + + /// A heading naming nothing starts no section, and takes the lines under it with it + /// rather than attaching them to the tag above. + #[test] + fn an_empty_heading_declares_nothing_and_swallows_its_own_body() { + let index = TagIndex::parse("## bug\nProse.\n\n## \nOrphaned.\n"); + + assert_eq!(index.tags.len(), 1); + assert_eq!(index.tags["bug"], "Prose."); + } + + /// A board that never had the file has an empty vocabulary rather than an error: every + /// board made before this existed is in that state. + #[test] + fn a_board_with_no_file_has_no_tags() { + let dir = tempfile::tempdir().unwrap(); + assert!(TagIndex::load(dir.path()).unwrap().tags.is_empty()); + } + + /// And a file that is there but cannot be read is an error, not an empty vocabulary. + /// The whole file is re-rendered on every write, so empty here would mean erased on the + /// next `tags add`. + #[test] + fn a_file_that_cannot_be_read_is_an_error_rather_than_an_empty_vocabulary() { + let dir = tempfile::tempdir().unwrap(); + // A directory where the file should be: `read_to_string` fails on it, which a + // missing file does not, so this is the path the error is actually for. + fs::create_dir(tags_path(dir.path())).unwrap(); + + assert!(TagIndex::load(dir.path()).is_err()); + } +} diff --git a/tests/cmd_tags.rs b/tests/cmd_tags.rs index 18be946..526ed63 100644 --- a/tests/cmd_tags.rs +++ b/tests/cmd_tags.rs @@ -4,6 +4,11 @@ //! tags exist, which is the question a grooming sweep starts from. So the properties //! under test are the ones that question needs: every status counted, case kept apart, //! alphabetical order, and an output a shell can parse. +//! +//! `tags add` is the other half of the same question. The listing reports the vocabulary +//! the tickets *carry*; the file reports the one the board *intends*, and the tests below +//! are mostly about the two being allowed to disagree without either one damaging the +//! other. use assert_cmd::Command; use assert_fs::TempDir; @@ -175,3 +180,234 @@ fn tags_skips_a_missing_status_directory() { assert_eq!(tags(&temp), vec!["bug\t1"]); } + +// ------------------------------------------------------------- the vocabulary -- + +fn vocabulary(temp: &TempDir) -> String { + fs::read_to_string(temp.path().join(".worklane").join("tags.md")).unwrap() +} + +/// The section a tag holds in the file, heading excluded, or `None` when it is not +/// declared. Cut out of the file rather than asserted against a whole rendering, so a +/// change to the preamble does not fail every test here. +fn declared(temp: &TempDir, tag: &str) -> Option { + let file = vocabulary(temp); + let (_, rest) = file.split_once(&format!("\n## {tag}\n"))?; + let body = match rest.split_once("\n## ") { + Some((body, _)) => body, + None => rest, + }; + + Some(body.trim().to_string()) +} + +/// The declaration lands in the file, with the annotation under it. +#[test] +fn tags_add_declares_a_tag_with_what_it_means() { + let temp = TempDir::new().unwrap(); + setup_worklane(&temp); + + let out = run( + &temp, + &[ + "tags", + "add", + "bug", + "--annotation", + "Something the binary does wrong.", + ], + ); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + + assert_eq!(declared(&temp, "bug").as_deref(), Some("Something the binary does wrong.")); +} + +/// Several flags are several lines, and an empty one is a paragraph break, the way a +/// description is written. +#[test] +fn an_annotation_takes_several_lines_and_a_paragraph_break() { + let temp = TempDir::new().unwrap(); + setup_worklane(&temp); + + run( + &temp, + &[ + "tags", + "add", + "bug", + "-a", + "What it is.", + "-a", + "", + "-a", + "When to use it.", + ], + ); + + assert_eq!(declared(&temp, "bug").as_deref(), Some("What it is.\n\nWhen to use it.")); +} + +/// A tag can be declared with nothing said about it. The word being agreed on is worth +/// recording before anyone has written the sentence. +#[test] +fn a_tag_can_be_declared_without_an_annotation() { + let temp = TempDir::new().unwrap(); + setup_worklane(&temp); + + let out = run(&temp, &["tags", "add", "cli"]); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + assert_eq!(declared(&temp, "cli").as_deref(), Some("_No annotation provided._")); +} + +/// Refused rather than overwritten, and the refusal names what does overwrite it: an +/// annotation is the sentence a team files tickets against, not something to replace by +/// typing `add` twice. +#[test] +fn declaring_a_tag_twice_is_refused_and_names_the_command_that_replaces_it() { + let temp = TempDir::new().unwrap(); + setup_worklane(&temp); + + run(&temp, &["tags", "add", "bug", "-a", "The first sentence."]); + let out = run(&temp, &["tags", "add", "bug", "-a", "A different sentence."]); + + assert!(!out.status.success()); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!(stderr.contains("tags set"), "{stderr}"); + assert_eq!(declared(&temp, "bug").as_deref(), Some("The first sentence.")); +} + +/// A comma is what separates one tag from the next, so a value carrying one could never be +/// matched by `--tag`. Refused at parse, with nothing written. +#[test] +fn a_tag_the_filter_could_never_match_is_refused() { + let temp = TempDir::new().unwrap(); + setup_worklane(&temp); + + for value in ["bug,cli", ""] { + let out = run(&temp, &["tags", "add", value]); + assert!(!out.status.success(), "'{value}' was accepted"); + } + + // Nothing was written on the way past, not even the empty file. + assert!(!temp.path().join(".worklane").join("tags.md").exists()); +} + +/// Surrounding space is trimmed rather than refused, because a ticket's Tags field is read +/// that way too: ` bug ` on a card is the tag `bug`, and the vocabulary has to agree. +#[test] +fn a_padded_tag_is_declared_under_its_trimmed_name() { + let temp = TempDir::new().unwrap(); + setup_worklane(&temp); + + run(&temp, &["tags", "add", " bug "]); + assert!(declared(&temp, "bug").is_some(), "{}", vocabulary(&temp)); +} + +/// An annotation line that would be read back as a heading is refused, since it would split +/// the section and declare whatever followed it. +#[test] +fn an_annotation_that_would_read_as_a_heading_is_refused() { + let temp = TempDir::new().unwrap(); + setup_worklane(&temp); + + let out = run(&temp, &["tags", "add", "bug", "-a", "## cli"]); + assert!(!out.status.success()); + assert!(!temp.path().join(".worklane").join("tags.md").exists()); +} + +/// The file is made on demand, the way `campaign add` makes the campaigns directory: a board +/// that predates the vocabulary must not need `worklane init` run over it. +#[test] +fn the_file_is_created_on_a_board_that_predates_it() { + let temp = TempDir::new().unwrap(); + setup_worklane(&temp); + assert!(!temp.path().join(".worklane").join("tags.md").exists()); + + run(&temp, &["tags", "add", "bug"]); + assert!(declared(&temp, "bug").is_some()); +} + +/// `init` writes it, so a new board has one file shape rather than two. +#[test] +fn init_writes_the_vocabulary_beside_the_status_directories() { + let temp = TempDir::new().unwrap(); + let out = run(&temp, &["init"]); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + + let file = vocabulary(&temp); + assert!(file.starts_with("# Tags"), "{file}"); + // The preamble and nothing else: a new board declares no tags. + assert!(!file.contains("\n## "), "{file}"); +} + +/// A second declaration keeps the first, and the file stays alphabetical: the whole file is +/// re-rendered, so this is the test that the re-render is not a truncation. +#[test] +fn declaring_a_tag_leaves_the_others_alone_and_keeps_the_order() { + let temp = TempDir::new().unwrap(); + setup_worklane(&temp); + + run(&temp, &["tags", "add", "tui", "-a", "The board view."]); + run(&temp, &["tags", "add", "bug", "-a", "Something wrong."]); + + assert_eq!(declared(&temp, "tui").as_deref(), Some("The board view.")); + assert_eq!(declared(&temp, "bug").as_deref(), Some("Something wrong.")); + + let file = vocabulary(&temp); + assert!(file.find("## bug").unwrap() < file.find("## tui").unwrap(), "{file}"); +} + +/// A file that is there and cannot be read stops the write rather than being taken for an +/// empty vocabulary. Empty would mean erased, since every declaration re-renders the file. +#[test] +fn a_vocabulary_that_cannot_be_read_is_refused_rather_than_replaced() { + let temp = TempDir::new().unwrap(); + let worklane = setup_worklane(&temp); + // A directory where the file should be: `read_to_string` fails on it, which a missing + // file does not. + fs::create_dir(worklane.join("tags.md")).unwrap(); + + let out = run(&temp, &["tags", "add", "bug"]); + assert!(!out.status.success()); + assert!(worklane.join("tags.md").is_dir(), "the file was replaced"); + + // And nothing was staged and left behind. + let stray: Vec<_> = fs::read_dir(&worklane) + .unwrap() + .filter_map(|e| e.ok()) + .filter(|e| e.file_name().to_string_lossy().starts_with(".wl-")) + .collect(); + assert!(stray.is_empty(), "a temp file was left in .worklane"); +} + +/// The vocabulary does not touch the listing, which counts tickets. The two disagreeing is +/// the normal state and the thing the file is for. +#[test] +fn a_declared_tag_is_not_a_carried_one() { + let temp = TempDir::new().unwrap(); + let worklane = setup_worklane(&temp); + create_ticket(&worklane, "backlog", "11111111", "bug"); + + run(&temp, &["tags", "add", "chore", "-a", "Housekeeping."]); + + // `chore` is declared and carried by nothing, `bug` is carried and declared by nothing, + // and the listing still answers only the second question. Reporting both is 9564ac9. + assert_eq!(tags(&temp), vec!["bug\t1"]); +} + +/// The bare form is the listing, byte for byte, because the shipped fish completion calls it +/// that way to fill in `ls --tag`. `tags ls` is the same thing spelled as a group. +#[test] +fn the_bare_form_and_ls_are_the_same_listing() { + let temp = TempDir::new().unwrap(); + let worklane = setup_worklane(&temp); + create_ticket(&worklane, "backlog", "11111111", "bug, cli"); + run(&temp, &["tags", "add", "chore"]); + + let bare = run(&temp, &["tags"]); + let group = run(&temp, &["tags", "ls"]); + + assert!(bare.status.success()); + assert_eq!(bare.stdout, group.stdout); + assert_eq!(String::from_utf8_lossy(&bare.stdout), "bug\t1\ncli\t1\n"); +}