(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:
co-authored by
Claude Opus 5
parent
6c43e62a4b
commit
3810e442c6
@@ -37,6 +37,21 @@ pub struct Cli {
|
||||
pub command: Command,
|
||||
}
|
||||
|
||||
/// Reject an empty value at parse time, so it lands as a usage error rather than a
|
||||
/// runtime one.
|
||||
///
|
||||
/// An empty value looks like a way to clear a field, and clearing is not supported
|
||||
/// yet. Refusing it keeps the gap visible and stops an accidentally empty variable
|
||||
/// from silently blanking a field. Only the scalars use this: for the multi-line
|
||||
/// sections an empty value is a paragraph break.
|
||||
fn non_empty(raw: &str) -> Result<String, String> {
|
||||
if raw.trim().is_empty() {
|
||||
return Err("value cannot be empty, and clearing a field is not supported yet".to_string());
|
||||
}
|
||||
|
||||
Ok(raw.to_string())
|
||||
}
|
||||
|
||||
/// Arguments that carry prose, and therefore have to accept a value starting with
|
||||
/// a hyphen.
|
||||
///
|
||||
@@ -119,6 +134,12 @@ pub enum Command {
|
||||
force: bool,
|
||||
},
|
||||
|
||||
/// Replace fields on an existing ticket
|
||||
Set(SetArgs),
|
||||
|
||||
/// Add to a section of an existing ticket
|
||||
Append(AppendArgs),
|
||||
|
||||
/// Add a comment to a ticket
|
||||
Comment {
|
||||
/// Ticket UUID or title
|
||||
@@ -133,3 +154,74 @@ pub enum Command {
|
||||
owner: Option<String>,
|
||||
},
|
||||
}
|
||||
|
||||
/// `set` replaces a field outright. Owner is deliberately absent: `chown` owns that
|
||||
/// field, and status is `mv`'s, so no field has two writers.
|
||||
///
|
||||
/// The group makes at least one field mandatory, so a bare `worklane set <ticket>` is
|
||||
/// a usage error rather than a silent no-op.
|
||||
#[derive(clap::Args)]
|
||||
#[command(group(
|
||||
clap::ArgGroup::new("set_fields")
|
||||
.required(true)
|
||||
.multiple(true)
|
||||
.args(["title", "description", "acceptance", "plan", "tags", "due", "priority"])
|
||||
))]
|
||||
pub struct SetArgs {
|
||||
/// Ticket UUID or title
|
||||
pub ticket: String,
|
||||
|
||||
/// Replace the ticket title, renaming the file to match
|
||||
#[arg(short, long, allow_hyphen_values = PROSE, value_parser = non_empty)]
|
||||
pub title: Option<String>,
|
||||
|
||||
/// Replace the description. Repeat the flag for more lines, empty for a paragraph break
|
||||
#[arg(short, long, allow_hyphen_values = PROSE)]
|
||||
pub description: Vec<String>,
|
||||
|
||||
/// Replace the acceptance criteria. Repeat the flag, one criterium per value
|
||||
#[arg(short, long, allow_hyphen_values = PROSE)]
|
||||
pub acceptance: Vec<String>,
|
||||
|
||||
/// Replace the implementation plan. Repeat the flag, one step per value
|
||||
#[arg(short, long, allow_hyphen_values = PROSE)]
|
||||
pub plan: Vec<String>,
|
||||
|
||||
/// Replace the tags
|
||||
#[arg(short = 'g', long, value_parser = non_empty)]
|
||||
pub tags: Vec<String>,
|
||||
|
||||
/// Replace the due date (YYYY-MM-DD)
|
||||
#[arg(long, value_parser = non_empty)]
|
||||
pub due: Option<String>,
|
||||
|
||||
/// Replace the priority, 1 (most urgent) to 5 (least)
|
||||
#[arg(long, value_parser = priority_level)]
|
||||
pub priority: Option<u8>,
|
||||
}
|
||||
|
||||
/// `append` only offers the sections that hold multiple lines, since appending to a
|
||||
/// scalar has no meaning.
|
||||
#[derive(clap::Args)]
|
||||
#[command(group(
|
||||
clap::ArgGroup::new("append_fields")
|
||||
.required(true)
|
||||
.multiple(true)
|
||||
.args(["description", "acceptance", "plan"])
|
||||
))]
|
||||
pub struct AppendArgs {
|
||||
/// Ticket UUID or title
|
||||
pub ticket: String,
|
||||
|
||||
/// Add a paragraph to the description. Repeat the flag for more lines within it
|
||||
#[arg(short, long, allow_hyphen_values = PROSE)]
|
||||
pub description: Vec<String>,
|
||||
|
||||
/// Add acceptance criteria. Repeat the flag, one criterium per value
|
||||
#[arg(short, long, allow_hyphen_values = PROSE)]
|
||||
pub acceptance: Vec<String>,
|
||||
|
||||
/// Add implementation plan steps, numbered on from the last. Repeat the flag
|
||||
#[arg(short, long, allow_hyphen_values = PROSE)]
|
||||
pub plan: Vec<String>,
|
||||
}
|
||||
|
||||
+251
-63
@@ -4,6 +4,7 @@ use std::fs;
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
|
||||
use crate::command::{AppendArgs, SetArgs};
|
||||
use crate::util::*;
|
||||
|
||||
pub fn cmd_init(start: &Path) -> Result<()> {
|
||||
@@ -314,6 +315,82 @@ pub fn cmd_show(search: &str, worklane_dir: &Path) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Write `content` over `path`, without ever leaving half a file behind.
|
||||
///
|
||||
/// Staged in a temp file and renamed into place, because `fs::write` truncates before
|
||||
/// it writes and a partial write would corrupt the ticket. The temp sits under
|
||||
/// `.worklane/` rather than beside the ticket, so a leftover from a hard kill is
|
||||
/// invisible to ticket lookup and to the listing instead of showing up as a stray
|
||||
/// untitled ticket.
|
||||
fn write_then_replace(
|
||||
worklane_dir: &Path,
|
||||
path: &Path,
|
||||
filename: &str,
|
||||
content: &str,
|
||||
title: &str,
|
||||
) -> Result<()> {
|
||||
let temp = worklane_dir.join(format!(".wl-{}.tmp", filename));
|
||||
|
||||
if let Err(e) = fs::write(&temp, content) {
|
||||
let _ = fs::remove_file(&temp);
|
||||
return Err(anyhow!(
|
||||
"Could not stage the update for ticket '{}' at {}: {}",
|
||||
title,
|
||||
temp.display(),
|
||||
e
|
||||
));
|
||||
}
|
||||
|
||||
if let Err(e) = fs::rename(&temp, path) {
|
||||
let _ = fs::remove_file(&temp);
|
||||
return Err(anyhow!(
|
||||
"Could not write ticket '{}' at {}: {}",
|
||||
title,
|
||||
path.display(),
|
||||
e
|
||||
));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The ticket file in `dir` carrying `uuid`.
|
||||
///
|
||||
/// Matched on the uuid, not the title. Titles are not unique, `add` allows duplicates
|
||||
/// on purpose, so a title scan could land on a different ticket than the one that was
|
||||
/// resolved: `mv <uuid-of-second>` moved the first ticket sharing its title.
|
||||
fn find_ticket_file(dir: &Path, uuid: &str, title: &str) -> Result<String> {
|
||||
if uuid.trim().is_empty() || is_unknown_value(uuid) {
|
||||
return Err(anyhow!(
|
||||
"Ticket '{}' has no ID field, so its file cannot be located",
|
||||
title
|
||||
));
|
||||
}
|
||||
|
||||
for entry in fs::read_dir(dir)? {
|
||||
let entry = entry?;
|
||||
let path = entry.path();
|
||||
if !path.extension().map_or(false, |e| e == "md") {
|
||||
continue;
|
||||
}
|
||||
|
||||
let name = match path.file_name() {
|
||||
Some(name) => name.to_string_lossy().to_string(),
|
||||
None => continue,
|
||||
};
|
||||
|
||||
if name.starts_with(uuid) {
|
||||
return Ok(name);
|
||||
}
|
||||
}
|
||||
|
||||
Err(anyhow!(
|
||||
"Could not find the file for ticket '{}' in {}",
|
||||
title,
|
||||
dir.display()
|
||||
))
|
||||
}
|
||||
|
||||
/// Put `content` in `filename` and move it from `from` to `to`, without ever
|
||||
/// leaving the ticket in two status directories or with half a file in it.
|
||||
///
|
||||
@@ -338,30 +415,7 @@ fn move_ticket_file(
|
||||
let source = from.join(filename);
|
||||
let dest = to.join(filename);
|
||||
|
||||
// Staged outside the status directories on purpose: a temp file left behind by a
|
||||
// hard kill is then invisible to ticket lookup and to the listing, rather than
|
||||
// showing up as a stray untitled ticket.
|
||||
let temp = worklane_dir.join(format!(".mv-{}.tmp", filename));
|
||||
|
||||
if let Err(e) = fs::write(&temp, content) {
|
||||
let _ = fs::remove_file(&temp);
|
||||
return Err(anyhow!(
|
||||
"Could not stage the update for ticket '{}' at {}: {}",
|
||||
title,
|
||||
temp.display(),
|
||||
e
|
||||
));
|
||||
}
|
||||
|
||||
if let Err(e) = fs::rename(&temp, &source) {
|
||||
let _ = fs::remove_file(&temp);
|
||||
return Err(anyhow!(
|
||||
"Could not update the status of ticket '{}' at {}: {}",
|
||||
title,
|
||||
source.display(),
|
||||
e
|
||||
));
|
||||
}
|
||||
write_then_replace(worklane_dir, &source, filename, content, title)?;
|
||||
|
||||
// The content is correct and in one place by now, so a failure here leaves the
|
||||
// ticket where it started rather than half moved.
|
||||
@@ -388,7 +442,7 @@ pub fn cmd_mv(ticket_id: &str, target_status: &str, force: bool, start: &Path) -
|
||||
}
|
||||
|
||||
let worklane_dir = find_worklane_dir(start)?;
|
||||
let (current_status, title, _) = resolve_ticket(ticket_id, &worklane_dir)?;
|
||||
let (current_status, title, resolved) = resolve_ticket(ticket_id, &worklane_dir)?;
|
||||
|
||||
let current_idx = forward_order
|
||||
.iter()
|
||||
@@ -424,45 +478,12 @@ pub fn cmd_mv(ticket_id: &str, target_status: &str, force: bool, start: &Path) -
|
||||
let current_path = worklane_dir.join(¤t_status);
|
||||
let target_path = worklane_dir.join(target_status);
|
||||
|
||||
// Find the ticket file
|
||||
let mut found_filename = String::new();
|
||||
for entry in fs::read_dir(¤t_path)? {
|
||||
let entry = entry?;
|
||||
let path = entry.path();
|
||||
if path.extension().map_or(false, |e| e == "md") {
|
||||
let file_content = fs::read_to_string(&path)?;
|
||||
let file_title = file_content
|
||||
.lines()
|
||||
.find(|l| l.starts_with("# "))
|
||||
.map(|l| l[2..].trim())
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
if file_title == title {
|
||||
found_filename = path.file_name().unwrap().to_string_lossy().to_string();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Updated before the file is even located, so a ticket without a Status field is
|
||||
// refused for that reason rather than for whatever the lookup notices first.
|
||||
let content = set_status_field(&resolved, target_status, &title)?;
|
||||
|
||||
if found_filename.is_empty() {
|
||||
return Err(anyhow!(
|
||||
"Could not find ticket file in {}",
|
||||
color_text(¤t_status, "orange")
|
||||
));
|
||||
}
|
||||
|
||||
// Read and update the ticket content before touching the filesystem, so a ticket
|
||||
// without a Status field is never half-moved.
|
||||
let source_path = current_path.join(&found_filename);
|
||||
let content = fs::read_to_string(&source_path).map_err(|e| {
|
||||
anyhow!(
|
||||
"Could not read ticket '{}' at {}: {}",
|
||||
title,
|
||||
source_path.display(),
|
||||
e
|
||||
)
|
||||
})?;
|
||||
let content = set_status_field(&content, target_status, &title)?;
|
||||
let found_filename =
|
||||
find_ticket_file(¤t_path, &parse_ticket_field(&resolved, "ID"), &title)?;
|
||||
|
||||
move_ticket_file(
|
||||
&worklane_dir,
|
||||
@@ -561,3 +582,170 @@ pub fn cmd_comment(
|
||||
println!("Comment added to '{}' ({})", title, filename);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The sections `set` and `append` can rewrite, paired with the flag that carries them.
|
||||
///
|
||||
/// One list, so both commands walk the same table and a section added later needs no
|
||||
/// change here.
|
||||
fn section_args<'a>(
|
||||
description: &'a [String],
|
||||
acceptance: &'a [String],
|
||||
plan: &'a [String],
|
||||
) -> [(&'static Section, &'a [String]); 3] {
|
||||
[
|
||||
(&DESCRIPTION, description),
|
||||
(&ACCEPTANCE, acceptance),
|
||||
(&PLAN, plan),
|
||||
]
|
||||
}
|
||||
|
||||
/// Write the ticket back, renaming the file when a new title changes its slug.
|
||||
///
|
||||
/// The content goes down first and the rename second, the same order and for the same
|
||||
/// reason as `mv`: a failure at the rename leaves a correct ticket under a stale name,
|
||||
/// which lookup still finds by uuid or title, rather than a half-written one.
|
||||
fn save_ticket(
|
||||
worklane_dir: &Path,
|
||||
status: &str,
|
||||
uuid: &str,
|
||||
title: &str,
|
||||
new_title: Option<&String>,
|
||||
content: &str,
|
||||
) -> Result<()> {
|
||||
let status_path = worklane_dir.join(status);
|
||||
let filename = find_ticket_file(&status_path, uuid, title)?;
|
||||
let path = status_path.join(&filename);
|
||||
|
||||
write_then_replace(worklane_dir, &path, &filename, content, title)?;
|
||||
|
||||
// The uuid is kept, so the new name cannot collide with another ticket, and an
|
||||
// unchanged slug means there is nothing to rename.
|
||||
if let Some(new_title) = new_title {
|
||||
let renamed = format!("{}_{}.md", uuid, slug(new_title));
|
||||
if renamed != filename {
|
||||
let destination = status_path.join(&renamed);
|
||||
fs::rename(&path, &destination).map_err(|e| {
|
||||
anyhow!(
|
||||
"Ticket '{}' was updated but could not be renamed to {}: {}",
|
||||
title,
|
||||
destination.display(),
|
||||
e
|
||||
)
|
||||
})?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn report(fields: &[&str], title: &str, verb: &str) {
|
||||
if fields.is_empty() {
|
||||
println!("No changes to '{}'", color_text(title, "green"));
|
||||
return;
|
||||
}
|
||||
|
||||
println!(
|
||||
"{} {} on '{}'",
|
||||
verb,
|
||||
fields.join(", "),
|
||||
color_text(title, "green")
|
||||
);
|
||||
}
|
||||
|
||||
pub fn cmd_set(args: &SetArgs, start: &Path) -> Result<()> {
|
||||
let worklane_dir = find_worklane_dir(start)?;
|
||||
let (status, title, original) = resolve_ticket(&args.ticket, &worklane_dir)?;
|
||||
let uuid = parse_ticket_field(&original, "ID");
|
||||
|
||||
let mut content = original.clone();
|
||||
let mut changed: Vec<&str> = Vec::new();
|
||||
|
||||
// Each edit is compared against the content going in, so a field set to the value
|
||||
// it already holds is reported as unchanged rather than claimed as an update.
|
||||
let mut apply = |content: &mut String, field: &'static str, next: String| {
|
||||
if *content != next {
|
||||
content.clone_from(&next);
|
||||
changed.push(field);
|
||||
}
|
||||
};
|
||||
|
||||
if let Some(new_title) = &args.title {
|
||||
let next = set_title(&content, new_title)?;
|
||||
apply(&mut content, "title", next);
|
||||
}
|
||||
|
||||
for (section, values) in section_args(&args.description, &args.acceptance, &args.plan) {
|
||||
if values.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let items = section.normalise(values);
|
||||
if items.is_empty() {
|
||||
return Err(anyhow!(
|
||||
"An empty {} is not a way to clear the section, and clearing is not supported yet",
|
||||
section.label
|
||||
));
|
||||
}
|
||||
|
||||
let next = set_section_body(&content, section, &items)?;
|
||||
apply(&mut content, section.label, next);
|
||||
}
|
||||
|
||||
if !args.tags.is_empty() {
|
||||
let next = set_metadata_field(&content, "Tags", &args.tags.join(", "), &title)?;
|
||||
apply(&mut content, "tags", next);
|
||||
}
|
||||
|
||||
if let Some(due) = &args.due {
|
||||
let next = set_metadata_field(&content, "Due", due, &title)?;
|
||||
apply(&mut content, "due", next);
|
||||
}
|
||||
|
||||
if let Some(priority) = args.priority {
|
||||
let next = set_metadata_field(&content, "Priority", &priority.to_string(), &title)?;
|
||||
apply(&mut content, "priority", next);
|
||||
}
|
||||
|
||||
if changed.is_empty() {
|
||||
report(&changed, &title, "Updated");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let renamed = changed.contains(&"title").then_some(()).and(args.title.as_ref());
|
||||
save_ticket(&worklane_dir, &status, &uuid, &title, renamed, &content)?;
|
||||
|
||||
let shown = args.title.clone().unwrap_or(title);
|
||||
report(&changed, &shown, "Updated");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn cmd_append(args: &AppendArgs, start: &Path) -> Result<()> {
|
||||
let worklane_dir = find_worklane_dir(start)?;
|
||||
let (status, title, original) = resolve_ticket(&args.ticket, &worklane_dir)?;
|
||||
let uuid = parse_ticket_field(&original, "ID");
|
||||
|
||||
let mut content = original.clone();
|
||||
let mut changed: Vec<&str> = Vec::new();
|
||||
|
||||
for (section, values) in section_args(&args.description, &args.acceptance, &args.plan) {
|
||||
if values.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let items = section.normalise(values);
|
||||
if items.is_empty() {
|
||||
return Err(anyhow!(
|
||||
"Nothing to append to the {}: every value given was blank",
|
||||
section.label
|
||||
));
|
||||
}
|
||||
|
||||
content = append_section_body(&content, section, &items)?;
|
||||
changed.push(section.label);
|
||||
}
|
||||
|
||||
save_ticket(&worklane_dir, &status, &uuid, &title, None, &content)?;
|
||||
|
||||
report(&changed, &title, "Appended to");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -70,6 +70,8 @@ fn main() -> Result<()> {
|
||||
status,
|
||||
force,
|
||||
} => cmd_mv(&ticket, &status, force, &start),
|
||||
Command::Set(args) => cmd_set(&args, &start),
|
||||
Command::Append(args) => cmd_append(&args, &start),
|
||||
Command::Comment { ticket, body, owner } => cmd_comment(&ticket, &body, &owner, &start),
|
||||
}
|
||||
}
|
||||
|
||||
+237
-13
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user