use anyhow::{Result, anyhow}; use chrono::Local; use std::collections::BTreeMap; use std::fs; use std::io::{BufRead, IsTerminal, Write}; use std::path::Path; use crate::campaign::*; use crate::command::{ AddArgs, AppendArgs, CampaignAddArgs, CampaignAppendArgs, CampaignSetArgs, CheckArgs, ChownArgs, LsArgs, RelateArgs, SetArgs, TagAddArgs, TagSetArgs, }; use crate::history::{Kind, change, format_history, read_history, write_entry}; use crate::install; use crate::tag::{TAGS_FILE, TagIndex, tags_path}; use crate::util::*; pub fn cmd_init(start: &Path) -> Result<()> { let dir = start.canonicalize().unwrap_or_else(|_| start.to_path_buf()); let worklane_dir = dir.join(".worklane"); if worklane_dir.exists() { println!("worklane already initialized in: {}", worklane_dir.display()); return Ok(()); } fs::create_dir_all(&worklane_dir)?; for folder in status_dirs() { fs::create_dir_all(worklane_dir.join(folder))?; } // Beside the status directories, not among them: a campaign has no status. Created // here for a new board, and on demand by `campaign add` for a board that predates // campaigns, which is why `status_dirs()` is untouched. fs::create_dir_all(campaigns_dir(&worklane_dir))?; // The tag vocabulary, beside both for the same reason, and written empty rather than // left for the first `tags add` to make. An empty file explains itself when it is // opened, which is the point of the preamble, and a board that has one from the start // has one file shape rather than two. `fs::write` and not `write_then_replace`: the // directory was made three lines ago, so there is nothing here to truncate. fs::write(tags_path(&worklane_dir), TagIndex::default().render())?; println!("Initialized worklane in: {}", worklane_dir.display()); Ok(()) } pub fn cmd_ls(args: &LsArgs, worklane_dir: &Path) -> Result<()> { // Resolved before anything is read, so an unknown campaign is refused rather than // silently listing nothing, and the name is available for the heading. Ahead of the // `--ids` branch too: a completion that quietly listed the whole board because the // campaign was misspelled would be worse than one that printed nothing. let campaign = match &args.campaign { Some(search) => Some(resolve_campaign(search, worklane_dir)?), None => None, }; let uuid = campaign.as_ref().map(|campaign| campaign.uuid.as_str()); let tag = args.tag.as_deref(); let priority_filter = args.priority; if args.ids { return list_ids(args.status, priority_filter, uuid, tag, worklane_dir); } if let Some(campaign) = &campaign { println!( "Members of campaign ({}) {}\n", color_text(short_id(&campaign.uuid), Color::Red), color_text(&campaign.title, Color::Green), ); } if let Some(status) = args.status { // The `Status` is kept alongside its name: the directory is joined from the // name, and the order the column prints in is keyed on the status itself. let name = status.as_str(); let status_path = worklane_dir.join(name); if !status_path.exists() { // The status itself is clap's to reject now, so reaching here means the // board is missing a directory it should have rather than that the name was // mistyped. `init` will not repair it: it leaves an existing `.worklane` // alone. return Err(anyhow!( "No '{}' directory in {}. Every board has all four; creating it is enough.", name, worklane_dir.display() )); } let mut items = filtered(collect_ticket_items(&status_path)?, priority_filter, uuid, tag); items.sort_by(|a, b| by_status_order(status, a, b)); if items.is_empty() { println!("No tickets in '{}' status.", name); return Ok(()); } println!("Tickets in '{}' status:\n", name); display_ticket_items(&items); } else { // List all statuses with their ticket counts let statuses = status_dirs(); println!("Tickets by status:\n"); for status in &statuses { let status_path = worklane_dir.join(status); if !status_path.exists() { continue; } let items = filtered(collect_ticket_items(&status_path)?, priority_filter, uuid, tag); let count = items.len(); let label = if count == 1 { "ticket" } else { "tickets" }; println!(" [{}] {} {}", status.to_uppercase(), count, label); } // Show all tickets except the two terminal statuses, grouped by status. Over // `Status::ALL` rather than the names, because each column is ordered by its own // entry stamp and the comparator is keyed on the status, not on the directory it // was read from. for status in Status::ALL { if !is_open(status.as_str()) { continue; } let status_path = worklane_dir.join(status.as_str()); if !status_path.exists() || !fs::metadata(&status_path)?.is_dir() { continue; } let mut items = match collect_ticket_items(&status_path) { Ok(items) => filtered(items, priority_filter, uuid, tag), Err(_) => continue, }; items.sort_by(|a, b| by_status_order(status, a, b)); if items.is_empty() { continue; } let status_header = color_text(&format!("[{}]", status.as_str().to_uppercase()), Color::Orange); println!("\n{}", status_header); display_ticket_items(&items); } } Ok(()) } /// The machine-readable listing: one ticket per line, its short id then its title, /// separated by a tab and unstyled. /// /// Two fields rather than the id alone because both readers want both. Fish takes what /// follows the tab as the description, which is what makes `worklane show ` a list /// of titles rather than of hex, and a script takes the id back out with `cut -f1`. The /// id is the same seven characters the listing prints, which is what a ticket is /// addressed by. /// /// Every status, done included, where the listing above leaves done out. A completion has /// to be able to name a finished ticket, since `show` and `comment` are most often /// pointed at one, and the status positional still narrows it. /// /// A missing status directory is skipped rather than refused, which is the one place this /// parts company with the listing. The caller is usually a shell filling in a candidate /// list, and an error printed over the prompt is worse there than no candidates. fn list_ids( status: Option, level: Option, campaign: Option<&str>, tag: Option<&str>, worklane_dir: &Path, ) -> Result<()> { let statuses = match status { Some(status) => vec![status], None => Status::ALL.to_vec(), }; for status in statuses { let status_path = worklane_dir.join(status.as_str()); if !status_path.exists() { continue; } // The same order the listing prints, so a completion and the board agree on // which ticket is at the head of a column. let mut items = filtered(collect_ticket_items(&status_path)?, level, campaign, tag); items.sort_by(|a, b| by_status_order(status, a, b)); for item in items { println!("{}\t{}", item.id, item.title); } } Ok(()) } /// The listing filters in one call, so the three places `ls` collects a column cannot /// end up applying a different set of them. /// /// Every filter is `Option`, and none asked for is everything kept, which is what makes /// them compose in any combination without a rule per pair. fn filtered( items: Vec, level: Option, campaign: Option<&str>, tag: Option<&str>, ) -> Vec { filter_by_tag(filter_by_campaign(filter_by_priority(items, level), campaign), tag) } /// Keep only the tickets carrying `tag`, or everything when none was asked for. /// /// Matched against the whole values `parse_tags` split out of the field rather than as a /// substring of it, so `--tag bug` is not answered by a ticket tagged `bugfix`, and a /// ticket with no tags matches nothing at all. /// /// Case sensitive, the opinion the field already takes everywhere else: `tag_color` /// draws `Bug` and `bug` in two colours because they are two tags, and a filter that /// folded them would list tickets carrying a tag nobody asked for. fn filter_by_tag(items: Vec, tag: Option<&str>) -> Vec { match tag { Some(tag) => items .into_iter() .filter(|item| item.tags.iter().any(|carried| carried == tag)) .collect(), None => items, } } /// Keep only the members of `campaign`, or everything when none was asked for. fn filter_by_campaign(items: Vec, campaign: Option<&str>) -> Vec { match campaign { Some(uuid) => items .into_iter() .filter(|item| item.campaign.as_deref() == Some(uuid)) .collect(), None => items, } } /// Keep only the tickets at `level`, or everything when no level was asked for. fn filter_by_priority(items: Vec, level: Option) -> Vec { match level { Some(level) => items .into_iter() .filter(|item| item.priority == Priority::Level(level)) .collect(), None => items, } } pub fn cmd_add(args: &AddArgs, start: &Path) -> Result<()> { let AddArgs { title, description, acceptance, plan, tags, due, owner, priority, } = args; let owner = match owner { Some(o) => Some(o.clone()), None => get_git_user(), }; let worklane_dir = find_worklane_dir(start)?; let backlog_dir = worklane_dir.join("backlog"); if !backlog_dir.exists() { return Err(anyhow!("Backlog directory not found. Run `worklane init` first.")); } let id = uuid::Uuid::new_v4(); let slug = slug(title); let filename = format!("{}_{}.md", id, slug); let filepath = backlog_dir.join(&filename); // Joined with a single newline, so an empty value is how a caller spells a // paragraph break and an all-blank description is no description at all. let description = trim_blank_ends(description); let description_text = if description.is_empty() { "_No description provided._".to_string() } else { description.join("\n") }; let mut body = format!( "# {}\n\ \n\ ## Description\n\ {}\n\ \n\ ## Acceptance Criteria\n\ {}\n\ \n\ ## Implementation Plan\n\ {}\n\ \n\ ## Metadata\n\ \n\ - **ID**: {}\n\ - **Priority**: {}\n\ - **Tags**: {}\n\ - **Due**: {}\n\ - **Owner**: {}\n\ - **Created At**: {}\n\ - **Status**: backlog\n\ ", title, description_text, if acceptance.is_empty() { "_No acceptance criteria provided._".to_string() } else { acceptance .iter() .map(|c| format!("- [ ] {}", c)) .collect::>() .join("\n") }, if plan.is_empty() { "_No implementation plan provided._".to_string() } else { plan.iter() .enumerate() .map(|(i, s)| format!("{}. {}", i + 1, s)) .collect::>() .join("\n") }, id, match priority { Some(level) => level.to_string(), None => "_Not set_".to_string(), }, if tags.is_empty() { "_None_".to_string() } else { tags.join(", ") }, due.as_deref().unwrap_or("_Not set_"), owner.as_deref().unwrap_or("_Not set_"), Local::now().format(TIMESTAMP_FORMAT), ); body.push('\n'); // No existence check ahead of this. The name carries a uuid generated a few lines // up, so a collision is not something that happens, and the branch that used to // guard the write claimed the *title* was taken, which is the opposite of what the // format allows: duplicate titles are supported and `add_allows_duplicate_titles` // pins it. `cmd_campaign_add` deliberately does not carry it either. What is left is // the write's own failure, named with the ticket and the path the way the other // writes in the tree name them. fs::write(&filepath, body).map_err(|e| { anyhow!("Could not write ticket '{}' at {}: {}", title, filepath.display(), e) })?; println!("Created ticket: {}", filename); Ok(()) } pub fn cmd_show(search: &str, worklane_dir: &Path) -> Result<()> { let (_status, title, content) = resolve_ticket(search, worklane_dir)?; let ticket_uuid = parse_ticket_field(&content, "ID"); // Read before anything is printed, so a board that cannot be read fails instead of // half printing a ticket. let resolved = resolved_for(&content, worklane_dir)?; // The only title in the output: content_trim_colored used to print it a second // time from the file content. Green per the colour guideline, and the rule is // measured in characters so a non-ASCII title is not over-drawn. println!("{}", color_text(&title, Color::Green)); println!("{}", "─".repeat(title.chars().count())); println!("\n{}", content_trim_colored(&content, &resolved)); if ticket_uuid != "_Not set_" { let entries = read_history(worklane_dir, &ticket_uuid)?; let formatted = format_history(&entries); println!("{}", formatted); } 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"; const TAG: &str = "tag"; /// 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 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. fn write_then_replace( worklane_dir: &Path, path: &Path, filename: &str, content: &str, kind: &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 {} '{}' at {}: {}", kind, title, temp.display(), e )); } if let Err(e) = fs::rename(&temp, path) { let _ = fs::remove_file(&temp); return Err(anyhow!( "Could not write {} '{}' at {}: {}", kind, title, path.display(), e )); } Ok(()) } /// 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. 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!( "Could not locate the file for {} '{}': it has no ID field", kind, title )); } for entry in fs::read_dir(dir)? { let entry = entry?; let path = entry.path(); if !path.extension().is_some_and(|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 {} '{}' in {}", kind, 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. /// /// Two atomic steps, in this order. The content is staged in a temp file and /// renamed over the source, so a partial write is thrown away and the original is /// untouched. Only then is the file renamed into the target directory. /// /// The old order renamed first and wrote second, so a failure in between left the /// ticket sitting in its new directory still claiming the old status. Writing /// straight to the target and deleting the source afterwards would instead have it /// in both directories at once. Neither happens here. The worst case is a ticket /// still in its old directory carrying a Status field one move ahead, which the /// next `mv` corrects, since the directory is what decides the current status. fn move_ticket_file( worklane_dir: &Path, from: &Path, to: &Path, filename: &str, content: &str, title: &str, ) -> Result<()> { let source = from.join(filename); let dest = to.join(filename); 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. fs::rename(&source, &dest) .map_err(|e| anyhow!("Could not move ticket '{}' to {}: {}", title, dest.display(), e)) } /// Refuse a move while a ticket it is `blocked by` is not done. /// /// Every move, not only the one into committed: an open blocker is a reason not to /// start and a reason not to finish, and one rule is easier to hold than a table of /// which transitions care. Called before anything is written, so a refusal leaves no /// rename, no rewritten field and no half moved ticket. /// /// A target the board does not have warns and allows the move. Refusing there would /// wedge the ticket behind a bookkeeping fault with no way out but `--force`, and a /// dangling uuid is not a dependency. fn check_blockers(worklane_dir: &Path, content: &str, title: &str) -> Result<()> { let blockers: Vec = parse_relations(content, title)? .into_iter() .filter(|relation| relation.kind == RelationKind::BlockedBy) .collect(); if blockers.is_empty() { return Ok(()); } let index = RelationIndex::load(worklane_dir)?; let mut open: Vec = Vec::new(); for blocker in &blockers { match index.get(&blocker.target) { // Discarded satisfies a block the way done does: there is nothing left to // wait for. Whether the dependent still makes sense was asked when the // blocker was discarded, which is `check_dependents`' refusal. Some(target) if !is_open(&target.status) => {} Some(target) => open.push(format!( " ({}) {} [{}]", color_text(short_id(&target.uuid), Color::Red), target.title, color_text(&target.status, Color::Orange), )), None => eprintln!( "Warning: ticket '{}' is blocked by {}, which is not on the board.", title, short_id(&blocker.target), ), } } if open.is_empty() { return Ok(()); } // Every open blocker, not the first: a ticket waiting on three of them is not // unblocked by clearing the one the message happened to name. Err(anyhow!( "Cannot move '{}' while it is blocked by:\n{}\nUse --force (-f) to move it anyway.", color_text(title, Color::Green), open.join("\n"), )) } /// Refuse discarding a ticket while open tickets are blocked by it. /// /// The mirror of [`check_blockers`], asked at the other end of the edge: those tickets /// recorded a dependency on work that is about to be declared never-happening, so their /// plans need a look before the ground moves. `-f` is the caller saying they looked. /// /// Tickets already done or discarded do not hold it up: a dependency that was satisfied /// or abandoned is nobody's plan anymore. fn check_dependents(worklane_dir: &Path, uuid: &str, title: &str) -> Result<()> { let index = RelationIndex::load(worklane_dir)?; // Every open dependent, not the first, for the reason `check_blockers` names them // all. let waiting: Vec = index .iter() .filter(|ticket| is_open(&ticket.status)) .filter(|ticket| { ticket .relations .iter() .any(|relation| relation.kind == RelationKind::BlockedBy && relation.target == uuid) }) .map(|ticket| { format!( " ({}) {} [{}]", color_text(short_id(&ticket.uuid), Color::Red), ticket.title, color_text(&ticket.status, Color::Orange), ) }) .collect(); if waiting.is_empty() { return Ok(()); } Err(anyhow!( "Cannot discard '{}' while open tickets are blocked by it:\n{}\nUse --force (-f) to discard it anyway.", color_text(title, Color::Green), waiting.join("\n"), )) } /// A status is a [`Status`] rather than a string, so an unknown one is clap's to refuse /// and nothing here has to check. What is left is the order of the flow, which is /// `Status::ALL`. pub fn cmd_mv( ticket_id: &str, target: Status, force: bool, actor: &Option, reason: &Option, start: &Path, ) -> Result<()> { let target_status = target.as_str(); // A reason is one fact on one line, which is how the renderer draws it, so a // newline smuggled in through the shell collapses with the whitespace around it. // All blank means none, rather than an empty field in the log. let reason = reason .as_deref() .map(str::split_whitespace) .map(|words| words.collect::>().join(" ")) .unwrap_or_default(); let worklane_dir = find_worklane_dir(start)?; let (current_status, title, resolved) = resolve_ticket(ticket_id, &worklane_dir)?; let current_idx = Status::ALL .iter() .position(|status| status.as_str() == current_status) .unwrap(); let target_idx = Status::ALL.iter().position(|status| *status == target).unwrap(); // Discarding is not a stage of work, so the walk rules below do not apply to // entering it: a ticket is abandoned from wherever it stands. They do apply to // leaving it, which with discarded last in `Status::ALL` is always a backward move, // so un-discarding needs `-f` with no rule of its own. let discarding = target == Status::Discarded; if !force && !discarding && target_idx < current_idx { return Err(anyhow!( "Cannot move backward from {} to {}. Use --force (-f) to allow.", color_text(¤t_status, Color::Orange), color_text(target_status, Color::Orange), )); } if !force && !discarding && target_idx != current_idx + 1 && target_idx != current_idx { return Err(anyhow!( "Can only move one stage forward at a time. Use --force (-f) to skip stages." )); } if current_status == target_status { println!( "Ticket is already in '{}' status.", color_text(target_status, Color::Orange) ); return Ok(()); } // After the no-op above, so a ticket is never refused for a move it is not making, // and behind `force`, which is where the other two overrides of a rule the board // keeps true already live. The two guards look opposite ways: a ticket being worked // must not run ahead of what it waits on, and a ticket being abandoned owes nothing // to its own blockers but must not be pulled out from under the tickets waiting on // it. if !force { match discarding { true => check_dependents(&worklane_dir, &parse_ticket_field(&resolved, "ID"), &title)?, false => check_blockers(&worklane_dir, &resolved, &title)?, } } let current_path = worklane_dir.join(¤t_status); let target_path = worklane_dir.join(target_status); // A board created before a status existed has no directory for it, and the first // move into one is the wrong place to refuse. Idempotent for every board that has // it. fs::create_dir_all(&target_path)?; // 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)?; // Behind every refusal above, so a move that does not happen writes no stamp, and // spliced in here rather than after the rename so it travels with the same // crash-safe write the Status field does. let content = set_status_stamp( &content, target, &Local::now().format(TIMESTAMP_FORMAT).to_string(), &title, )?; let found_filename = find_entry_file(¤t_path, TICKET, &parse_ticket_field(&resolved, "ID"), &title)?; move_ticket_file( &worklane_dir, ¤t_path, &target_path, &found_filename, &content, &title, )?; // After the move, never before: an entry for a move that was refused would be a log // of things that did not happen. The no-op above returns without one for the same // reason, and without its --reason with it. write_entry( &worklane_dir, &parse_ticket_field(&resolved, "ID"), Kind::Status, &change(¤t_status, target_status), &resolve_actor(actor.as_deref()), &reason, )?; println!( "Moved ticket '{}' from {} to {}", color_text(&title, Color::Green), color_text(¤t_status, Color::Orange), color_text(target_status, Color::Orange), ); Ok(()) } pub fn cmd_comment( ticket_id: &str, body: &str, actor: &Option, start: &Path, ) -> Result<()> { if body.is_empty() { return Err(anyhow!("Comment body is required.")); } let worklane_dir = find_worklane_dir(start)?; let (_status, title, content) = resolve_ticket(ticket_id, &worklane_dir)?; let ticket_uuid = parse_ticket_field(&content, "ID"); if ticket_uuid == "_Not set_" { return Err(anyhow!("Could not determine ticket ID.")); } let filename = write_entry( &worklane_dir, &ticket_uuid, Kind::Comment, body, &resolve_actor(actor.as_deref()), "", )?; 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), ] } /// The lines a caller's values amount to, or the refusal an all-blank call earns. /// /// An empty value is a paragraph break, so a call whose values are *every one* blank asked /// for nothing, and writing an empty section is not what it meant. Shared by `set` and /// `campaign set` because the rule is the section's rather than the object's. /// /// `instead` is the way out, and it is the caller's because the callers differ: a ticket's /// section is emptied with `--clear `, and a campaign's description has no cleared /// form at all, per [`CampaignSetArgs`]. fn replaced_items(section: &Section, values: &[String], instead: &str) -> Result> { let items = section.normalise(values); if items.is_empty() { return Err(anyhow!( "An empty value is a paragraph break, not a way to empty the {}: {}", section.label, instead )); } Ok(items) } /// The same for `append`, which has no way out to name: appending nothing was never a way /// to empty anything, so the message says only that there was nothing to add. fn appended_items(section: &Section, values: &[String]) -> Result> { let items = section.normalise(values); if items.is_empty() { return Err(anyhow!( "Nothing to append to the {}: every value given was blank", section.label )); } Ok(items) } /// 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 dir = worklane_dir.join(status); save_entry(worklane_dir, &dir, TICKET, uuid, title, new_title, content) } /// 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) } /// 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 = dir.join(&renamed); fs::rename(&path, &destination).map_err(|e| { anyhow!( "Could not rename {} '{}' to {} after updating it: {}", kind, title, destination.display(), e ) })?; } } 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) { report_in(fields, title, Color::Green, verb) } /// The same, for a subject that is not a title. /// /// Green means title, everywhere, so the one caller whose subject is a tag cannot use it: /// a tag is drawn in a `TAG_COLORS` slot or it is drawn wrong, and green is deliberately /// not one of them. The colour is passed in rather than decided here, which is the trade /// `paint` makes with `color_text`, and it keeps the wording in one place so a tag reports /// a no-op in the same words a ticket does. fn report_in(fields: &[&str], title: &str, color: Color, verb: &str) { if fields.is_empty() { println!("No changes to '{}'", color_text(title, color)); return; } println!("{} {} on '{}'", verb, fields.join(", "), color_text(title, color)); } 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(); let mut cleared: 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); } for (section, values) in section_args(&args.description, &args.acceptance, &args.plan) { if values.is_empty() { continue; } let clear = format!("use --clear {}", section.clear.map_or("", Clearable::name)); let items = replaced_items(section, values, &clear)?; let next = set_section_body(&content, section, &items)?; 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, &mut changed, "tags", next); } if let Some(due) = &args.due { let next = set_metadata_field(&content, "Due", due, &title)?; 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, &mut changed, "priority", next); } // 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(()); } let renamed = changed.contains(&"title").then_some(()).and(args.title.as_ref()); save_ticket(&worklane_dir, &status, &uuid, &title, renamed, &content)?; // Tags alone, of everything `set` writes. The other fields change often enough that a // log of them is noise, and `apply` is what decides this: a field it did not record as // changed was already what the call asked for. Emptying the field counts, since // `--clear tags` is the same field going somewhere. if changed.contains(&"tags") || cleared.contains(&"tags") { write_entry( &worklane_dir, &uuid, Kind::Tags, &change( &parse_ticket_field(&original, "Tags"), &parse_ticket_field(&content, "Tags"), ), &resolve_actor(args.actor.as_deref()), "", )?; } let shown = args.title.clone().unwrap_or(title); if !changed.is_empty() { report(&changed, &shown, "Updated"); } if !cleared.is_empty() { report(&cleared, &shown, "Cleared"); } Ok(()) } /// Rewrite the Owner field, the only writer of it. /// /// The user comes first at the call site, after Unix `chown`, and the reasoning for /// reversing the ticket-first order is on the `Chown` variant. A swapped call is left /// to resolution: nothing here inspects `user` to see whether it also names a ticket, /// since the check would only fire on the case resolution already refuses and would /// 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. 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.unwrap_or(NOT_SET), &title)?; if content == original { report(&[], &title, "Updated"); return Ok(()); } save_ticket(&worklane_dir, &status, &uuid, &title, None, &content)?; // Behind the no-change return above, so a chown to the owner a ticket already has // records nothing, and after the save, so a failed write logs nothing. write_entry( &worklane_dir, &uuid, Kind::Owner, &change( &parse_ticket_field(&original, "Owner"), &parse_ticket_field(&content, "Owner"), ), &resolve_actor(args.actor.as_deref()), "", )?; let verb = match user { Some(_) => "Updated", None => "Cleared", }; report(&["owner"], &title, verb); 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 = appended_items(section, values)?; 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(()) } /// Record a relation from one ticket to another. /// /// One side is written and the inverse is derived wherever it is shown. `blocked by` /// goes on the gated ticket rather than `blocks` on the blocker: the gated ticket is the /// one whose move is refused and whose author knows about the dependency. `relates to` /// is symmetric, so it is written once, on whichever end the caller ran it from. /// /// The kinds are a flag each rather than a `--kind` value, so an unknown kind is a /// usage error at the door instead of a line written into the file and refused on the /// way back out. /// The stored relation a `--clear` names, or `None` when the ticket does not hold it. /// /// Two tiers, in this order. A uuid prefix against the targets this ticket already /// stores, which is the only tier that can reach a dangling edge: the target's ticket is /// gone, so no search of the board resolves it, and that is the case most likely to need /// clearing. Then the ordinary ticket search, so a title or a prefix of a live ticket /// works here the way it does in every other argument. /// /// The prefix tier is the ticket's own relations and not the board, so it stays cheap and /// cannot be made ambiguous by a ticket somewhere else. `MIN_ID_SEARCH` is the same floor /// `resolve_in` puts under its id tier, and the comparison is case insensitive for the /// same reason: an id typed back off a listing has to resolve in whatever case it was /// read. /// /// A search that reaches neither tier is an error, not a no-op. A relation the ticket does /// not hold reports no change, which is what the caller asked for either way, but a search /// naming nothing at all is a typo and reporting no change for it would swallow it. fn find_relation( existing: &[Relation], kind: RelationKind, search: &str, title: &str, worklane_dir: &Path, ) -> Result> { let held: Vec<&Relation> = existing.iter().filter(|held| held.kind == kind).collect(); let wanted = search.to_lowercase(); let by_prefix: Vec<&Relation> = held .iter() .copied() .filter(|held| { search.chars().count() >= MIN_ID_SEARCH && held.target.to_lowercase().starts_with(&wanted) }) .collect(); match by_prefix.as_slice() { [only] => return Ok(Some((*only).clone())), // Named rather than guessed at, the way an ambiguous ticket search is: the // candidates are printed and nothing is written. [_, _, ..] => { return Err(anyhow!( "'{}' matches {} '{}' relations on '{}': {}. Name more of the id", search, by_prefix.len(), kind.label(), title, by_prefix .iter() .map(|held| short_id(&held.target)) .collect::>() .join(", ") )); } [] => {} } match resolve_ticket(search, worklane_dir) { Ok((_status, _target_title, target)) => { let target_uuid = parse_ticket_field(&target, "ID"); Ok(held.into_iter().find(|held| held.target == target_uuid).cloned()) } // The resolver's own reason is carried through, so an ambiguous search says it is // ambiguous rather than being reported as nothing at all. Err(reason) => Err(anyhow!( "No '{}' relation on '{}' matches '{}': {}", kind.label(), title, search, reason )), } } pub fn cmd_relate(args: &RelateArgs, 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 existing = parse_relations(&original, &title)?; // Every target resolved, every kind parsed and every refusal raised before a byte is // written, so a call naming one good ticket and one bad one records neither. let asked = args.cleared()?; let mut items: Vec = Vec::new(); let mut changed: Vec<&str> = Vec::new(); // Every addition the call asked for, whether or not it is one to write. `items` drops // the ones already held, and a contradiction has to be caught on what was *asked*: a // relation already in the file is not in `items`, so comparing against that would let // `--blocked-by X --clear blocked-by X` quietly remove it. let mut requested: Vec = Vec::new(); for (kind, targets) in args.requested() { for search in targets { let (_target_status, target_title, target) = resolve_ticket(search, &worklane_dir)?; let target_uuid = parse_ticket_field(&target, "ID"); if target_uuid.trim().is_empty() || is_unknown_value(&target_uuid) { return Err(anyhow!( "Ticket '{}' has no ID field, so nothing can point at it", target_title )); } if target_uuid == uuid { return Err(anyhow!( "A ticket cannot relate to itself, and '{}' is the ticket being edited", title )); } let relation = Relation { kind, target: target_uuid }; requested.push(relation.clone()); // Already held, either in the file or earlier in this call. Recording it // twice would read as two dependencies on one ticket. if existing.contains(&relation) || items.contains(&relation.item()) { continue; } items.push(relation.item()); if !changed.contains(&kind.label()) { changed.push(kind.label()); } } } let mut dropped: Vec = Vec::new(); let mut cleared: Vec<&str> = Vec::new(); for (kind, search) in asked { let Some(relation) = find_relation(&existing, kind, search, &title, &worklane_dir)? else { continue; }; // Both directions in one call, the way `set --clear` refuses a field it is also // replacing: nothing is written rather than one of the two silently winning. if requested.contains(&relation) { return Err(anyhow!( "--{} and --clear {} name the same relation to '{}', so nothing was written", kind.flag(), kind.flag(), short_id(&relation.target) )); } if dropped.contains(&relation) { continue; } dropped.push(relation); if !cleared.contains(&kind.label()) { cleared.push(kind.label()); } } if items.is_empty() && dropped.is_empty() { report(&[], &title, "Recorded"); return Ok(()); } // Removals first, by rewriting the section from what is left, then additions appended // to that. Two passes rather than one rebuild of the whole section: a call with no // `--clear` then takes exactly the path it always took, and `append_section_body` goes // on deciding where a new line lands. let mut content = original.clone(); if !dropped.is_empty() { let kept: Vec = existing .iter() .filter(|held| !dropped.contains(held)) .map(|held| held.item()) .collect(); // The placeholder rather than an empty body when the last edge goes, which is the // line `add` writes and the line `append` treats as no content, so the section can // be written to again without it being left above what follows. content = match kept.is_empty() { true => clear_section_body(&content, &RELATIONS)?, false => set_section_body(&content, &RELATIONS, &kept)?, }; } if !items.is_empty() { content = append_section_body(&ensure_section(&content, &RELATIONS), &RELATIONS, &items)?; } save_ticket(&worklane_dir, &status, &uuid, &title, None, &content)?; if !changed.is_empty() { report(&changed, &title, "Recorded"); } if !cleared.is_empty() { report(&cleared, &title, "Cleared"); } Ok(()) } // ------------------------------------------------------------------- campaigns -- /// File a new campaign. /// /// Written through `write_then_replace` rather than `fs::write`, so a failure leaves no /// half-written campaign behind. `cmd_add` predates that primitive and still uses the /// plain write; the difference is noted on the ticket rather than fixed here. pub fn cmd_campaign_add(args: &CampaignAddArgs, start: &Path) -> Result<()> { let CampaignAddArgs { title, description, codename, owner, } = args; let worklane_dir = find_worklane_dir(start)?; let dir = ensure_campaigns_dir(&worklane_dir)?; let owner = match owner { Some(owner) => Some(owner.clone()), None => get_git_user(), }; let id = uuid::Uuid::new_v4(); let filename = format!("{}_{}.md", id, slug(title)); let path = dir.join(&filename); let body = campaign_body( title, description, codename.as_deref(), &id, owner.as_deref(), &Local::now().format(TIMESTAMP_FORMAT).to_string(), ); write_then_replace(&worklane_dir, &path, &filename, &body, CAMPAIGN, title)?; println!("Created campaign: {}", filename); Ok(()) } /// List the campaigns with how far each has got. /// /// The counts come from one pass over the status directories per campaign. That is a /// scan per row rather than one scan reused, and it is deliberate: the alternative is a /// map from campaign uuid to counts built in a single walk, which is worth writing when /// a board has enough campaigns to notice and is premature now. pub fn cmd_campaign_ls(worklane_dir: &Path, ids: bool) -> Result<()> { let index = CampaignIndex::load(worklane_dir)?; // Ahead of the empty check, which prints prose: a completion must offer nothing // rather than offer a sentence, the same bargain `list_ids` takes with a missing // status directory. if ids { for campaign in index.iter() { println!("{}\t{}", short_id(&campaign.uuid), campaign.title); } return Ok(()); } if index.is_empty() { println!("No campaigns yet. `worklane campaign add --title` files one."); return Ok(()); } let colored = should_use_colors(); println!("Campaigns:\n"); for campaign in index.iter() { let standing = Standing::of(&members(worklane_dir, &campaign.uuid)?); let state = match standing.state() { Some(state) => format!(" [{}]", paint(state, Color::Orange, colored)), None => String::new(), }; // The codename between the id and the title, in the colour the board draws it in // and with the same mark: the answer to "which campaign is this" is one word, and // it should be the same word wherever it is read. A campaign filed without one // spends nothing on it, the way an untagged card spends no row. let codename = match campaign.codename.is_some() { true => { let label = campaign_label(&campaign.uuid, campaign.codename.as_deref()); format!("{} ", paint_cells(&[label], colored)) } false => String::new(), }; println!( " ({}) {}{} | {}{}", paint(short_id(&campaign.uuid), Color::Red, colored), codename, campaign.title, standing.label(), state, ); } Ok(()) } /// Every tag on the board: the ones the tickets carry, the ones the file declares, and /// what each declared one means. /// /// The vocabulary itself, which nothing else could answer: `ls --tag` filters by a tag /// already known, and the decorated listing does not print tags at all. A grooming sweep /// starts by asking what the vocabulary *is*, and `assets/PLAN.md` used to have to say /// that the question could only be answered by reading the tickets. /// /// **The union of the two vocabularies, not either one.** Since `tags.md` exists there are /// two: the tags the file declares and the tags the tickets carry. A declared tag nothing /// carries lists at zero rather than being dropped, and a carried tag nothing declares /// still lists. Those two cases are the whole reason to declare tags at all, so this is /// the command that has to show them apart. /// /// **Alphabetical, and case sensitive.** `--tag` matches a whole value case sensitively, /// so `bug` and `Bug` are two tags and listing them as one would hide the reason a filter /// came back short. Sorting puts them next to each other, which is where a near-duplicate /// is spotted. /// /// Machine-readable, the second output in the tree that is: the tag, a tab, the count, and /// a tab and the annotation's opening line for a tag the file declares. Fish reads what /// follows the first tab as a description, a script takes `cut -f1`, and neither wants an /// escape sequence. /// /// **A carried but undeclared tag is marked by the absence of the third field**, which is /// where the shape comes from. Anything appended to the tag itself would have a completion /// offer a tag that does not exist, and anything added to the count would stop the second /// field being a number. Absence costs neither, and it buys the one property a marker /// could not: a board with no `tags.md` has every tag undeclared, so it prints two fields /// a line, which is byte for byte what this printed before the file existed. The shipped /// fish completion of an older version is still reading that. /// /// Every status, done included, for the reason `ls --ids` includes it: a tag retired months /// ago is still part of the answer to what the vocabulary has been. pub fn cmd_tags(worklane_dir: &Path) -> Result<()> { // Through the same `load` `tags add` uses, so a file that is there and cannot be read // is an error here too. The listing is the one tag command that could go on without the // file, and reporting a vocabulary while silently treating a broken file as no file is // the wrong half of the answer. let index = TagIndex::load(worklane_dir)?; // BTreeMap rather than a sort afterwards: the order is the point, and the counting // wants a map anyway. Seeded from the vocabulary rather than merged into afterwards, // which is what puts a declared tag nothing carries in at zero. let mut counts: BTreeMap = index.names().map(|tag| (tag.to_string(), 0)).collect(); for status in status_dirs() { let status_path = worklane_dir.join(status); // Skipped rather than refused, as in `list_ids`, and for the same reason. if !status_path.exists() { continue; } for item in collect_ticket_items(&status_path)? { for tag in item.tags { *counts.entry(tag).or_default() += 1; } } } for (tag, count) in counts { match index.summary(&tag) { Some(summary) => println!("{tag}\t{count}\t{summary}"), None => println!("{tag}\t{count}"), } } Ok(()) } /// Declare a tag, and what it means. /// /// The counterpart of `cmd_tags`, which reports the vocabulary the tickets *carry*. This /// writes the one the board *intends*, and the two are deliberately not kept in step: a /// declaration tags nothing, so the file cannot be used to work out what is in use, and /// `tags add` on a word no ticket carries is the normal case rather than a mistake. /// /// **A tag already declared is refused rather than overwritten**, the way `add` refuses /// nothing and `campaign set --codename` refuses a replacement without `--force`. An /// annotation is the sentence a whole team files tickets against, so replacing one by /// typing `add` twice is not something to do by accident. The refusal names the command /// that does replace it, since that is the next thing the caller wants. /// /// The whole file is re-rendered from the parsed vocabulary, so declaring a tag also /// re-sorts the file and rewrites its preamble. That is why an unreadable file is an error /// in `TagIndex::load` rather than an empty vocabulary: here, empty would mean erased. pub fn cmd_tag_add(args: &TagAddArgs, start: &Path) -> Result<()> { let worklane_dir = find_worklane_dir(start)?; let mut index = TagIndex::load(&worklane_dir)?; if index.declared(&args.tag) { return Err(anyhow!( "Tag '{}' is already declared, so nothing was written. \ Use `worklane tags set` to change what it means", args.tag )); } // Joined with a single newline, so an empty value is a paragraph break, exactly as it // is for a description. let annotation = trim_blank_ends(&args.annotation).join("\n"); index.declare(&args.tag, &annotation); write_then_replace( &worklane_dir, &tags_path(&worklane_dir), TAGS_FILE, &index.render(), TAG, &args.tag, )?; // The tag in its own colour, which is the colour it is drawn in on every card and in // every listing: `tag_color` is a pure function of the word. println!("Declared tag: {}", color_text(&args.tag, tag_color(&args.tag))); Ok(()) } /// Replace what a declared tag means. /// /// The other half of `tags add`, and the half `campaign` still lacks for its description, /// 32e98ab. An annotation is the sentence a whole team files tickets against, so getting it /// wrong once must not be permanent. /// /// **A tag that is not declared is refused rather than declared here.** `add` and `set` are /// a pair, each refusing what the other is for, so which of the two wrote a line is never a /// question of which one happened to be typed. The refusal names the other command, the way /// `add`'s names this one. /// /// The no-op compares the rendered file rather than the annotation, which is what `apply` /// does for a ticket: the file is the thing that would be written, so it is the thing worth /// asking whether the write would change. pub fn cmd_tag_set(args: &TagSetArgs, start: &Path) -> Result<()> { let worklane_dir = find_worklane_dir(start)?; let mut index = TagIndex::load(&worklane_dir)?; if !index.declared(&args.tag) { return Err(anyhow!( "No tag '{}' is declared, so nothing was written. \ Use `worklane tags add` to declare it", args.tag )); } let original = index.render(); index.declare(&args.tag, &trim_blank_ends(&args.annotation).join("\n")); let next = index.render(); let mut changed: Vec<&'static str> = Vec::new(); if original != next { changed.push("annotation"); write_then_replace( &worklane_dir, &tags_path(&worklane_dir), TAGS_FILE, &next, TAG, &args.tag, )?; } report_in(&changed, &args.tag, tag_color(&args.tag), "Updated"); 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. /// /// **Replacing a codename the campaign already has needs `--force`.** Once a campaign has /// one it is referred to by it: it is on every card in the campaign, it is what resolves the /// campaign at the command line, and changing it out from under that is the same mistake /// overwriting an edited skill document would be. So it is refused, and the refusal names /// both words and the flag, the way `install-skill` names `--force` rather than leaving it /// to be found. /// /// Checked before any edit is applied, like `SetArgs::contested`, so a call that also /// carries `--title` writes neither field rather than half of what was asked for. /// /// No-op detection compares the whole file, the way `set` and `chown` do, so setting a /// codename a campaign already carries writes nothing. That is a no-op and not a refusal: /// `--force` is about overwriting a *different* word, and there is nothing to overwrite. /// /// **The description goes through `set_section_body` and the `DESCRIPTION` entry**, the /// section table `cmd_set` and `campaign_body` already read, so what a campaign's one prose /// section *is* stays decided in one place. A second definition scoped to campaigns would /// drift on the spelling of the heading, which is the drift `campaign_body` was written /// against. /// /// A campaign whose Description heading is gone is refused by that call rather than given /// the section back through `ensure_section`. Every campaign the tool has ever filed carries /// the heading, so an insertion path here would be reachable only from a hand-edited file: /// that is the opposite of the Relations case, where `add` writes nothing and the insertion /// is the only path there is. 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 overwrite = match (&args.codename, &campaign.codename) { (Some(wanted), Some(held)) if wanted != held => Some((held, wanted)), _ => None, }; if let Some((held, wanted)) = overwrite.filter(|_| !args.force) { return Err(anyhow!( "Campaign '{}' is already codenamed '{}', so nothing was written. \ Pass --force to replace it with '{}'", title, held, wanted )); } 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 !args.description.is_empty() { let items = replaced_items( &DESCRIPTION, &args.description, "a campaign's description has no cleared form", )?; let next = set_section_body(&content, &DESCRIPTION, &items)?; apply(&mut content, &mut changed, DESCRIPTION.label, 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(()) } /// Add a paragraph to a campaign's description. /// /// The other half of `campaign set --description`, and `cmd_append` for a campaign: the same /// `append_section_body` and the same `DESCRIPTION` entry, so a paragraph lands under a /// campaign's description the way it lands under a ticket's, blank line and all. A campaign /// filed with no description holds the placeholder, and that is replaced rather than /// followed, which is `append_section_body`'s rule and not a case handled here. /// /// No whole-file comparison, unlike `set`: every value blank is refused above, so there is /// nothing left that appends nothing. `cmd_append` says it the same way. /// /// One section, so there is no loop and no list to report: what changed is the description /// or the call failed. pub fn cmd_campaign_append(args: &CampaignAppendArgs, start: &Path) -> Result<()> { let worklane_dir = find_worklane_dir(start)?; let campaign = resolve_campaign(&args.campaign, &worklane_dir)?; let items = appended_items(&DESCRIPTION, &args.description)?; let content = append_section_body(&campaign.content, &DESCRIPTION, &items)?; save_campaign(&worklane_dir, &campaign.uuid, &campaign.title, None, &content)?; report(&[DESCRIPTION.label], &campaign.title, "Appended to"); Ok(()) } /// Show a campaign, then its members grouped by status. /// /// Every status is shown, done included, unlike `ls`, which leaves done out of its /// listing. A campaign's whole point is what is finished against what is left, so /// hiding the finished half would hide the answer. pub fn cmd_campaign_show(search: &str, worklane_dir: &Path) -> Result<()> { let campaign = resolve_campaign(search, worklane_dir)?; println!("{}", color_text(&campaign.title, Color::Green)); println!("{}", "─".repeat(campaign.title.chars().count())); // No relations and no campaign of its own: a campaign is not a ticket, and neither // belongs to one. println!("\n{}", content_trim_colored(&campaign.content, &Resolved::default())); let grouped = members(worklane_dir, &campaign.uuid)?; let standing = Standing::of(&grouped); println!("{}", color_text("Members", Color::Orange)); println!("{}", "─".repeat("Members".chars().count())); println!("\n{}", standing.label()); for (status, items) in &grouped { if items.is_empty() { continue; } println!("\n{}", color_text(&format!("[{}]", status.to_uppercase()), Color::Orange)); display_ticket_items(items); } Ok(()) } /// Put a ticket in a campaign, the only writer of the Campaign field. /// /// The campaign is resolved first, so a call naming a good ticket and a bad campaign /// writes nothing. A ticket names at most one campaign because the field is rewritten /// rather than added to, so assigning a ticket that is already in one moves it. /// /// No-op detection compares the whole file, the way `set` and `chown` do, so assigning /// a ticket to the campaign it already names writes nothing. pub fn cmd_assign( campaign_search: &str, ticket_id: &str, actor: &Option, start: &Path, ) -> Result<()> { let worklane_dir = find_worklane_dir(start)?; let campaign = resolve_campaign(campaign_search, &worklane_dir)?; let (status, title, original) = resolve_ticket(ticket_id, &worklane_dir)?; let uuid = parse_ticket_field(&original, "ID"); let content = set_or_insert_metadata_field(&original, CAMPAIGN_FIELD, &campaign.uuid, &title)?; if content == original { println!( "Ticket '{}' is already in campaign '{}'", color_text(&title, Color::Green), campaign.title, ); return Ok(()); } save_ticket(&worklane_dir, &status, &uuid, &title, None, &content)?; // Behind the no-change return above and after the save, the rule every writer // follows. The entry records `Campaign::name`, not the uuid the field holds: what // the reader should see is settled here, when the entry is written. A campaign the // board no longer has reads `_missing_`, the way the Campaign field itself renders // a dangling uuid. let before = match parse_campaign(&original) { None => NOT_SET.to_string(), Some(old) => CampaignIndex::load(&worklane_dir)? .get(&old) .map(|was| was.name().to_string()) .unwrap_or_else(|| MISSING.to_string()), }; write_entry( &worklane_dir, &uuid, Kind::Campaign, &change(&before, campaign.name()), &resolve_actor(actor.as_deref()), "", )?; println!( "Assigned '{}' to campaign '{}'", color_text(&title, Color::Green), campaign.title, ); Ok(()) } /// Which criterion to act on, asked for when the caller did not say. /// /// A terminal gets the list and a prompt. Anything else gets the same list as an /// error, which is what `resolve_ticket` does for an ambiguous match and for the same /// reason: the opencode wrapper throws on the exit code and keeps stderr, so a list /// printed to stdout would be discarded and an agent would learn nothing. Prompting /// regardless would leave it blocked on a stdin that never closes. fn ask_which_criterion(criteria: &[Criterion], title: &str) -> Result { let listing = criteria_list(criteria); if !std::io::stdin().is_terminal() { return Err(anyhow!( "Which criterion of '{}'?\n{}\n\nRe-run with the number, or a substring of the text.", title, listing )); } println!("Acceptance criteria of '{}':", color_text(title, Color::Green)); println!("{}", listing); // Either form, since find_criteria takes both. print!("Number or text: "); std::io::stdout().flush()?; let mut answer = String::new(); std::io::stdin().lock().read_line(&mut answer)?; // An empty needle matches every criterion, so it would otherwise be reported as // ambiguous rather than as nothing having been chosen. if answer.trim().is_empty() { return Err(anyhow!("No criterion chosen")); } let chosen = find_criteria(criteria, &answer); match chosen.len() { 1 => Ok(chosen[0]), 0 => Err(anyhow!( "'{}' matches none of the {} criteria", answer.trim(), criteria.len() )), _ => Err(anyhow!( "'{}' matches more than one criterion, use the number", answer.trim() )), } } /// Every criterion the terms name, in the order `show` numbers them and without /// repeats. /// /// Resolved before a byte is written, and one bad term refuses the whole batch. A call /// that ticked the terms it understood and then failed would leave the ticket /// half-marked, with nothing in the file to say which half the caller meant, and the /// obvious retry would be reading the ticket back to find out. /// /// The offending term is named on its own rather than every failure at once: each /// message carries the criteria listing, so a batch of them would repeat the list per /// bad term and bury the first one. fn resolve_criteria(criteria: &[Criterion], terms: &[String], title: &str) -> Result> { let mut chosen: Vec = Vec::new(); for term in terms { if is_all_criteria(term) { chosen.extend(0..criteria.len()); continue; } let found = find_criteria(criteria, term); match found.len() { 1 => chosen.push(found[0]), 0 if is_index(term) => { return Err(anyhow!( "'{}' is not one of the {} criteria of '{}':\n{}", term.trim(), criteria.len(), title, criteria_list(criteria) )); } 0 => { return Err(anyhow!( "No criterion of '{}' matches '{}'. Its criteria are:\n{}", title, term, criteria_list(criteria) )); } _ => { return Err(anyhow!( "'{}' matches {} criteria of '{}':\n{}\n\nUse the number instead.", term, found.len(), title, numbered_criteria(criteria, &found) )); } } } // Sorted so the report reads in the order `show` numbers the criteria whatever // order the terms arrived in, and deduped so a criterion named twice, or by both // `all` and its own number, is reported once. chosen.sort_unstable(); chosen.dedup(); Ok(chosen) } pub fn cmd_check(args: &CheckArgs, checked: bool, start: &Path) -> Result<()> { let worklane_dir = find_worklane_dir(start)?; let (status, title, content) = resolve_ticket(&args.ticket, &worklane_dir)?; let criteria = criteria(&content); if criteria.is_empty() { return Err(anyhow!("Ticket '{}' has no acceptance criteria", title)); } let chosen = match args.criteria.as_slice() { [] => vec![ask_which_criterion(&criteria, &title)?], terms => resolve_criteria(&criteria, terms, &title)?, }; // Only the criteria that are not already in the target state, so a batch where // every box is already ticked writes nothing, the way a single one always has. let changing: Vec = chosen .iter() .copied() .filter(|offset| criteria[*offset].checked != checked) .collect(); if !changing.is_empty() { let lines: Vec = changing.iter().map(|offset| criteria[*offset].line).collect(); let updated = set_criteria(&content, &lines, checked); let uuid = parse_ticket_field(&content, "ID"); save_ticket(&worklane_dir, &status, &uuid, &title, None, &updated)?; } // Reported after the write, one line per criterion the call named, so nothing // claims a mark the file does not carry. let verb = if checked { "checked" } else { "unchecked" }; let past = if checked { "Checked" } else { "Unchecked" }; for offset in chosen { let criterion = &criteria[offset]; let state = if criterion.checked == checked { format!("Already {}", verb) } else { past.to_string() }; println!("{} {}: {}", state, offset + 1, color_text(&criterion.text, Color::Green)); } Ok(()) } /// Install the agent skills, or print one so a modified copy can be diffed. /// /// No board is looked for. The documents are what teach an agent worklane, so needing /// a `.worklane` to install them would put them out of reach exactly when they are /// wanted. /// /// With no name, every shipped document is installed. Narrowing to one is the /// exception rather than the rule, so that a document added in a later version reaches /// anyone who already knows the command. pub fn cmd_install_skill(skill: Option<&str>, force: bool, print: bool) -> Result<()> { if print { // Printing every document would run them together into something that is not // any of them, and the point of `--print` is to diff one against its copy. let name = skill.ok_or_else(|| { anyhow!( "name the skill to print, as in `worklane install-skill worklane --print`. This binary ships {}", install::skill_names() ) })?; print!("{}", install::skill_named(name)?.content); return Ok(()); } let chosen: Vec<&install::Asset> = match skill { Some(name) => vec![install::skill_named(name)?], None => install::SKILLS.iter().collect(), }; let root = install::skills_root()?; let written = install_each(&chosen, &root, force, |asset| { format!("worklane install-skill {} --print", asset.name) })?; // Once, and only when something arrived: repeating it per document would make the // instruction look like part of each outcome rather than the one thing to do next. if written { println!("Claude Code and opencode pick it up on their next session"); } Ok(()) } /// Write each asset under `root` and report what happened to it. /// /// Shared by both install commands, which differ in what they install and in what they /// say afterwards, never in how an outcome is reported. `compare` is the invocation the /// refusal points at, which is the one line that has to name the command it came from. /// /// Returns whether anything was written, because that is what decides the closing line: /// each command has its own thing to say about what picks the asset up, and neither /// should say it once per asset. fn install_each( chosen: &[&install::Asset], root: &Path, force: bool, compare: impl Fn(&install::Asset) -> String, ) -> Result { let mut written = false; for asset in chosen { match asset.install(root, force)? { install::Outcome::Written(path) => { println!("Installed the {} {} to: {}", asset.name, asset.what, path.display()); written = true; } install::Outcome::Unchanged(path) => { println!("Already up to date: {}", path.display()); } install::Outcome::Refused(path) => { println!("Differs from the version in this binary: {}", path.display()); println!("Compare with `{}`, or overwrite with --force", compare(asset)); } } } Ok(written) } /// Install the opencode tool definitions. /// /// No name argument, where `install-skill` has an optional one: there is a single tool /// file, so a name could only be right or wrong, and `--print` needs no help deciding /// what to print. pub fn cmd_install_tool(force: bool, print: bool) -> Result<()> { if print { print!("{}", install::TOOL.content); return Ok(()); } let chosen: Vec<&install::Asset> = install::TOOLS.iter().collect(); let root = install::tools_root()?; let written = install_each(&chosen, &root, force, |_| "worklane install-tool --print".to_string())?; // Not "on its next session", which is what the skills say: opencode reads its config // once at startup and does not reload it, so a running one keeps the tools it began // with. The second line is there because the file is executable and looks like it // needs a toolchain: it does not, it runs inside opencode. if written { println!( "opencode loads it in every project. Restart it: the config is read at startup and never reloaded" ); println!( "Nothing else to install. It runs in opencode's own runtime, so neither Bun nor @opencode-ai/plugin is needed on this machine" ); } Ok(()) }