(4179958) Add a Relations section for blocked by, regression of and relates to, and bump to 0.11.0
`relate` is the only writer of the section, the way `chown` is the only writer of Owner: a relation names a target that has to be resolved to a uuid first, so `set` and `append` are deliberately kept out of it. One flag per kind, so an unknown kind is a usage error rather than a line refused on the way back out. One direction is stored and the inverse is derived by a scan. `blocked by` goes on the gated ticket, whose move `mv` now refuses while the target is not done, naming every open blocker; `-f` bypasses it beside the backward and skipping moves. A target that is not on the board warns and allows the move. The rendered block is built outside `content_trim` and passed in, since half of it comes from other tickets. The section is created on demand rather than by `add`, so a ticket written before it existed gains it without being regenerated. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5
parent
b56b31d2d9
commit
3085b0226f
+663
-42
@@ -236,6 +236,15 @@ fn ambiguous(search: &str, matches: &[(String, String, String, String)]) -> anyh
|
||||
/// `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.
|
||||
fn heading_title(content: &str) -> String {
|
||||
content
|
||||
.lines()
|
||||
.find(|line| line.starts_with("# "))
|
||||
.map(|line| line[2..].trim().to_string())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn resolve_ticket(search: &str, worklane_dir: &Path) -> Result<(String, String, String)> {
|
||||
let search_lower = search.to_lowercase();
|
||||
let long_enough_for_an_id = search.chars().count() >= MIN_ID_SEARCH;
|
||||
@@ -263,12 +272,7 @@ pub fn resolve_ticket(search: &str, worklane_dir: &Path) -> Result<(String, Stri
|
||||
Ok(c) => c,
|
||||
Err(_) => continue,
|
||||
};
|
||||
let title = content
|
||||
.lines()
|
||||
.find(|l| l.starts_with("# "))
|
||||
.map(|l| l[2..].trim())
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
let title = heading_title(&content);
|
||||
let filename = path
|
||||
.file_stem()
|
||||
.map(|s| s.to_string_lossy().to_string())
|
||||
@@ -343,47 +347,88 @@ pub fn format_comments_with(
|
||||
|
||||
result
|
||||
}
|
||||
pub fn content_trim_colored(content: &str) -> String {
|
||||
content_trim(content, should_use_colors())
|
||||
pub fn content_trim_colored(content: &str, relations: &str) -> String {
|
||||
content_trim(content, should_use_colors(), relations)
|
||||
}
|
||||
|
||||
/// 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 String, heading: &str, colored: bool) {
|
||||
let name = heading.strip_prefix("## ").unwrap_or(heading);
|
||||
|
||||
out.push_str(&paint(name, Color::Orange, colored));
|
||||
out.push('\n');
|
||||
out.push_str(&"─".repeat(name.chars().count()));
|
||||
out.push('\n');
|
||||
out.push('\n');
|
||||
}
|
||||
|
||||
/// The ticket body rendered for display, with the colour decision passed in.
|
||||
///
|
||||
/// The TUI needs the plain form: ratatui draws styled spans, and an escape sequence
|
||||
/// embedded in a paragraph would be printed as literal bytes.
|
||||
pub fn content_trim(content: &str, colored: bool) -> String {
|
||||
///
|
||||
/// `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 {
|
||||
let lines: Vec<&str> = content.trim().lines().collect();
|
||||
let mut result = String::new();
|
||||
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;
|
||||
result.push_str(&paint(section_name, Color::Orange, colored));
|
||||
result.push('\n');
|
||||
// Measured on the name as displayed, in characters. The rule used to span
|
||||
// the raw line, so it ran three past the heading for the "## ", and byte
|
||||
// length over-drew for anything non-ASCII.
|
||||
result.push_str(&"─".repeat(section_name.chars().count()));
|
||||
result.push('\n');
|
||||
result.push('\n');
|
||||
|
||||
// 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, colored);
|
||||
result.push_str(relations);
|
||||
result.push('\n');
|
||||
shown_relations = true;
|
||||
}
|
||||
|
||||
push_heading(&mut result, section_name, colored);
|
||||
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 = lines[i..]
|
||||
.iter()
|
||||
.position(|l| l.starts_with("## "))
|
||||
.map_or(lines.len(), |offset| i + offset);
|
||||
let end = section_end(&lines, i);
|
||||
result.push_str(&render_metadata_table(&lines[i..end], colored));
|
||||
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_str(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;
|
||||
}
|
||||
|
||||
@@ -451,6 +496,16 @@ pub fn content_trim(content: &str, colored: bool) -> String {
|
||||
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, colored);
|
||||
result.push_str(relations);
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
@@ -485,8 +540,9 @@ fn colorize_ordered(line: &str, colored: bool) -> String {
|
||||
line.to_string()
|
||||
}
|
||||
|
||||
/// Space between the field column and the value column.
|
||||
const METADATA_GUTTER: &str = " ";
|
||||
/// 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> {
|
||||
@@ -561,7 +617,7 @@ fn render_metadata_table(lines: &[&str], colored: bool) -> String {
|
||||
MetadataRow::Field { name, value } => {
|
||||
result.push_str(&paint(name, Color::Red, colored));
|
||||
result.push_str(&" ".repeat(field_width - name.chars().count()));
|
||||
result.push_str(METADATA_GUTTER);
|
||||
result.push_str(COLUMN_GUTTER);
|
||||
result.push_str(&metadata_value_cell(name, value, colored));
|
||||
}
|
||||
// The decision this row is rendered under, not the one the terminal
|
||||
@@ -778,6 +834,8 @@ pub enum SectionKind {
|
||||
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.
|
||||
@@ -816,6 +874,19 @@ pub const PLAN: Section = Section {
|
||||
kind: SectionKind::Numbered,
|
||||
};
|
||||
|
||||
/// 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,
|
||||
};
|
||||
|
||||
impl Section {
|
||||
/// The values a caller supplied, reduced to the lines that belong in the body.
|
||||
///
|
||||
@@ -824,7 +895,7 @@ impl Section {
|
||||
pub fn normalise(&self, values: &[String]) -> Vec<String> {
|
||||
match self.kind {
|
||||
SectionKind::Prose => trim_blank_ends(values).to_vec(),
|
||||
SectionKind::Checklist | SectionKind::Numbered => values
|
||||
SectionKind::Checklist | SectionKind::Numbered | SectionKind::Bullets => values
|
||||
.iter()
|
||||
.filter(|value| !value.trim().is_empty())
|
||||
.cloned()
|
||||
@@ -837,6 +908,7 @@ impl Section {
|
||||
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()
|
||||
@@ -853,17 +925,22 @@ fn is_numbered_item(line: &str) -> bool {
|
||||
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<std::ops::Range<usize>> {
|
||||
let at = lines.iter().position(|line| line.trim_end() == heading)?;
|
||||
let after = at + 1;
|
||||
let end = lines[after..]
|
||||
.iter()
|
||||
.position(|line| line.starts_with("## "))
|
||||
.map_or(lines.len(), |offset| after + offset);
|
||||
|
||||
Some(after..end)
|
||||
Some(after..section_end(lines, after))
|
||||
}
|
||||
|
||||
/// Where the body's content ends, ignoring the blank lines that separate it from
|
||||
@@ -936,6 +1013,334 @@ pub fn append_section_body(content: &str, section: &Section, items: &[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<String> = 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",
|
||||
}
|
||||
}
|
||||
|
||||
/// 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,
|
||||
];
|
||||
}
|
||||
|
||||
/// 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<Relation> {
|
||||
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::<Vec<_>>()
|
||||
.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<Vec<Relation>> {
|
||||
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<Relation>,
|
||||
}
|
||||
|
||||
/// 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<RelatedTicket>,
|
||||
}
|
||||
|
||||
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<RelatedTicket>) -> Self {
|
||||
Self { tickets }
|
||||
}
|
||||
|
||||
pub fn load(worklane_dir: &Path) -> Result<Self> {
|
||||
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)
|
||||
}
|
||||
|
||||
/// 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 relation's target as it reads: the short id, then the title.
|
||||
///
|
||||
/// `_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 {
|
||||
let id = paint(short_id(uuid), Color::Red, colored);
|
||||
|
||||
match target {
|
||||
Some(ticket) => format!("({}) {}", id, ticket.title),
|
||||
None => format!("({}) {}", id, paint("_missing_", Color::Grey, 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
|
||||
/// against it, named from this end. Rendered from the index rather than from the body
|
||||
/// alone, because a bare uuid says nothing and half the relations are not in the file.
|
||||
pub fn render_relations(
|
||||
stored: &[Relation],
|
||||
index: &RelationIndex,
|
||||
uuid: &str,
|
||||
colored: bool,
|
||||
) -> String {
|
||||
let mut rows: Vec<(&'static str, String)> = stored
|
||||
.iter()
|
||||
.map(|relation| {
|
||||
(
|
||||
relation.kind.label(),
|
||||
target_cell(index.get(&relation.target), &relation.target, colored),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
|
||||
rows.extend(index.inbound(uuid).into_iter().map(|(kind, holder)| {
|
||||
(
|
||||
kind.inverse_label(),
|
||||
target_cell(Some(holder), &holder.uuid, colored),
|
||||
)
|
||||
}));
|
||||
|
||||
if rows.is_empty() {
|
||||
return String::new();
|
||||
}
|
||||
|
||||
// Measured on the labels, which carry no colour, and padded before the target cell
|
||||
// is joined on, for the reason the metadata table is: an escape sequence counted
|
||||
// towards a width tilts the column the moment colour is on.
|
||||
let width = rows
|
||||
.iter()
|
||||
.map(|(label, _)| label.chars().count())
|
||||
.max()
|
||||
.unwrap_or(0);
|
||||
|
||||
let mut out = String::new();
|
||||
for (label, cell) in &rows {
|
||||
out.push_str(label);
|
||||
out.push_str(&" ".repeat(width - label.chars().count()));
|
||||
out.push_str(COLUMN_GUTTER);
|
||||
out.push_str(cell);
|
||||
out.push('\n');
|
||||
}
|
||||
|
||||
out
|
||||
}
|
||||
|
||||
/// The rendered Relations block for one ticket, reading the board for the rest of it.
|
||||
///
|
||||
/// The colour decision is passed in rather than asked for, like everything else the
|
||||
/// body renders: the board draws the same text with colour off.
|
||||
pub fn relations_block(content: &str, worklane_dir: &Path, colored: bool) -> Result<String> {
|
||||
let title = heading_title(content);
|
||||
let stored = parse_relations(content, &title)?;
|
||||
let index = RelationIndex::load(worklane_dir)?;
|
||||
|
||||
Ok(render_relations(
|
||||
&stored,
|
||||
&index,
|
||||
&parse_ticket_field(content, "ID"),
|
||||
colored,
|
||||
))
|
||||
}
|
||||
|
||||
/// 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.
|
||||
@@ -1307,11 +1712,10 @@ pub fn collect_ticket_items(status_path: impl AsRef<Path>) -> Result<Vec<TicketI
|
||||
.iter()
|
||||
.filter_map(|e| {
|
||||
let content = fs::read_to_string(e.path()).ok()?;
|
||||
let title = content
|
||||
.lines()
|
||||
.find(|l| l.starts_with("# "))
|
||||
.map(|l| l[2..].trim().to_string())
|
||||
.unwrap_or_else(|| "_No title_".to_string());
|
||||
let 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();
|
||||
@@ -1632,7 +2036,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, "");
|
||||
|
||||
assert!(
|
||||
!rendered.contains('\x1b'),
|
||||
@@ -1648,7 +2052,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, "");
|
||||
|
||||
assert!(
|
||||
rendered.contains(&format!("{}1.", Color::Cyan.ansi())),
|
||||
@@ -1750,7 +2154,7 @@ mod tests {
|
||||
|
||||
#[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", "");
|
||||
|
||||
// Eleven characters, not fourteen: the rule used to span "## Description"
|
||||
assert!(
|
||||
@@ -1761,14 +2165,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", "");
|
||||
|
||||
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", "");
|
||||
|
||||
assert!(!rendered.contains("Only Once"), "{rendered:?}");
|
||||
// And no gap where it was
|
||||
@@ -1778,7 +2182,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, "");
|
||||
|
||||
assert_eq!(rendered, "Metadata\n────────\n\nID abc\nOwner alice\n");
|
||||
}
|
||||
@@ -1786,7 +2190,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, "");
|
||||
|
||||
assert!(rendered.contains("ID abc"), "{rendered:?}");
|
||||
assert!(rendered.contains("Notes\n─────\n"), "{rendered:?}");
|
||||
@@ -2058,4 +2462,221 @@ mod tests {
|
||||
assert_eq!(format_created_at(value), "", "for {value:?}");
|
||||
}
|
||||
}
|
||||
// --------------------------------------------------------------- relations --
|
||||
|
||||
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<Relation>) -> 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"));
|
||||
}
|
||||
|
||||
#[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)];
|
||||
|
||||
assert_eq!(
|
||||
render_relations(&stored, &index, SELF, false),
|
||||
"regression of (b1b2c3d) The blocker\n\
|
||||
blocks (ccccccc) The other one\n\
|
||||
relates to (ccccccc) The other one\n"
|
||||
);
|
||||
}
|
||||
|
||||
/// 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)];
|
||||
|
||||
assert_eq!(
|
||||
render_relations(&stored, &RelationIndex::new(Vec::new()), SELF, false),
|
||||
"blocked by (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(&[], &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, "blocked by (b1b2c3d) The blocker\n");
|
||||
|
||||
assert!(
|
||||
rendered.contains("Relations\n─────────\n\nblocked by (b1b2c3d) The blocker\n\nMetadata"),
|
||||
"{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, "blocks (641e3d5) The gated one\n");
|
||||
|
||||
assert!(
|
||||
rendered.contains("Body.\n\nRelations\n─────────\n\nblocks (641e3d5) The gated one\n\nMetadata"),
|
||||
"{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, "blocks (641e3d5) X\n");
|
||||
|
||||
assert!(rendered.ends_with("Relations\n─────────\n\nblocks (641e3d5) X\n"), "{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, "");
|
||||
|
||||
assert!(rendered.contains("Relations\n─────────\n\n_No relations._\n"), "{rendered:?}");
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user