(74904dc) Let a ticket field be cleared back to unset, and bump to 0.18.0

`set --clear <field>` is the one way to take a value away, repeatable, with
the field as a `ValueEnum` value: an unknown one is a usage error listing the
six that are not, and the shells complete them for free. Not a per-field
`--clear-due`, which is a flag per field to keep in step with the one it
undoes, and not an empty value, which is already a paragraph break for a
section and would make an accidentally empty variable a silent delete.

What goes back is what `add` writes for a field it was never given, through
the new `NOT_SET` and `NONE` constants and each section's placeholder, so a
cleared ticket and one filed without the field read the same. Sections are in
scope and go back through `clear_section_body` rather than
`set_section_body`: the latter runs its items through `Section::render`, which
would have written `- [ ] _No acceptance criteria provided._`.

Owner is `chown --clear <ticket>`, so the field keeps its one writer. The flag
carries the ticket because the ticket is chown's second positional and a bare
flag would land it in the user's slot for the handler to read back out, which
is hand-parsing what clap can state. It writes `_Not set_` rather than the git
user: `add` falls back to the git user because it is filing something new, and
an owner taken away says nobody owns this.

The empty-value error split in two rather than being reworded. `non_empty`
says only that the value cannot be empty, for the arguments with no empty
form; `clearable` names `--clear`, for the arguments whose field has one. One
message for both would have lied about `ls --tag`.

Replacing and clearing one field in a single call is refused rather than
resolved by whichever was applied last, and cleared fields are reported as
`Cleared due on '...'` beside `Updated priority on '...'`, since one list
would say `Updated` of a field that was emptied.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Ansho Rei
2026-08-23 00:04:28 +02:00
co-authored by Claude Opus 5
parent 175c1d016d
commit cc5f9b8a46
15 changed files with 810 additions and 92 deletions
+105 -18
View File
@@ -4,7 +4,7 @@ use std::sync::LazyLock;
use chrono::NaiveDate;
use crate::util::{PRIORITY_RANGE, RelationKind, Status, priority_legend};
use crate::util::{Clearable, PRIORITY_RANGE, RelationKind, Status, priority_legend};
/// clap wants a `&str` with a long enough lifetime, and the legend is built from
/// the same ramp the listing uses rather than spelled out a second time.
@@ -43,13 +43,31 @@ pub struct Cli {
/// 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.
/// Two messages rather than one, because the arguments that use this fall into two
/// kinds. A search term or a title has no empty form at all, and that is all this says.
/// A field that *can* be emptied says so and names `--clear`, which is [`clearable`]
/// below: an accidentally empty variable must not blank a field silently, and somebody
/// typing an empty value on purpose is reaching for exactly the flag that does it.
///
/// Only the scalars use either one. 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());
return Err("value cannot be empty".to_string());
}
Ok(raw.to_string())
}
/// Reject an empty value on an argument whose field can be cleared, and say how.
///
/// The message names no command, because the arguments that use this belong to three:
/// `set --tags`, `set --due`, `add --due` and the `chown` user. `set` and `chown` both
/// take a `--clear`; `add` does not, and there a field is left unset by omitting the
/// flag, which is what the caller was reaching for anyway.
fn clearable(raw: &str) -> Result<String, String> {
if raw.trim().is_empty() {
return Err("value cannot be empty, use --clear to return a field to unset".to_string());
}
Ok(raw.to_string())
@@ -73,7 +91,7 @@ fn non_empty(raw: &str) -> Result<String, String> {
fn iso_date(raw: &str) -> Result<String, String> {
// An empty value keeps the message that explains why it is refused, since somebody
// typing it is reaching for a way to clear the field rather than mistyping a date.
non_empty(raw)?;
clearable(raw)?;
let bytes = raw.as_bytes();
let shaped = raw.len() == 10 && bytes[4] == b'-' && bytes[7] == b'-';
@@ -143,7 +161,7 @@ pub enum Command {
/// Record a relation from one ticket to another
Relate(RelateArgs),
/// Change the owner of a ticket
/// Change the owner of a ticket, or return it to unset
///
/// User first, ticket second, after Unix `chown`. That reverses the ticket-first
/// order `mv`, `comment` and `show` use, deliberately: the name borrows the Unix
@@ -154,14 +172,7 @@ pub enum Command {
/// username usually will not, so the call fails on its own. It is silently wrong
/// only when both arguments resolve, which needs a ticket whose title matches the
/// username.
Chown {
/// New owner. Free text, like `add --owner`, checked against nothing
#[arg(value_parser = non_empty)]
user: String,
/// Ticket UUID or title
ticket: String,
},
Chown(ChownArgs),
/// Open the board view
Tui {
@@ -361,7 +372,7 @@ pub struct AddArgs {
clap::ArgGroup::new("set_fields")
.required(true)
.multiple(true)
.args(["title", "description", "acceptance", "plan", "tags", "due", "priority"])
.args(["title", "description", "acceptance", "plan", "tags", "due", "priority", "clear"])
))]
pub struct SetArgs {
/// Ticket UUID or title
@@ -384,7 +395,7 @@ pub struct SetArgs {
pub plan: Vec<String>,
/// Replace the tags
#[arg(short = 'g', long, value_parser = non_empty)]
#[arg(short = 'g', long, value_parser = clearable)]
pub tags: Vec<String>,
/// Replace the due date (YYYY-MM-DD)
@@ -398,6 +409,82 @@ pub struct SetArgs {
/// Replace the priority, 1 (most urgent) to 5 (least)
#[arg(long, value_parser = priority_level)]
pub priority: Option<u8>,
/// Return a field to unset. Repeat the flag for more than one
///
/// The counterpart to the flag it names, and the only way to take a value away: an
/// empty value is a paragraph break for a section and a usage error for a scalar, so
/// neither can spell this. What goes back is what `add` writes for a field it was
/// never given.
///
/// No `title`, which addresses the ticket and names its file, and no `owner`, which
/// is `chown --clear`'s. The reasoning for each is on `util::Clearable`.
#[arg(long, value_name = "FIELD")]
pub clear: Vec<Clearable>,
}
impl SetArgs {
/// A field this call both replaces and clears, if there is one.
///
/// clap cannot express the conflict, because `--clear` carries the field as a value
/// rather than in the flag's own name. So it is checked once here and refused, rather
/// than resolved by whichever of the two happens to be applied last, which is a
/// silent answer to a contradictory call.
pub fn contested(&self) -> Option<Clearable> {
self.clear.iter().copied().find(|field| match field {
Clearable::Due => self.due.is_some(),
Clearable::Tags => !self.tags.is_empty(),
Clearable::Priority => self.priority.is_some(),
Clearable::Description => !self.description.is_empty(),
Clearable::Acceptance => !self.acceptance.is_empty(),
Clearable::Plan => !self.plan.is_empty(),
})
}
}
/// `chown` is the only writer of Owner, so clearing the field has to live here too, and
/// that is what shapes the arguments.
///
/// **`--clear` carries the ticket rather than being a bare flag.** The ticket is the
/// *second* positional, so `chown --clear 1b78a24` with a plain flag would land the
/// ticket in the user's slot, and reading it back out of there is hand-parsing what clap
/// can state outright. The typed call is the same either way; only who checks it differs.
///
/// The two forms are mutually exclusive, and each argument says so, so a call carrying
/// both is a usage error from clap rather than a decision made here.
#[derive(clap::Args)]
pub struct ChownArgs {
/// New owner. Free text, like `add --owner`, checked against nothing
#[arg(value_parser = clearable, required_unless_present = "clear", conflicts_with = "clear")]
pub user: Option<String>,
/// Ticket UUID or title
#[arg(required_unless_present = "clear", conflicts_with = "clear")]
pub ticket: Option<String>,
/// Return the owner to unset on this ticket, which is named here since there is no
/// user to name
#[arg(long, value_name = "TICKET", value_parser = non_empty)]
pub clear: Option<String>,
}
impl ChownArgs {
/// The ticket the call names, and the owner to write on it, `None` being unset.
///
/// `None` for the pair is unreachable while the constraints above hold, and is an
/// error at the call site rather than a panic, so loosening one of them costs a
/// message instead of a crash.
pub fn target(&self) -> Option<(&str, Option<&str>)> {
match (
self.clear.as_deref(),
self.user.as_deref(),
self.ticket.as_deref(),
) {
(Some(ticket), None, None) => Some((ticket, None)),
(None, Some(user), Some(ticket)) => Some((ticket, Some(user))),
_ => None,
}
}
}
/// `append` only offers the sections that hold multiple lines, since appending to a
+27
View File
@@ -118,6 +118,11 @@ complete -c worklane \
# than by position.
complete -c worklane {ticket_flags} -x -a '(worklane ls --ids)'
# `chown --clear` names the ticket in the flag too, since with no user to give there is
# no second positional to put it in. Scoped to `chown`, unlike the rule above: `set`
# has a `--clear` of its own that takes a field name, and clap already offers those.
complete -c worklane -n '__fish_seen_subcommand_from chown' -l clear -x -a '(worklane ls --ids)'
# clap emits the four for `mv --status`, which is an option, but the fish generator
# emits nothing for the possible values of a positional. So the one place a status is
# positional needs them listed, and the same goes for the shell below.
@@ -198,6 +203,28 @@ mod tests {
}
}
/// `chown --clear` takes a ticket, so it is completed like one, and only under
/// `chown`: `set --clear` is the same flag name carrying a field.
#[test]
fn chowns_clear_is_completed_with_tickets_and_sets_is_not() {
let script = fish_dynamic();
let rule = script
.lines()
.find(|line| line.starts_with("complete") && line.contains("-l clear"))
.expect("chown --clear has a rule of its own");
assert!(rule.contains("__fish_seen_subcommand_from chown"), "{rule}");
assert!(rule.contains("worklane ls --ids"), "{rule}");
let chown = command().find_subcommand("chown").expect("chown exists").clone();
assert!(
chown.get_arguments().any(|arg| arg.get_long() == Some("clear")),
"`chown` has no --clear for the rule to complete"
);
assert!(
!TICKET_FLAGS.contains(&"clear"),
"--clear in TICKET_FLAGS would offer tickets to `set --clear`, which takes a field"
);
}
/// The flags completed as tickets have to be `relate`'s actual flags, or the rule
/// completes an option nothing accepts.
#[test]
+69 -24
View File
@@ -6,7 +6,7 @@ use std::path::Path;
use crate::campaign::*;
use crate::command::{
AddArgs, AppendArgs, CampaignAddArgs, CheckArgs, LsArgs, RelateArgs, SetArgs,
AddArgs, AppendArgs, CampaignAddArgs, CheckArgs, ChownArgs, LsArgs, RelateArgs, SetArgs,
};
use crate::install;
use crate::util::*;
@@ -805,6 +805,19 @@ fn save_ticket(
Ok(())
}
/// Take an edit, or record that it changed nothing.
///
/// 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. That is also
/// what makes clearing an already unset field free: the sentinel it writes is the one
/// already there, so the strings match and nothing is written.
fn apply(content: &mut String, changed: &mut Vec<&'static str>, field: &'static str, next: String) {
if *content != next {
content.clone_from(&next);
changed.push(field);
}
}
fn report(fields: &[&str], title: &str, verb: &str) {
if fields.is_empty() {
println!("No changes to '{}'", color_text(title, Color::Green));
@@ -820,25 +833,24 @@ fn report(fields: &[&str], title: &str, verb: &str) {
}
pub fn cmd_set(args: &SetArgs, start: &Path) -> Result<()> {
if let Some(field) = args.contested() {
let name = field.name();
return Err(anyhow!(
"--{name} and --clear {name} contradict each other, so nothing was written"
));
}
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);
}
};
let mut cleared: Vec<&str> = Vec::new();
if let Some(new_title) = &args.title {
let next = set_title(&content, new_title)?;
apply(&mut content, "title", next);
apply(&mut content, &mut changed, "title", next);
}
for (section, values) in section_args(&args.description, &args.acceptance, &args.plan) {
@@ -849,32 +861,46 @@ pub fn cmd_set(args: &SetArgs, start: &Path) -> Result<()> {
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
"An empty value is a paragraph break, not a way to empty the {}: use --clear {}",
section.label,
section.clear.map_or("", Clearable::name)
));
}
let next = set_section_body(&content, section, &items)?;
apply(&mut content, section.label, next);
apply(&mut content, &mut changed, section.label, next);
}
if !args.tags.is_empty() {
let next = set_metadata_field(&content, "Tags", &args.tags.join(", "), &title)?;
apply(&mut content, "tags", next);
apply(&mut content, &mut changed, "tags", next);
}
if let Some(due) = &args.due {
let next = set_metadata_field(&content, "Due", due, &title)?;
apply(&mut content, "due", next);
apply(&mut content, &mut changed, "due", next);
}
if let Some(priority) = args.priority {
let next = set_metadata_field(&content, "Priority", &priority.to_string(), &title)?;
apply(&mut content, "priority", next);
apply(&mut content, &mut changed, "priority", next);
}
if changed.is_empty() {
report(&changed, &title, "Updated");
// Last, and into a list of their own. No field can be in both, since `contested`
// refused that above, so the order is free and the report is what decides it: a
// caller is told what was replaced and what was emptied in those words.
for field in &args.clear {
let next = match field.unset() {
Unset::Field { field, sentinel } => {
set_metadata_field(&content, field, sentinel, &title)?
}
Unset::Section(section) => clear_section_body(&content, section)?,
};
apply(&mut content, &mut cleared, field.label(), next);
}
if changed.is_empty() && cleared.is_empty() {
report(&[], &title, "Updated");
return Ok(());
}
@@ -882,7 +908,12 @@ pub fn cmd_set(args: &SetArgs, start: &Path) -> Result<()> {
save_ticket(&worklane_dir, &status, &uuid, &title, renamed, &content)?;
let shown = args.title.clone().unwrap_or(title);
report(&changed, &shown, "Updated");
if !changed.is_empty() {
report(&changed, &shown, "Updated");
}
if !cleared.is_empty() {
report(&cleared, &shown, "Cleared");
}
Ok(())
}
@@ -895,13 +926,23 @@ pub fn cmd_set(args: &SetArgs, start: &Path) -> Result<()> {
/// stay silent on the one it cannot, a ticket whose title is the username.
///
/// No-op detection compares the whole file, the way `set` does, so an owner set to the
/// value it already holds is reported unchanged and nothing is written.
pub fn cmd_chown(user: &str, ticket_id: &str, start: &Path) -> Result<()> {
/// value it already holds is reported unchanged and nothing is written. The same
/// comparison is what makes clearing an already unset owner free.
///
/// **Clearing writes [`NOT_SET`], not the git user.** `add` falls back to the git user
/// for a ticket it is filing, which is a default for something new; an owner taken away
/// says nobody owns this, and putting the person running the command there instead would
/// hand them a ticket they were giving up.
pub fn cmd_chown(args: &ChownArgs, start: &Path) -> Result<()> {
let (ticket_id, user) = args.target().ok_or_else(|| {
anyhow!("chown takes a user and a ticket, or --clear with the ticket alone")
})?;
let worklane_dir = find_worklane_dir(start)?;
let (status, title, original) = resolve_ticket(ticket_id, &worklane_dir)?;
let uuid = parse_ticket_field(&original, "ID");
let content = set_metadata_field(&original, "Owner", user, &title)?;
let content = set_metadata_field(&original, "Owner", user.unwrap_or(NOT_SET), &title)?;
if content == original {
report(&[], &title, "Updated");
@@ -910,7 +951,11 @@ pub fn cmd_chown(user: &str, ticket_id: &str, start: &Path) -> Result<()> {
save_ticket(&worklane_dir, &status, &uuid, &title, None, &content)?;
report(&["owner"], &title, "Updated");
let verb = match user {
Some(_) => "Updated",
None => "Cleared",
};
report(&["owner"], &title, verb);
Ok(())
}
+1 -1
View File
@@ -387,7 +387,7 @@ mod tests {
for required in [
"Propose the whole set of edits",
"replaces the whole\nfield", // `set --tags` is the destructive one
"cannot be cleared", // and a due date cannot be taken back
"not\nback to what it held", // and --clear is not an undo
"blocked by", // ordering constrains any dating plan
"worklane campaign ls",
"does not touch",
+1 -1
View File
@@ -63,7 +63,7 @@ fn main() -> Result<()> {
Some(Command::Set(args)) => cmd_set(&args, &start),
Some(Command::Append(args)) => cmd_append(&args, &start),
Some(Command::Relate(args)) => cmd_relate(&args, &start),
Some(Command::Chown { user, ticket }) => cmd_chown(&user, &ticket, &start),
Some(Command::Chown(args)) => cmd_chown(&args, &start),
Some(Command::Check(args)) => cmd_check(&args, true, &start),
Some(Command::Uncheck(args)) => cmd_check(&args, false, &start),
Some(Command::Comment {
+209 -3
View File
@@ -936,9 +936,22 @@ fn render_metadata_table(lines: &[&str], colored: bool, campaign: &str) -> Strin
result
}
/// What a scalar metadata field holds when it holds nothing.
///
/// A constant rather than a literal per site, because it is now written on purpose:
/// clearing a field puts it back, and the value it goes back to has to be the one `add`
/// wrote, or a cleared ticket and a never-set one would differ in the file.
pub const NOT_SET: &str = "_Not set_";
/// The same for Tags, which is a list.
///
/// A list that holds nothing reads as none rather than as not set, which is the
/// distinction `add` already makes and clearing has to keep.
pub const NONE: &str = "_None_";
pub fn is_unknown_value(value: &str) -> bool {
let trimmed = value.trim();
trimmed == "_None_" || trimmed == "_Not set_" || trimmed == "-None-" || trimmed == "-Not set-"
trimmed == NONE || trimmed == NOT_SET || trimmed == "-None-" || trimmed == "-Not set-"
}
/// Replace `**bold**` with colour, or leave the line exactly as it is.
@@ -1017,7 +1030,7 @@ pub fn parse_ticket_field(content: &str, field: &str) -> String {
metadata_lines(content)
.find_map(|line| metadata_field_body(line).strip_prefix(&prefix))
.map(|value| value.trim().to_string())
.unwrap_or_else(|| "_Not set_".to_string())
.unwrap_or_else(|| NOT_SET.to_string())
}
fn is_status_line(line: &str) -> bool {
@@ -1371,6 +1384,12 @@ pub struct Section {
/// appending to an empty section replaces the placeholder rather than following it.
pub placeholder: &'static str,
pub kind: SectionKind,
/// The `--clear` value that empties this section, where `set` can reach it at all.
///
/// `None` for Relations, for the same reason it is absent from `section_args`: its
/// only writer is `relate`, so `set` has no way to fill it and no business emptying
/// it either.
pub clear: Option<Clearable>,
}
pub const DESCRIPTION: Section = Section {
@@ -1378,6 +1397,7 @@ pub const DESCRIPTION: Section = Section {
label: "description",
placeholder: "_No description provided._",
kind: SectionKind::Prose,
clear: Some(Clearable::Description),
};
pub const ACCEPTANCE: Section = Section {
@@ -1385,6 +1405,7 @@ pub const ACCEPTANCE: Section = Section {
label: "acceptance criteria",
placeholder: "_No acceptance criteria provided._",
kind: SectionKind::Checklist,
clear: Some(Clearable::Acceptance),
};
pub const PLAN: Section = Section {
@@ -1392,6 +1413,7 @@ pub const PLAN: Section = Section {
label: "implementation plan",
placeholder: "_No implementation plan provided._",
kind: SectionKind::Numbered,
clear: Some(Clearable::Plan),
};
/// The edges to other tickets, one per line.
@@ -1405,6 +1427,7 @@ pub const RELATIONS: Section = Section {
label: "relations",
placeholder: "_No relations._",
kind: SectionKind::Bullets,
clear: None,
};
impl Section {
@@ -1438,6 +1461,108 @@ impl Section {
}
}
/// A field `set --clear` can return to the state a new ticket is born in.
///
/// The names are the flags they undo, so `--clear due` reads as the opposite of
/// `--due`. Three fields a ticket carries are deliberately absent:
///
/// - **Title** has no unset state. It addresses the ticket, it names the file through
/// its slug, and `add` requires it, so there is nothing to go back to.
/// - **Owner** is `chown`'s, and clearing it through `set` would give the field a
/// second writer, which is the rule the missing `set --owner` exists to keep.
/// - **Status**, **Campaign** and the three stamps belong to `mv` and `assign` for the
/// same reason.
#[derive(Copy, Clone, Debug, PartialEq, Eq, clap::ValueEnum)]
pub enum Clearable {
Due,
Tags,
Priority,
Description,
Acceptance,
Plan,
}
/// What clearing a field writes back.
pub enum Unset {
/// A metadata line, back to the sentinel `add` writes when the flag is omitted.
Field {
field: &'static str,
sentinel: &'static str,
},
/// A section body, back to the placeholder `add` writes for an empty one.
Section(&'static Section),
}
impl Clearable {
/// Every field that can be cleared.
///
/// `#[cfg(test)]` because nothing in the binary walks the list: clap emits the
/// values for `--clear` from the `ValueEnum` itself, so the only caller is the suite
/// that checks each one against the ticket it empties.
#[cfg(test)]
pub const ALL: [Clearable; 6] = [
Clearable::Due,
Clearable::Tags,
Clearable::Priority,
Clearable::Description,
Clearable::Acceptance,
Clearable::Plan,
];
/// What clearing the field amounts to.
///
/// The sentinels are [`NOT_SET`] and [`NONE`] rather than strings written out here,
/// so a cleared field is byte-identical to one `add` left alone. That is the whole
/// promise of the command: a ticket that has been cleared and one that was never
/// given the field read the same.
pub fn unset(self) -> Unset {
match self {
Clearable::Due => Unset::Field {
field: "Due",
sentinel: NOT_SET,
},
Clearable::Tags => Unset::Field {
field: "Tags",
sentinel: NONE,
},
Clearable::Priority => Unset::Field {
field: "Priority",
sentinel: NOT_SET,
},
Clearable::Description => Unset::Section(&DESCRIPTION),
Clearable::Acceptance => Unset::Section(&ACCEPTANCE),
Clearable::Plan => Unset::Section(&PLAN),
}
}
/// The value the flag takes, as clap spells it.
///
/// Written out rather than read off `to_possible_value`, because it is used in error
/// messages that tell a caller what to type and a `&'static str` is what those want.
/// `the_clear_values_are_the_names_clap_accepts` keeps the two in step.
pub fn name(self) -> &'static str {
match self {
Clearable::Due => "due",
Clearable::Tags => "tags",
Clearable::Priority => "priority",
Clearable::Description => "description",
Clearable::Acceptance => "acceptance",
Clearable::Plan => "plan",
}
}
/// How the change is named in output.
///
/// The label `set` already prints when it *writes* the field, so a cleared field is
/// named the way a replaced one is rather than in the flag's own spelling.
pub fn label(self) -> &'static str {
match self.unset() {
Unset::Field { .. } => self.name(),
Unset::Section(section) => section.label,
}
}
}
/// 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();
@@ -1481,12 +1606,32 @@ fn join_lines(lines: &[String]) -> String {
/// 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> {
replace_section_body(content, section, section.render(items, 1))
}
/// Return a section to the placeholder `add` writes for an empty one.
///
/// Not [`set_section_body`] with the placeholder as its one item: the placeholder is a
/// line of the format rather than content, and `render` would dress it as `- [ ] _No
/// acceptance criteria provided._` in every section but the description. It is the same
/// line `append` already treats as no content, so a cleared section can be appended to
/// without the placeholder being left above what follows it.
pub fn clear_section_body(content: &str, section: &Section) -> Result<String> {
replace_section_body(content, section, vec![section.placeholder.to_string()])
}
/// The line surgery both of the above are, given a body that is already rendered.
fn replace_section_body(
content: &str,
section: &Section,
body_lines: Vec<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));
out.extend(body_lines);
// One blank line before whatever section follows, matching how `add` writes it.
if body.end < lines.len() {
out.push(String::new());
@@ -3791,6 +3936,67 @@ mod tests {
assert!(parse_relation("- blocked by").unwrap_err().to_string().contains("no target"));
}
/// The two directions of the pairing have to agree, or `--clear acceptance` would
/// empty one section while the error message about an empty value named another.
#[test]
fn every_clearable_section_points_back_at_the_field_that_clears_it() {
for field in Clearable::ALL {
if let Unset::Section(section) = field.unset() {
assert_eq!(
section.clear,
Some(field),
"{} does not point back at --clear {}",
section.heading,
field.name()
);
}
}
assert_eq!(RELATIONS.clear, None, "set must not be able to empty Relations");
}
/// The names are written out for the error messages, so this is what keeps them the
/// names clap actually accepts.
#[test]
fn the_clear_values_are_the_names_clap_accepts() {
for field in Clearable::ALL {
let possible = clap::ValueEnum::to_possible_value(&field).expect("not hidden");
assert_eq!(possible.get_name(), field.name());
}
}
/// The sentinel a cleared field goes back to is the one `add` writes for a field it
/// was never given, which is the whole promise of the flag.
#[test]
fn a_cleared_scalar_holds_the_sentinel_add_writes() {
for field in Clearable::ALL {
let Unset::Field { field: name, sentinel } = field.unset() else {
continue;
};
let expected = match name {
"Tags" => NONE,
_ => NOT_SET,
};
assert_eq!(sentinel, expected, "{name}");
assert!(is_unknown_value(sentinel), "{name} clears to something readable as set");
}
}
/// The placeholder goes in as a line of the format, not as an item: dressed by
/// `render` it would read `- [ ] _No acceptance criteria provided._`.
#[test]
fn clearing_a_section_writes_the_bare_placeholder() {
let content = "# T\n\n## Acceptance Criteria\n- [x] Done\n- [ ] Not\n\n## Metadata\n\n- **ID**: x\n";
let cleared = clear_section_body(content, &ACCEPTANCE).unwrap();
assert!(
cleared.contains(&format!("## Acceptance Criteria\n{}\n", ACCEPTANCE.placeholder)),
"{cleared}"
);
// Everything outside the section is where it was.
assert!(cleared.contains("- **ID**: x"), "{cleared}");
// And a second clear is the same string, which is what makes the no-op free.
assert_eq!(clear_section_body(&cleared, &ACCEPTANCE).unwrap(), cleared);
}
#[test]
fn the_placeholder_is_no_relations_rather_than_a_bad_line() {
let content = format!(