(da03690) Add set and append for editing a ticket, and bump to 0.5.0

Nothing could change a ticket after it was created. mv wrote status, comment
appended a file, and that was the whole set of mutations, so correcting a typo
or adding a criterion meant hand editing the markdown.

Two commands rather than the one vague "edit" the ticket described. set replaces
a field, append adds to a section, so the verb carries the meaning instead of a
prefix on seven flag names, and append only offers the three sections that hold
multiple lines. Owner is absent from both, it belongs to the chown command filed
alongside this, and status stays mv's. One field, one writer.

Sections are a table, DESCRIPTION, ACCEPTANCE and PLAN, each carrying a heading,
a label, the placeholder add writes when empty, and a kind. Both commands walk
it, so a section added later is one entry rather than edits in two places.

Everything is targeted line surgery and never a regenerated file, which is what
keeps a ticked criterion ticked and a handwritten section intact when an
unrelated field changes. Appending to a numbered section continues from the
count already there rather than renumbering above it, so a handwritten line
survives exactly as written. Appending to an empty section replaces the
placeholder instead of following it.

An empty value is a paragraph break for a section and a usage error for a
scalar, since it looks like a way to clear a field and clearing is not supported
yet. No-op detection compares the whole file before and after each edit, so a
field set to the value it already holds is reported unchanged and nothing is
written.

Two things came out of building it. move_ticket_file's staged write is extracted
as write_then_replace, now the only way any ticket file is written. And the file
is located by uuid rather than by title: titles are not unique, add allows
duplicates on purpose, and the old title scan meant mv <uuid-of-second> moved
the first ticket sharing its title. Reproduced, fixed, and pinned by a test.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Ansho Rei
2026-08-21 02:36:20 +02:00
co-authored by Claude Opus 5
parent 6c43e62a4b
commit 3810e442c6
12 changed files with 1216 additions and 79 deletions
+237 -13
View File
@@ -578,12 +578,20 @@ fn is_status_line(line: &str) -> bool {
body.starts_with("**Status**:") || body.starts_with("**-Status**:")
}
// Rewrite the Status field in the Metadata section, leaving every other line untouched.
//
// Scoped to the section for the same reason as parse_ticket_field: a description line
// shaped like the Status field would otherwise be rewritten in its place, corrupting
// the prose and leaving the real metadata stale.
pub fn set_status_field(content: &str, target_status: &str, title: &str) -> Result<String> {
/// Rewrite one field in the Metadata section, leaving every other line untouched.
///
/// Scoped to the section for the same reason as `parse_ticket_field`: a description
/// line shaped like a metadata field would otherwise be rewritten in its place,
/// corrupting the prose and leaving the real metadata stale.
///
/// The matcher is a parameter because Status has a legacy spelling to repair, which no
/// other field has.
fn set_metadata_line(
content: &str,
field: &str,
value: &str,
matches: impl Fn(&str) -> bool,
) -> Option<String> {
let mut updated = String::with_capacity(content.len());
let mut in_metadata = false;
let mut found = false;
@@ -593,9 +601,62 @@ pub fn set_status_field(content: &str, target_status: &str, title: &str) -> Resu
in_metadata = is_metadata_heading(line);
}
if in_metadata && !found && is_status_line(line) {
updated.push_str("- **Status**: ");
updated.push_str(target_status);
if in_metadata && !found && matches(line) {
updated.push_str("- **");
updated.push_str(field);
updated.push_str("**: ");
updated.push_str(value);
found = true;
} else {
updated.push_str(line);
}
updated.push('\n');
}
if found { Some(updated) } else { None }
}
pub fn set_status_field(content: &str, target_status: &str, title: &str) -> Result<String> {
set_metadata_line(content, "Status", target_status, is_status_line).ok_or_else(|| {
anyhow!(
"Ticket '{}' has no Status field in its Metadata section",
title
)
})
}
/// Rewrite a metadata field other than Status.
///
/// A field that is not already in the file is an error rather than an insertion. Every
/// ticket `add` writes carries the full set in a fixed order, and nothing else writes
/// these files, so a missing field means a hand-made ticket and guessing where the line
/// belongs would be inventing a format.
pub fn set_metadata_field(content: &str, field: &str, value: &str, title: &str) -> Result<String> {
let prefix = format!("**{}**:", field);
set_metadata_line(content, field, value, |line| {
metadata_field_body(line).starts_with(&prefix)
})
.ok_or_else(|| {
anyhow!(
"Ticket '{}' has no {} field in its Metadata section",
title,
field
)
})
}
/// Rewrite the title heading, the first `# ` line in the file.
///
/// `## ` headings do not match: the second character has to be a space.
pub fn set_title(content: &str, title: &str) -> Result<String> {
let mut updated = String::with_capacity(content.len());
let mut found = false;
for line in content.lines() {
if !found && line.starts_with("# ") {
updated.push_str("# ");
updated.push_str(title);
found = true;
} else {
updated.push_str(line);
@@ -604,10 +665,7 @@ pub fn set_status_field(content: &str, target_status: &str, title: &str) -> Resu
}
if !found {
return Err(anyhow!(
"Ticket '{}' has no Status field in its Metadata section",
title
));
return Err(anyhow!("Ticket '{}' has no title heading", title));
}
Ok(updated)
@@ -625,6 +683,172 @@ pub fn format_created_at(created_at: &str) -> String {
}
}
/// How a section stores the lines the tool owns.
pub enum SectionKind {
/// Lines as written, a blank one acting as a paragraph break.
Prose,
/// One `- [ ] ` item per line.
Checklist,
/// One `N. ` step per line.
Numbered,
}
/// A section of a ticket whose body `set` and `append` can rewrite.
///
/// A table rather than a match arm per section, so adding a section later is one entry
/// here instead of edits spread across both commands.
pub struct Section {
pub heading: &'static str,
/// How the section is named in output, lowercase so it reads the same way the
/// metadata field labels do.
pub label: &'static str,
/// What `add` writes when the section is left empty. Treated as no content, so
/// appending to an empty section replaces the placeholder rather than following it.
pub placeholder: &'static str,
pub kind: SectionKind,
}
pub const DESCRIPTION: Section = Section {
heading: "## Description",
label: "description",
placeholder: "_No description provided._",
kind: SectionKind::Prose,
};
pub const ACCEPTANCE: Section = Section {
heading: "## Acceptance Criteria",
label: "acceptance criteria",
placeholder: "_No acceptance criteria provided._",
kind: SectionKind::Checklist,
};
pub const PLAN: Section = Section {
heading: "## Implementation Plan",
label: "implementation plan",
placeholder: "_No implementation plan provided._",
kind: SectionKind::Numbered,
};
impl Section {
/// The values a caller supplied, reduced to the lines that belong in the body.
///
/// Prose keeps interior blanks, since those are paragraph breaks. A list has one
/// item per value, so a blank there is nothing at all.
pub fn normalise(&self, values: &[String]) -> Vec<String> {
match self.kind {
SectionKind::Prose => trim_blank_ends(values).to_vec(),
SectionKind::Checklist | SectionKind::Numbered => values
.iter()
.filter(|value| !value.trim().is_empty())
.cloned()
.collect(),
}
}
/// `items` as body lines, numbering from `first` where the section is numbered.
fn render(&self, items: &[String], first: usize) -> Vec<String> {
match self.kind {
SectionKind::Prose => items.to_vec(),
SectionKind::Checklist => items.iter().map(|i| format!("- [ ] {}", i)).collect(),
SectionKind::Numbered => items
.iter()
.enumerate()
.map(|(offset, step)| format!("{}. {}", first + offset, step))
.collect(),
}
}
}
/// Whether the line opens with `N. `, the shape a numbered step is stored in.
fn is_numbered_item(line: &str) -> bool {
let digits = line.chars().take_while(|c| c.is_ascii_digit()).count();
// ASCII digits are one byte each, so the count is also the byte offset.
digits > 0 && line[digits..].starts_with(". ")
}
/// 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)
}
/// Where the body's content ends, ignoring the blank lines that separate it from
/// whatever follows.
fn body_content_end(lines: &[&str], body: &std::ops::Range<usize>) -> usize {
let mut end = body.end;
while end > body.start && lines[end - 1].trim().is_empty() {
end -= 1;
}
end
}
fn join_lines(lines: &[String]) -> String {
let mut out = lines.join("\n");
out.push('\n');
out
}
/// Replace a section's body with `items`, leaving every line outside it untouched.
pub fn set_section_body(content: &str, section: &Section, items: &[String]) -> Result<String> {
let lines: Vec<&str> = content.lines().collect();
let body = section_body(&lines, section.heading)
.ok_or_else(|| anyhow!("Ticket has no {} section", section.label))?;
let mut out: Vec<String> = lines[..body.start].iter().map(|l| l.to_string()).collect();
out.extend(section.render(items, 1));
// One blank line before whatever section follows, matching how `add` writes it.
if body.end < lines.len() {
out.push(String::new());
}
out.extend(lines[body.end..].iter().map(|l| l.to_string()));
Ok(join_lines(&out))
}
/// Add `items` to the end of a section's body.
///
/// Prose gains a blank line first, so the addition reads as a new paragraph. A numbered
/// section continues from the count of steps already there rather than renumbering what
/// is above it, which keeps any handwritten line in the section exactly as it was.
pub fn append_section_body(content: &str, section: &Section, items: &[String]) -> Result<String> {
let lines: Vec<&str> = content.lines().collect();
let body = section_body(&lines, section.heading)
.ok_or_else(|| anyhow!("Ticket has no {} section", section.label))?;
let at = body_content_end(&lines, &body);
let existing: Vec<&&str> = lines[body.start..at]
.iter()
.filter(|line| !line.trim().is_empty())
.collect();
// An empty section is a placeholder, and following it with a paragraph would leave
// "_No description provided._" above the description.
if existing.len() == 1 && existing[0].trim() == section.placeholder {
return set_section_body(content, section, items);
}
let first = match section.kind {
SectionKind::Numbered => 1 + existing.iter().filter(|l| is_numbered_item(l)).count(),
_ => 1,
};
let mut out: Vec<String> = lines[..at].iter().map(|l| l.to_string()).collect();
if matches!(section.kind, SectionKind::Prose) && at > body.start {
out.push(String::new());
}
out.extend(section.render(items, first));
out.extend(lines[at..].iter().map(|l| l.to_string()));
Ok(join_lines(&out))
}
/// The slice with blank values trimmed from both ends, interior ones kept.
///
/// Description values are joined with a single newline, so an empty value is how a