diff --git a/AGENTS.md b/AGENTS.md index bf07b84..bac7ec8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -93,7 +93,7 @@ and this file is for what someone changing worklane's own code needs. - **Position is counted, not inferred.** The four `__worklane_*` predicates all read `$tokens[2]` and the token count rather than using `__fish_seen_subcommand_from`, because `campaign ls` and `campaign show` are also an `ls` and a `show` that fish has seen, and because matching against the ticket list would run worklane again inside the condition. `first_arg_of` and `second_arg_of` count a top-level command's arguments, `nested_arg_of` matches a parent and a child so `campaign show ` can be told from `chown alice `, which sit at the same token count, and `command_is` asks only which command this is, at any position in it - **Every rule carrying `-l` needs a `__worklane_command_is`, and `every_rule_naming_an_option_is_scoped_to_a_command` is what enforces it.** A bare `complete -c worklane -l tag` does not just complete that option's values, it tells fish the whole tool accepts `--tag`: `worklane init --` offered six options that only `relate` and `ls` have. Fixed in 55ee6e3. `__fish_seen_subcommand_from ls` is not the scope to use, for the nesting reason above - **The five completion lists are kept honest by tests** that walk the clap definition and fail on an argument left out of them. `TICKET_COMMANDS` and `TICKET_SECOND_COMMANDS` by position, `TICKET_FLAGS`, `CAMPAIGN_COMMANDS`, `CAMPAIGN_NESTED_COMMANDS`, `CAMPAIGN_FLAGS` and `TAG_FLAGS` likewise. The walk is one function, `every_argument`, since the tests differ only in the id they look for. Each also asserts *how many* it found, so a walker that stopped finding arguments fails rather than passing every assertion by never running them -- **A campaign is named in three shapes and a tag in one**, which is why the lists are not one list: a campaign is `assign`'s first positional, `campaign show`'s only argument and `ls --campaign`'s value, and each needs a different fish rule. A tag is only ever an option value, and its values come from a different command +- **A campaign is named in three shapes and a tag in one**, which is why the lists are not one list: a campaign is `assign`'s first positional, the first argument of `campaign show` and `campaign set`, and `ls --campaign`'s value, and each needs a different fish rule. A tag is only ever an option value, and its values come from a different command - **`ls --ids` is the machine-readable listing**, and one of the three outputs in the tree meant to be parsed: the short id, a tab, the title, unstyled. Two fields because fish reads what follows a tab as the description and a script reads `cut -f1`. It includes done, which the decorated listing leaves out, because a completion has to be able to name a finished ticket, and it skips a missing status directory rather than refusing, because an error printed over a shell prompt is worse than no candidates. The filters still apply, and an unknown `--campaign` is still refused - **`campaign ls --ids` is the same flag and the same two fields for the other object**, and it deliberately skips the member counting the decorated listing does: `members()` reads every ticket on the board, and the caller here is a shell filling in candidates on a keypress. It also prints nothing on an empty board, where the decorated listing prints a sentence, because a sentence offered as a candidate is worse than no candidates - **`worklane tags` is the third, and it is a command rather than a mode on `ls`.** Two reasons: `ls --tag ` answers what carries a tag and cannot answer what tags exist, which is the question a grooming sweep starts from, and a `--tags` beside a `--tag` is one letter from a filter that means something else. Alphabetical and case sensitive, matching the filter, so `bug` and `Bug` list separately and land next to each other, which is where a near-duplicate is spotted. Every status, done included: a tag that has fallen out of use is still part of what the vocabulary has been. `assets/PLAN.md` used to tell the agent to count tags with a `show` per ticket, and now points here @@ -178,6 +178,10 @@ and this file is for what someone changing worklane's own code needs. - `campaign ls` scans the status directories **once per campaign** to count members. That is a scan per row rather than one walk reused, and it is deliberate: the map-from-uuid version is worth writing when a board has enough campaigns to notice - **The TUI got a card label and a frame, not a campaign tab.** 61879a4 decided it. A tab would have had to answer what its columns are, and a campaign groups *across* the flow rather than within one status, so the honest answer is the four statuses filtered — which is a filter on the board it already has rather than a fifth tab. So: a label on the card, a frame above the columns while one is selected, and `c` for the picker. The cost the earlier decision balked at, a campaigns read per reload, is paid once per project in `columns_of` and is what names the label; see The Board View - **A campaign is named by its codename on the board, and by its short id when it has none.** The uuid does not fit on a card and the title is a sentence, which is the gap `Codename` fills. `campaign_label` builds it in one place, as a `Cell`, so the CLI paints it and the board makes a span of it; the mark is `CAMPAIGN_MARK`, `~`, beside `#` for a tag +- **`campaign set` is the only writer of a filed campaign's fields, and it carries the two scalars.** d637288 decided it: a `set` rather than a flag on something narrower, because the file has more than one editable thing and the moment somebody wants to fix a typo in a title there would be a second command to design. `--title`, which renames the file the way `set --title` does, and `--codename`. `campaign add` writing a field at creation is not a second writer, exactly as `add --title` and `set --title` coexist +- **No `campaign set --description`, and that is the line, not an oversight.** `set` and `append` are a pair for a prose section: a way to replace a description with no way to add a paragraph is half of it. The two scalars have no append form at all, which is the same line `append` already draws for a ticket. `campaign_set_offers_no_description_and_no_owner` pins it. No `--owner` either, because nothing writes a campaign's Owner today and giving `set` one would settle by accident whether `chown` grows a campaign; and no `--clear`, because a wrong codename is replaced rather than emptied and `Clearable` is `SetArgs`'s, its variants being a ticket's fields +- **The codename is written through `set_or_insert_metadata_field`, not `set_metadata_field`.** Every campaign filed before the field existed has no such line, and those are exactly the campaigns the command is for, which is the same reasoning that puts `assign` on the upsert. **`Codename` is therefore in `METADATA_ORDER`, directly after ID**, so an inserted one lands where `campaign_body` writes it and a campaign given a codename later is the same file as one filed with it. Nothing upserts it on a ticket, so its place in a ticket's order costs nothing +- **One write path for tickets and campaigns.** `save_entry` is the body, `save_ticket` and `save_campaign` are the named wrappers, and `write_then_replace` and `find_entry_file` take the noun as a `&str` so a failure says "campaign" where it is one. A campaign file is a ticket file in every way that matters here, `_.md` in a directory, and the rename happens only after the write has landed. Every message puts the noun mid-sentence so there is no capital to case - `campaign_body()` builds the file from `DESCRIPTION` and `METADATA_HEADING` rather than its own string literals, so the two file formats cannot drift apart on the spelling of a heading. A campaign has no acceptance criteria (its definition of done is derived), no implementation plan and no Status - The campaigns directory is created by `init` and **on demand** by `campaign add`, since every board made before campaigns existed has none and a `worklane init` over a live board to get one would be a strange thing to have to do diff --git a/Cargo.lock b/Cargo.lock index 0ae393c..e2add34 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1503,7 +1503,7 @@ dependencies = [ [[package]] name = "worklane" -version = "0.20.0" +version = "0.21.0" dependencies = [ "anyhow", "assert_cmd", diff --git a/Cargo.toml b/Cargo.toml index 878933b..5350ffa 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "worklane" -version = "0.20.0" +version = "0.21.0" edition = "2024" [dependencies] diff --git a/README.md b/README.md index b2606f7..2930c4b 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,7 @@ Worklane is a local Kanban flow for agentic software development. | `worklane uncheck [criteria...]` | Unticks acceptance criteria, addressed the same way | | `worklane comment ` | Adds a comment to a ticket by UUID or title | | `worklane campaign add` | Files a campaign in `.worklane/campaigns/` with `--title`, `--description`, `--codename` and `--owner`. A campaign has no status: its state is derived, open until every member is done. `--codename` is one word to call it by, `v1` or `beaver`, which is what the board draws on every card in it and what every command that takes a campaign will also resolve it by | +| `worklane campaign set ` | Replaces `--title`, which renames the file keeping the uuid, and `--codename`. At least one required. The only way to change a campaign after it is filed, and the way a campaign filed before codenames existed gets one. No `--description`: replacing prose without an `append` to add a paragraph is half a pair | | `worklane campaign ls` | Lists the campaigns as their short id, their codename, their title and how many members are done. `--ids` prints one per line as the id, a tab and the title, unstyled, for a script or a completion | | `worklane campaign show ` | Shows a campaign and its members grouped by status, done included, since what is finished against what is left is the question a campaign asks | | `worklane assign ` | Puts a ticket in a campaign, the only command that writes the Campaign field. Campaign first and ticket second, after `chown`. A ticket is in at most one, so assigning one that already belongs somewhere moves it | diff --git a/assets/PLAN.md b/assets/PLAN.md index f76239f..8b00896 100644 --- a/assets/PLAN.md +++ b/assets/PLAN.md @@ -160,6 +160,7 @@ fields; a goal is a campaign. worklane campaign ls worklane campaign show v1 worklane campaign add --title "..." --codename v1 --description "..." +worklane campaign set v1 --codename beaver # or --title, on one already filed worklane assign v1 1b78a24 ``` @@ -181,7 +182,7 @@ tui is usable on a narrow terminal" is a campaign. "The tui tickets" is a tag. board draws on every card in it and the shortest thing that addresses it at the command line, and a campaign filed without one is drawn by its short id, which says nothing. A campaign already on the board that has no codename is worth pointing out for the same - reason a near-duplicate tag is. + reason a near-duplicate tag is, and `campaign set` is how it gets one without refiling. Proposing a campaign means naming the goal, the members, and what is deliberately left out of it. The last part is what makes it a goal rather than a pile. diff --git a/assets/SKILL.md b/assets/SKILL.md index 59d3e33..3f1e685 100644 --- a/assets/SKILL.md +++ b/assets/SKILL.md @@ -211,6 +211,7 @@ worklane campaign add --title "First public release" --codename v1 \ worklane campaign ls # every campaign, its codename, how far it has got worklane campaign ls --ids # id and title, tab separated, like ls --ids worklane campaign show v1 # its body, then its members by status +worklane campaign set v1 --title "..." # replace the title or the codename worklane assign v1 1b78a24 # put a ticket in it worklane ls --campaign v1 # only that campaign's tickets ``` @@ -219,7 +220,13 @@ worklane ls --campaign v1 # only that campaign's tickets draws on every card in the campaign, because a uuid does not fit there and a title is a sentence, and it is the shortest thing that addresses the campaign at the command line. Optional: a campaign without one is drawn and listed by its short id instead, which -resolves but says nothing. +resolves but says nothing. `campaign set --codename ` gives one to a +campaign that is already filed, which is what every campaign filed before the field +existed needs. + +`campaign set` is the only way to change a campaign after it is filed, and it reaches the +title and the codename only. There is no way to edit a campaign's description or its owner +yet. `assign` takes the **campaign first and the ticket second**, like `chown`, and is the only writer of the field. `add` has no `--campaign` and neither has `set`, so membership diff --git a/src/command.rs b/src/command.rs index 53d3648..051c999 100644 --- a/src/command.rs +++ b/src/command.rs @@ -286,13 +286,24 @@ pub enum Command { /// What a campaign can be asked for. /// /// No `mv`: a campaign has no status to move it to, its state is derived from its -/// members. No `set` or `append` either, which is a gap rather than a decision, since -/// nothing yet edits a campaign after it is filed. +/// members. +/// +/// No `append`, and therefore no `set --description`: `set` and `append` are a pair for a +/// prose section, and a way to replace a description with no way to add a paragraph to one +/// is half of it. That pair is its own ticket. `set` here carries the two scalars, which +/// have no append form at all, the same line `append` already draws for a ticket. #[derive(clap::Subcommand)] pub enum CampaignCommand { /// File a new campaign Add(CampaignAddArgs), + /// Replace fields on an existing campaign + /// + /// The only way to change a campaign after it is filed. `campaign add --codename` writes + /// the field at creation the way `add --title` does for a ticket; this is what replaces + /// it, so every campaign filed before the field existed can still be given one. + Set(CampaignSetArgs), + /// List campaigns with their member counts Ls { /// Print one campaign per line as its id and title, tab separated, for a script @@ -313,6 +324,44 @@ pub enum CampaignCommand { }, } +/// What can be replaced on a campaign that is already filed: its title and its codename. +/// +/// The two scalars, and deliberately not the description. See [`CampaignCommand`]. +/// +/// No `--owner`: nothing writes a campaign's Owner today, and giving `set` one would settle +/// by accident whether `chown` grows a campaign or `set` keeps the field, which is the +/// one-field-one-writer question and not this command's to answer. +/// +/// No `--clear`: nothing has asked to empty a codename, a wrong one is replaced rather than +/// emptied, and the vocabulary is a real question — `Clearable` is `SetArgs`'s and its +/// variants are a ticket's fields, so reusing it here would put a ticket's enum on a +/// campaign and inventing a second one is a decision worth making on purpose. +/// +/// The group makes at least one field mandatory, so a bare `worklane campaign set ` is a +/// usage error rather than a silent no-op, exactly as it is for [`SetArgs`]. +#[derive(clap::Args)] +#[command(group( + clap::ArgGroup::new("campaign_set_fields") + .required(true) + .multiple(true) + .args(["title", "codename"]) +))] +pub struct CampaignSetArgs { + /// Campaign UUID, title, filename or codename + pub campaign: String, + + /// Replace the campaign title, renaming the file to match + #[arg(short, long, allow_hyphen_values = PROSE, value_parser = non_empty)] + pub title: Option, + + /// Replace the codename, a single word to call the campaign by + /// + /// The same parser `campaign add --codename` takes, so a codename is one thing however + /// it was written. + #[arg(short, long, value_parser = codename)] + pub codename: Option, +} + /// What a campaign holds: a title, a description and an owner. /// /// Deliberately narrower than [`AddArgs`]. There are no acceptance criteria, because a diff --git a/src/completions.rs b/src/completions.rs index 471b509..b3c7619 100644 --- a/src/completions.rs +++ b/src/completions.rs @@ -50,11 +50,11 @@ pub const CAMPAIGN_COMMANDS: [&str; 1] = ["assign"]; /// Nested subcommands whose first argument is a campaign, as `parent child`. /// -/// `campaign show` is the only one, and it is why the fish half needs a third position -/// helper: its argument is the *third* token, where `__worklane_first_arg_of` reads the -/// second and `__worklane_second_arg_of` counts a top-level command's arguments. Neither -/// can tell `campaign show ` from `chown alice ` by position. -pub const CAMPAIGN_NESTED_COMMANDS: [(&str, &str); 1] = [("campaign", "show")]; +/// `campaign show` and `campaign set`, and they are why the fish half needs a third +/// position helper: their argument is the *third* token, where `__worklane_first_arg_of` +/// reads the second and `__worklane_second_arg_of` counts a top-level command's arguments. +/// Neither can tell `campaign show ` from `chown alice ` by position. +pub const CAMPAIGN_NESTED_COMMANDS: [(&str, &str); 2] = [("campaign", "show"), ("campaign", "set")]; /// Options whose value is a campaign. pub const CAMPAIGN_FLAGS: [&str; 1] = ["campaign"]; @@ -348,7 +348,7 @@ mod tests { // A guard on the walker itself: if it stopped finding arguments, every assertion // above would pass by never running. - assert_eq!(seen, 3, "expected assign, campaign show and ls --campaign"); + assert_eq!(seen, 4, "expected assign, campaign show, campaign set and ls --campaign"); } /// Tags have their own list because their values come from `worklane tags` rather than diff --git a/src/handlers.rs b/src/handlers.rs index a59f89b..db36b0f 100644 --- a/src/handlers.rs +++ b/src/handlers.rs @@ -7,7 +7,8 @@ use std::path::Path; use crate::campaign::*; use crate::command::{ - AddArgs, AppendArgs, CampaignAddArgs, CheckArgs, ChownArgs, LsArgs, RelateArgs, SetArgs, + AddArgs, AppendArgs, CampaignAddArgs, CampaignSetArgs, CheckArgs, ChownArgs, LsArgs, + RelateArgs, SetArgs, }; use crate::install; use crate::util::*; @@ -442,10 +443,19 @@ pub fn cmd_show(search: &str, worklane_dir: &Path) -> Result<()> { Ok(()) } +/// What is being written, for the messages a failure carries. +/// +/// A `&str` naming the thing rather than two copies of the write path: a campaign file is +/// a ticket file in every way that matters here, `_.md` in a directory, and the +/// only difference is the word a failure has to use. Every message below puts it +/// mid-sentence so there is no capital to case. +const TICKET: &str = "ticket"; +const CAMPAIGN: &str = "campaign"; + /// 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 +/// it writes and a partial write would corrupt the file. 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. @@ -454,6 +464,7 @@ fn write_then_replace( path: &Path, filename: &str, content: &str, + kind: &str, title: &str, ) -> Result<()> { let temp = worklane_dir.join(format!(".wl-{}.tmp", filename)); @@ -461,7 +472,8 @@ fn write_then_replace( if let Err(e) = fs::write(&temp, content) { let _ = fs::remove_file(&temp); return Err(anyhow!( - "Could not stage the update for ticket '{}' at {}: {}", + "Could not stage the update for {} '{}' at {}: {}", + kind, title, temp.display(), e @@ -470,21 +482,29 @@ fn write_then_replace( 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)); + return Err(anyhow!( + "Could not write {} '{}' at {}: {}", + kind, + title, + path.display(), + e + )); } Ok(()) } -/// The ticket file in `dir` carrying `uuid`. +/// The file in `dir` carrying `uuid`, ticket or campaign. /// /// 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 ` moved the first ticket sharing its title. -fn find_ticket_file(dir: &Path, uuid: &str, title: &str) -> Result { +/// resolved: `mv ` moved the first ticket sharing its title. The same holds +/// for a campaign, whose file is named the same way. +fn find_entry_file(dir: &Path, kind: &str, uuid: &str, title: &str) -> Result { if uuid.trim().is_empty() || is_unknown_value(uuid) { return Err(anyhow!( - "Ticket '{}' has no ID field, so its file cannot be located", + "Could not locate the file for {} '{}': it has no ID field", + kind, title )); } @@ -507,7 +527,8 @@ fn find_ticket_file(dir: &Path, uuid: &str, title: &str) -> Result { } Err(anyhow!( - "Could not find the file for ticket '{}' in {}", + "Could not find the file for {} '{}' in {}", + kind, title, dir.display() )) @@ -537,7 +558,7 @@ fn move_ticket_file( let source = from.join(filename); let dest = to.join(filename); - write_then_replace(worklane_dir, &source, filename, content, title)?; + write_then_replace(worklane_dir, &source, filename, content, TICKET, 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. @@ -660,7 +681,7 @@ pub fn cmd_mv(ticket_id: &str, target: Status, force: bool, start: &Path) -> Res )?; let found_filename = - find_ticket_file(¤t_path, &parse_ticket_field(&resolved, "ID"), &title)?; + find_entry_file(¤t_path, TICKET, &parse_ticket_field(&resolved, "ID"), &title)?; move_ticket_file( &worklane_dir, @@ -756,21 +777,56 @@ fn save_ticket( 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); + let dir = worklane_dir.join(status); + save_entry(worklane_dir, &dir, TICKET, uuid, title, new_title, content) +} - write_then_replace(worklane_dir, &path, &filename, content, title)?; +/// The same for a campaign, whose directory is `campaigns/` and which sits in no status. +/// +/// A named wrapper rather than a `save_entry` at the call site, so the campaign handler +/// reads the way the ticket handlers do and neither has to know which directory the other +/// writes to. +fn save_campaign( + worklane_dir: &Path, + uuid: &str, + title: &str, + new_title: Option<&String>, + content: &str, +) -> Result<()> { + let dir = campaigns_dir(worklane_dir); + save_entry(worklane_dir, &dir, CAMPAIGN, uuid, title, new_title, content) +} - // The uuid is kept, so the new name cannot collide with another ticket, and an +/// Write a file back where it was, renaming it when the title changed. +/// +/// One body for tickets and campaigns. Both are `_.md` in a directory, both are +/// written through `write_then_replace` so a failure leaves no half file, and both rename +/// only after the write has landed: renaming first and writing second is what leaves a file +/// under a name that does not match what is in it. +fn save_entry( + worklane_dir: &Path, + dir: &Path, + kind: &str, + uuid: &str, + title: &str, + new_title: Option<&String>, + content: &str, +) -> Result<()> { + let filename = find_entry_file(dir, kind, uuid, title)?; + let path = dir.join(&filename); + + write_then_replace(worklane_dir, &path, &filename, content, kind, title)?; + + // The uuid is kept, so the new name cannot collide with another entry, 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); + let destination = dir.join(&renamed); fs::rename(&path, &destination).map_err(|e| { anyhow!( - "Ticket '{}' was updated but could not be renamed to {}: {}", + "Could not rename {} '{}' to {} after updating it: {}", + kind, title, destination.display(), e @@ -1065,7 +1121,7 @@ pub fn cmd_campaign_add(args: &CampaignAddArgs, start: &Path) -> Result<()> { &Local::now().format(TIMESTAMP_FORMAT).to_string(), ); - write_then_replace(&worklane_dir, &path, &filename, &body, title)?; + write_then_replace(&worklane_dir, &path, &filename, &body, CAMPAIGN, title)?; println!("Created campaign: {}", filename); Ok(()) @@ -1172,6 +1228,52 @@ pub fn cmd_tags(worklane_dir: &Path) -> Result<()> { Ok(()) } +/// Replace fields on a campaign that is already filed. +/// +/// `cmd_set` for a campaign, and built out of the same parts: `set_title` for the heading, +/// `set_metadata_field` for the field, `apply` for whether an edit changed anything, and +/// `report` for what it says afterwards. Nothing about writing a field lives twice, which is +/// the shape `cmd_chown` already took. +/// +/// The **codename is inserted when the campaign has no such line**, rather than refused. +/// `set_metadata_field` refuses a field that is not there, which is right for the fields +/// `add` writes; every campaign filed before the field existed has none, and those are +/// exactly the campaigns this command is for. So it goes through +/// `set_or_insert_metadata_field`, the upsert `assign` already uses for the Campaign field +/// on a ticket, for the same reason. +/// +/// No-op detection compares the whole file, the way `set` and `chown` do, so setting a +/// codename a campaign already carries writes nothing. +pub fn cmd_campaign_set(args: &CampaignSetArgs, start: &Path) -> Result<()> { + let worklane_dir = find_worklane_dir(start)?; + let campaign = resolve_campaign(&args.campaign, &worklane_dir)?; + let title = campaign.title.clone(); + + let mut content = campaign.content.clone(); + let mut changed: Vec<&str> = Vec::new(); + + if let Some(new_title) = &args.title { + let next = set_title(&content, new_title)?; + apply(&mut content, &mut changed, "title", next); + } + + if let Some(codename) = &args.codename { + let next = set_or_insert_metadata_field(&content, CODENAME_FIELD, codename, &title)?; + apply(&mut content, &mut changed, "codename", next); + } + + if changed.is_empty() { + report(&[], &title, "Updated"); + return Ok(()); + } + + let renamed = changed.contains(&"title").then_some(()).and(args.title.as_ref()); + save_campaign(&worklane_dir, &campaign.uuid, &title, renamed, &content)?; + + report(&changed, args.title.as_ref().unwrap_or(&title), "Updated"); + Ok(()) +} + /// Show a campaign, then its members grouped by status. /// /// Every status is shown, done included, unlike `ls`, which leaves done out of its diff --git a/src/main.rs b/src/main.rs index 9416356..ae51ec8 100644 --- a/src/main.rs +++ b/src/main.rs @@ -71,6 +71,7 @@ fn main() -> Result<()> { let worklane_dir = find_worklane_dir(&start)?; cmd_campaign_ls(&worklane_dir, ids) } + CampaignCommand::Set(args) => cmd_campaign_set(&args, &start), CampaignCommand::Show { campaign } => { let worklane_dir = find_worklane_dir(&start)?; cmd_campaign_show(&campaign, &worklane_dir) diff --git a/src/util.rs b/src/util.rs index 4293935..f7ba154 100644 --- a/src/util.rs +++ b/src/util.rs @@ -1261,8 +1261,16 @@ pub fn parse_tags(content: &str) -> Vec { /// stamps follow `Created At`, since they answer the same question it does about a /// later moment, and they are in flow order for a reader who sees one after another /// across a board. -const METADATA_ORDER: [&str; 11] = [ +/// +/// `Codename` is a *campaign's* field and sits here for the same reason Campaign does: this +/// is the one list that decides where an inserted field lands, and a campaign filed before +/// the field existed is precisely the file `campaign set --codename` has to insert into. +/// Directly after ID, because that is where `campaign_body` writes it, so a campaign given +/// a codename later ends up with the same file as one filed with it. Nothing ever upserts +/// it on a ticket, so its place in a ticket's order costs nothing. +const METADATA_ORDER: [&str; 12] = [ "ID", + CODENAME_FIELD, "Priority", "Tags", "Due", diff --git a/tests/cmd_campaign.rs b/tests/cmd_campaign.rs index ff0ac48..9a669c3 100644 --- a/tests/cmd_campaign.rs +++ b/tests/cmd_campaign.rs @@ -144,6 +144,21 @@ fn find(worklane: &Path, uuid: &str) -> PathBuf { panic!("no file for ticket {uuid}"); } +/// A campaign's content by uuid, found rather than named, since `campaign set --title` +/// renames the file and a test that named it would be asserting the old name. +fn campaign_file(worklane: &Path, uuid: &str) -> String { + for entry in fs::read_dir(worklane.join("campaigns")) + .unwrap() + .filter_map(|e| e.ok()) + { + if entry.file_name().to_string_lossy().starts_with(uuid) { + return fs::read_to_string(entry.path()).unwrap(); + } + } + + panic!("no file for campaign {uuid}"); +} + fn ticket(worklane: &Path, uuid: &str) -> String { fs::read_to_string(find(worklane, uuid)).unwrap() } @@ -856,3 +871,245 @@ fn a_ticket_search_is_unaffected_by_the_codename_tier() { assert!(stdout(&out).contains("The member"), "{}", stdout(&out)); let _ = worklane; } + +// ---------------------------------------------------------------- campaign set -- + +/// The point of the command: a campaign already on the board can be given a codename, +/// which `campaign add --codename` cannot do because `add` files a new one. +#[test] +fn campaign_set_gives_a_filed_campaign_a_codename() { + let temp = TempDir::new().unwrap(); + let worklane = board(&temp); + + let out = run(&temp, &["campaign", "set", "v1 release", "--codename", "beaver"]); + assert!(out.status.success(), "{}", stderr(&out)); + assert!(stdout(&out).contains("Updated codename"), "{}", stdout(&out)); + + let content = campaign_file(&worklane, CAMP_A); + assert!(content.contains("- **Codename**: beaver"), "{content}"); +} + +/// `create_campaign` writes no Codename line at all, which is every campaign filed before +/// the field existed, so the insertion path is the one this command is actually for. +/// It lands under the ID, where `campaign add` writes it, so a campaign given a codename +/// later is the same file as one filed with it. +#[test] +fn the_codename_is_inserted_under_the_id_when_the_line_is_absent() { + let temp = TempDir::new().unwrap(); + let worklane = board(&temp); + assert!( + !campaign_file(&worklane, CAMP_A).contains("Codename"), + "the fixture changed" + ); + + run(&temp, &["campaign", "set", "v1 release", "-c", "v1"]); + + let content = campaign_file(&worklane, CAMP_A); + let id = content.find("- **ID**:").expect("no id"); + let codename = content.find("- **Codename**:").expect("no codename"); + let owner = content.find("- **Owner**:").expect("no owner"); + assert!(id < codename && codename < owner, "{content}"); +} + +/// One parser, so a codename is one thing however it was written. The board draws it as a +/// label with a mark and no quoting, and that does not depend on which command wrote it. +#[test] +fn campaign_set_validates_the_codename_the_way_add_does() { + let temp = TempDir::new().unwrap(); + let worklane = board(&temp); + + for value in ["two words", ""] { + let out = run(&temp, &["campaign", "set", "v1 release", "--codename", value]); + assert_eq!(out.status.code(), Some(2), "{value:?}: {}", stderr(&out)); + assert!( + !campaign_file(&worklane, CAMP_A).contains("Codename"), + "{value:?} was written" + ); + } + + // And the message is the one `campaign add` gives, since the parser is the same. + let out = run(&temp, &["campaign", "set", "v1 release", "--codename", "two words"]); + assert!(stderr(&out).contains("single word"), "{}", stderr(&out)); +} + +/// A bare `campaign set ` is a usage error rather than a silent no-op, exactly +/// as it is for `set`. +#[test] +fn campaign_set_with_no_field_is_a_usage_error() { + let temp = TempDir::new().unwrap(); + let worklane = board(&temp); + + let out = run(&temp, &["campaign", "set", "v1 release"]); + assert_eq!(out.status.code(), Some(2), "{}", stderr(&out)); + assert!( + !campaign_file(&worklane, CAMP_A).contains("Codename"), + "something was written" + ); +} + +/// Replacing the title renames the file, keeping the uuid, the way `set --title` does. That +/// is the reason this is a `set` rather than a flag on something narrower. +#[test] +fn campaign_set_renames_the_file_with_the_title() { + let temp = TempDir::new().unwrap(); + let worklane = board(&temp); + // A member first, so the rename has something to break. + run(&temp, &["assign", "v1 release", MEMBER]); + + let out = run( + &temp, + &[ + "campaign", + "set", + "v1 release", + "--title", + "First public release", + ], + ); + assert!(out.status.success(), "{}", stderr(&out)); + + let names = campaigns(&worklane); + assert!( + names.contains(&format!("{CAMP_A}_first-public-release.md")), + "not renamed: {names:?}" + ); + assert!( + !names.contains(&format!("{CAMP_A}_v1-release.md")), + "the old file is still there: {names:?}" + ); + + let content = campaign_file(&worklane, CAMP_A); + assert!(content.starts_with("# First public release\n"), "{content}"); + // The uuid is kept, so membership survives the rename: it is stored on the member as + // the uuid, and nothing has to be rewritten when the campaign is renamed. + assert!(content.contains(&format!("- **ID**: {CAMP_A}")), "{content}"); + let out = run(&temp, &["ls", "--campaign", "First public release"]); + assert!( + stdout(&out).contains("The member"), + "membership was lost: {}", + stdout(&out) + ); +} + +/// Both fields in one call, since the group is `multiple`. +#[test] +fn campaign_set_takes_the_title_and_the_codename_together() { + let temp = TempDir::new().unwrap(); + let worklane = board(&temp); + + let out = run( + &temp, + &[ + "campaign", + "set", + "v1 release", + "-t", + "First public release", + "-c", + "v1", + ], + ); + assert!(out.status.success(), "{}", stderr(&out)); + assert!(stdout(&out).contains("title, codename"), "{}", stdout(&out)); + + let content = campaign_file(&worklane, CAMP_A); + assert!(content.starts_with("# First public release\n"), "{content}"); + assert!(content.contains("- **Codename**: v1"), "{content}"); +} + +/// The whole-file comparison `set` and `chown` use, so writing what is already there +/// writes nothing and says so. +#[test] +fn setting_the_codename_a_campaign_already_has_writes_nothing() { + let temp = TempDir::new().unwrap(); + let worklane = board(&temp); + run(&temp, &["campaign", "set", "v1 release", "-c", "v1"]); + + let before = campaign_file(&worklane, CAMP_A); + let out = run(&temp, &["campaign", "set", "v1", "-c", "v1"]); + + assert!(out.status.success(), "{}", stderr(&out)); + assert!(stdout(&out).contains("No changes"), "{}", stdout(&out)); + assert_eq!(campaign_file(&worklane, CAMP_A), before, "the file was rewritten"); +} + +/// A codename set here resolves the campaign afterwards, which is the whole point of the +/// field being typable: the tier is in the shared resolver, not in `campaign add`. +#[test] +fn a_codename_set_afterwards_resolves_the_campaign() { + let temp = TempDir::new().unwrap(); + let worklane = board(&temp); + run(&temp, &["campaign", "set", "v1 release", "-c", "beaver"]); + + let out = run(&temp, &["assign", "beaver", MEMBER]); + assert!(out.status.success(), "{}", stderr(&out)); + assert!( + ticket(&worklane, MEMBER).contains(&format!("- **Campaign**: {CAMP_A}")), + "{}", + ticket(&worklane, MEMBER) + ); +} + +/// Nothing else in the file moves. A campaign carries prose and an owner this command +/// cannot reach, and a hand-written section has to survive an edit to a field. +#[test] +fn content_the_command_cannot_reach_survives_a_set() { + let temp = TempDir::new().unwrap(); + let worklane = board(&temp); + + let path = worklane + .join("campaigns") + .join(format!("{}_{}.md", CAMP_A, slug("v1 release"))); + let original = fs::read_to_string(&path).unwrap(); + fs::write( + &path, + original.replace("## Metadata", "## Notes\nA handwritten note.\n\n## Metadata"), + ) + .unwrap(); + + run(&temp, &["campaign", "set", "v1 release", "-c", "v1"]); + + let content = campaign_file(&worklane, CAMP_A); + assert!(content.contains("A handwritten note."), "{content}"); + assert!(content.contains("What has to ship together."), "{content}"); + assert!(content.contains("- **Owner**: alice"), "{content}"); + assert!(!content.contains("**Status**"), "a status was invented: {content}"); +} + +/// A campaign that does not resolve leaves everything alone, the answer `assign` already +/// gives an unknown campaign. +#[test] +fn an_unknown_campaign_is_refused_and_nothing_is_written() { + let temp = TempDir::new().unwrap(); + let worklane = board(&temp); + + let out = run(&temp, &["campaign", "set", "nothing-by-that-name", "-c", "v1"]); + assert_eq!(out.status.code(), Some(1), "{}", stderr(&out)); + assert!(stderr(&out).contains("No campaign found"), "{}", stderr(&out)); + assert!( + !campaign_file(&worklane, CAMP_A).contains("Codename"), + "something was written" + ); + assert!( + !campaign_file(&worklane, CAMP_B).contains("Codename"), + "something was written" + ); +} + +/// No `--description`: `set` and `append` are a pair for a prose section, and a way to +/// replace a description with no way to add a paragraph is half of it. Pinned so the +/// omission stays a decision rather than becoming an oversight somebody fills in. +#[test] +fn campaign_set_offers_no_description_and_no_owner() { + let temp = TempDir::new().unwrap(); + setup_worklane(&temp); + + let out = run(&temp, &["campaign", "set", "--help"]); + let help = stdout(&out); + + assert!(help.contains("--codename"), "{help}"); + assert!(help.contains("--title"), "{help}"); + assert!(!help.contains("--description"), "{help}"); + assert!(!help.contains("--owner"), "{help}"); + assert!(!help.contains("--clear"), "{help}"); +}