Files
worklane/src/tag.rs
T
Ansho ReiandClaude Opus 5 7126138d46 (0fd1ddc) Pick a tag in the tui, and bump to 0.27.1
The board could be cut by campaign and not by the axis `ls --tag` has answered
since 2f3796e. `t` opens a picker of every tag the board declares or carries,
and taking one filters every column to the cards carrying it, matched whole and
case sensitively the way the listing matches.

The picker is one piece of machinery over two lists rather than a second
picker. `PickerRow::key` is what made that cheap: a campaign is keyed by its
uuid and a tag by itself, both strings, so stepping over selectable rows,
keeping the highlight across a rebuild and taking a row with `enter` are
written once. Only the list and what the answer filters differ.

`Tab::campaign` became `Tab::filter`, an enum of whole, campaign or tag, with
`select_filter` its only writer. Picking either clears the other because they
are one field rather than because two setters remember to, which is also what
the shared frame slot needs: it holds one frame and can now only be asked to
name one thing.

The tag sections are declared above undeclared and neither is truncated, where
the completed campaigns are: a finished campaign is done with and that tail
only grows, while an undeclared tag is the row a reader most wants to see.
`campaign` and `campaigns` would have sat one under the other here the day the
second was invented.

The digest stamps `tags.md`, or a tag declared elsewhere would never reach an
open picker. The footer names the tag in its own colour beside `q board`,
because a tag draws no frame until 2a83bd4 and nothing else would say why the
cards are missing.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-24 10:03:29 +02:00

362 lines
15 KiB
Rust

//! 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<String, String>,
}
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<Self> {
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<String>)> = 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)
}
/// Every tag the file declares, alphabetical, whatever the board carries.
///
/// The half of the listing the status directories cannot answer. A tag declared and
/// never applied is carried by no ticket, so counting alone drops it, and that tag is
/// most of the reason the file exists: a word the board agreed on and nobody has
/// reached for yet is exactly what a grooming sweep wants to see.
pub fn names(&self) -> impl Iterator<Item = &str> {
self.tags.keys().map(String::as_str)
}
/// What a tag means, whole, or `None` for a tag the file does not declare.
///
/// The raw section, paragraphs and all, where [`Self::summary`] is the one line a
/// listing has room for. `Some("")` is a tag declared with nothing said about it, which
/// the caller has to tell apart from `None`: the board draws the two in different
/// sections.
pub fn annotation(&self, tag: &str) -> Option<&str> {
self.tags.get(tag).map(String::as_str)
}
/// The opening line of what a tag means, or `None` for a tag the file does not declare.
///
/// The cut to one line lives here rather than on the parse, the way
/// [`CampaignRow::summary`] takes one line off a description the read carries whole:
/// the annotation is prose with paragraphs in it, and which view wants how much of it
/// is the view's business.
///
/// **`None` is what marks a carried but undeclared tag**, since `cmd_tags` prints no
/// third field for it. Nothing is appended to the tag itself and nothing is added to
/// the count, so `cut -f1` still yields the tag values and a board with no file at all
/// lists what it listed before the file existed.
///
/// A declared tag with nothing said about it answers [`NO_ANNOTATION`] rather than an
/// empty string, because an empty third field is a trailing tab and nothing else: it
/// would be the only difference between declared and not, and it would be invisible in
/// a terminal and in a completion alike. The placeholder is also what the file itself
/// holds under that heading, so the field stays the section's opening line either way.
///
/// [`CampaignRow::summary`]: crate::tui::CampaignRow::summary
/// [`NO_ANNOTATION`]: crate::tag::NO_ANNOTATION
pub fn summary(&self, tag: &str) -> Option<&str> {
let annotation = self.tags.get(tag)?;
Some(match annotation.lines().next() {
Some(line) => line,
None => NO_ANNOTATION,
})
}
/// 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());
}
}