use clap::Parser; use std::sync::LazyLock; use chrono::NaiveDate; use crate::util::{Clearable, PRIORITY_RANGE, RelationKind, Status, priority_legend}; /// clap wants a `&str` with a long enough lifetime, and the legend is built from /// the same ramp the listing uses rather than spelled out a second time. static PRIORITY_LEGEND: LazyLock = LazyLock::new(priority_legend); /// Reject a level outside the range at parse time, so no command has to. fn priority_level(raw: &str) -> Result { match raw.parse::() { Ok(level) if PRIORITY_RANGE.contains(&level) => Ok(level), _ => Err(format!( "priority must be a whole number from {} to {}", PRIORITY_RANGE.start(), PRIORITY_RANGE.end() )), } } /// What `--version` prints: the crate version and the commit it was built from. /// /// The sha is the part that matters. Two binaries built weeks apart both call /// themselves 0.1.0, so without it there is no way to tell whether the copy on /// PATH is the one carrying a given fix. const VERSION: &str = concat!(env!("CARGO_PKG_VERSION"), " (", env!("WORKLANE_GIT_SHA"), ")"); #[derive(Parser)] #[command(name = "worklane")] #[command(about = "A CLI tool for managing project status")] #[command(version = VERSION)] #[command(propagate_version = true)] pub struct Cli { /// Absent opens the board view, the way a bare `frig` does. #[command(subcommand)] pub command: Option, } /// Reject an empty value at parse time, so it lands as a usage error rather than a /// runtime one. /// /// Two messages rather than one, because the arguments that use this fall into two /// kinds. A search term or a title has no empty form at all, and that is all this says. /// A field that *can* be emptied says so and names `--clear`, which is [`clearable`] /// below: an accidentally empty variable must not blank a field silently, and somebody /// typing an empty value on purpose is reaching for exactly the flag that does it. /// /// Only the scalars use either one. For the multi-line sections an empty value is a /// paragraph break. fn non_empty(raw: &str) -> Result { if raw.trim().is_empty() { return Err("value cannot be empty".to_string()); } Ok(raw.to_string()) } /// Reject an empty value on an argument whose field can be cleared, and say how. /// /// The message names no command, because the arguments that use this belong to three: /// `set --tags`, `set --due`, `add --due` and the `chown` user. `set` and `chown` both /// take a `--clear`; `add` does not, and there a field is left unset by omitting the /// flag, which is what the caller was reaching for anyway. fn clearable(raw: &str) -> Result { if raw.trim().is_empty() { return Err("value cannot be empty, use --clear to return a field to unset".to_string()); } Ok(raw.to_string()) } /// Reject a due date that is not a real calendar date in the promised form. /// /// At parse time, like `priority_level`, so a mistyped date is a usage error with /// nothing written rather than a value the board goes on showing. `--due` is one of the /// scalars deliberately left without `PROSE`, so this is the same bargain: nothing here /// holds prose, and a wrong value should stop the command. /// /// **The shape is checked before chrono sees it.** `%Y-%m-%d` accepts an unpadded /// `2026-8-9`, which would then be stored exactly as typed and sort before `2026-10-01` /// in any comparison of the strings. Checking the length and the two dashes first is /// what lets a valid date be stored unchanged rather than normalised on the way in. /// /// Strict on the way in, tolerant on the way out: `util::due_date` still cuts a /// datetime down to its date, because a file written before this existed, or by hand, /// can hold one and still has to render. fn iso_date(raw: &str) -> Result { // An empty value keeps the message that explains why it is refused, since somebody // typing it is reaching for a way to clear the field rather than mistyping a date. clearable(raw)?; let bytes = raw.as_bytes(); let shaped = raw.len() == 10 && bytes[4] == b'-' && bytes[7] == b'-'; if !shaped || NaiveDate::parse_from_str(raw, "%Y-%m-%d").is_err() { // Not echoing the value: clap has already printed `invalid value '...' for // '--due '` above this line, and `priority_level` says its piece the same // way. return Err( "due date must be a real calendar date written as YYYY-MM-DD, for example 2026-08-29" .to_string(), ); } Ok(raw.to_string()) } /// Arguments that carry prose, and therefore have to accept a value starting with /// a hyphen. /// /// Ticket text quotes flag names constantly, and without this a criterion reading /// "--print is supported" is parsed as a flag and the whole ticket is refused. The /// trade, spelled out in AGENTS.md: on these arguments a genuinely mistyped flag /// now lands as content instead of raising a usage error. That is the right way /// round for prose, and it is why `due`, `priority`, `tags`, `owner` and `status` /// are deliberately left without it. const PROSE: bool = true; #[derive(clap::Subcommand)] pub enum Command { /// Initialize worklane in the current project Init, /// Add a new ticket to the backlog Add(AddArgs), /// List tickets, optionally filtered by status #[command(after_help = PRIORITY_LEGEND.as_str())] Ls(LsArgs), /// Show a ticket by UUID or title Show { /// Ticket UUID or title to search for id: String, }, /// Move a ticket to a different status Mv { /// Ticket UUID or title ticket: String, /// Target status #[arg(short, long)] status: Status, /// Force move (allows backward or non-sequential moves) #[arg(short, long)] force: bool, }, /// Replace fields on an existing ticket Set(SetArgs), /// Add to a section of an existing ticket Append(AppendArgs), /// Record a relation from one ticket to another Relate(RelateArgs), /// Change the owner of a ticket, or return it to unset /// /// User first, ticket second, after Unix `chown`. That reverses the ticket-first /// order `mv`, `comment` and `show` use, deliberately: the name borrows the Unix /// association, so the argument order borrows it too. /// /// A swap is caught by resolution rather than by a check of its own. Given /// `chown 641e3d5 alice` the second argument has to resolve as a ticket, and a bare /// username usually will not, so the call fails on its own. It is silently wrong /// only when both arguments resolve, which needs a ticket whose title matches the /// username. Chown(ChownArgs), /// Open the board view Tui { /// Projects to monitor, each resolved to the first `.worklane` at or above it. /// Several are shown as tabs. Defaults to the working directory paths: Vec, }, /// Tick acceptance criteria Check(CheckArgs), /// Untick acceptance criteria Uncheck(CheckArgs), /// Add a comment to a ticket Comment { /// Ticket UUID or title ticket: String, /// Comment body (required) #[arg(allow_hyphen_values = PROSE)] body: String, /// Owner #[arg(short, long)] owner: Option, }, /// Group tickets that have to be finished together Campaign { #[command(subcommand)] command: CampaignCommand, }, /// Put a ticket in a campaign /// /// Campaign first, ticket second, after `chown` and for the same reason: the /// container is what the call is about, and the order is worth being consistent /// about across the two commands that name two things. /// /// The only writer of the Campaign field. `add` has no `--campaign` and `set` has /// no `--campaign`, so the field keeps one writer the way Owner and Status do. Assign { /// Campaign UUID or title campaign: String, /// Ticket UUID or title ticket: String, }, /// Print a shell completion script /// /// The structure comes from the clap definition, so a flag added here appears /// without anyone remembering to. Fish gets a hand-written half appended for the /// values only the board knows, see `completions.rs`. Completions { /// fish, bash, zsh, elvish or powershell shell: clap_complete::Shell, }, /// Install the agent skills that teach an agent to use worklane /// /// Every shipped document by default. The optional name narrows it to one, and /// `--print` requires it: a diff is against one document, and printing them all /// concatenated would only look like one. InstallSkill { /// Skill to install or print, all of them if omitted skill: Option, /// Overwrite an existing copy that has been modified #[arg(long)] force: bool, /// Write it to stdout instead of installing it #[arg(long)] print: bool, }, } /// 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. #[derive(clap::Subcommand)] pub enum CampaignCommand { /// File a new campaign Add(CampaignAddArgs), /// List campaigns with their member counts Ls, /// Show a campaign and its members grouped by status Show { /// Campaign UUID or title campaign: String, }, } /// What a campaign holds: a title, a description and an owner. /// /// Deliberately narrower than [`AddArgs`]. There are no acceptance criteria, because a /// campaign's definition of done is derived from its members rather than written down, /// and no implementation plan. Priority, tags and a due date are left out because /// nothing reads them yet, and a field written but never shown is a field that goes /// stale unnoticed. #[derive(clap::Args)] pub struct CampaignAddArgs { /// Campaign title #[arg(short, long, allow_hyphen_values = PROSE)] pub title: String, /// What the campaign is for. Use multiple flags for multiline descriptions #[arg(short, long, allow_hyphen_values = PROSE)] pub description: Vec, /// Owner. Defaults to the git user #[arg(short, long)] pub owner: Option, } /// `ls` holds four filters, an output mode and nothing else, which is the boundary the /// Rust Style rule in AGENTS.md names: two of the filters are adjacent `Option` /// values that a caller can swap silently, so the mode that joined them came as a /// struct rather than a sixth parameter, the way `add` became [`AddArgs`]. #[derive(clap::Args)] pub struct LsArgs { /// Filter by status pub status: Option, /// Only show tickets at this priority, 1 (most urgent) to 5 (least) #[arg(long, value_parser = priority_level)] pub priority: Option, /// Only show tickets carrying this tag, matched whole #[arg(long, value_parser = non_empty)] pub tag: Option, /// Only show the members of this campaign, by UUID or title #[arg(long, value_parser = non_empty)] pub campaign: Option, /// Print one ticket per line as its id and title, tab separated, for a script or a /// completion. Done included, and the filters still apply #[arg(long)] pub ids: bool, } /// `add` carries every field a new ticket can hold, so it is a struct rather than an /// inline variant: nine parameters at the call site is what `too_many_arguments` is /// for, and `set`, `append` and `check` already pass their arguments this way. /// /// No `ArgGroup`: `--title` is required on its own, and everything else is optional /// because a ticket with only a title is a valid thing to file. #[derive(clap::Args)] pub struct AddArgs { /// Ticket title #[arg(short, long, allow_hyphen_values = PROSE)] pub title: String, /// Ticket description. Use multiple flags to create multiline descriptions. #[arg(short, long, allow_hyphen_values = PROSE)] pub description: Vec, /// Acceptance criteria. Accepts multiple flags, each will be interpreted as a single criterium #[arg(short, long, allow_hyphen_values = PROSE)] pub acceptance: Vec, /// Implementation plan. Accepts multiple flags, each will be interpreted as a single step #[arg(short, long, allow_hyphen_values = PROSE)] pub plan: Vec, /// Tags (comma-separated) #[arg(short = 'g', long)] pub tags: Vec, /// Due date (YYYY-MM-DD) #[arg(long, value_parser = iso_date)] pub due: Option, /// Owner #[arg(short, long)] pub owner: Option, /// Priority, 1 (most urgent) to 5 (least). Left unset if omitted. #[arg(long, value_parser = priority_level)] pub priority: Option, } /// `set` replaces a field outright. Owner is deliberately absent: `chown` owns that /// field, and status is `mv`'s, so no field has two writers. /// /// The group makes at least one field mandatory, so a bare `worklane set ` is /// a usage error rather than a silent no-op. #[derive(clap::Args)] #[command(group( clap::ArgGroup::new("set_fields") .required(true) .multiple(true) .args(["title", "description", "acceptance", "plan", "tags", "due", "priority", "clear"]) ))] pub struct SetArgs { /// Ticket UUID or title pub ticket: String, /// Replace the ticket title, renaming the file to match #[arg(short, long, allow_hyphen_values = PROSE, value_parser = non_empty)] pub title: Option, /// Replace the description. Repeat the flag for more lines, empty for a paragraph break #[arg(short, long, allow_hyphen_values = PROSE)] pub description: Vec, /// Replace the acceptance criteria. Repeat the flag, one criterium per value #[arg(short, long, allow_hyphen_values = PROSE)] pub acceptance: Vec, /// Replace the implementation plan. Repeat the flag, one step per value #[arg(short, long, allow_hyphen_values = PROSE)] pub plan: Vec, /// Replace the tags #[arg(short = 'g', long, value_parser = clearable)] pub tags: Vec, /// Replace the due date (YYYY-MM-DD) /// /// The same parser as `add`: one field, one definition of what a due date is. The /// planning skill sets dates through `set` rather than `add`, so validating only /// the one that files a ticket would leave the path that is actually used open. #[arg(long, value_parser = iso_date)] pub due: Option, /// Replace the priority, 1 (most urgent) to 5 (least) #[arg(long, value_parser = priority_level)] pub priority: Option, /// Return a field to unset. Repeat the flag for more than one /// /// The counterpart to the flag it names, and the only way to take a value away: an /// empty value is a paragraph break for a section and a usage error for a scalar, so /// neither can spell this. What goes back is what `add` writes for a field it was /// never given. /// /// No `title`, which addresses the ticket and names its file, and no `owner`, which /// is `chown --clear`'s. The reasoning for each is on `util::Clearable`. #[arg(long, value_name = "FIELD")] pub clear: Vec, } impl SetArgs { /// A field this call both replaces and clears, if there is one. /// /// clap cannot express the conflict, because `--clear` carries the field as a value /// rather than in the flag's own name. So it is checked once here and refused, rather /// than resolved by whichever of the two happens to be applied last, which is a /// silent answer to a contradictory call. pub fn contested(&self) -> Option { self.clear.iter().copied().find(|field| match field { Clearable::Due => self.due.is_some(), Clearable::Tags => !self.tags.is_empty(), Clearable::Priority => self.priority.is_some(), Clearable::Description => !self.description.is_empty(), Clearable::Acceptance => !self.acceptance.is_empty(), Clearable::Plan => !self.plan.is_empty(), }) } } /// `chown` is the only writer of Owner, so clearing the field has to live here too, and /// that is what shapes the arguments. /// /// **`--clear` carries the ticket rather than being a bare flag.** The ticket is the /// *second* positional, so `chown --clear 1b78a24` with a plain flag would land the /// ticket in the user's slot, and reading it back out of there is hand-parsing what clap /// can state outright. The typed call is the same either way; only who checks it differs. /// /// The two forms are mutually exclusive, and each argument says so, so a call carrying /// both is a usage error from clap rather than a decision made here. #[derive(clap::Args)] pub struct ChownArgs { /// New owner. Free text, like `add --owner`, checked against nothing #[arg(value_parser = clearable, required_unless_present = "clear", conflicts_with = "clear")] pub user: Option, /// Ticket UUID or title #[arg(required_unless_present = "clear", conflicts_with = "clear")] pub ticket: Option, /// Return the owner to unset on this ticket, which is named here since there is no /// user to name #[arg(long, value_name = "TICKET", value_parser = non_empty)] pub clear: Option, } impl ChownArgs { /// The ticket the call names, and the owner to write on it, `None` being unset. /// /// `None` for the pair is unreachable while the constraints above hold, and is an /// error at the call site rather than a panic, so loosening one of them costs a /// message instead of a crash. pub fn target(&self) -> Option<(&str, Option<&str>)> { match (self.clear.as_deref(), self.user.as_deref(), self.ticket.as_deref()) { (Some(ticket), None, None) => Some((ticket, None)), (None, Some(user), Some(ticket)) => Some((ticket, Some(user))), _ => None, } } } /// `append` only offers the sections that hold multiple lines, since appending to a /// scalar has no meaning. #[derive(clap::Args)] #[command(group( clap::ArgGroup::new("append_fields") .required(true) .multiple(true) .args(["description", "acceptance", "plan"]) ))] pub struct AppendArgs { /// Ticket UUID or title pub ticket: String, /// Add a paragraph to the description. Repeat the flag for more lines within it #[arg(short, long, allow_hyphen_values = PROSE)] pub description: Vec, /// Add acceptance criteria. Repeat the flag, one criterium per value #[arg(short, long, allow_hyphen_values = PROSE)] pub acceptance: Vec, /// Add implementation plan steps, numbered on from the last. Repeat the flag #[arg(short, long, allow_hyphen_values = PROSE)] pub plan: Vec, } /// `relate` is the only writer of the Relations section, the way `chown` is the only /// writer of Owner. One flag per kind rather than a `--kind` value: the accepted kinds /// are then clap's business, an unknown one is a usage error, and a call reads as a /// sentence about the ticket it names. /// /// Each flag repeats, so several relations of one kind land in a single call. The /// targets are ticket searches, resolved by the same three tiers every other ticket /// argument is, and stored as the target's uuid. #[derive(clap::Args)] #[command(group( clap::ArgGroup::new("relation_kinds") .required(true) .multiple(true) .args(["blocked_by", "regression_of", "relates_to"]) ))] pub struct RelateArgs { /// Ticket UUID or title pub ticket: String, /// Ticket this one waits on. Its own moves are refused until the target is done #[arg(long, value_parser = non_empty)] pub blocked_by: Vec, /// Ticket whose fix this one broke #[arg(long, value_parser = non_empty)] pub regression_of: Vec, /// Ticket this one is merely related to. Symmetric, so it is recorded once #[arg(long, value_parser = non_empty)] pub relates_to: Vec, } impl RelateArgs { /// The relations asked for, one entry per kind, so the handler walks a table /// instead of repeating itself three times. pub fn requested(&self) -> [(RelationKind, &[String]); 3] { [ (RelationKind::BlockedBy, &self.blocked_by), (RelationKind::RegressionOf, &self.regression_of), (RelationKind::RelatesTo, &self.relates_to), ] } } /// `check` and `uncheck` are separate commands rather than one verb with a flag, /// because the two read as opposites at the call site and neither needs the other's /// name to make sense. /// /// The criteria are optional: without any the criteria are listed and the index asked /// for, or, where there is no terminal to ask at, returned as an error carrying the /// same list. /// /// Several terms in one call because finishing a ticket means ticking every box, and /// one invocation per box resolved the ticket and rewrote the file each time. The /// terms are variadic rather than a repeated flag: they address something that is /// already there, the way the ticket positional does, instead of carrying content the /// way `--acceptance` does. #[derive(clap::Args)] pub struct CheckArgs { /// Ticket UUID or title pub ticket: String, /// Criterion indexes as shown by `show`, substrings of their text, or `all`. Prompts if omitted pub criteria: Vec, }