(7bfb9fc) Add campaigns, a ticket container assigned through worklane assign, and bump to 0.12.0

There was no way to group the tickets that have to be finished together. A
goal such as a v1 release was either one ticket that could not describe its
parts, or a set of tickets with the goal restated in every description and
nothing tying them together.

A campaign is a file of its own under `.worklane/campaigns/`, with a title, a
description and metadata, and it sits in no status directory. Its state is
derived instead: open until every member is done. Deriving it means there is
no such thing as a done campaign holding an open ticket, and no second
forward-only ruleset beside `mv`'s. An empty campaign is neither open nor
done, since calling it done would make a container nothing has been filed
against the most complete thing on the board.

Membership is one field on the *member*, Campaign in the ticket Metadata,
written only by `assign`. The member list is deliberately not on the campaign:
that would put membership in two places and make one file that every
assignment edits, contended the moment two agents share a board. So `add`
gains no `--campaign` and neither does `set`.

`add` does not write the field either. Every ticket written before campaigns
existed has none, so the insertion path has to exist regardless, and leaving
it out of `add` means one path that is always exercised rather than two. That
is the Relations argument from 4179958, applied to a field instead of a
section. `set_or_insert_metadata_field` is the upsert and `METADATA_ORDER` is
its anchor list, the way `SECTION_ORDER` is `ensure_section`'s, so Campaign
lands beside Status rather than at the end and Status stays last. A file with
no Metadata heading is an error rather than an insertion, per 641e3d5.

The three tiers came out of `resolve_ticket` into `resolve_in`, shared by both
kinds. 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. Two
things fell out of that. `Found.dir` is the status for a ticket and empty for
a campaign, which is what drops the bracket from the ambiguity listing for
one. And `resolve_ticket` can now explain a search that names a campaign, so
`mv`, `show`, `chown` and everything else that takes a ticket give the same
reason instead of a bare "no ticket found" — one place rather than a check per
command. Only on the zero-match path, so an ambiguous ticket error is never
replaced by a complaint about a directory the caller never mentioned.

The stored value is the full uuid, per the same rule the Relations section
follows, and the title is resolved for display. `reference_cell` is now shared
between the two, so a dangling campaign and a dangling relation target are
both `_missing_` rather than each inventing a spelling. `Resolved` carries
what `content_trim` cannot render from the file alone: a struct rather than
two more parameters, so the next such field is one entry instead of an edit at
every call site.

`campaign show` lists done members, unlike `ls`, which leaves the done column
out of its listing. What is finished against what is left is the whole
question a campaign asks. `ls --campaign` is the other way round and keeps
every rule `ls` already has.

Deliberately out of scope. The derived progress figure is 1cb999f, now
recorded as blocked by this, since nothing here can compute it yet.
Unassigning needs a field cleared back to unset, which is 74904dc. And the
board gets neither a campaign tab nor a card marker: the detail view resolves
the field because it renders the body, and that is all. A marker would want a
read per reload and the four corners are already spent, which is the b8ce18c
reasoning; filed as 61879a4.

Twenty-four integration tests and eleven unit tests, covering assign,
reassign, the no-op, a dangling campaign, the ls filter, `mv` refusing a
campaign, insertion placement, and a handwritten section and unknown metadata
field surviving an assignment verbatim.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Ansho Rei
2026-08-22 00:52:57 +02:00
co-authored by Claude Opus 5
parent 41a65f95b2
commit 5b0bac9c2d
11 changed files with 1694 additions and 84 deletions
+400 -65
View File
@@ -203,6 +203,18 @@ pub fn get_git_user() -> Option<String> {
}
})
}
/// 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)`.
///
@@ -210,16 +222,25 @@ pub fn get_git_user() -> Option<String> {
/// is the only combination the opencode wrapper can relay: it throws on the exit
/// code and keeps stderr, so the list printed to stdout was thrown away and the
/// agent saw nothing but a bare exit code.
fn ambiguous(search: &str, matches: &[(String, String, String, String)]) -> anyhow::Error {
let mut message = format!("Multiple tickets found matching '{}':\n", search);
///
/// `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)),
};
for (i, (status, title, _, id)) in matches.iter().enumerate() {
message.push_str(&format!(
" {}. ({}) {} [{}]\n",
" {}. ({}) {}{}\n",
i + 1,
color_text(short_id(id), Color::Red),
title,
color_text(status, Color::Orange),
color_text(short_id(&found.uuid), Color::Red),
found.title,
status,
));
}
@@ -237,7 +258,9 @@ fn ambiguous(search: &str, matches: &[(String, String, String, String)]) -> anyh
pub const MIN_ID_SEARCH: usize = 4;
/// The ticket's title, from the first `# ` heading, or empty when it has none.
fn heading_title(content: &str) -> String {
///
/// 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("# "))
@@ -245,25 +268,39 @@ fn heading_title(content: &str) -> String {
.unwrap_or_default()
}
pub fn resolve_ticket(search: &str, worklane_dir: &Path) -> Result<(String, String, String)> {
/// 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 three-tier search, run over `dirs`, returning the first tier that matched
/// anything.
///
/// Three 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.
///
/// 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<Vec<Found>> {
let search_lower = search.to_lowercase();
let long_enough_for_an_id = search.chars().count() >= MIN_ID_SEARCH;
// Three 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.
let mut by_id: Vec<(String, String, String, String)> = Vec::new();
let mut by_title: Vec<(String, String, String, String)> = Vec::new();
let mut by_filename: Vec<(String, String, String, String)> = Vec::new();
let mut by_id: Vec<Found> = Vec::new();
let mut by_title: Vec<Found> = Vec::new();
let mut by_filename: Vec<Found> = Vec::new();
for status in status_dirs() {
let status_path = worklane_dir.join(status);
if !status_path.exists() {
for (name, path) in dirs {
if !path.exists() {
continue;
}
let entries = fs::read_dir(&status_path)?;
for entry in entries.filter_map(|e| e.ok()) {
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;
@@ -288,7 +325,12 @@ pub fn resolve_ticket(search: &str, worklane_dir: &Path) -> Result<(String, Stri
continue;
}
let found = (status.to_string(), title, content, uuid.to_string());
let found = Found {
dir: name.clone(),
title,
content,
uuid: uuid.to_string(),
};
if by_prefix {
by_id.push(found);
} else if in_title {
@@ -299,22 +341,40 @@ pub fn resolve_ticket(search: &str, worklane_dir: &Path) -> Result<(String, Stri
}
}
let mut matches = match (by_id.is_empty(), by_title.is_empty()) {
Ok(match (by_id.is_empty(), by_title.is_empty()) {
(false, _) => by_id,
(true, false) => by_title,
(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 <campaign>` 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(search, &matches));
return Err(ambiguous("ticket", search, &matches));
}
let (status, title, content, _short_id) = matches.remove(0);
Ok((status, title, content))
let found = matches.remove(0);
Ok((found.dir, found.title, found.content))
}
pub fn format_comments(comments: &[(String, String, String, String)]) -> String {
format_comments_with(comments, should_use_colors())
@@ -347,8 +407,28 @@ pub fn format_comments_with(
result
}
pub fn content_trim_colored(content: &str, relations: &str) -> String {
content_trim(content, should_use_colors(), relations)
/// 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 block [`render_relations`] built, or empty for a ticket with no relations.
pub relations: String,
/// The Campaign value as it reads, from [`reference_cell`]. Empty leaves the stored
/// value to render as it sits, which is what a ticket in no campaign wants.
pub campaign: String,
}
pub fn content_trim_colored(content: &str, resolved: &Resolved) -> String {
content_trim(content, should_use_colors(), resolved)
}
/// A section heading, its rule, and the blank line the body opens under.
@@ -371,11 +451,10 @@ fn push_heading(out: &mut String, heading: &str, colored: bool) {
/// The TUI needs the plain form: ratatui draws styled spans, and an escape sequence
/// embedded in a paragraph would be printed as literal bytes.
///
/// `relations` is the block [`relations_block`] built, or empty. It is passed in rather
/// than derived here because half of it comes from other tickets: the section stores
/// one side of each edge and bare uuids for its targets, so the body alone cannot say
/// what a relation points at, nor that anything points back.
pub fn content_trim(content: &str, colored: bool, relations: &str) -> String {
/// [`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 {
let relations = resolved.relations.as_str();
let lines: Vec<&str> = content.trim().lines().collect();
let mut result = String::new();
let mut current_section = "";
@@ -412,7 +491,11 @@ pub fn content_trim(content: &str, colored: bool, relations: &str) -> String {
// falling through to the line-at-a-time cases below.
if is_metadata_heading(line) {
let end = section_end(&lines, i);
result.push_str(&render_metadata_table(&lines[i..end], colored));
result.push_str(&render_metadata_table(
&lines[i..end],
colored,
&resolved.campaign,
));
i = end;
}
@@ -571,7 +654,15 @@ fn metadata_row(line: &str) -> MetadataRow<'_> {
}
/// The value cell for a field, styled per the colour guideline.
fn metadata_value_cell(name: &str, value: &str, colored: bool) -> String {
///
/// `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_cell(name: &str, value: &str, colored: bool, campaign: &str) -> String {
if name == CAMPAIGN_FIELD && !campaign.is_empty() {
return campaign.to_string();
}
if name == "Priority" {
// Reads as a glyph, while the file keeps storing the number.
let (glyph, colour) = priority_mark(priority_from_value(value));
@@ -590,7 +681,7 @@ fn metadata_value_cell(name: &str, value: &str, colored: bool) -> String {
/// Taken as a block rather than a line at a time because the field column cannot be
/// sized until every name has been seen. The file is untouched by this: it goes on
/// storing the markdown list, and this is only how the list is shown.
fn render_metadata_table(lines: &[&str], colored: bool) -> String {
fn render_metadata_table(lines: &[&str], colored: bool, campaign: &str) -> String {
// The heading already emits its own blank separator, so the one the template
// puts under it would otherwise open the section with a gap.
let start = lines
@@ -618,7 +709,7 @@ fn render_metadata_table(lines: &[&str], colored: bool) -> String {
result.push_str(&paint(name, Color::Red, colored));
result.push_str(&" ".repeat(field_width - name.chars().count()));
result.push_str(COLUMN_GUTTER);
result.push_str(&metadata_value_cell(name, value, colored));
result.push_str(&metadata_value_cell(name, value, colored, campaign));
}
// The decision this row is rendered under, not the one the terminal
// would give: `colorize_line` asked `should_use_colors()` here, which is
@@ -682,7 +773,7 @@ fn is_delimiter(chars: &[char], at: usize) -> bool {
chars.get(at) == Some(&'*') && chars.get(at + 1) == Some(&'*')
}
const METADATA_HEADING: &str = "## Metadata";
pub const METADATA_HEADING: &str = "## Metadata";
fn is_metadata_heading(line: &str) -> bool {
line.trim_end() == METADATA_HEADING
@@ -789,6 +880,120 @@ pub fn set_metadata_field(content: &str, field: &str, value: &str, title: &str)
})
}
/// 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 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<String> {
let value = parse_ticket_field(content, CAMPAIGN_FIELD);
match is_unknown_value(&value) || value.trim().is_empty() {
true => None,
false => Some(value),
}
}
/// The metadata fields in the order `add` writes them, with `Campaign` in its place
/// 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.
const METADATA_ORDER: [&str; 8] = [
"ID",
"Priority",
"Tags",
"Due",
"Owner",
"Created At",
CAMPAIGN_FIELD,
"Status",
];
/// 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,
title: &str,
) -> Result<String> {
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, 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.
fn insert_metadata_field(content: &str, field: &str, value: &str, title: &str) -> Result<String> {
let lines: Vec<&str> = content.lines().collect();
let heading = lines
.iter()
.position(|line| is_metadata_heading(line))
.ok_or_else(|| {
anyhow!(
"Ticket '{}' has no Metadata section, so its {} field cannot be written",
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<String> = 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))
}
/// Rewrite the title heading, the first `# ` line in the file.
///
/// `## ` headings do not match: the second character has to be a space.
@@ -1258,19 +1463,26 @@ impl RelationIndex {
}
}
/// A relation's target as it reads: the short id, then the title.
/// A cross reference as it reads: the short id, then the name it points at.
///
/// `_missing_` rather than a bare uuid for a target the board no longer has. The id is
/// kept either way, since it is the only thing left to go looking for.
fn target_cell(target: Option<&RelatedTicket>, uuid: &str, colored: bool) -> String {
/// `_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. Shared by the
/// relations block and the Campaign field, so a dangling reference is spelled one way
/// wherever it is shown.
pub fn reference_cell(uuid: &str, name: Option<&str>, colored: bool) -> String {
let id = paint(short_id(uuid), Color::Red, colored);
match target {
Some(ticket) => format!("({}) {}", id, ticket.title),
match name {
Some(name) => format!("({}) {}", id, name),
None => format!("({}) {}", id, paint("_missing_", Color::Grey, colored)),
}
}
/// A relation's target as it reads.
fn target_cell(target: Option<&RelatedTicket>, uuid: &str, colored: bool) -> String {
reference_cell(uuid, target.map(|ticket| ticket.title.as_str()), colored)
}
/// The Relations section as it is shown, or empty when there is nothing to show.
///
/// Both directions, stored first: the relations the ticket holds, then the ones held
@@ -1592,6 +1804,11 @@ pub struct TicketItem {
/// ticket body on every draw rather than on the tick that changed something. The
/// listing ignores it, as it ignores `path`.
pub criteria: Option<Progress>,
/// 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<String>,
/// 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,
@@ -1747,6 +1964,7 @@ pub fn collect_ticket_items(status_path: impl AsRef<Path>) -> Result<Vec<TicketI
created: format_created_at(&created_at),
priority: parse_priority(&content),
criteria: progress,
campaign: parse_campaign(&content),
path: e.path(),
})
})
@@ -1933,6 +2151,7 @@ mod tests {
"- **Owner**: alice",
],
false,
"",
);
assert_eq!(
@@ -1946,7 +2165,7 @@ mod tests {
#[test]
fn a_long_field_name_widens_the_column_for_every_row() {
let rendered =
render_metadata_table(&["- **ID**: abc", "- **Handled By Team**: ops"], false);
render_metadata_table(&["- **ID**: abc", "- **Handled By Team**: ops"], false, "");
assert_eq!(
rendered,
@@ -1967,8 +2186,8 @@ mod tests {
"- **Owner**: Ansho Rei",
];
let plain = render_metadata_table(&lines, false);
let coloured = render_metadata_table(&lines, true);
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);
@@ -1977,7 +2196,7 @@ mod tests {
#[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);
let rendered = render_metadata_table(&["- **Créé à**: oui", "- **ID**: abc"], false, "");
assert_eq!(
rendered,
@@ -1989,7 +2208,7 @@ mod tests {
#[test]
fn a_non_ascii_value_leaves_the_column_alone() {
let lines = ["- **Owner**: 日本語", "- **ID**: abc"];
let rendered = render_metadata_table(&lines, false);
let rendered = render_metadata_table(&lines, false, "");
assert_eq!(
rendered,
@@ -2000,7 +2219,7 @@ mod tests {
#[test]
fn a_field_the_tool_does_not_know_still_gets_a_row() {
let rendered = render_metadata_table(&["- **ID**: abc", "- **Sprint**: 14"], false);
let rendered = render_metadata_table(&["- **ID**: abc", "- **Sprint**: 14"], false, "");
assert!(rendered.contains("Sprint 14"), "{rendered:?}");
}
@@ -2008,7 +2227,7 @@ mod tests {
#[test]
fn a_line_that_is_not_a_field_is_carried_through() {
let rendered =
render_metadata_table(&["- **ID**: abc", "a hand written note"], false);
render_metadata_table(&["- **ID**: abc", "a hand written note"], false, "");
assert_eq!(
rendered,
@@ -2019,7 +2238,7 @@ mod tests {
#[test]
fn the_priority_cell_carries_the_mark_and_the_stored_number() {
let rendered = render_metadata_table(&["- **Priority**: 2"], false);
let rendered = render_metadata_table(&["- **Priority**: 2"], false, "");
let (glyph, _) = priority_mark(Priority::Level(2));
assert_eq!(rendered, format!("Priority {glyph} 2\n"));
@@ -2027,7 +2246,7 @@ mod tests {
#[test]
fn an_unset_priority_reads_as_unset_in_the_table() {
let rendered = render_metadata_table(&["- **Priority**: _Not set_"], false);
let rendered = render_metadata_table(&["- **Priority**: _Not set_"], false, "");
let (glyph, _) = priority_mark(Priority::Unset);
assert_eq!(rendered, format!("Priority {glyph} _Not set_\n"));
@@ -2042,7 +2261,7 @@ mod tests {
/// 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, "");
let rendered = content_trim(BOTH_LEAKS, false, &Resolved::default());
assert!(
!rendered.contains('\x1b'),
@@ -2058,7 +2277,7 @@ mod tests {
/// 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, "");
let rendered = content_trim(BOTH_LEAKS, true, &Resolved::default());
assert!(
rendered.contains(&format!("{}1.", Color::Cyan.ansi())),
@@ -2181,9 +2400,125 @@ mod tests {
fs::remove_dir_all(&dir).unwrap();
}
/// 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", "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", "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", "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", "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", "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}");
}
#[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_colored("# T\n\n## Description\nbody\n", "");
let rendered = content_trim_colored("# T\n\n## Description\nbody\n", &Resolved::default());
// Eleven characters, not fourteen: the rule used to span "## Description"
assert!(
@@ -2194,14 +2529,14 @@ mod tests {
#[test]
fn a_non_ascii_section_name_is_not_over_drawn() {
let rendered = content_trim_colored("# T\n\n## Résumé\nbody\n", "");
let rendered = content_trim_colored("# T\n\n## Résumé\nbody\n", &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_colored("# Only Once\n\n## Description\nbody\n", "");
let rendered = content_trim_colored("# Only Once\n\n## Description\nbody\n", &Resolved::default());
assert!(!rendered.contains("Only Once"), "{rendered:?}");
// And no gap where it was
@@ -2211,7 +2546,7 @@ mod tests {
#[test]
fn the_metadata_section_renders_as_a_table_inside_the_body() {
let content = "# T\n\n## Metadata\n\n- **ID**: abc\n- **Owner**: alice\n";
let rendered = content_trim_colored(content, "");
let rendered = content_trim_colored(content, &Resolved::default());
assert_eq!(rendered, "Metadata\n────────\n\nID abc\nOwner alice\n");
}
@@ -2219,7 +2554,7 @@ mod tests {
#[test]
fn a_section_after_metadata_still_renders() {
let content = "# T\n\n## Metadata\n\n- **ID**: abc\n\n## Notes\n\nafter\n";
let rendered = content_trim_colored(content, "");
let rendered = content_trim_colored(content, &Resolved::default());
assert!(rendered.contains("ID abc"), "{rendered:?}");
assert!(rendered.contains("Notes\n─────\n"), "{rendered:?}");
@@ -2667,7 +3002,7 @@ mod tests {
"# T\n\n## Relations\n- blocked by {}\n\n## Metadata\n\n- **ID**: {}\n",
TARGET, SELF
);
let rendered = content_trim(&content, false, "blocked by (b1b2c3d) The blocker\n");
let rendered = content_trim(&content, false, &Resolved { relations: "blocked by (b1b2c3d) The blocker\n".to_string(), ..Default::default() });
assert!(
rendered.contains("Relations\n─────────\n\nblocked by (b1b2c3d) The blocker\n\nMetadata"),
@@ -2682,7 +3017,7 @@ mod tests {
#[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, "blocks (641e3d5) The gated one\n");
let rendered = content_trim(&content, false, &Resolved { relations: "blocks (641e3d5) The gated one\n".to_string(), ..Default::default() });
assert!(
rendered.contains("Body.\n\nRelations\n─────────\n\nblocks (641e3d5) The gated one\n\nMetadata"),
@@ -2694,7 +3029,7 @@ mod tests {
/// 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, "blocks (641e3d5) X\n");
let rendered = content_trim("# T\n\n## Description\nBody.\n", false, &Resolved { relations: "blocks (641e3d5) X\n".to_string(), ..Default::default() });
assert!(rendered.ends_with("Relations\n─────────\n\nblocks (641e3d5) X\n"), "{rendered:?}");
}
@@ -2704,7 +3039,7 @@ mod tests {
#[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, "");
let rendered = content_trim(content, false, &Resolved::default());
assert!(rendered.contains("Relations\n─────────\n\n_No relations._\n"), "{rendered:?}");
}