Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5b0bac9c2d | ||
|
|
41a65f95b2 |
@@ -5,17 +5,19 @@
|
||||
- `src/command.rs` - CLI argument definitions using clap derive
|
||||
- `src/handlers.rs` - one `cmd_*` per subcommand
|
||||
- `src/util.rs` - the ticket format, resolution, rendering and the palette
|
||||
- `src/campaign.rs` - the campaign file format, its resolution, its index and its members
|
||||
- `src/tui.rs` - board state, the change digest, and the ratatui draw
|
||||
- `src/install.rs` - the embedded agent assets and the compare-and-refuse install
|
||||
- `assets/SKILL.md` - the agent skill `install-skill` ships, embedded with `include_str!`
|
||||
- `tests/` - Integration tests using `assert_cmd` and `assert_fs`, one file per command
|
||||
- Unit tests live beside the code in `#[cfg(test)] mod tests`, in `util.rs`, `handlers.rs` and `tui.rs`
|
||||
- Ticket files stored as `.md` in `.worklane/<status>/` directories
|
||||
- Campaign files stored as `.md` in `.worklane/campaigns/`, which is beside the status directories and deliberately not in `status_dirs()`
|
||||
|
||||
## Ticket File Format
|
||||
- Filenames: `<uuid_v4>_<slug>.md`
|
||||
- The slug is the title through `slug()`: lowercased, alphanumerics plus `-` and `_` kept, spaces turned into dashes. `Ticket 06` lands as `<uuid>_ticket-06.md`. Derive fixture filenames through `slug()`, never by hand
|
||||
- Metadata fields parsed by `parse_ticket_field()`: `ID`, `Priority`, `Tags`, `Due`, `Owner`, `Created At`, `Status`
|
||||
- Metadata fields parsed by `parse_ticket_field()`: `ID`, `Priority`, `Tags`, `Due`, `Owner`, `Created At`, `Campaign`, `Status`. `Campaign` is the one no ticket is born with: `add` does not write it, so it is inserted on demand
|
||||
- Format: `**Field Name**: value`
|
||||
- Ticket structure: `# Title` → `## Description` → `## Acceptance Criteria` → `## Implementation Plan` → `## Metadata`
|
||||
- Comments stored in `.worklane/comments/<ticket_uuid>/<timestamp>.md` with `**Comment**`, `**Author**`, `**Time**` fields
|
||||
@@ -32,7 +34,7 @@ and this file is for what someone changing worklane's own code needs.
|
||||
## Testing
|
||||
- Run: `cargo test`
|
||||
- Tests use `assert_cmd` and `assert_fs` for CLI testing
|
||||
- `setup_worklane()` creates temp `.worklane/` with all four status folders pre-created
|
||||
- `setup_worklane()` creates temp `.worklane/` with all four status folders pre-created, plus `campaigns/` in `cmd_campaign.rs`, which is also where the on-demand creation is tested from a board without it
|
||||
- `create_ticket()` writes fully-formed markdown files directly (no `--` separator for positional args in test commands)
|
||||
- **`cargo clippy --all-targets` is clean. Keep it clean**, and do not silence a lint that is pointing at something real. The only two `allow`s in the tree sit on the `create_ticket` fixtures in `cmd_mv.rs` and `cmd_show.rs`, each carrying the reason and what would replace it
|
||||
|
||||
@@ -92,6 +94,23 @@ and this file is for what someone changing worklane's own code needs.
|
||||
- **A blocker that is not on the board warns and allows the move.** Refusing would wedge the ticket with no way out but `-f`, and a uuid nothing carries is a bookkeeping fault rather than a dependency. The refusal names **every** open blocker, since clearing the one that happened to be printed would leave the ticket blocked
|
||||
- Left out on purpose: removing a relation, which 4179958 assigns to 74904dc, and a blocked marker on the TUI card, which is its own ticket. Nothing on a card is worth a scan of the board per tick until the card is designed for it
|
||||
|
||||
### Campaigns
|
||||
|
||||
- **A campaign's state is derived, never stored.** Open until every member is done, computed by `Standing` from the members. A `Status` field on the campaign would be the same state in two places, and the two would disagree the moment a member moved. It is also why there is no `campaign mv` and no forward-only ruleset beside `mv`'s
|
||||
- **A campaign with no members is neither open nor done.** `Standing::state()` returns `None` there, and both callers print `no members`. Calling it done would make a container nothing has been filed against the most complete thing on the board; calling it open would claim work that does not exist
|
||||
- **Membership is one field on the member**, `Campaign` in the ticket Metadata, written only by `assign`. The member list is deliberately *not* on the campaign: that would put membership in two places, and would make one file that every assignment edits, which is contended the moment two agents share a board. So `add` has no `--campaign` and `set` has no `--campaign`, the same rule as Owner and Status
|
||||
- **The full uuid is stored and the title is resolved for display**, as the Relations section already does. `reference_cell` is shared between the two, so a dangling campaign and a dangling relation target are both spelled `_missing_` rather than each inventing a spelling
|
||||
- **`add` does not write the field.** Every ticket written before campaigns existed has none, so the insertion path has to exist regardless; leaving it out of `add` means one path that is always exercised rather than two. Same reasoning as the Relations section
|
||||
- `set_or_insert_metadata_field()` is the upsert, and `METADATA_ORDER` is its anchor list, the way `SECTION_ORDER` is `ensure_section`'s. Campaign is placed before Status, so Status stays last where every file already keeps it. A file with no `## Metadata` heading is an **error, not an insertion**: per 641e3d5 such a file has no fields at all, and writing one above the prose would invent a shape nothing reads
|
||||
- **The three tiers are `resolve_in()`, shared by tickets and campaigns.** A campaign is addressed exactly the way a ticket is, and a second resolver would be a second copy of the precedence rules to keep in step. `Found.dir` is the status for a ticket and empty for a campaign, which is what makes the ambiguity listing drop the bracket for one
|
||||
- **`resolve_ticket` explains a search that names a campaign**, rather than each command doing it. One place, so `mv`, `show`, `chown` and everything else that takes a ticket give the same reason instead of a bare "no ticket found". Checked only on the zero-match path, so it costs nothing normally, and only when exactly one campaign matches: an ambiguous ticket error must not be replaced by a complaint about a directory the caller never mentioned
|
||||
- **`Resolved` carries what `content_trim` cannot render from the file.** The relations block and the campaign cell both come from elsewhere on the board. A struct rather than two more parameters, so the next such field is one entry here instead of an edit at every call site
|
||||
- `campaign show` lists **done** members, unlike `ls`, which leaves the done column out of its listing. What is finished against what is left is the whole question a campaign asks, so hiding half the answer is not an option. `ls --campaign` is the other way round: it is the ordinary board filtered, and keeps every rule `ls` already has
|
||||
- `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 gets neither a campaign tab nor a card marker**, for now. The detail view resolves the field because it renders the body, and that is all. A marker on a card would want a campaigns read per reload and the four corners are already spent; same reasoning as the blocked marker, which is also its own ticket
|
||||
- `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
|
||||
|
||||
### The Board View
|
||||
- `worklane` with no subcommand and `worklane tui` both open it, the way a bare `frig` does. `Cli::command` is therefore an `Option`
|
||||
- The worklane directory is looked for **before** the terminal, so running outside one gives the usual "No .worklane directory found" rather than a complaint about the tty. Both errors stay reachable and both are testable without a pty
|
||||
|
||||
Generated
+1
-1
@@ -1494,7 +1494,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "worklane"
|
||||
version = "0.11.0"
|
||||
version = "0.12.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"assert_cmd",
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "worklane"
|
||||
version = "0.11.0"
|
||||
version = "0.12.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
|
||||
+35
-2
@@ -105,8 +105,8 @@ one command here that does not start with the ticket. The user is free text and
|
||||
checked against nothing. Swap the two and the call fails, because the username has to
|
||||
resolve as a ticket.
|
||||
|
||||
`worklane init` creates `.worklane/` with the four status directories, for a repo that
|
||||
has no board yet.
|
||||
`worklane init` creates `.worklane/` with the four status directories and the campaigns
|
||||
directory beside them, for a repo that has no board yet.
|
||||
|
||||
## Relating tickets
|
||||
|
||||
@@ -130,6 +130,39 @@ Recording a relation the ticket already holds reports no change. A ticket cannot
|
||||
to itself, and a target that later disappears shows as `_missing_` rather than silently
|
||||
going away.
|
||||
|
||||
## Campaigns
|
||||
|
||||
A campaign groups the tickets that have to be finished together: a release, a migration,
|
||||
anything whose parts are separate tickets but whose goal is one thing. It is a file of
|
||||
its own under `.worklane/campaigns/`, with a title and a description, and it sits in no
|
||||
status directory. Its state is derived instead, open until every member is done, so
|
||||
there is no such thing as a done campaign holding an open ticket.
|
||||
|
||||
```
|
||||
worklane campaign add --title "v1 release" \
|
||||
--description "Everything that has to ship before the tag."
|
||||
worklane campaign ls # every campaign and how far it has got
|
||||
worklane campaign show "v1 release" # its body, then its members by status
|
||||
worklane assign "v1 release" 1b78a24 # put a ticket in it
|
||||
worklane ls --campaign "v1 release" # only that campaign's tickets
|
||||
```
|
||||
|
||||
`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
|
||||
has one writer the way owner and status do.
|
||||
|
||||
A ticket is in at most one campaign, so assigning one that already belongs somewhere
|
||||
moves it rather than adding a second. Assigning it to the campaign it already names
|
||||
reports no change and writes nothing.
|
||||
|
||||
`campaign show` lists done members too, unlike `ls`, which leaves the done column out of
|
||||
its listing: a campaign is precisely the question of what is finished against what is
|
||||
left.
|
||||
|
||||
A campaign is addressed the way a ticket is, by uuid prefix, title or filename, but it
|
||||
is not a ticket. Passing one where a ticket is expected is refused with a message saying
|
||||
so, and there is no way to move a campaign, because it has no status to move.
|
||||
|
||||
## Search the backlog before filing
|
||||
|
||||
Run `worklane ls` in the directory the ticket would land in and look for the same issue,
|
||||
|
||||
+294
@@ -0,0 +1,294 @@
|
||||
//! Campaigns: the container for tickets that have to be finished together.
|
||||
//!
|
||||
//! A campaign is a file of its own under `.worklane/campaigns/`, holding a title, a
|
||||
//! description and metadata. It has no status directory and never sits in one. Its
|
||||
//! state is derived instead: open until every member is done. Deriving it means there
|
||||
//! is no such thing as a done campaign holding an open ticket, and no second
|
||||
//! forward-only ruleset to reason about beside `mv`'s.
|
||||
//!
|
||||
//! Membership is one field on the *member*, `Campaign` in the ticket Metadata, written
|
||||
//! only by `assign`. The member list is deliberately not stored on the campaign: that
|
||||
//! would put membership in two places, and would make one file that every assignment
|
||||
//! edits, which is contended the moment two agents share a board.
|
||||
|
||||
use anyhow::{Result, anyhow};
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::util::*;
|
||||
|
||||
/// Where campaigns live, beside the status directories rather than among them.
|
||||
pub const CAMPAIGNS_DIR: &str = "campaigns";
|
||||
|
||||
pub fn campaigns_dir(worklane_dir: &Path) -> PathBuf {
|
||||
worklane_dir.join(CAMPAIGNS_DIR)
|
||||
}
|
||||
|
||||
/// The campaigns directory, created if the board predates it.
|
||||
///
|
||||
/// `init` writes it for a new board, but every board made before campaigns existed has
|
||||
/// none, and refusing to file a campaign there would mean a `worklane init` over a live
|
||||
/// board just to get a directory.
|
||||
pub fn ensure_campaigns_dir(worklane_dir: &Path) -> Result<PathBuf> {
|
||||
let dir = campaigns_dir(worklane_dir);
|
||||
|
||||
fs::create_dir_all(&dir)
|
||||
.map_err(|e| anyhow!("Could not create {}: {}", dir.display(), e))?;
|
||||
|
||||
Ok(dir)
|
||||
}
|
||||
|
||||
/// A campaign as it comes off disk.
|
||||
pub struct Campaign {
|
||||
pub uuid: String,
|
||||
pub title: String,
|
||||
pub content: String,
|
||||
}
|
||||
|
||||
/// The campaigns directory as [`resolve_in`] takes it.
|
||||
///
|
||||
/// The name is empty because a campaign has no status: it is what makes the ambiguity
|
||||
/// listing print an id and a title with no bracket after it.
|
||||
fn campaign_paths(worklane_dir: &Path) -> Vec<(String, PathBuf)> {
|
||||
vec![(String::new(), campaigns_dir(worklane_dir))]
|
||||
}
|
||||
|
||||
/// A campaign by the same three tiers a ticket resolves by, scoped to its own
|
||||
/// directory.
|
||||
///
|
||||
/// The tiers are [`resolve_in`]'s, not a second copy: a campaign is addressed the way
|
||||
/// everything else here is, and two resolvers would be two sets of precedence rules to
|
||||
/// keep in step.
|
||||
pub fn resolve_campaign(search: &str, worklane_dir: &Path) -> Result<Campaign> {
|
||||
let mut matches = resolve_in(search, &campaign_paths(worklane_dir))?;
|
||||
|
||||
if matches.is_empty() {
|
||||
return Err(anyhow!("No campaign found matching '{}'", search));
|
||||
}
|
||||
|
||||
if matches.len() > 1 {
|
||||
return Err(ambiguous("campaign", search, &matches));
|
||||
}
|
||||
|
||||
let found = matches.remove(0);
|
||||
let uuid = parse_ticket_field(&found.content, "ID");
|
||||
|
||||
if uuid.trim().is_empty() || is_unknown_value(&uuid) {
|
||||
return Err(anyhow!(
|
||||
"Campaign '{}' has no ID field, so nothing can be assigned to it",
|
||||
found.title
|
||||
));
|
||||
}
|
||||
|
||||
Ok(Campaign {
|
||||
uuid,
|
||||
title: found.title,
|
||||
content: found.content,
|
||||
})
|
||||
}
|
||||
|
||||
/// The title of the campaign a search names, for a caller that only needs to say so.
|
||||
///
|
||||
/// Used by `resolve_ticket` to explain a search that names a campaign rather than a
|
||||
/// ticket. Deliberately swallows both failures: nothing matched and too much matched
|
||||
/// both mean "this is not the explanation", and an error here would replace a clear
|
||||
/// "no ticket found" with a complaint about a directory the caller never mentioned.
|
||||
pub fn campaign_named(search: &str, worklane_dir: &Path) -> Option<String> {
|
||||
resolve_campaign(search, worklane_dir)
|
||||
.ok()
|
||||
.map(|campaign| campaign.title)
|
||||
}
|
||||
|
||||
/// Every campaign on the board, read in one pass.
|
||||
///
|
||||
/// One pass for the same reason [`RelationIndex`] takes one: rendering a ticket's
|
||||
/// Campaign field or listing the campaigns both need every one of them, and a lookup
|
||||
/// per ticket would read the directory once per row.
|
||||
pub struct CampaignIndex {
|
||||
campaigns: Vec<Campaign>,
|
||||
}
|
||||
|
||||
impl CampaignIndex {
|
||||
pub fn load(worklane_dir: &Path) -> Result<Self> {
|
||||
let dir = campaigns_dir(worklane_dir);
|
||||
let mut campaigns = Vec::new();
|
||||
|
||||
// A board with no campaigns directory has no campaigns, which is not an error:
|
||||
// every board made before campaigns existed is in that state.
|
||||
if !dir.exists() {
|
||||
return Ok(Self { campaigns });
|
||||
}
|
||||
|
||||
for entry in fs::read_dir(&dir)?.filter_map(|e| e.ok()) {
|
||||
let path = entry.path();
|
||||
if !path.extension().is_some_and(|e| e == "md") {
|
||||
continue;
|
||||
}
|
||||
let Ok(content) = fs::read_to_string(&path) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
campaigns.push(Campaign {
|
||||
uuid: parse_ticket_field(&content, "ID"),
|
||||
title: heading_title(&content),
|
||||
content,
|
||||
});
|
||||
}
|
||||
|
||||
// By title, so a listing does not depend on the order the directory hands its
|
||||
// entries back in.
|
||||
campaigns.sort_by_key(|campaign| campaign.title.to_lowercase());
|
||||
Ok(Self { campaigns })
|
||||
}
|
||||
|
||||
/// The campaign carrying `uuid`, or nothing when the board no longer has it.
|
||||
pub fn get(&self, uuid: &str) -> Option<&Campaign> {
|
||||
self.campaigns.iter().find(|campaign| campaign.uuid == uuid)
|
||||
}
|
||||
|
||||
pub fn iter(&self) -> impl Iterator<Item = &Campaign> {
|
||||
self.campaigns.iter()
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.campaigns.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
/// The Campaign field as it reads, or empty for a ticket in no campaign.
|
||||
///
|
||||
/// A uuid no campaign carries renders as `_missing_`, the way a dangling relation
|
||||
/// target does, rather than as the bare value the file stores: the value is a full
|
||||
/// uuid, so showing it raw is thirty-six characters that say nothing about what is
|
||||
/// gone.
|
||||
pub fn campaign_cell(content: &str, index: &CampaignIndex, colored: bool) -> String {
|
||||
let Some(uuid) = parse_campaign(content) else {
|
||||
return String::new();
|
||||
};
|
||||
|
||||
reference_cell(
|
||||
&uuid,
|
||||
index.get(&uuid).map(|campaign| campaign.title.as_str()),
|
||||
colored,
|
||||
)
|
||||
}
|
||||
|
||||
/// The parts [`content_trim`] cannot render from the ticket file alone.
|
||||
///
|
||||
/// Both halves read the tree beside the ticket, so they are gathered in one place
|
||||
/// rather than at each call site.
|
||||
pub fn resolved_for(content: &str, worklane_dir: &Path, colored: bool) -> Result<Resolved> {
|
||||
Ok(Resolved {
|
||||
relations: relations_block(content, worklane_dir, colored)?,
|
||||
campaign: campaign_cell(content, &CampaignIndex::load(worklane_dir)?, colored),
|
||||
})
|
||||
}
|
||||
|
||||
/// The members of a campaign, grouped by status in flow order.
|
||||
///
|
||||
/// Read through `collect_ticket_items`, the source `ls` and the board already use, so
|
||||
/// there is no second parser and the rows print the way every other listing does.
|
||||
/// Empty groups are kept: a campaign's shape is the four statuses, and a caller that
|
||||
/// wants only the filled ones can say so.
|
||||
pub fn members(worklane_dir: &Path, uuid: &str) -> Result<Vec<(&'static str, Vec<TicketItem>)>> {
|
||||
let mut grouped = Vec::new();
|
||||
|
||||
for status in status_dirs() {
|
||||
let status_path = worklane_dir.join(status);
|
||||
let items = match status_path.exists() {
|
||||
true => collect_ticket_items(&status_path)?,
|
||||
false => Vec::new(),
|
||||
};
|
||||
|
||||
grouped.push((
|
||||
status,
|
||||
items
|
||||
.into_iter()
|
||||
.filter(|item| item.campaign.as_deref() == Some(uuid))
|
||||
.collect(),
|
||||
));
|
||||
}
|
||||
|
||||
Ok(grouped)
|
||||
}
|
||||
|
||||
/// How far a campaign has got: members done against members held.
|
||||
pub struct Standing {
|
||||
pub done: usize,
|
||||
pub total: usize,
|
||||
}
|
||||
|
||||
impl Standing {
|
||||
pub fn of(grouped: &[(&'static str, Vec<TicketItem>)]) -> Self {
|
||||
Self {
|
||||
done: grouped
|
||||
.iter()
|
||||
.filter(|(status, _)| *status == DONE)
|
||||
.map(|(_, items)| items.len())
|
||||
.sum(),
|
||||
total: grouped.iter().map(|(_, items)| items.len()).sum(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The count as it reads, or `no members` for a campaign nothing has been filed
|
||||
/// against.
|
||||
pub fn label(&self) -> String {
|
||||
match self.total {
|
||||
0 => "no members".to_string(),
|
||||
total => format!("{}/{} done", self.done, total),
|
||||
}
|
||||
}
|
||||
|
||||
/// A campaign is done when it holds members and every one of them is done.
|
||||
///
|
||||
/// An empty campaign is neither, hence the `None`: calling it done would make a
|
||||
/// container nothing has been filed against the most complete thing on the board,
|
||||
/// and calling it open would claim work that does not exist.
|
||||
pub fn state(&self) -> Option<&'static str> {
|
||||
match (self.total, self.done == self.total) {
|
||||
(0, _) => None,
|
||||
(_, true) => Some(DONE),
|
||||
(_, false) => Some("open"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The campaign file as it is written.
|
||||
///
|
||||
/// The same shape a ticket has, minus what a campaign has no use for: no acceptance
|
||||
/// criteria, because its definition of done is derived from its members rather than
|
||||
/// written down, no implementation plan, and no Status, because it sits in no status
|
||||
/// directory. The headings and the placeholder come from the section table in
|
||||
/// `util.rs`, so the two file formats cannot drift apart on the spelling of a heading.
|
||||
pub fn campaign_body(
|
||||
title: &str,
|
||||
description: &[String],
|
||||
id: &uuid::Uuid,
|
||||
owner: Option<&str>,
|
||||
created_at: &str,
|
||||
) -> String {
|
||||
// Joined with a single newline, so an empty value is how a caller spells a
|
||||
// paragraph break, exactly as it is for a ticket.
|
||||
let description = trim_blank_ends(description);
|
||||
let description_text = match description.is_empty() {
|
||||
true => DESCRIPTION.placeholder.to_string(),
|
||||
false => description.join("\n"),
|
||||
};
|
||||
|
||||
format!(
|
||||
"# {title}\n\
|
||||
\n\
|
||||
{description_heading}\n\
|
||||
{description_text}\n\
|
||||
\n\
|
||||
{metadata_heading}\n\
|
||||
\n\
|
||||
- **ID**: {id}\n\
|
||||
- **Owner**: {owner}\n\
|
||||
- **Created At**: {created_at}\n\
|
||||
",
|
||||
description_heading = DESCRIPTION.heading,
|
||||
metadata_heading = METADATA_HEADING,
|
||||
owner = owner.unwrap_or("_Not set_"),
|
||||
)
|
||||
}
|
||||
@@ -81,6 +81,10 @@ pub enum Command {
|
||||
/// Only show tickets at this priority, 1 (most urgent) to 5 (least)
|
||||
#[arg(long, value_parser = priority_level)]
|
||||
priority: Option<u8>,
|
||||
|
||||
/// Only show the members of this campaign, by UUID or title
|
||||
#[arg(long, value_parser = non_empty)]
|
||||
campaign: Option<String>,
|
||||
},
|
||||
|
||||
/// Show a ticket by UUID or title
|
||||
@@ -159,6 +163,28 @@ pub enum Command {
|
||||
owner: Option<String>,
|
||||
},
|
||||
|
||||
/// 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,
|
||||
},
|
||||
|
||||
/// Install the agent skill that teaches an agent to use worklane
|
||||
InstallSkill {
|
||||
/// Overwrite an existing copy that has been modified
|
||||
@@ -171,6 +197,48 @@ 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.
|
||||
#[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<String>,
|
||||
|
||||
/// Owner. Defaults to the git user
|
||||
#[arg(short, long)]
|
||||
pub owner: Option<String>,
|
||||
}
|
||||
|
||||
/// `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.
|
||||
|
||||
+196
-6
@@ -4,7 +4,8 @@ use std::fs;
|
||||
use std::io::{BufRead, IsTerminal, Write};
|
||||
use std::path::Path;
|
||||
|
||||
use crate::command::{AddArgs, AppendArgs, CheckArgs, RelateArgs, SetArgs};
|
||||
use crate::campaign::*;
|
||||
use crate::command::{AddArgs, AppendArgs, CampaignAddArgs, CheckArgs, RelateArgs, SetArgs};
|
||||
use crate::install;
|
||||
use crate::util::*;
|
||||
|
||||
@@ -27,6 +28,11 @@ pub fn cmd_init(start: &Path) -> Result<()> {
|
||||
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))?;
|
||||
|
||||
println!("Initialized worklane in: {}", worklane_dir.display());
|
||||
Ok(())
|
||||
}
|
||||
@@ -34,8 +40,25 @@ pub fn cmd_init(start: &Path) -> Result<()> {
|
||||
pub fn cmd_ls(
|
||||
status_filter: &Option<String>,
|
||||
priority_filter: Option<u8>,
|
||||
campaign_filter: &Option<String>,
|
||||
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.
|
||||
let campaign = match campaign_filter {
|
||||
Some(search) => Some(resolve_campaign(search, worklane_dir)?),
|
||||
None => None,
|
||||
};
|
||||
let uuid = campaign.as_ref().map(|campaign| campaign.uuid.as_str());
|
||||
|
||||
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) = status_filter {
|
||||
let status_path = worklane_dir.join(status);
|
||||
if !status_path.exists() {
|
||||
@@ -45,7 +68,7 @@ pub fn cmd_ls(
|
||||
));
|
||||
}
|
||||
|
||||
let items = filter_by_priority(collect_ticket_items(&status_path)?, priority_filter);
|
||||
let items = filtered(collect_ticket_items(&status_path)?, priority_filter, uuid);
|
||||
|
||||
if items.is_empty() {
|
||||
println!("No tickets in '{}' status.", status);
|
||||
@@ -63,7 +86,7 @@ pub fn cmd_ls(
|
||||
if !status_path.exists() {
|
||||
continue;
|
||||
}
|
||||
let items = filter_by_priority(collect_ticket_items(&status_path)?, priority_filter);
|
||||
let items = filtered(collect_ticket_items(&status_path)?, priority_filter, uuid);
|
||||
let count = items.len();
|
||||
let label = if count == 1 { "ticket" } else { "tickets" };
|
||||
println!(" [{}] {} {}", status.to_uppercase(), count, label);
|
||||
@@ -79,7 +102,7 @@ pub fn cmd_ls(
|
||||
continue;
|
||||
}
|
||||
let items = match collect_ticket_items(&status_path) {
|
||||
Ok(items) => filter_by_priority(items, priority_filter),
|
||||
Ok(items) => filtered(items, priority_filter, uuid),
|
||||
Err(_) => continue,
|
||||
};
|
||||
if items.is_empty() {
|
||||
@@ -94,6 +117,23 @@ pub fn cmd_ls(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The listing filters in one call, so the three places `ls` collects a column cannot
|
||||
/// end up applying a different set of them.
|
||||
fn filtered(items: Vec<TicketItem>, level: Option<u8>, campaign: Option<&str>) -> Vec<TicketItem> {
|
||||
filter_by_campaign(filter_by_priority(items, level), campaign)
|
||||
}
|
||||
|
||||
/// Keep only the members of `campaign`, or everything when none was asked for.
|
||||
fn filter_by_campaign(items: Vec<TicketItem>, campaign: Option<&str>) -> Vec<TicketItem> {
|
||||
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<TicketItem>, level: Option<u8>) -> Vec<TicketItem> {
|
||||
match level {
|
||||
@@ -304,14 +344,14 @@ pub fn cmd_show(search: &str, worklane_dir: &Path) -> Result<()> {
|
||||
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 relations = relations_block(&content, worklane_dir, should_use_colors())?;
|
||||
let resolved = resolved_for(&content, worklane_dir, should_use_colors())?;
|
||||
|
||||
// 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, &relations));
|
||||
println!("\n{}", content_trim_colored(&content, &resolved));
|
||||
|
||||
if ticket_uuid != "_Not set_" {
|
||||
let comments_dir = worklane_dir.join("comments").join(&ticket_uuid);
|
||||
@@ -883,6 +923,156 @@ pub fn cmd_relate(args: &RelateArgs, start: &Path) -> Result<()> {
|
||||
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,
|
||||
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,
|
||||
&id,
|
||||
owner.as_deref(),
|
||||
&Local::now().format(TIMESTAMP_FORMAT).to_string(),
|
||||
);
|
||||
|
||||
write_then_replace(&worklane_dir, &path, &filename, &body, 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) -> Result<()> {
|
||||
let index = CampaignIndex::load(worklane_dir)?;
|
||||
|
||||
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(),
|
||||
};
|
||||
|
||||
println!(
|
||||
" ({}) {} | {}{}",
|
||||
paint(short_id(&campaign.uuid), Color::Red, colored),
|
||||
campaign.title,
|
||||
standing.label(),
|
||||
state,
|
||||
);
|
||||
}
|
||||
|
||||
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, 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)?;
|
||||
|
||||
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
|
||||
|
||||
+19
-2
@@ -1,6 +1,7 @@
|
||||
use anyhow::Result;
|
||||
use clap::Parser;
|
||||
|
||||
mod campaign;
|
||||
mod command;
|
||||
mod handlers;
|
||||
mod install;
|
||||
@@ -44,9 +45,13 @@ fn main() -> Result<()> {
|
||||
Some(Command::Tui { paths }) => run_tui(&paths, &start),
|
||||
Some(Command::Init) => cmd_init(&start),
|
||||
Some(Command::Add(args)) => cmd_add(&args, &start),
|
||||
Some(Command::Ls { status, priority }) => {
|
||||
Some(Command::Ls {
|
||||
status,
|
||||
priority,
|
||||
campaign,
|
||||
}) => {
|
||||
let worklane_dir = find_worklane_dir(&start)?;
|
||||
cmd_ls(&status, priority, &worklane_dir)
|
||||
cmd_ls(&status, priority, &campaign, &worklane_dir)
|
||||
}
|
||||
Some(Command::Show { id }) => {
|
||||
let worklane_dir = find_worklane_dir(&start)?;
|
||||
@@ -68,6 +73,18 @@ fn main() -> Result<()> {
|
||||
body,
|
||||
owner,
|
||||
}) => cmd_comment(&ticket, &body, &owner, &start),
|
||||
Some(Command::Campaign { command }) => match command {
|
||||
CampaignCommand::Add(args) => cmd_campaign_add(&args, &start),
|
||||
CampaignCommand::Ls => {
|
||||
let worklane_dir = find_worklane_dir(&start)?;
|
||||
cmd_campaign_ls(&worklane_dir)
|
||||
}
|
||||
CampaignCommand::Show { campaign } => {
|
||||
let worklane_dir = find_worklane_dir(&start)?;
|
||||
cmd_campaign_show(&campaign, &worklane_dir)
|
||||
}
|
||||
},
|
||||
Some(Command::Assign { campaign, ticket }) => cmd_assign(&campaign, &ticket, &start),
|
||||
// No board is looked for: the point of the skill is to teach an agent worklane
|
||||
// before there is a `.worklane` anywhere.
|
||||
Some(Command::InstallSkill { force, print }) => cmd_install_skill(force, print),
|
||||
|
||||
+57
-5
@@ -504,12 +504,14 @@ fn detail_of(card: &Card) -> Detail {
|
||||
let uuid = parse_ticket_field(&content, "ID");
|
||||
let worklane_dir = ticket.path.parent().and_then(|status| status.parent());
|
||||
|
||||
// Both of these read the tree beside the ticket, and both fall back to nothing: one
|
||||
// All of these read the tree beside the ticket, and all fall back to nothing: one
|
||||
// unreadable file must not take the board down with it. The relations cost a scan of
|
||||
// the board, paid only while a ticket is open and only on a tick that changed
|
||||
// something, which is what already reloads every card.
|
||||
let relations = worklane_dir
|
||||
.and_then(|dir| relations_block(&content, dir, false).ok())
|
||||
// something, which is what already reloads every card. The campaign title costs a
|
||||
// read of one small directory beside it, for the same reason `show` pays it: the
|
||||
// field stores a uuid, and a card that displayed one raw would say nothing.
|
||||
let resolved = worklane_dir
|
||||
.and_then(|dir| crate::campaign::resolved_for(&content, dir, false).ok())
|
||||
.unwrap_or_default();
|
||||
let comments = match worklane_dir {
|
||||
Some(worklane_dir) => {
|
||||
@@ -518,7 +520,7 @@ fn detail_of(card: &Card) -> Detail {
|
||||
None => Vec::new(),
|
||||
};
|
||||
|
||||
let mut out = content_trim(&content, false, &relations);
|
||||
let mut out = content_trim(&content, false, &resolved);
|
||||
|
||||
out.push('\n');
|
||||
out.push_str(&format_comments_with(&comments, false));
|
||||
@@ -2725,6 +2727,56 @@ mod tests {
|
||||
assert!(text.contains("blocks (1111111) A holder"), "{text:?}");
|
||||
}
|
||||
|
||||
/// The detail view resolves the Campaign field the way `show` does. The field stores
|
||||
/// a uuid, so an unresolved one would put thirty-six characters of hex on screen.
|
||||
#[test]
|
||||
fn the_detail_view_shows_the_campaign_title() {
|
||||
let dir = board_dir();
|
||||
let campaign = "cccccccc-0000-4000-8000-000000000000";
|
||||
std::fs::create_dir_all(dir.join("campaigns")).unwrap();
|
||||
std::fs::write(
|
||||
dir.join("campaigns").join(format!("{campaign}_v1-release.md")),
|
||||
format!("# v1 release\n\n## Metadata\n\n- **ID**: {campaign}\n"),
|
||||
)
|
||||
.unwrap();
|
||||
write_ticket(
|
||||
&dir,
|
||||
"backlog",
|
||||
"11111111-0000-4000-8000-000000000000",
|
||||
"A member",
|
||||
&format!("- **Campaign**: {campaign}\n"),
|
||||
);
|
||||
|
||||
let mut board = one_board(&dir);
|
||||
board.toggle_detail();
|
||||
|
||||
let text = &board.detail.as_ref().expect("no detail").text;
|
||||
assert!(text.contains("(ccccccc) v1 release"), "{text:?}");
|
||||
assert!(!text.contains(campaign), "the bare uuid reached the screen: {text:?}");
|
||||
}
|
||||
|
||||
/// A board with no campaigns directory is every board made before campaigns existed.
|
||||
/// The detail view still has to draw.
|
||||
#[test]
|
||||
fn a_board_with_no_campaigns_directory_still_draws_a_ticket() {
|
||||
let dir = board_dir();
|
||||
write_ticket(
|
||||
&dir,
|
||||
"backlog",
|
||||
"11111111-0000-4000-8000-000000000000",
|
||||
"A ticket",
|
||||
"- **Campaign**: cccccccc-0000-4000-8000-000000000000\n",
|
||||
);
|
||||
|
||||
let mut board = one_board(&dir);
|
||||
board.toggle_detail();
|
||||
|
||||
let text = &board.detail.as_ref().expect("no detail").text;
|
||||
assert!(text.contains("A description."), "the body was lost: {text:?}");
|
||||
// No campaigns to resolve against, so the reference reads as gone.
|
||||
assert!(text.contains("_missing_"), "{text:?}");
|
||||
}
|
||||
|
||||
/// The CLI refuses a relations line it cannot read, naming the ticket. The board
|
||||
/// cannot: one hand-edited file must not take every other card down with it.
|
||||
#[test]
|
||||
|
||||
+430
-66
@@ -203,6 +203,18 @@ pub fn get_git_user() -> Option<String> {
|
||||
}
|
||||
})
|
||||
}
|
||||
/// One file a search matched, and where it was found.
|
||||
pub struct Found {
|
||||
/// The name the match is reported under: the status directory for a ticket, and
|
||||
/// empty for a campaign, which has no status of its own.
|
||||
pub dir: String,
|
||||
pub title: String,
|
||||
pub content: String,
|
||||
/// The uuid from the filename, which is what the first tier matches a prefix
|
||||
/// against.
|
||||
pub uuid: String,
|
||||
}
|
||||
|
||||
/// The candidate list for an ambiguous search, as an error rather than a print
|
||||
/// followed by `exit(1)`.
|
||||
///
|
||||
@@ -210,16 +222,25 @@ pub fn get_git_user() -> Option<String> {
|
||||
/// is the only combination the opencode wrapper can relay: it throws on the exit
|
||||
/// code and keeps stderr, so the list printed to stdout was thrown away and the
|
||||
/// agent saw nothing but a bare exit code.
|
||||
fn ambiguous(search: &str, matches: &[(String, String, String, String)]) -> anyhow::Error {
|
||||
let mut message = format!("Multiple tickets found matching '{}':\n", search);
|
||||
///
|
||||
/// `noun` names what was searched, since campaigns resolve through the same tiers and
|
||||
/// "multiple tickets found" would be a lie for one.
|
||||
pub fn ambiguous(noun: &str, search: &str, matches: &[Found]) -> anyhow::Error {
|
||||
let mut message = format!("Multiple {}s found matching '{}':\n", noun, search);
|
||||
|
||||
for (i, found) in matches.iter().enumerate() {
|
||||
// A campaign is in no status directory, so there is no bracket to print for it.
|
||||
let status = match found.dir.is_empty() {
|
||||
true => String::new(),
|
||||
false => format!(" [{}]", color_text(&found.dir, Color::Orange)),
|
||||
};
|
||||
|
||||
for (i, (status, title, _, id)) in matches.iter().enumerate() {
|
||||
message.push_str(&format!(
|
||||
" {}. ({}) {} [{}]\n",
|
||||
" {}. ({}) {}{}\n",
|
||||
i + 1,
|
||||
color_text(short_id(id), Color::Red),
|
||||
title,
|
||||
color_text(status, Color::Orange),
|
||||
color_text(short_id(&found.uuid), Color::Red),
|
||||
found.title,
|
||||
status,
|
||||
));
|
||||
}
|
||||
|
||||
@@ -237,7 +258,9 @@ fn ambiguous(search: &str, matches: &[(String, String, String, String)]) -> anyh
|
||||
pub const MIN_ID_SEARCH: usize = 4;
|
||||
|
||||
/// The ticket's title, from the first `# ` heading, or empty when it has none.
|
||||
fn heading_title(content: &str) -> String {
|
||||
///
|
||||
/// Public for the campaign index, whose files carry their title the same way.
|
||||
pub fn heading_title(content: &str) -> String {
|
||||
content
|
||||
.lines()
|
||||
.find(|line| line.starts_with("# "))
|
||||
@@ -245,25 +268,39 @@ fn heading_title(content: &str) -> String {
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn resolve_ticket(search: &str, worklane_dir: &Path) -> Result<(String, String, String)> {
|
||||
/// The status directories as [`resolve_in`] takes them.
|
||||
fn status_paths(worklane_dir: &Path) -> Vec<(String, std::path::PathBuf)> {
|
||||
status_dirs()
|
||||
.into_iter()
|
||||
.map(|status| (status.to_string(), worklane_dir.join(status)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The three-tier search, run over `dirs`, returning the first tier that matched
|
||||
/// anything.
|
||||
///
|
||||
/// Three tiers, filled in one pass and consulted in order. A uuid prefix has to win
|
||||
/// outright rather than join a flat list: ticket titles reference other tickets by id,
|
||||
/// so an exact prefix match was reported as ambiguous against whichever title happened
|
||||
/// to mention it.
|
||||
///
|
||||
/// Shared by tickets and campaigns rather than written twice. A campaign is addressed
|
||||
/// exactly the way a ticket is, and a second resolver would be a second copy of the
|
||||
/// precedence rules to keep in step. Each entry pairs the name a match is reported
|
||||
/// under with the directory to read, so what a location means is the caller's to say.
|
||||
pub fn resolve_in(search: &str, dirs: &[(String, std::path::PathBuf)]) -> Result<Vec<Found>> {
|
||||
let search_lower = search.to_lowercase();
|
||||
let long_enough_for_an_id = search.chars().count() >= MIN_ID_SEARCH;
|
||||
|
||||
// Three tiers, filled in one pass and consulted in order. A uuid prefix has to win
|
||||
// outright rather than join a flat list: ticket titles reference other tickets by
|
||||
// id, so an exact prefix match was reported as ambiguous against whichever title
|
||||
// happened to mention it.
|
||||
let mut by_id: Vec<(String, String, String, String)> = Vec::new();
|
||||
let mut by_title: Vec<(String, String, String, String)> = Vec::new();
|
||||
let mut by_filename: Vec<(String, String, String, String)> = Vec::new();
|
||||
let mut by_id: Vec<Found> = Vec::new();
|
||||
let mut by_title: Vec<Found> = Vec::new();
|
||||
let mut by_filename: Vec<Found> = Vec::new();
|
||||
|
||||
for status in status_dirs() {
|
||||
let status_path = worklane_dir.join(status);
|
||||
if !status_path.exists() {
|
||||
for (name, path) in dirs {
|
||||
if !path.exists() {
|
||||
continue;
|
||||
}
|
||||
let entries = fs::read_dir(&status_path)?;
|
||||
for entry in entries.filter_map(|e| e.ok()) {
|
||||
for entry in fs::read_dir(path)?.filter_map(|e| e.ok()) {
|
||||
let path = entry.path();
|
||||
if !path.extension().is_some_and(|e| e == "md") {
|
||||
continue;
|
||||
@@ -288,7 +325,12 @@ pub fn resolve_ticket(search: &str, worklane_dir: &Path) -> Result<(String, Stri
|
||||
continue;
|
||||
}
|
||||
|
||||
let found = (status.to_string(), title, content, uuid.to_string());
|
||||
let found = Found {
|
||||
dir: name.clone(),
|
||||
title,
|
||||
content,
|
||||
uuid: uuid.to_string(),
|
||||
};
|
||||
if by_prefix {
|
||||
by_id.push(found);
|
||||
} else if in_title {
|
||||
@@ -299,22 +341,40 @@ pub fn resolve_ticket(search: &str, worklane_dir: &Path) -> Result<(String, Stri
|
||||
}
|
||||
}
|
||||
|
||||
let mut matches = match (by_id.is_empty(), by_title.is_empty()) {
|
||||
Ok(match (by_id.is_empty(), by_title.is_empty()) {
|
||||
(false, _) => by_id,
|
||||
(true, false) => by_title,
|
||||
(true, true) => by_filename,
|
||||
};
|
||||
})
|
||||
}
|
||||
|
||||
pub fn resolve_ticket(search: &str, worklane_dir: &Path) -> Result<(String, String, String)> {
|
||||
let mut matches = resolve_in(search, &status_paths(worklane_dir))?;
|
||||
|
||||
if matches.is_empty() {
|
||||
// A campaign is the other thing a search can name, and it is on no status
|
||||
// directory, so it never reaches the tiers above. Explained here rather than in
|
||||
// each command, so every argument that takes a ticket says the same thing and
|
||||
// `mv <campaign>` refuses with a reason instead of a hunt for a typo.
|
||||
if let Some(title) = crate::campaign::campaign_named(search, worklane_dir) {
|
||||
return Err(anyhow!(
|
||||
"'{}' is a campaign, not a ticket. A campaign sits in no status \
|
||||
directory: its state is derived from its members. \
|
||||
Try `worklane campaign show {}`.",
|
||||
title,
|
||||
search
|
||||
));
|
||||
}
|
||||
|
||||
return Err(anyhow!("No ticket found matching '{}'", search));
|
||||
}
|
||||
|
||||
if matches.len() > 1 {
|
||||
return Err(ambiguous(search, &matches));
|
||||
return Err(ambiguous("ticket", search, &matches));
|
||||
}
|
||||
|
||||
let (status, title, content, _short_id) = matches.remove(0);
|
||||
Ok((status, title, content))
|
||||
let found = matches.remove(0);
|
||||
Ok((found.dir, found.title, found.content))
|
||||
}
|
||||
pub fn format_comments(comments: &[(String, String, String, String)]) -> String {
|
||||
format_comments_with(comments, should_use_colors())
|
||||
@@ -347,8 +407,28 @@ pub fn format_comments_with(
|
||||
|
||||
result
|
||||
}
|
||||
pub fn content_trim_colored(content: &str, relations: &str) -> String {
|
||||
content_trim(content, should_use_colors(), relations)
|
||||
/// The parts of a ticket's body that cannot be rendered from the file alone.
|
||||
///
|
||||
/// Both are resolved against the rest of the board. The Relations section stores one
|
||||
/// side of each edge and a bare uuid for each target, so the body alone cannot say what
|
||||
/// a relation points at nor that anything points back. The Campaign field stores a uuid
|
||||
/// whose title lives in another file entirely.
|
||||
///
|
||||
/// Passed in rather than derived in [`content_trim`], which has only the body, and so
|
||||
/// the board can render the same text with colour off. A struct rather than two more
|
||||
/// parameters, so the next thing resolved from the board is one field here instead of
|
||||
/// an edit at every call site.
|
||||
#[derive(Default)]
|
||||
pub struct Resolved {
|
||||
/// The block [`render_relations`] built, or empty for a ticket with no relations.
|
||||
pub relations: String,
|
||||
/// The Campaign value as it reads, from [`reference_cell`]. Empty leaves the stored
|
||||
/// value to render as it sits, which is what a ticket in no campaign wants.
|
||||
pub campaign: String,
|
||||
}
|
||||
|
||||
pub fn content_trim_colored(content: &str, resolved: &Resolved) -> String {
|
||||
content_trim(content, should_use_colors(), resolved)
|
||||
}
|
||||
|
||||
/// A section heading, its rule, and the blank line the body opens under.
|
||||
@@ -371,11 +451,10 @@ fn push_heading(out: &mut String, heading: &str, colored: bool) {
|
||||
/// The TUI needs the plain form: ratatui draws styled spans, and an escape sequence
|
||||
/// embedded in a paragraph would be printed as literal bytes.
|
||||
///
|
||||
/// `relations` is the block [`relations_block`] built, or empty. It is passed in rather
|
||||
/// than derived here because half of it comes from other tickets: the section stores
|
||||
/// one side of each edge and bare uuids for its targets, so the body alone cannot say
|
||||
/// what a relation points at, nor that anything points back.
|
||||
pub fn content_trim(content: &str, colored: bool, relations: &str) -> String {
|
||||
/// [`Resolved`] carries the parts that come from elsewhere on the board, since the
|
||||
/// body alone cannot render them.
|
||||
pub fn content_trim(content: &str, colored: bool, resolved: &Resolved) -> String {
|
||||
let relations = resolved.relations.as_str();
|
||||
let lines: Vec<&str> = content.trim().lines().collect();
|
||||
let mut result = String::new();
|
||||
let mut current_section = "";
|
||||
@@ -412,7 +491,11 @@ pub fn content_trim(content: &str, colored: bool, relations: &str) -> String {
|
||||
// falling through to the line-at-a-time cases below.
|
||||
if is_metadata_heading(line) {
|
||||
let end = section_end(&lines, i);
|
||||
result.push_str(&render_metadata_table(&lines[i..end], colored));
|
||||
result.push_str(&render_metadata_table(
|
||||
&lines[i..end],
|
||||
colored,
|
||||
&resolved.campaign,
|
||||
));
|
||||
i = end;
|
||||
}
|
||||
|
||||
@@ -571,7 +654,15 @@ fn metadata_row(line: &str) -> MetadataRow<'_> {
|
||||
}
|
||||
|
||||
/// The value cell for a field, styled per the colour guideline.
|
||||
fn metadata_value_cell(name: &str, value: &str, colored: bool) -> String {
|
||||
///
|
||||
/// `campaign` is the resolved cell for the Campaign field, empty when there is none.
|
||||
/// The file stores the full uuid, per the rule the Relations section already follows,
|
||||
/// so a bare value here would be thirty-six characters saying nothing.
|
||||
fn metadata_value_cell(name: &str, value: &str, colored: bool, campaign: &str) -> String {
|
||||
if name == CAMPAIGN_FIELD && !campaign.is_empty() {
|
||||
return campaign.to_string();
|
||||
}
|
||||
|
||||
if name == "Priority" {
|
||||
// Reads as a glyph, while the file keeps storing the number.
|
||||
let (glyph, colour) = priority_mark(priority_from_value(value));
|
||||
@@ -590,7 +681,7 @@ fn metadata_value_cell(name: &str, value: &str, colored: bool) -> String {
|
||||
/// Taken as a block rather than a line at a time because the field column cannot be
|
||||
/// sized until every name has been seen. The file is untouched by this: it goes on
|
||||
/// storing the markdown list, and this is only how the list is shown.
|
||||
fn render_metadata_table(lines: &[&str], colored: bool) -> String {
|
||||
fn render_metadata_table(lines: &[&str], colored: bool, campaign: &str) -> String {
|
||||
// The heading already emits its own blank separator, so the one the template
|
||||
// puts under it would otherwise open the section with a gap.
|
||||
let start = lines
|
||||
@@ -618,7 +709,7 @@ fn render_metadata_table(lines: &[&str], colored: bool) -> String {
|
||||
result.push_str(&paint(name, Color::Red, colored));
|
||||
result.push_str(&" ".repeat(field_width - name.chars().count()));
|
||||
result.push_str(COLUMN_GUTTER);
|
||||
result.push_str(&metadata_value_cell(name, value, colored));
|
||||
result.push_str(&metadata_value_cell(name, value, colored, campaign));
|
||||
}
|
||||
// The decision this row is rendered under, not the one the terminal
|
||||
// would give: `colorize_line` asked `should_use_colors()` here, which is
|
||||
@@ -682,7 +773,7 @@ fn is_delimiter(chars: &[char], at: usize) -> bool {
|
||||
chars.get(at) == Some(&'*') && chars.get(at + 1) == Some(&'*')
|
||||
}
|
||||
|
||||
const METADATA_HEADING: &str = "## Metadata";
|
||||
pub const METADATA_HEADING: &str = "## Metadata";
|
||||
|
||||
fn is_metadata_heading(line: &str) -> bool {
|
||||
line.trim_end() == METADATA_HEADING
|
||||
@@ -789,6 +880,120 @@ pub fn set_metadata_field(content: &str, field: &str, value: &str, title: &str)
|
||||
})
|
||||
}
|
||||
|
||||
/// The metadata field naming the campaign a ticket belongs to.
|
||||
///
|
||||
/// Written only by `assign`, the way Owner is written only by `chown`. Storing the
|
||||
/// member list on the campaign instead would put membership in two places and make one
|
||||
/// file that every assignment edits, which is contended the moment two agents share a
|
||||
/// board.
|
||||
pub const CAMPAIGN_FIELD: &str = "Campaign";
|
||||
|
||||
/// The campaign uuid a ticket names, or nothing when it names none.
|
||||
///
|
||||
/// Absent and unset are the same answer: a ticket that has never been assigned has no
|
||||
/// field at all, since `add` does not write one, and a ticket whose field reads
|
||||
/// `_Not set_` is in no campaign either.
|
||||
pub fn parse_campaign(content: &str) -> Option<String> {
|
||||
let value = parse_ticket_field(content, CAMPAIGN_FIELD);
|
||||
|
||||
match is_unknown_value(&value) || value.trim().is_empty() {
|
||||
true => None,
|
||||
false => Some(value),
|
||||
}
|
||||
}
|
||||
|
||||
/// The metadata fields in the order `add` writes them, with `Campaign` in its place
|
||||
/// among them.
|
||||
///
|
||||
/// The anchor list for inserting a field the file does not have yet, exactly as
|
||||
/// [`SECTION_ORDER`] is for a missing section. Campaign sits beside Status because the
|
||||
/// two answer the same kind of question, where the ticket belongs rather than what it
|
||||
/// is, and Status stays last, which is where every file already keeps it.
|
||||
const METADATA_ORDER: [&str; 8] = [
|
||||
"ID",
|
||||
"Priority",
|
||||
"Tags",
|
||||
"Due",
|
||||
"Owner",
|
||||
"Created At",
|
||||
CAMPAIGN_FIELD,
|
||||
"Status",
|
||||
];
|
||||
|
||||
/// Rewrite a metadata field, adding the line when the file has no such field yet.
|
||||
///
|
||||
/// [`set_metadata_field`] refuses a field that is not already there, which is right for
|
||||
/// the fields `add` writes: a missing one means a hand-made ticket. Campaign is
|
||||
/// different, because no ticket written before campaigns existed carries it and `add`
|
||||
/// deliberately does not write one. The insertion path therefore has to exist for every
|
||||
/// such ticket, which is the same reasoning that keeps the Relations section out of
|
||||
/// `add`: one path that is always exercised beats two.
|
||||
pub fn set_or_insert_metadata_field(
|
||||
content: &str,
|
||||
field: &str,
|
||||
value: &str,
|
||||
title: &str,
|
||||
) -> Result<String> {
|
||||
let prefix = format!("**{}**:", field);
|
||||
|
||||
match set_metadata_line(content, field, value, |line| {
|
||||
metadata_field_body(line).starts_with(&prefix)
|
||||
}) {
|
||||
Some(updated) => Ok(updated),
|
||||
None => insert_metadata_field(content, field, value, title),
|
||||
}
|
||||
}
|
||||
|
||||
/// Add a metadata line the file does not have, in its place among the fields it does.
|
||||
///
|
||||
/// A file with no Metadata section is an error rather than an insertion. There is no
|
||||
/// format to guess at there, and per 641e3d5 such a file has no fields at all, so
|
||||
/// writing one above the prose would be inventing a shape nothing else reads.
|
||||
fn insert_metadata_field(content: &str, field: &str, value: &str, title: &str) -> Result<String> {
|
||||
let lines: Vec<&str> = content.lines().collect();
|
||||
let heading = lines
|
||||
.iter()
|
||||
.position(|line| is_metadata_heading(line))
|
||||
.ok_or_else(|| {
|
||||
anyhow!(
|
||||
"Ticket '{}' has no Metadata section, so its {} field cannot be written",
|
||||
title,
|
||||
field
|
||||
)
|
||||
})?;
|
||||
|
||||
let body = (heading + 1)..section_end(&lines, heading + 1);
|
||||
|
||||
// Before the first field that follows this one in the order and is actually in the
|
||||
// file, the way `ensure_section` goes against `SECTION_ORDER`. A ticket written
|
||||
// before the field existed therefore gains it in its place rather than at the end.
|
||||
let following = METADATA_ORDER
|
||||
.iter()
|
||||
.skip_while(|name| **name != field)
|
||||
.skip(1)
|
||||
.filter_map(|name| {
|
||||
let prefix = format!("**{}**:", name);
|
||||
lines[body.clone()]
|
||||
.iter()
|
||||
.position(|line| metadata_field_body(line).starts_with(&prefix))
|
||||
.map(|offset| body.start + offset)
|
||||
})
|
||||
.min();
|
||||
|
||||
let at = match following {
|
||||
Some(at) => at,
|
||||
// Nothing in the file follows it, so after the last line that holds anything:
|
||||
// the blank line before the next section has to stay where it is.
|
||||
None => body_content_end(&lines, &body),
|
||||
};
|
||||
|
||||
let mut out: Vec<String> = lines[..at].iter().map(|l| l.to_string()).collect();
|
||||
out.push(format!("- **{}**: {}", field, value));
|
||||
out.extend(lines[at..].iter().map(|l| l.to_string()));
|
||||
|
||||
Ok(join_lines(&out))
|
||||
}
|
||||
|
||||
/// Rewrite the title heading, the first `# ` line in the file.
|
||||
///
|
||||
/// `## ` headings do not match: the second character has to be a space.
|
||||
@@ -1258,19 +1463,26 @@ impl RelationIndex {
|
||||
}
|
||||
}
|
||||
|
||||
/// A relation's target as it reads: the short id, then the title.
|
||||
/// A cross reference as it reads: the short id, then the name it points at.
|
||||
///
|
||||
/// `_missing_` rather than a bare uuid for a target the board no longer has. The id is
|
||||
/// kept either way, since it is the only thing left to go looking for.
|
||||
fn target_cell(target: Option<&RelatedTicket>, uuid: &str, colored: bool) -> String {
|
||||
/// `_missing_` rather than a bare uuid for something the board no longer holds. The id
|
||||
/// is kept either way, since it is the only thing left to go looking for. Shared by the
|
||||
/// relations block and the Campaign field, so a dangling reference is spelled one way
|
||||
/// wherever it is shown.
|
||||
pub fn reference_cell(uuid: &str, name: Option<&str>, colored: bool) -> String {
|
||||
let id = paint(short_id(uuid), Color::Red, colored);
|
||||
|
||||
match target {
|
||||
Some(ticket) => format!("({}) {}", id, ticket.title),
|
||||
match name {
|
||||
Some(name) => format!("({}) {}", id, name),
|
||||
None => format!("({}) {}", id, paint("_missing_", Color::Grey, colored)),
|
||||
}
|
||||
}
|
||||
|
||||
/// A relation's target as it reads.
|
||||
fn target_cell(target: Option<&RelatedTicket>, uuid: &str, colored: bool) -> String {
|
||||
reference_cell(uuid, target.map(|ticket| ticket.title.as_str()), colored)
|
||||
}
|
||||
|
||||
/// The Relations section as it is shown, or empty when there is nothing to show.
|
||||
///
|
||||
/// Both directions, stored first: the relations the ticket holds, then the ones held
|
||||
@@ -1592,6 +1804,11 @@ pub struct TicketItem {
|
||||
/// ticket body on every draw rather than on the tick that changed something. The
|
||||
/// listing ignores it, as it ignores `path`.
|
||||
pub criteria: Option<Progress>,
|
||||
/// The campaign uuid the ticket names, or `None` for a ticket in none.
|
||||
///
|
||||
/// Read here for the reason `criteria` is: `ls --campaign` filters on what this
|
||||
/// pass already produced, rather than reading every ticket a second time to ask.
|
||||
pub campaign: Option<String>,
|
||||
/// The file this came from. The listing ignores it; the TUI opens it for the
|
||||
/// detail view rather than resolving the ticket a second time.
|
||||
pub path: std::path::PathBuf,
|
||||
@@ -1706,7 +1923,13 @@ pub fn display_ticket_items(items: &[TicketItem]) {
|
||||
}
|
||||
|
||||
pub fn collect_ticket_items(status_path: impl AsRef<Path>) -> Result<Vec<TicketItem>> {
|
||||
let entries: Vec<_> = fs::read_dir(status_path)?.filter_map(|e| e.ok()).collect();
|
||||
let entries: Vec<_> = fs::read_dir(status_path)?
|
||||
.filter_map(|e| e.ok())
|
||||
// A status directory is a plain directory, so anything can be dropped in it.
|
||||
// Without the extension a stray notes.txt was listed as a titleless ticket and
|
||||
// counted in the summary alongside the real ones.
|
||||
.filter(|e| e.path().extension().is_some_and(|ext| ext == "md"))
|
||||
.collect();
|
||||
|
||||
let mut items: Vec<TicketItem> = entries
|
||||
.iter()
|
||||
@@ -1741,6 +1964,7 @@ pub fn collect_ticket_items(status_path: impl AsRef<Path>) -> Result<Vec<TicketI
|
||||
created: format_created_at(&created_at),
|
||||
priority: parse_priority(&content),
|
||||
criteria: progress,
|
||||
campaign: parse_campaign(&content),
|
||||
path: e.path(),
|
||||
})
|
||||
})
|
||||
@@ -1927,6 +2151,7 @@ mod tests {
|
||||
"- **Owner**: alice",
|
||||
],
|
||||
false,
|
||||
"",
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
@@ -1940,7 +2165,7 @@ mod tests {
|
||||
#[test]
|
||||
fn a_long_field_name_widens_the_column_for_every_row() {
|
||||
let rendered =
|
||||
render_metadata_table(&["- **ID**: abc", "- **Handled By Team**: ops"], false);
|
||||
render_metadata_table(&["- **ID**: abc", "- **Handled By Team**: ops"], false, "");
|
||||
|
||||
assert_eq!(
|
||||
rendered,
|
||||
@@ -1961,8 +2186,8 @@ mod tests {
|
||||
"- **Owner**: Ansho Rei",
|
||||
];
|
||||
|
||||
let plain = render_metadata_table(&lines, false);
|
||||
let coloured = render_metadata_table(&lines, true);
|
||||
let plain = render_metadata_table(&lines, false, "");
|
||||
let coloured = render_metadata_table(&lines, true, "");
|
||||
|
||||
assert_ne!(coloured, plain, "colour produced no escapes at all");
|
||||
assert_eq!(unstyled(&coloured), plain);
|
||||
@@ -1971,7 +2196,7 @@ mod tests {
|
||||
#[test]
|
||||
fn a_non_ascii_field_name_is_measured_in_characters() {
|
||||
// "Créé à" is 6 characters and 8 bytes, so a byte-width column pads it short
|
||||
let rendered = render_metadata_table(&["- **Créé à**: oui", "- **ID**: abc"], false);
|
||||
let rendered = render_metadata_table(&["- **Créé à**: oui", "- **ID**: abc"], false, "");
|
||||
|
||||
assert_eq!(
|
||||
rendered,
|
||||
@@ -1983,7 +2208,7 @@ mod tests {
|
||||
#[test]
|
||||
fn a_non_ascii_value_leaves_the_column_alone() {
|
||||
let lines = ["- **Owner**: 日本語", "- **ID**: abc"];
|
||||
let rendered = render_metadata_table(&lines, false);
|
||||
let rendered = render_metadata_table(&lines, false, "");
|
||||
|
||||
assert_eq!(
|
||||
rendered,
|
||||
@@ -1994,7 +2219,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn a_field_the_tool_does_not_know_still_gets_a_row() {
|
||||
let rendered = render_metadata_table(&["- **ID**: abc", "- **Sprint**: 14"], false);
|
||||
let rendered = render_metadata_table(&["- **ID**: abc", "- **Sprint**: 14"], false, "");
|
||||
|
||||
assert!(rendered.contains("Sprint 14"), "{rendered:?}");
|
||||
}
|
||||
@@ -2002,7 +2227,7 @@ mod tests {
|
||||
#[test]
|
||||
fn a_line_that_is_not_a_field_is_carried_through() {
|
||||
let rendered =
|
||||
render_metadata_table(&["- **ID**: abc", "a hand written note"], false);
|
||||
render_metadata_table(&["- **ID**: abc", "a hand written note"], false, "");
|
||||
|
||||
assert_eq!(
|
||||
rendered,
|
||||
@@ -2013,7 +2238,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn the_priority_cell_carries_the_mark_and_the_stored_number() {
|
||||
let rendered = render_metadata_table(&["- **Priority**: 2"], false);
|
||||
let rendered = render_metadata_table(&["- **Priority**: 2"], false, "");
|
||||
let (glyph, _) = priority_mark(Priority::Level(2));
|
||||
|
||||
assert_eq!(rendered, format!("Priority {glyph} 2\n"));
|
||||
@@ -2021,7 +2246,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn an_unset_priority_reads_as_unset_in_the_table() {
|
||||
let rendered = render_metadata_table(&["- **Priority**: _Not set_"], false);
|
||||
let rendered = render_metadata_table(&["- **Priority**: _Not set_"], false, "");
|
||||
let (glyph, _) = priority_mark(Priority::Unset);
|
||||
|
||||
assert_eq!(rendered, format!("Priority {glyph} _Not set_\n"));
|
||||
@@ -2036,7 +2261,7 @@ mod tests {
|
||||
/// is no place for an escape sequence, and two paths asked the terminal instead.
|
||||
#[test]
|
||||
fn the_body_carries_no_escape_when_the_colour_is_off() {
|
||||
let rendered = content_trim(BOTH_LEAKS, false, "");
|
||||
let rendered = content_trim(BOTH_LEAKS, false, &Resolved::default());
|
||||
|
||||
assert!(
|
||||
!rendered.contains('\x1b'),
|
||||
@@ -2052,7 +2277,7 @@ mod tests {
|
||||
/// could be a colouring path that was simply deleted.
|
||||
#[test]
|
||||
fn the_body_colours_the_plan_number_and_a_metadata_note_when_the_colour_is_on() {
|
||||
let rendered = content_trim(BOTH_LEAKS, true, "");
|
||||
let rendered = content_trim(BOTH_LEAKS, true, &Resolved::default());
|
||||
|
||||
assert!(
|
||||
rendered.contains(&format!("{}1.", Color::Cyan.ansi())),
|
||||
@@ -2152,9 +2377,148 @@ mod tests {
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collect_ticket_items_lists_only_md_files() {
|
||||
let dir = std::env::temp_dir().join(format!("worklane-stray-{}", uuid::Uuid::new_v4()));
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
|
||||
fs::write(
|
||||
dir.join("11111111-0000-4000-8000-000000000001.md"),
|
||||
"# Real\n\n## Metadata\n\n- **Owner**: alice\n",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(dir.join("notes.txt"), "# Stray\n").unwrap();
|
||||
// A directory read_to_string happened to reject, so it was already skipped by
|
||||
// accident. Kept here so the extension filter is what keeps it out.
|
||||
fs::create_dir_all(dir.join("subdir")).unwrap();
|
||||
|
||||
let items = collect_ticket_items(&dir).unwrap();
|
||||
let titles: Vec<&str> = items.iter().map(|item| item.title.as_str()).collect();
|
||||
|
||||
assert_eq!(titles, vec!["Real"], "{titles:?}");
|
||||
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
/// The template ticket, and the shape every insertion test measures against.
|
||||
fn with_metadata(fields: &str) -> String {
|
||||
format!("# T\n\n## Description\nBody.\n\n## Metadata\n\n{fields}")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_absent_metadata_field_is_inserted_in_its_place() {
|
||||
let content = with_metadata("- **ID**: abc\n- **Owner**: alice\n- **Status**: backlog\n");
|
||||
|
||||
let updated =
|
||||
set_or_insert_metadata_field(&content, CAMPAIGN_FIELD, "c-uuid", "T").unwrap();
|
||||
|
||||
// Against METADATA_ORDER, so Status stays last where every file keeps it.
|
||||
assert!(
|
||||
updated.contains("- **Owner**: alice\n- **Campaign**: c-uuid\n- **Status**: backlog\n"),
|
||||
"{updated}"
|
||||
);
|
||||
}
|
||||
|
||||
/// Nothing in the order follows it in this file, so it goes after the last line that
|
||||
/// holds anything rather than past the blank that separates the section from the
|
||||
/// next one. The blank has to stay where it is.
|
||||
#[test]
|
||||
fn an_absent_field_with_nothing_after_it_lands_at_the_end_of_the_section() {
|
||||
let content = with_metadata("- **ID**: abc\n- **Owner**: alice\n\n## Notes\nAfter.\n");
|
||||
|
||||
let updated =
|
||||
set_or_insert_metadata_field(&content, CAMPAIGN_FIELD, "c-uuid", "T").unwrap();
|
||||
|
||||
assert!(
|
||||
updated.contains(
|
||||
"- **Owner**: alice\n- **Campaign**: c-uuid\n\n## Notes\nAfter.\n"
|
||||
),
|
||||
"{updated}"
|
||||
);
|
||||
}
|
||||
|
||||
/// An existing field is rewritten, not doubled, which is what keeps a ticket in at
|
||||
/// most one campaign.
|
||||
#[test]
|
||||
fn a_field_already_there_is_rewritten_rather_than_added() {
|
||||
let content = with_metadata(
|
||||
"- **ID**: abc\n- **Campaign**: first\n- **Status**: backlog\n",
|
||||
);
|
||||
|
||||
let updated =
|
||||
set_or_insert_metadata_field(&content, CAMPAIGN_FIELD, "second", "T").unwrap();
|
||||
|
||||
assert_eq!(updated.matches("**Campaign**:").count(), 1, "{updated}");
|
||||
assert!(updated.contains("- **Campaign**: second"), "{updated}");
|
||||
}
|
||||
|
||||
/// Prose above the section is free text, and tickets in this repo quote field
|
||||
/// markers constantly. An insertion must not be steered by one.
|
||||
#[test]
|
||||
fn a_marker_in_the_description_does_not_take_the_insertion() {
|
||||
let content = "# T\n\n## Description\n- **Campaign**: not a field\n\n\
|
||||
## Metadata\n\n- **ID**: abc\n- **Status**: backlog\n";
|
||||
|
||||
let updated =
|
||||
set_or_insert_metadata_field(content, CAMPAIGN_FIELD, "c-uuid", "T").unwrap();
|
||||
|
||||
assert!(updated.contains("- **Campaign**: not a field"), "{updated}");
|
||||
assert!(
|
||||
updated.contains("- **ID**: abc\n- **Campaign**: c-uuid\n- **Status**: backlog"),
|
||||
"{updated}"
|
||||
);
|
||||
}
|
||||
|
||||
/// No Metadata heading means no fields at all, per 641e3d5, so there is no format to
|
||||
/// guess at and writing one above the prose would invent a shape nothing reads.
|
||||
#[test]
|
||||
fn a_file_with_no_metadata_section_is_an_error_rather_than_an_insertion() {
|
||||
let content = "# T\n\n## Description\nBody.\n";
|
||||
|
||||
let error = set_or_insert_metadata_field(content, CAMPAIGN_FIELD, "c-uuid", "T")
|
||||
.expect_err("a file with no Metadata section gained a field");
|
||||
|
||||
assert!(error.to_string().contains("no Metadata section"), "{error}");
|
||||
assert!(error.to_string().contains("Campaign"), "{error}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_campaign_field_that_is_unset_or_absent_reads_as_no_campaign() {
|
||||
assert_eq!(parse_campaign(&with_metadata("- **ID**: abc\n")), None);
|
||||
assert_eq!(
|
||||
parse_campaign(&with_metadata("- **Campaign**: _Not set_\n")),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
parse_campaign(&with_metadata("- **Campaign**: c-uuid\n")),
|
||||
Some("c-uuid".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
/// The Campaign row shows the resolved cell, and every other row is untouched by it.
|
||||
#[test]
|
||||
fn the_campaign_row_shows_the_cell_it_was_given() {
|
||||
let lines = ["- **Campaign**: c-uuid", "- **Owner**: alice"];
|
||||
|
||||
let rendered = render_metadata_table(&lines, false, "(c-uuid) v1 release");
|
||||
|
||||
assert!(rendered.contains("Campaign (c-uuid) v1 release"), "{rendered}");
|
||||
assert!(rendered.contains("Owner alice"), "{rendered}");
|
||||
}
|
||||
|
||||
/// With no cell to show, the stored value renders as it sits. That is what a ticket
|
||||
/// in no campaign wants, and it keeps the field readable on a board whose campaigns
|
||||
/// directory cannot be read.
|
||||
#[test]
|
||||
fn the_campaign_row_falls_back_to_the_stored_value() {
|
||||
let rendered = render_metadata_table(&["- **Campaign**: c-uuid"], false, "");
|
||||
|
||||
assert!(rendered.contains("Campaign c-uuid"), "{rendered}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_section_rule_matches_the_width_of_its_name() {
|
||||
let rendered = content_trim_colored("# T\n\n## Description\nbody\n", "");
|
||||
let rendered = content_trim_colored("# T\n\n## Description\nbody\n", &Resolved::default());
|
||||
|
||||
// Eleven characters, not fourteen: the rule used to span "## Description"
|
||||
assert!(
|
||||
@@ -2165,14 +2529,14 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn a_non_ascii_section_name_is_not_over_drawn() {
|
||||
let rendered = content_trim_colored("# T\n\n## Résumé\nbody\n", "");
|
||||
let rendered = content_trim_colored("# T\n\n## Résumé\nbody\n", &Resolved::default());
|
||||
|
||||
assert!(rendered.starts_with("Résumé\n──────\n"), "{rendered:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_body_leaves_the_title_to_cmd_show() {
|
||||
let rendered = content_trim_colored("# Only Once\n\n## Description\nbody\n", "");
|
||||
let rendered = content_trim_colored("# Only Once\n\n## Description\nbody\n", &Resolved::default());
|
||||
|
||||
assert!(!rendered.contains("Only Once"), "{rendered:?}");
|
||||
// And no gap where it was
|
||||
@@ -2182,7 +2546,7 @@ mod tests {
|
||||
#[test]
|
||||
fn the_metadata_section_renders_as_a_table_inside_the_body() {
|
||||
let content = "# T\n\n## Metadata\n\n- **ID**: abc\n- **Owner**: alice\n";
|
||||
let rendered = content_trim_colored(content, "");
|
||||
let rendered = content_trim_colored(content, &Resolved::default());
|
||||
|
||||
assert_eq!(rendered, "Metadata\n────────\n\nID abc\nOwner alice\n");
|
||||
}
|
||||
@@ -2190,7 +2554,7 @@ mod tests {
|
||||
#[test]
|
||||
fn a_section_after_metadata_still_renders() {
|
||||
let content = "# T\n\n## Metadata\n\n- **ID**: abc\n\n## Notes\n\nafter\n";
|
||||
let rendered = content_trim_colored(content, "");
|
||||
let rendered = content_trim_colored(content, &Resolved::default());
|
||||
|
||||
assert!(rendered.contains("ID abc"), "{rendered:?}");
|
||||
assert!(rendered.contains("Notes\n─────\n"), "{rendered:?}");
|
||||
@@ -2638,7 +3002,7 @@ mod tests {
|
||||
"# T\n\n## Relations\n- blocked by {}\n\n## Metadata\n\n- **ID**: {}\n",
|
||||
TARGET, SELF
|
||||
);
|
||||
let rendered = content_trim(&content, false, "blocked by (b1b2c3d) The blocker\n");
|
||||
let rendered = content_trim(&content, false, &Resolved { relations: "blocked by (b1b2c3d) The blocker\n".to_string(), ..Default::default() });
|
||||
|
||||
assert!(
|
||||
rendered.contains("Relations\n─────────\n\nblocked by (b1b2c3d) The blocker\n\nMetadata"),
|
||||
@@ -2653,7 +3017,7 @@ mod tests {
|
||||
#[test]
|
||||
fn the_body_injects_the_block_when_the_file_has_no_section() {
|
||||
let content = format!("# T\n\n## Description\nBody.\n\n## Metadata\n\n- **ID**: {}\n", SELF);
|
||||
let rendered = content_trim(&content, false, "blocks (641e3d5) The gated one\n");
|
||||
let rendered = content_trim(&content, false, &Resolved { relations: "blocks (641e3d5) The gated one\n".to_string(), ..Default::default() });
|
||||
|
||||
assert!(
|
||||
rendered.contains("Body.\n\nRelations\n─────────\n\nblocks (641e3d5) The gated one\n\nMetadata"),
|
||||
@@ -2665,7 +3029,7 @@ mod tests {
|
||||
/// worth more at the end than dropped.
|
||||
#[test]
|
||||
fn the_body_appends_the_block_when_there_is_no_metadata() {
|
||||
let rendered = content_trim("# T\n\n## Description\nBody.\n", false, "blocks (641e3d5) X\n");
|
||||
let rendered = content_trim("# T\n\n## Description\nBody.\n", false, &Resolved { relations: "blocks (641e3d5) X\n".to_string(), ..Default::default() });
|
||||
|
||||
assert!(rendered.ends_with("Relations\n─────────\n\nblocks (641e3d5) X\n"), "{rendered:?}");
|
||||
}
|
||||
@@ -2675,7 +3039,7 @@ mod tests {
|
||||
#[test]
|
||||
fn an_empty_block_leaves_the_section_as_written() {
|
||||
let content = "# T\n\n## Relations\n_No relations._\n\n## Metadata\n\n- **ID**: x\n";
|
||||
let rendered = content_trim(content, false, "");
|
||||
let rendered = content_trim(content, false, &Resolved::default());
|
||||
|
||||
assert!(rendered.contains("Relations\n─────────\n\n_No relations._\n"), "{rendered:?}");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,602 @@
|
||||
use assert_cmd::Command;
|
||||
use assert_fs::TempDir;
|
||||
use assert_fs::fixture::{PathChild, PathCreateDir};
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
const BIN_NAME: &str = env!("CARGO_BIN_EXE_worklane");
|
||||
|
||||
/// Two campaigns, so a filter has something to exclude, and three tickets: one in each
|
||||
/// campaign and one in neither.
|
||||
const CAMP_A: &str = "aa11bb22-33cc-4dd4-8ee5-ff6677889900";
|
||||
const CAMP_B: &str = "bb22cc33-44dd-4ee5-8ff6-001122334455";
|
||||
const MEMBER: &str = "641e3d5c-1b0e-4d2f-9a7e-3c8b5f0a2d61";
|
||||
const OTHER: &str = "b1b2c3d4-5e6f-4a7b-8c9d-0e1f2a3b4c5d";
|
||||
const LONER: &str = "f1f2f3f4-5a6b-4c7d-8e9f-0a1b2c3d4e5f";
|
||||
|
||||
fn setup_worklane(temp: &TempDir) -> PathBuf {
|
||||
let worklane = temp.child(".worklane");
|
||||
worklane.create_dir_all().unwrap();
|
||||
|
||||
for dir in ["backlog", "committed", "reviewing", "done", "campaigns"] {
|
||||
worklane.child(dir).create_dir_all().unwrap();
|
||||
}
|
||||
|
||||
worklane.path().to_path_buf()
|
||||
}
|
||||
|
||||
fn slug(title: &str) -> String {
|
||||
title
|
||||
.to_lowercase()
|
||||
.chars()
|
||||
.filter(|c| c.is_alphanumeric() || *c == ' ' || *c == '-' || *c == '_')
|
||||
.map(|c| if c == ' ' { '-' } else { c })
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A ticket with a ticked criterion, a section the tool knows nothing about and a
|
||||
/// metadata field it has never heard of, so every test can check that an assignment
|
||||
/// leaves all three exactly as they were.
|
||||
///
|
||||
/// Deliberately carries no Campaign field: no ticket written before campaigns existed
|
||||
/// has one, and `add` still does not write one, so the insertion path is what every
|
||||
/// assignment goes through.
|
||||
fn create_ticket(worklane: &Path, status: &str, title: &str, uuid: &str) -> PathBuf {
|
||||
let path = worklane
|
||||
.join(status)
|
||||
.join(format!("{}_{}.md", uuid, slug(title)));
|
||||
|
||||
fs::write(
|
||||
&path,
|
||||
format!(
|
||||
"# {title}\n\
|
||||
\n\
|
||||
## Description\n\
|
||||
Prose that mentions **Campaign**: not a field, in the body.\n\
|
||||
\n\
|
||||
## Acceptance Criteria\n\
|
||||
- [x] Crit one\n\
|
||||
\n\
|
||||
## Implementation Plan\n\
|
||||
1. Step one\n\
|
||||
\n\
|
||||
## Notes\n\
|
||||
A handwritten note the tool knows nothing about.\n\
|
||||
\n\
|
||||
## Metadata\n\
|
||||
\n\
|
||||
- **ID**: {uuid}\n\
|
||||
- **Priority**: 3\n\
|
||||
- **Tags**: alpha\n\
|
||||
- **Due**: _Not set_\n\
|
||||
- **Handled By Team**: ops\n\
|
||||
- **Owner**: alice\n\
|
||||
- **Created At**: 2026-08-21 02:10:17\n\
|
||||
- **Status**: {status}\n"
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
path
|
||||
}
|
||||
|
||||
fn create_campaign(worklane: &Path, title: &str, uuid: &str) -> PathBuf {
|
||||
let path = worklane
|
||||
.join("campaigns")
|
||||
.join(format!("{}_{}.md", uuid, slug(title)));
|
||||
|
||||
fs::write(
|
||||
&path,
|
||||
format!(
|
||||
"# {title}\n\
|
||||
\n\
|
||||
## Description\n\
|
||||
What has to ship together.\n\
|
||||
\n\
|
||||
## Metadata\n\
|
||||
\n\
|
||||
- **ID**: {uuid}\n\
|
||||
- **Owner**: alice\n\
|
||||
- **Created At**: 2026-08-21 02:10:17\n"
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
path
|
||||
}
|
||||
|
||||
fn board(temp: &TempDir) -> PathBuf {
|
||||
let worklane = setup_worklane(temp);
|
||||
create_campaign(&worklane, "v1 release", CAMP_A);
|
||||
create_campaign(&worklane, "v2 release", CAMP_B);
|
||||
create_ticket(&worklane, "backlog", "The member", MEMBER);
|
||||
create_ticket(&worklane, "done", "The other member", OTHER);
|
||||
create_ticket(&worklane, "backlog", "The loner", LONER);
|
||||
worklane
|
||||
}
|
||||
|
||||
fn run(temp: &TempDir, args: &[&str]) -> std::process::Output {
|
||||
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
|
||||
cmd.current_dir(temp.path()).args(args);
|
||||
cmd.assert().get_output().clone()
|
||||
}
|
||||
|
||||
fn stdout(out: &std::process::Output) -> String {
|
||||
String::from_utf8_lossy(&out.stdout).to_string()
|
||||
}
|
||||
|
||||
fn stderr(out: &std::process::Output) -> String {
|
||||
String::from_utf8_lossy(&out.stderr).to_string()
|
||||
}
|
||||
|
||||
fn find(worklane: &Path, uuid: &str) -> PathBuf {
|
||||
for status in ["backlog", "committed", "reviewing", "done"] {
|
||||
for entry in fs::read_dir(worklane.join(status))
|
||||
.unwrap()
|
||||
.filter_map(|e| e.ok())
|
||||
{
|
||||
if entry.file_name().to_string_lossy().starts_with(uuid) {
|
||||
return entry.path();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
panic!("no file for ticket {uuid}");
|
||||
}
|
||||
|
||||
fn ticket(worklane: &Path, uuid: &str) -> String {
|
||||
fs::read_to_string(find(worklane, uuid)).unwrap()
|
||||
}
|
||||
|
||||
fn campaigns(worklane: &Path) -> Vec<String> {
|
||||
let mut names: Vec<String> = fs::read_dir(worklane.join("campaigns"))
|
||||
.unwrap()
|
||||
.filter_map(|e| e.ok())
|
||||
.map(|e| e.file_name().to_string_lossy().to_string())
|
||||
.collect();
|
||||
names.sort();
|
||||
names
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ filing one --
|
||||
|
||||
#[test]
|
||||
fn campaign_add_writes_a_uuid_title_description_and_metadata() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = setup_worklane(&temp);
|
||||
|
||||
let out = run(
|
||||
&temp,
|
||||
&[
|
||||
"campaign",
|
||||
"add",
|
||||
"--title",
|
||||
"v1 release",
|
||||
"--description",
|
||||
"Everything that ships together.",
|
||||
"--owner",
|
||||
"alice",
|
||||
],
|
||||
);
|
||||
assert!(out.status.success(), "{}", stderr(&out));
|
||||
|
||||
let names = campaigns(&worklane);
|
||||
assert_eq!(names.len(), 1, "{names:?}");
|
||||
let name = &names[0];
|
||||
assert!(name.ends_with("_v1-release.md"), "{name}");
|
||||
|
||||
let content = fs::read_to_string(worklane.join("campaigns").join(name)).unwrap();
|
||||
assert!(content.starts_with("# v1 release\n"), "{content}");
|
||||
assert!(content.contains("Everything that ships together."), "{content}");
|
||||
assert!(content.contains("- **Owner**: alice"), "{content}");
|
||||
assert!(content.contains("- **Created At**: 20"), "{content}");
|
||||
|
||||
// The uuid in the file is the one in the filename, since that is what `assign`
|
||||
// stores and what every lookup compares against.
|
||||
let uuid = name.split('_').next().unwrap();
|
||||
assert!(content.contains(&format!("- **ID**: {uuid}")), "{content}");
|
||||
}
|
||||
|
||||
/// A campaign has no status, so its file carries none. A Status field would be a second
|
||||
/// place for a state that is derived, and the two would disagree the moment a member
|
||||
/// moved.
|
||||
#[test]
|
||||
fn a_campaign_carries_no_status_and_no_criteria() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = setup_worklane(&temp);
|
||||
|
||||
run(&temp, &["campaign", "add", "--title", "v1 release"]);
|
||||
|
||||
let name = campaigns(&worklane).remove(0);
|
||||
let content = fs::read_to_string(worklane.join("campaigns").join(name)).unwrap();
|
||||
|
||||
assert!(!content.contains("**Status**"), "{content}");
|
||||
assert!(!content.contains("Acceptance Criteria"), "{content}");
|
||||
assert!(!content.contains("Implementation Plan"), "{content}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_is_created_without_a_title() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = setup_worklane(&temp);
|
||||
|
||||
let out = run(&temp, &["campaign", "add", "--description", "No title here."]);
|
||||
|
||||
assert_eq!(out.status.code(), Some(2), "{}", stderr(&out));
|
||||
assert!(campaigns(&worklane).is_empty(), "{:?}", campaigns(&worklane));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn init_creates_the_campaigns_directory() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
|
||||
let out = run(&temp, &["init"]);
|
||||
assert!(out.status.success(), "{}", stderr(&out));
|
||||
|
||||
assert!(temp.child(".worklane").child("campaigns").path().is_dir());
|
||||
}
|
||||
|
||||
/// A board made before campaigns existed has no such directory, and a `worklane init`
|
||||
/// over a live board to get one would be a strange thing to have to do.
|
||||
#[test]
|
||||
fn the_campaigns_directory_is_created_for_a_board_that_predates_it() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = temp.child(".worklane");
|
||||
worklane.create_dir_all().unwrap();
|
||||
for dir in ["backlog", "committed", "reviewing", "done"] {
|
||||
worklane.child(dir).create_dir_all().unwrap();
|
||||
}
|
||||
assert!(!worklane.child("campaigns").path().exists());
|
||||
|
||||
let out = run(&temp, &["campaign", "add", "--title", "v1 release"]);
|
||||
assert!(out.status.success(), "{}", stderr(&out));
|
||||
|
||||
assert_eq!(campaigns(worklane.path()).len(), 1);
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------- assigning --
|
||||
|
||||
#[test]
|
||||
fn assign_writes_the_campaign_field_in_the_metadata_section() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = board(&temp);
|
||||
|
||||
let out = run(&temp, &["assign", "v1 release", MEMBER]);
|
||||
assert!(out.status.success(), "{}", stderr(&out));
|
||||
|
||||
let content = ticket(&worklane, MEMBER);
|
||||
assert!(content.contains(&format!("- **Campaign**: {CAMP_A}")), "{content}");
|
||||
|
||||
// Scoped to the section: the description quotes the marker, and the field has to
|
||||
// land under the heading rather than over the prose.
|
||||
let metadata = content.split("## Metadata").nth(1).unwrap();
|
||||
assert!(metadata.contains(&format!("- **Campaign**: {CAMP_A}")), "{content}");
|
||||
assert!(
|
||||
content.contains("Prose that mentions **Campaign**: not a field, in the body."),
|
||||
"the description was rewritten: {content}"
|
||||
);
|
||||
}
|
||||
|
||||
/// The field goes in its place among the others rather than at the end, so Status stays
|
||||
/// last, which is where every file already keeps it.
|
||||
#[test]
|
||||
fn the_field_is_inserted_before_status() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = board(&temp);
|
||||
|
||||
run(&temp, &["assign", "v1 release", MEMBER]);
|
||||
|
||||
let content = ticket(&worklane, MEMBER);
|
||||
let campaign_at = content.find("- **Campaign**:").unwrap();
|
||||
let status_at = content.find("- **Status**:").unwrap();
|
||||
assert!(campaign_at < status_at, "{content}");
|
||||
}
|
||||
|
||||
/// All three tiers, since a campaign is addressed the way a ticket is: a uuid prefix, a
|
||||
/// title substring, and a substring reaching the middle of the filename.
|
||||
#[test]
|
||||
fn a_campaign_resolves_by_uuid_prefix_title_or_filename() {
|
||||
for search in ["aa11", "v1 release", "4dd4"] {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = board(&temp);
|
||||
|
||||
let out = run(&temp, &["assign", search, MEMBER]);
|
||||
assert!(out.status.success(), "{search}: {}", stderr(&out));
|
||||
assert!(
|
||||
ticket(&worklane, MEMBER).contains(&format!("- **Campaign**: {CAMP_A}")),
|
||||
"{search}: {}",
|
||||
ticket(&worklane, MEMBER)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_ticket_names_at_most_one_campaign() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = board(&temp);
|
||||
|
||||
run(&temp, &["assign", "v1 release", MEMBER]);
|
||||
let out = run(&temp, &["assign", "v2 release", MEMBER]);
|
||||
assert!(out.status.success(), "{}", stderr(&out));
|
||||
|
||||
let content = ticket(&worklane, MEMBER);
|
||||
assert_eq!(
|
||||
content.matches("- **Campaign**:").count(),
|
||||
1,
|
||||
"reassigning added a second field: {content}"
|
||||
);
|
||||
assert!(content.contains(&format!("- **Campaign**: {CAMP_B}")), "{content}");
|
||||
assert!(!content.contains(CAMP_A), "{content}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn assigning_the_campaign_already_named_writes_nothing() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = board(&temp);
|
||||
|
||||
run(&temp, &["assign", "v1 release", MEMBER]);
|
||||
let before = ticket(&worklane, MEMBER);
|
||||
|
||||
let out = run(&temp, &["assign", "v1 release", MEMBER]);
|
||||
assert!(out.status.success(), "{}", stderr(&out));
|
||||
assert!(stdout(&out).contains("already in campaign"), "{}", stdout(&out));
|
||||
assert_eq!(ticket(&worklane, MEMBER), before);
|
||||
}
|
||||
|
||||
/// The campaign is resolved before the ticket is touched, so a call naming a good
|
||||
/// ticket and a campaign that does not exist writes nothing at all.
|
||||
#[test]
|
||||
fn an_unknown_campaign_leaves_the_ticket_alone() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = board(&temp);
|
||||
let before = ticket(&worklane, MEMBER);
|
||||
|
||||
let out = run(&temp, &["assign", "v9 release", MEMBER]);
|
||||
|
||||
assert!(!out.status.success());
|
||||
assert!(stderr(&out).contains("No campaign found matching"), "{}", stderr(&out));
|
||||
assert_eq!(ticket(&worklane, MEMBER), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn content_the_tool_does_not_know_survives_an_assignment() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = board(&temp);
|
||||
|
||||
run(&temp, &["assign", "v1 release", MEMBER]);
|
||||
|
||||
let content = ticket(&worklane, MEMBER);
|
||||
assert!(content.contains("## Notes"), "{content}");
|
||||
assert!(
|
||||
content.contains("A handwritten note the tool knows nothing about."),
|
||||
"{content}"
|
||||
);
|
||||
assert!(content.contains("- **Handled By Team**: ops"), "{content}");
|
||||
// And the ticked criterion is still ticked.
|
||||
assert!(content.contains("- [x] Crit one"), "{content}");
|
||||
}
|
||||
|
||||
/// One field, one writer. `assign` owns Campaign the way `chown` owns Owner.
|
||||
#[test]
|
||||
fn neither_add_nor_set_offers_a_campaign_flag() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = board(&temp);
|
||||
|
||||
let added = run(&temp, &["add", "--title", "New one", "--campaign", "v1 release"]);
|
||||
assert_eq!(added.status.code(), Some(2), "{}", stderr(&added));
|
||||
|
||||
let set = run(&temp, &["set", MEMBER, "--campaign", "v1 release"]);
|
||||
assert_eq!(set.status.code(), Some(2), "{}", stderr(&set));
|
||||
|
||||
// The stored shape, not the bare marker: the fixture description quotes the marker
|
||||
// on purpose, so an unscoped match here would pass whatever the commands did.
|
||||
assert!(!ticket(&worklane, MEMBER).contains("- **Campaign**:"));
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------------- reading --
|
||||
|
||||
#[test]
|
||||
fn campaign_ls_lists_campaigns_with_their_member_counts() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let _worklane = board(&temp);
|
||||
|
||||
run(&temp, &["assign", "v1 release", MEMBER]);
|
||||
run(&temp, &["assign", "v1 release", OTHER]);
|
||||
|
||||
let out = run(&temp, &["campaign", "ls"]);
|
||||
assert!(out.status.success(), "{}", stderr(&out));
|
||||
|
||||
let listing = stdout(&out);
|
||||
// One of the two members is in done, so the campaign is open and half finished.
|
||||
assert!(listing.contains("v1 release | 1/2 done [open]"), "{listing}");
|
||||
// Nothing has been filed against the other one.
|
||||
assert!(listing.contains("v2 release | no members"), "{listing}");
|
||||
}
|
||||
|
||||
/// A campaign is done when it holds members and every one of them is done. An empty one
|
||||
/// is neither, which is why it reads `no members` rather than `0/0 done`.
|
||||
#[test]
|
||||
fn a_campaign_whose_every_member_is_done_reads_done() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let _worklane = board(&temp);
|
||||
|
||||
run(&temp, &["assign", "v1 release", OTHER]);
|
||||
|
||||
let listing = stdout(&run(&temp, &["campaign", "ls"]));
|
||||
assert!(listing.contains("v1 release | 1/1 done [done]"), "{listing}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn campaign_show_prints_the_body_and_the_members_grouped_by_status() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let _worklane = board(&temp);
|
||||
|
||||
run(&temp, &["assign", "v1 release", MEMBER]);
|
||||
run(&temp, &["assign", "v1 release", OTHER]);
|
||||
|
||||
let out = run(&temp, &["campaign", "show", "aa11"]);
|
||||
assert!(out.status.success(), "{}", stderr(&out));
|
||||
|
||||
let shown = stdout(&out);
|
||||
assert!(shown.contains("v1 release"), "{shown}");
|
||||
assert!(shown.contains("What has to ship together."), "{shown}");
|
||||
assert!(shown.contains("1/2 done"), "{shown}");
|
||||
assert!(shown.contains("[BACKLOG]"), "{shown}");
|
||||
assert!(shown.contains("The member"), "{shown}");
|
||||
// Done members are shown here, unlike in `ls`: what is finished against what is
|
||||
// left is the whole question a campaign asks.
|
||||
assert!(shown.contains("[DONE]"), "{shown}");
|
||||
assert!(shown.contains("The other member"), "{shown}");
|
||||
// And a ticket in no campaign is not a member of this one.
|
||||
assert!(!shown.contains("The loner"), "{shown}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ls_campaign_lists_only_that_campaigns_members() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let _worklane = board(&temp);
|
||||
|
||||
run(&temp, &["assign", "v1 release", MEMBER]);
|
||||
run(&temp, &["assign", "v2 release", LONER]);
|
||||
|
||||
let out = run(&temp, &["ls", "--campaign", "v1 release"]);
|
||||
assert!(out.status.success(), "{}", stderr(&out));
|
||||
|
||||
let listing = stdout(&out);
|
||||
assert!(listing.contains("The member"), "{listing}");
|
||||
assert!(!listing.contains("The loner"), "{listing}");
|
||||
assert!(listing.contains("[BACKLOG] 1 ticket"), "{listing}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ls_campaign_refuses_a_campaign_that_does_not_exist() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let _worklane = board(&temp);
|
||||
|
||||
let out = run(&temp, &["ls", "--campaign", "v9 release"]);
|
||||
|
||||
assert!(!out.status.success());
|
||||
assert!(stderr(&out).contains("No campaign found matching"), "{}", stderr(&out));
|
||||
}
|
||||
|
||||
/// The stored value is a full uuid, so a campaign that has been deleted has to be
|
||||
/// reported as gone rather than shown raw, the way a dangling relation target is.
|
||||
#[test]
|
||||
fn a_campaign_that_no_longer_exists_reads_as_missing() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = board(&temp);
|
||||
|
||||
run(&temp, &["assign", "v1 release", MEMBER]);
|
||||
fs::remove_file(worklane.join("campaigns").join(format!("{CAMP_A}_v1-release.md"))).unwrap();
|
||||
|
||||
let out = run(&temp, &["show", MEMBER]);
|
||||
assert!(out.status.success(), "{}", stderr(&out));
|
||||
|
||||
let shown = stdout(&out);
|
||||
assert!(shown.contains("_missing_"), "{shown}");
|
||||
// The short id survives, since it is the only thing left to go looking for.
|
||||
assert!(shown.contains("(aa11bb2)"), "{shown}");
|
||||
assert!(!shown.contains(CAMP_A), "the bare uuid was shown: {shown}");
|
||||
}
|
||||
|
||||
/// The title is shown rather than the uuid the file stores: thirty-six characters of
|
||||
/// hex in a metadata table say nothing about which campaign it is.
|
||||
#[test]
|
||||
fn a_ticket_shows_the_campaign_title_not_its_uuid() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let _worklane = board(&temp);
|
||||
|
||||
run(&temp, &["assign", "v1 release", MEMBER]);
|
||||
|
||||
let shown = stdout(&run(&temp, &["show", MEMBER]));
|
||||
assert!(shown.contains("(aa11bb2) v1 release"), "{shown}");
|
||||
assert!(!shown.contains(CAMP_A), "{shown}");
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------- not a ticket --
|
||||
|
||||
/// A campaign is in no status directory, so `mv` has nothing to move. It says so rather
|
||||
/// than reporting a ticket it could not find, which would send the caller hunting for a
|
||||
/// typo in a name that is perfectly correct.
|
||||
#[test]
|
||||
fn mv_refuses_a_campaign() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = board(&temp);
|
||||
|
||||
let out = run(&temp, &["mv", "v1 release", "--status", "committed"]);
|
||||
|
||||
assert!(!out.status.success());
|
||||
let message = stderr(&out);
|
||||
assert!(message.contains("is a campaign, not a ticket"), "{message}");
|
||||
assert!(message.contains("no status directory"), "{message}");
|
||||
|
||||
// And it stayed where it was: nothing was moved into a status directory.
|
||||
assert!(
|
||||
worklane
|
||||
.join("campaigns")
|
||||
.join(format!("{CAMP_A}_v1-release.md"))
|
||||
.exists()
|
||||
);
|
||||
for status in ["backlog", "committed", "reviewing", "done"] {
|
||||
let moved = fs::read_dir(worklane.join(status))
|
||||
.unwrap()
|
||||
.filter_map(|e| e.ok())
|
||||
.any(|e| e.file_name().to_string_lossy().starts_with(CAMP_A));
|
||||
assert!(!moved, "a campaign reached the {status} directory");
|
||||
}
|
||||
}
|
||||
|
||||
/// Every command that takes a ticket gives the same explanation, because the refusal is
|
||||
/// in resolution rather than in `mv`.
|
||||
#[test]
|
||||
fn a_campaign_is_refused_wherever_a_ticket_is_expected() {
|
||||
for args in [
|
||||
vec!["show", "v1 release"],
|
||||
vec!["comment", "v1 release", "A note."],
|
||||
vec!["chown", "bob", "v1 release"],
|
||||
] {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let _worklane = board(&temp);
|
||||
|
||||
let out = run(&temp, &args);
|
||||
assert!(!out.status.success(), "{args:?}");
|
||||
assert!(
|
||||
stderr(&out).contains("is a campaign, not a ticket"),
|
||||
"{args:?}: {}",
|
||||
stderr(&out)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A search that names neither still says nothing was found, rather than complaining
|
||||
/// about a directory the caller never mentioned.
|
||||
#[test]
|
||||
fn a_search_that_names_nothing_still_reports_no_ticket() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let _worklane = board(&temp);
|
||||
|
||||
let out = run(&temp, &["show", "nothing at all"]);
|
||||
|
||||
assert!(!out.status.success());
|
||||
assert!(
|
||||
stderr(&out).contains("No ticket found matching"),
|
||||
"{}",
|
||||
stderr(&out)
|
||||
);
|
||||
}
|
||||
|
||||
/// A campaign resolves by the same tiers a ticket does, so it can be ambiguous the same
|
||||
/// way, and the listing has to name campaigns rather than tickets.
|
||||
#[test]
|
||||
fn an_ambiguous_campaign_lists_the_candidates() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let _worklane = board(&temp);
|
||||
|
||||
let out = run(&temp, &["campaign", "show", "release"]);
|
||||
|
||||
assert!(!out.status.success());
|
||||
let message = stderr(&out);
|
||||
assert!(message.contains("Multiple campaigns found matching"), "{message}");
|
||||
assert!(message.contains("v1 release"), "{message}");
|
||||
assert!(message.contains("v2 release"), "{message}");
|
||||
}
|
||||
Reference in New Issue
Block a user