Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e20396ce6b | ||
|
|
f5204f6d8b | ||
|
|
b28ddb9210 | ||
|
|
f557437f62 | ||
|
|
75fb2b3a6d | ||
|
|
8b440593e2 | ||
|
|
ab1dae098c | ||
|
|
2503f9aee9 | ||
|
|
ddbd45e332 |
@@ -37,6 +37,7 @@ Add a new ticket to the backlog.
|
||||
- `--tags` (or `-g`): Tags (comma-separated)
|
||||
- `--due` (or `--due`): Due date in YYYY-MM-DD format
|
||||
- `--owner` (or `-o`): Owner name
|
||||
- `--priority`: Priority level, 1 (most urgent) to 5 (least). Unset if omitted
|
||||
|
||||
```bash
|
||||
worklane add -t "Implement login" -d "Add user login page" -t login,auth -p "Design UI" "Build backend" "Write tests" --due 2026-06-01 --owner "ilya"
|
||||
@@ -56,11 +57,15 @@ List tickets, optionally filtered by status.
|
||||
**Valid statuses:** `backlog`, `committed`, `reviewing`, `done`
|
||||
|
||||
```
|
||||
worklane ls # List all tickets
|
||||
worklane ls backlog # List tickets in backlog
|
||||
worklane ls done # List completed tickets
|
||||
worklane ls # List all tickets
|
||||
worklane ls backlog # List tickets in backlog
|
||||
worklane ls done # List completed tickets
|
||||
worklane ls --priority 1 # Only the most urgent, any status
|
||||
worklane ls backlog --priority 2 # Composes with the status filter
|
||||
```
|
||||
|
||||
Tickets are listed priority first, then by title. Tickets with no priority sort last.
|
||||
|
||||
### `worklane show`
|
||||
|
||||
Show the full details of a single ticket by UUID or title.
|
||||
|
||||
@@ -76,6 +76,10 @@ export const add = tool({
|
||||
owner: tool.schema
|
||||
.string()
|
||||
.describe("Ticket owner name. If omitted, defaults to the git user."),
|
||||
priority: tool.schema
|
||||
.string()
|
||||
.describe("Priority level, 1 (most urgent) to 5 (least). Left unset if omitted.")
|
||||
.optional(),
|
||||
},
|
||||
async execute(args: Record<string, any>, context: ToolContext) {
|
||||
if (!args.title) {
|
||||
@@ -109,6 +113,7 @@ export const add = tool({
|
||||
if (args.tags) cmd.push("--tags", args.tags);
|
||||
if (args.due) cmd.push("--due", args.due);
|
||||
if (args.owner) cmd.push("--owner", args.owner);
|
||||
if (args.priority) cmd.push("--priority", String(args.priority));
|
||||
|
||||
try {
|
||||
return await run(cmd, context);
|
||||
@@ -120,15 +125,20 @@ export const add = tool({
|
||||
|
||||
export const ls = tool({
|
||||
description:
|
||||
"List all worklane tickets. Optionally filter by status (backlog, committed, reviewing, done).",
|
||||
"List all worklane tickets, sorted by priority then title. Optionally filter by status and by priority.",
|
||||
args: {
|
||||
status: tool.schema
|
||||
.enum(["backlog", "committed", "reviewing", "done"])
|
||||
.describe("Filter by status")
|
||||
.optional(),
|
||||
priority: tool.schema
|
||||
.string()
|
||||
.describe("Only show tickets at this priority, 1 (most urgent) to 5 (least)")
|
||||
.optional(),
|
||||
},
|
||||
async execute(args: Record<string, any>, context: ToolContext) {
|
||||
const cmd = args.status ? ["ls", args.status] : ["ls"];
|
||||
if (args.priority) cmd.push("--priority", String(args.priority));
|
||||
try {
|
||||
return await run(cmd, context);
|
||||
} catch (err: any) {
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
|
||||
## Ticket File Format
|
||||
- Filenames: `<uuid_v4>_<slug>.md`
|
||||
- Metadata fields parsed by `parse_ticket_field()`: `ID`, `Tags`, `Due`, `Owner`, `Created At`, `Status`
|
||||
- Metadata fields parsed by `parse_ticket_field()`: `ID`, `Priority`, `Tags`, `Due`, `Owner`, `Created At`, `Status`
|
||||
- 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
|
||||
@@ -31,12 +31,20 @@
|
||||
- Use `unwrap_or_else(|| expr)` for lazy defaults, `unwrap_or(val)` for eager defaults
|
||||
- Use `anyhow!()` with context strings that include identifying info (e.g. UUID, title) not bare values
|
||||
|
||||
### CLI Arguments
|
||||
- The prose arguments carry `allow_hyphen_values`, via the `PROSE` constant in `command.rs`: `add --title`, `--description`, `--acceptance`, `--plan`, and the `comment` body. Ticket text quotes flag names constantly, and without it a criterion reading `--print is supported` is parsed as a flag and the whole ticket is refused with nothing written
|
||||
- **The trade:** on those five arguments a genuinely mistyped flag now lands as content rather than raising a usage error. That is the right way round for prose and the wrong way round for anything else, which is why `due`, `priority`, `tags`, `owner` and `status` are deliberately left without it. A mistyped flag there is still a usage error, exit 2, and no ticket is written. Do not add `PROSE` to a new argument unless it holds prose
|
||||
- The ticket positionals (`show <id>`, `mv <ticket>`, `comment <ticket>`) are also left alone, so a search term starting with a hyphen is a usage error. Reachable now that a hyphen-leading title can be stored: use the UUID, or put the flags first and separate with `--`, as in `mv --status committed -- -leading-title`
|
||||
- A bare `--` is a value when it follows an option (`--title -- ` stores `--`) and clap's end-of-options marker when it sits in a positional. So a `comment` body of exactly `--` needs its own separator, `comment <ticket> -- --`. Without it the body is reported missing and nothing is written, which is a clear failure rather than a silent drop
|
||||
- `add` has no positionals, so anything after a bare `--` is an unexpected argument and fails
|
||||
|
||||
### Color and Output
|
||||
- Use `color_text()` helper for colored output — it respects `should_use_colors()` (terminal detection)
|
||||
- Color codes are defined in `get_color()`: red (31), cyan (36), orange (33), green (32), grey (38;5;8), magenta (1;35)
|
||||
- Color codes are defined in `get_color()`: red (31), cyan (36), orange (33), green (32), grey (38;5;8), magenta (1;35), brightred (38;5;9)
|
||||
- Reset color with `\x1b[0m` after colored text
|
||||
- Bold uses `\x1b[1;35m` (magenta bold)
|
||||
- Always test color output works correctly in both terminal and pipe modes
|
||||
- `quiet_broken_pipe()` runs first in `main`, restoring the default `SIGPIPE` disposition. A truncated pipe therefore kills the process with signal 13, which a shell reports as 141, instead of making `println!` panic. Do not wrap prints to handle write errors and do not reinstate `SIG_IGN`; the exit codes are documented in the README
|
||||
|
||||
### Color Guideline
|
||||
- UUID → red (31)
|
||||
@@ -44,12 +52,18 @@
|
||||
- Timestamp → cyan (36)
|
||||
- Title → green (32)
|
||||
- Unknown values (`_None_`, `_Not set_`) → grey (38;5;8)
|
||||
- Priority ramp → brightred (1), red (2), orange (3), cyan (4), grey (5). Green is deliberately absent: it means title
|
||||
- Grey is indexed colour 8 in the 256-colour form, not SGR 90 or 37. Both of those failed on a real palette: 90 leans on the bright-black slot and 37 can sit on top of the default foreground. `\x1b[38;5;8m` is byte for byte what crossterm emits for ratatui's `Color::DarkGray`, the grey frig and pantop use for dimmed rows
|
||||
|
||||
### Code Organization
|
||||
- Colorization functions (`colorize_line`, `colorize_metadata`, `colorize_ordered`, `content_trim_colored`) handle markdown formatting
|
||||
- Colorization functions (`colorize_line`, `colorize_ordered`, `content_trim_colored`) handle markdown formatting
|
||||
- `show` renders the Metadata section as a two column table via `render_metadata_table`, not line by line. Column width is measured on the raw field names in characters and padding is applied before anything is styled: measuring a coloured string counts its escapes towards its width. `paint()` is `color_text()` with the colour decision passed in, which is what lets a test render both ways in one process
|
||||
- The title is printed once, by `cmd_show`. `content_trim_colored` skips the `# ` heading in the file content
|
||||
- Rules under headings are measured on the displayed name in characters, never on the raw line or in bytes
|
||||
- `resolve_ticket()` scans all status directories — it's the single source for ticket lookup by UUID prefix, title, or filename
|
||||
- `parse_ticket_field()` handles extracting metadata values from markdown format
|
||||
- `move_ticket_file()` stages the updated content in a temp file under `.worklane/`, renames it over the source, and only then renames the file into the target directory. Do not reorder these: renaming first and writing second leaves a ticket in its new directory claiming the old status, and writing to the target then deleting the source puts it in two directories at once. The temp lives outside the status directories so a leftover is never read as a ticket. A failure at the last step leaves the ticket in its old directory with a Status one move ahead, which the next `mv` corrects
|
||||
- Field lookup, read and write, is scoped to the lines under the `## Metadata` heading and anchored to the start of the line. Prose above it is free text: tickets in this repo quote field markers in their descriptions, and an unscoped search reads or rewrites those instead. `set_status_field()` carries the same scoping
|
||||
|
||||
### Ticket Resolution
|
||||
- `resolve_ticket()` returns `(status, title, content)` tuple
|
||||
|
||||
Generated
+2
-1
@@ -1029,13 +1029,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "worklane"
|
||||
version = "0.1.2"
|
||||
version = "0.3.3"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"assert_cmd",
|
||||
"assert_fs",
|
||||
"chrono",
|
||||
"clap",
|
||||
"libc",
|
||||
"tempfile",
|
||||
"uuid",
|
||||
]
|
||||
|
||||
+2
-1
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "worklane"
|
||||
version = "0.1.2"
|
||||
version = "0.3.3"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
@@ -8,6 +8,7 @@ clap = { version = "4", features = ["derive"] }
|
||||
anyhow = "1"
|
||||
uuid = { version = "1", features = ["v4"] }
|
||||
chrono = { version = "0.4", features = ["serde"] }
|
||||
libc = "0.2"
|
||||
|
||||
[dev-dependencies]
|
||||
assert_cmd = "2"
|
||||
|
||||
@@ -6,8 +6,21 @@ Worklane is a local Kanban flow for agentic software development.
|
||||
| Command | Description |
|
||||
|---------|-------------|
|
||||
| `worklane init` | Creates `.worklane/` with backlog, committed, reviewing, done directories |
|
||||
| `worklane add` | Creates a ticket in backlog with `--title`, `--description`, `--acceptance`, `--plan`, `--tags`, `--due`, `--owner` flags |
|
||||
| `worklane ls` | Lists tickets, optionally filtered by `--status` |
|
||||
| `worklane add` | Creates a ticket in backlog with `--title`, `--description`, `--acceptance`, `--plan`, `--tags`, `--due`, `--owner`, `--priority` flags |
|
||||
| `worklane ls [status]` | Lists tickets, sorted by priority then title. Optional positional status, and `--priority <1-5>` |
|
||||
| `worklane show <id>` | Shows ticket by UUID prefix (8+ chars) or title substring |
|
||||
| `worklane mv <id> --status <target> [-f]` | Moves ticket between statuses. Default: forward only, one stage at a time. `-f` bypasses both restrictions |
|
||||
| `worklane comment <ticket> <body>` | Adds a comment to a ticket by UUID or title |
|
||||
|
||||
## Exit codes
|
||||
| Code | Meaning |
|
||||
|------|---------|
|
||||
| 0 | Success |
|
||||
| 1 | An error, such as no matching ticket or an ambiguous search |
|
||||
| 2 | A usage mistake, such as an unknown flag |
|
||||
| 141 | Output was piped to a reader that stopped early, for example `worklane ls \| head -3` |
|
||||
|
||||
141 is 128 + 13, the shell's way of reporting death by `SIGPIPE`. Worklane restores
|
||||
the default signal disposition so a truncated pipe is quiet, the way `head` and
|
||||
`sort` are, rather than printing a panic. A script using `set -o pipefail` will see
|
||||
141 for a case that is not a failure, so guard for it there.
|
||||
|
||||
+45
-4
@@ -1,5 +1,25 @@
|
||||
use clap::Parser;
|
||||
|
||||
use std::sync::LazyLock;
|
||||
|
||||
use crate::util::{PRIORITY_RANGE, priority_legend};
|
||||
|
||||
/// clap wants a `&str` with a long enough lifetime, and the legend is built from
|
||||
/// the same ramp the listing uses rather than spelled out a second time.
|
||||
static PRIORITY_LEGEND: LazyLock<String> = LazyLock::new(priority_legend);
|
||||
|
||||
/// Reject a level outside the range at parse time, so no command has to.
|
||||
fn priority_level(raw: &str) -> Result<u8, String> {
|
||||
match raw.parse::<u8>() {
|
||||
Ok(level) if PRIORITY_RANGE.contains(&level) => Ok(level),
|
||||
_ => Err(format!(
|
||||
"priority must be a whole number from {} to {}",
|
||||
PRIORITY_RANGE.start(),
|
||||
PRIORITY_RANGE.end()
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// What `--version` prints: the crate version and the commit it was built from.
|
||||
///
|
||||
/// The sha is the part that matters. Two binaries built weeks apart both call
|
||||
@@ -17,6 +37,17 @@ pub struct Cli {
|
||||
pub command: Command,
|
||||
}
|
||||
|
||||
/// Arguments that carry prose, and therefore have to accept a value starting with
|
||||
/// a hyphen.
|
||||
///
|
||||
/// Ticket text quotes flag names constantly, and without this a criterion reading
|
||||
/// "--print is supported" is parsed as a flag and the whole ticket is refused. The
|
||||
/// trade, spelled out in AGENTS.md: on these arguments a genuinely mistyped flag
|
||||
/// now lands as content instead of raising a usage error. That is the right way
|
||||
/// round for prose, and it is why `due`, `priority`, `tags`, `owner` and `status`
|
||||
/// are deliberately left without it.
|
||||
const PROSE: bool = true;
|
||||
|
||||
#[derive(clap::Subcommand)]
|
||||
pub enum Command {
|
||||
/// Initialize worklane in the current project
|
||||
@@ -25,19 +56,19 @@ pub enum Command {
|
||||
/// Add a new ticket to the backlog
|
||||
Add {
|
||||
/// Ticket title
|
||||
#[arg(short, long)]
|
||||
#[arg(short, long, allow_hyphen_values = PROSE)]
|
||||
title: String,
|
||||
|
||||
/// Ticket description. Use multiple flags to create multiline descriptions.
|
||||
#[arg(short, long)]
|
||||
#[arg(short, long, allow_hyphen_values = PROSE)]
|
||||
description: Vec<String>,
|
||||
|
||||
/// Acceptance criteria. Accepts multiple flags, each will be interpreted as a single criterium
|
||||
#[arg(short, long)]
|
||||
#[arg(short, long, allow_hyphen_values = PROSE)]
|
||||
acceptance: Vec<String>,
|
||||
|
||||
/// Implementation plan. Accepts multiple flags, each will be interpreted as a single step
|
||||
#[arg(short, long)]
|
||||
#[arg(short, long, allow_hyphen_values = PROSE)]
|
||||
plan: Vec<String>,
|
||||
|
||||
/// Tags (comma-separated)
|
||||
@@ -51,12 +82,21 @@ pub enum Command {
|
||||
/// Owner
|
||||
#[arg(short, long)]
|
||||
owner: Option<String>,
|
||||
|
||||
/// Priority, 1 (most urgent) to 5 (least). Left unset if omitted.
|
||||
#[arg(long, value_parser = priority_level)]
|
||||
priority: Option<u8>,
|
||||
},
|
||||
|
||||
/// List tickets, optionally filtered by status
|
||||
#[command(after_help = PRIORITY_LEGEND.as_str())]
|
||||
Ls {
|
||||
/// Filter by status (backlog, committed, reviewing, done)
|
||||
status: Option<String>,
|
||||
|
||||
/// Only show tickets at this priority, 1 (most urgent) to 5 (least)
|
||||
#[arg(long, value_parser = priority_level)]
|
||||
priority: Option<u8>,
|
||||
},
|
||||
|
||||
/// Show a ticket by UUID or title
|
||||
@@ -85,6 +125,7 @@ pub enum Command {
|
||||
ticket: String,
|
||||
|
||||
/// Comment body (required)
|
||||
#[arg(allow_hyphen_values = PROSE)]
|
||||
body: String,
|
||||
|
||||
/// Owner
|
||||
|
||||
+108
-14
@@ -29,7 +29,11 @@ pub fn cmd_init(start: &Path) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn cmd_ls(status_filter: &Option<String>, worklane_dir: &Path) -> Result<()> {
|
||||
pub fn cmd_ls(
|
||||
status_filter: &Option<String>,
|
||||
priority_filter: Option<u8>,
|
||||
worklane_dir: &Path,
|
||||
) -> Result<()> {
|
||||
if let Some(status) = status_filter {
|
||||
let status_path = worklane_dir.join(status);
|
||||
if !status_path.exists() {
|
||||
@@ -39,7 +43,7 @@ pub fn cmd_ls(status_filter: &Option<String>, worklane_dir: &Path) -> Result<()>
|
||||
));
|
||||
}
|
||||
|
||||
let items = collect_ticket_items(&status_path)?;
|
||||
let items = filter_by_priority(collect_ticket_items(&status_path)?, priority_filter);
|
||||
|
||||
if items.is_empty() {
|
||||
println!("No tickets in '{}' status.", status);
|
||||
@@ -57,8 +61,8 @@ pub fn cmd_ls(status_filter: &Option<String>, worklane_dir: &Path) -> Result<()>
|
||||
if !status_path.exists() {
|
||||
continue;
|
||||
}
|
||||
let entries: Vec<_> = fs::read_dir(&status_path)?.filter_map(|e| e.ok()).collect();
|
||||
let count = entries.len();
|
||||
let items = filter_by_priority(collect_ticket_items(&status_path)?, priority_filter);
|
||||
let count = items.len();
|
||||
let label = if count == 1 { "ticket" } else { "tickets" };
|
||||
println!(" [{}] {} {}", status.to_uppercase(), count, label);
|
||||
}
|
||||
@@ -73,7 +77,7 @@ pub fn cmd_ls(status_filter: &Option<String>, worklane_dir: &Path) -> Result<()>
|
||||
continue;
|
||||
}
|
||||
let items = match collect_ticket_items(&status_path) {
|
||||
Ok(items) => items,
|
||||
Ok(items) => filter_by_priority(items, priority_filter),
|
||||
Err(_) => continue,
|
||||
};
|
||||
if items.is_empty() {
|
||||
@@ -88,6 +92,17 @@ pub fn cmd_ls(status_filter: &Option<String>, worklane_dir: &Path) -> Result<()>
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
Some(level) => items
|
||||
.into_iter()
|
||||
.filter(|item| item.priority == Priority::Level(level))
|
||||
.collect(),
|
||||
None => items,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn cmd_add(
|
||||
title: &str,
|
||||
description: &[String],
|
||||
@@ -96,6 +111,7 @@ pub fn cmd_add(
|
||||
tags: &[String],
|
||||
due: &Option<String>,
|
||||
owner: &Option<String>,
|
||||
priority: Option<u8>,
|
||||
start: &Path,
|
||||
) -> Result<()> {
|
||||
let owner = match owner {
|
||||
@@ -141,6 +157,7 @@ pub fn cmd_add(
|
||||
## Metadata\n\
|
||||
\n\
|
||||
- **ID**: {}\n\
|
||||
- **Priority**: {}\n\
|
||||
- **Tags**: {}\n\
|
||||
- **Due**: {}\n\
|
||||
- **Owner**: {}\n\
|
||||
@@ -168,6 +185,10 @@ pub fn cmd_add(
|
||||
.join("\n")
|
||||
},
|
||||
id,
|
||||
match priority {
|
||||
Some(level) => level.to_string(),
|
||||
None => "_Not set_".to_string(),
|
||||
},
|
||||
if tags.is_empty() {
|
||||
"_None_".to_string()
|
||||
} else {
|
||||
@@ -273,8 +294,11 @@ pub fn cmd_show(search: &str, worklane_dir: &Path) -> Result<()> {
|
||||
let (_status, title, content) = resolve_ticket(search, worklane_dir)?;
|
||||
let ticket_uuid = parse_ticket_field(&content, "ID");
|
||||
|
||||
println!("{}", title);
|
||||
println!("{}", "─".repeat(title.len()));
|
||||
// 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, "green"));
|
||||
println!("{}", "─".repeat(title.chars().count()));
|
||||
println!("\n{}", content_trim_colored(&content));
|
||||
|
||||
if ticket_uuid != "_Not set_" {
|
||||
@@ -287,6 +311,67 @@ pub fn cmd_show(search: &str, worklane_dir: &Path) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Put `content` in `filename` and move it from `from` to `to`, without ever
|
||||
/// leaving the ticket in two status directories or with half a file in it.
|
||||
///
|
||||
/// Two atomic steps, in this order. The content is staged in a temp file and
|
||||
/// renamed over the source, so a partial write is thrown away and the original is
|
||||
/// untouched. Only then is the file renamed into the target directory.
|
||||
///
|
||||
/// The old order renamed first and wrote second, so a failure in between left the
|
||||
/// ticket sitting in its new directory still claiming the old status. Writing
|
||||
/// straight to the target and deleting the source afterwards would instead have it
|
||||
/// in both directories at once. Neither happens here. The worst case is a ticket
|
||||
/// still in its old directory carrying a Status field one move ahead, which the
|
||||
/// next `mv` corrects, since the directory is what decides the current status.
|
||||
fn move_ticket_file(
|
||||
worklane_dir: &Path,
|
||||
from: &Path,
|
||||
to: &Path,
|
||||
filename: &str,
|
||||
content: &str,
|
||||
title: &str,
|
||||
) -> Result<()> {
|
||||
let source = from.join(filename);
|
||||
let dest = to.join(filename);
|
||||
|
||||
// Staged outside the status directories on purpose: a temp file left behind by a
|
||||
// hard kill is then invisible to ticket lookup and to the listing, rather than
|
||||
// showing up as a stray untitled ticket.
|
||||
let temp = worklane_dir.join(format!(".mv-{}.tmp", filename));
|
||||
|
||||
if let Err(e) = fs::write(&temp, content) {
|
||||
let _ = fs::remove_file(&temp);
|
||||
return Err(anyhow!(
|
||||
"Could not stage the update for ticket '{}' at {}: {}",
|
||||
title,
|
||||
temp.display(),
|
||||
e
|
||||
));
|
||||
}
|
||||
|
||||
if let Err(e) = fs::rename(&temp, &source) {
|
||||
let _ = fs::remove_file(&temp);
|
||||
return Err(anyhow!(
|
||||
"Could not update the status of ticket '{}' at {}: {}",
|
||||
title,
|
||||
source.display(),
|
||||
e
|
||||
));
|
||||
}
|
||||
|
||||
// The content is correct and in one place by now, so a failure here leaves the
|
||||
// ticket where it started rather than half moved.
|
||||
fs::rename(&source, &dest).map_err(|e| {
|
||||
anyhow!(
|
||||
"Could not move ticket '{}' to {}: {}",
|
||||
title,
|
||||
dest.display(),
|
||||
e
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
pub fn cmd_mv(ticket_id: &str, target_status: &str, force: bool, start: &Path) -> Result<()> {
|
||||
let valid_statuses = ["backlog", "committed", "reviewing", "done"];
|
||||
let forward_order = ["backlog", "committed", "reviewing", "done"];
|
||||
@@ -366,15 +451,24 @@ pub fn cmd_mv(ticket_id: &str, target_status: &str, force: bool, start: &Path) -
|
||||
// Read and update the ticket content before touching the filesystem, so a ticket
|
||||
// without a Status field is never half-moved.
|
||||
let source_path = current_path.join(&found_filename);
|
||||
let content = fs::read_to_string(&source_path)?;
|
||||
let content = fs::read_to_string(&source_path).map_err(|e| {
|
||||
anyhow!(
|
||||
"Could not read ticket '{}' at {}: {}",
|
||||
title,
|
||||
source_path.display(),
|
||||
e
|
||||
)
|
||||
})?;
|
||||
let content = set_status_field(&content, target_status, &title)?;
|
||||
|
||||
// Move the file
|
||||
let dest_path = target_path.join(&found_filename);
|
||||
fs::rename(&source_path, &dest_path)?;
|
||||
|
||||
// Write back updated content
|
||||
fs::write(&dest_path, content)?;
|
||||
move_ticket_file(
|
||||
&worklane_dir,
|
||||
¤t_path,
|
||||
&target_path,
|
||||
&found_filename,
|
||||
&content,
|
||||
&title,
|
||||
)?;
|
||||
|
||||
println!(
|
||||
"Moved ticket '{}' from {} to {}",
|
||||
|
||||
+25
-2
@@ -9,7 +9,28 @@ use command::*;
|
||||
use handlers::*;
|
||||
use util::*;
|
||||
|
||||
/// Die quietly when stdout is closed early, the way every other Unix tool does.
|
||||
///
|
||||
/// Rust sets `SIGPIPE` to `SIG_IGN` at startup, which turns a closed pipe into an
|
||||
/// io error that `println!` panics on. So `worklane ls | head -3` printed a panic
|
||||
/// and a backtrace instead of three lines, which is both alarming and easy to
|
||||
/// mistake for a real fault. Restoring the default handler makes `| head` behave.
|
||||
///
|
||||
/// The cost is that a truncated pipe now kills the process with signal 13 rather
|
||||
/// than returning a code, so `pipefail` sees 141 instead of 101. That is what
|
||||
/// `head` and `sort` do, and it is recorded in the README.
|
||||
fn quiet_broken_pipe() {
|
||||
// SAFETY: setting a signal disposition to the default is always valid, and
|
||||
// this runs before any thread is spawned.
|
||||
unsafe {
|
||||
libc::signal(libc::SIGPIPE, libc::SIG_DFL);
|
||||
}
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
// Before any output, so no write can beat it to a closed pipe.
|
||||
quiet_broken_pipe();
|
||||
|
||||
let cli = Cli::parse();
|
||||
|
||||
let start = std::env::current_dir()?;
|
||||
@@ -24,6 +45,7 @@ fn main() -> Result<()> {
|
||||
tags,
|
||||
due,
|
||||
owner,
|
||||
priority,
|
||||
} => cmd_add(
|
||||
&title,
|
||||
&description,
|
||||
@@ -32,11 +54,12 @@ fn main() -> Result<()> {
|
||||
&tags,
|
||||
&due,
|
||||
&owner,
|
||||
priority,
|
||||
&start,
|
||||
),
|
||||
Command::Ls { status } => {
|
||||
Command::Ls { status, priority } => {
|
||||
let worklane_dir = find_worklane_dir(&start)?;
|
||||
cmd_ls(&status, &worklane_dir)
|
||||
cmd_ls(&status, priority, &worklane_dir)
|
||||
}
|
||||
Command::Show { id } => {
|
||||
let worklane_dir = find_worklane_dir(&start)?;
|
||||
|
||||
+715
-89
@@ -67,18 +67,28 @@ pub fn get_color(color: &str) -> &'static str {
|
||||
// Bold, per the guideline in AGENTS.md. Its absence meant colorize_line
|
||||
// asked for a colour that did not exist and got an empty prefix.
|
||||
"magenta" => "\x1b[1;35m",
|
||||
// Indexed, for the same reason grey is: this is the spelling that renders.
|
||||
"brightred" => "\x1b[38;5;9m",
|
||||
_ => "",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn color_text(text: &str, color: &str) -> String {
|
||||
if should_use_colors() {
|
||||
/// `color_text` with the decision passed in rather than asked for.
|
||||
///
|
||||
/// The seam matters for anything that aligns columns: a caller has to be able to
|
||||
/// render both ways in one process to prove the padding does not depend on it.
|
||||
pub fn paint(text: &str, color: &str, enabled: bool) -> String {
|
||||
if enabled {
|
||||
format!("{}{}{}", get_color(color), text, "\x1b[0m")
|
||||
} else {
|
||||
text.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn color_text(text: &str, color: &str) -> String {
|
||||
paint(text, color, should_use_colors())
|
||||
}
|
||||
|
||||
pub fn find_worklane_dir(start: &Path) -> Result<std::path::PathBuf> {
|
||||
let mut current = start.canonicalize()?;
|
||||
|
||||
@@ -249,30 +259,54 @@ pub fn format_comments(comments: &[(String, String, String, String)]) -> String
|
||||
}
|
||||
pub fn content_trim_colored(content: &str) -> String {
|
||||
let lines: Vec<&str> = content.trim().lines().collect();
|
||||
let colored = should_use_colors();
|
||||
let mut result = String::new();
|
||||
let mut current_section = "";
|
||||
let mut i = 0;
|
||||
|
||||
while i < lines.len() {
|
||||
let line = lines[i];
|
||||
|
||||
for line in &lines {
|
||||
// Track current section
|
||||
if line.starts_with("## ") {
|
||||
if let Some(section_name) = line.strip_prefix("## ") {
|
||||
current_section = line;
|
||||
let section_name = &line[3..];
|
||||
result.push_str(&color_text(section_name, "orange"));
|
||||
result.push_str(&paint(section_name, "orange", colored));
|
||||
result.push('\n');
|
||||
result.push_str(&"─".repeat(line.len()));
|
||||
// Measured on the name as displayed, in characters. The rule used to span
|
||||
// the raw line, so it ran three past the heading for the "## ", and byte
|
||||
// length over-drew for anything non-ASCII.
|
||||
result.push_str(&"─".repeat(section_name.chars().count()));
|
||||
result.push('\n');
|
||||
result.push('\n');
|
||||
i += 1;
|
||||
|
||||
// Metadata is rendered as a block, so it is consumed here rather than
|
||||
// falling through to the line-at-a-time cases below.
|
||||
if is_metadata_heading(line) {
|
||||
let end = lines[i..]
|
||||
.iter()
|
||||
.position(|l| l.starts_with("## "))
|
||||
.map_or(lines.len(), |offset| i + offset);
|
||||
result.push_str(&render_metadata_table(&lines[i..end], colored));
|
||||
i = end;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// First line is the title header - color it in green
|
||||
// The title belongs to cmd_show, which prints it with its rule. Printing it
|
||||
// again from the file content is what repeated it in every show output.
|
||||
if line.starts_with("# ") && current_section.is_empty() {
|
||||
let header = &line[2..]; // Remove "# "
|
||||
result.push_str(&color_text(header, "green"));
|
||||
result.push('\n');
|
||||
i += 1;
|
||||
// Along with the blank line the template puts under it, so dropping the
|
||||
// title does not leave a gap where it used to be.
|
||||
while i < lines.len() && lines[i].trim().is_empty() {
|
||||
i += 1;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
i += 1;
|
||||
|
||||
// Implementation Plan - color numbers in cyan
|
||||
if current_section == "## Implementation Plan" {
|
||||
result.push_str(&colorize_ordered(line));
|
||||
@@ -280,16 +314,9 @@ pub fn content_trim_colored(content: &str) -> String {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Metadata - color field names in RED
|
||||
if current_section == "## Metadata" {
|
||||
result.push_str(&colorize_metadata(line));
|
||||
result.push('\n');
|
||||
continue;
|
||||
}
|
||||
|
||||
// Acceptance Criteria checkboxes
|
||||
if line.starts_with("- [ ]") {
|
||||
result.push_str(&color_text("- [ ]", "grey"));
|
||||
result.push_str(&paint("- [ ]", "grey", colored));
|
||||
result.push_str(&line[5..]);
|
||||
result.push('\n');
|
||||
continue;
|
||||
@@ -344,41 +371,91 @@ pub fn colorize_ordered(line: &str) -> String {
|
||||
line.to_string()
|
||||
}
|
||||
|
||||
pub fn colorize_metadata(line: &str) -> String {
|
||||
if !line.contains("**") {
|
||||
return line.to_string();
|
||||
/// Space between the field column and the value column.
|
||||
const METADATA_GUTTER: &str = " ";
|
||||
|
||||
/// One line of the Metadata section, as the table sees it.
|
||||
enum MetadataRow<'a> {
|
||||
/// A `- **Name**: value` line, the shape the file stores fields in.
|
||||
Field { name: &'a str, value: &'a str },
|
||||
/// Anything else, carried through verbatim so a hand-written note in the
|
||||
/// section is not dropped on the way to the screen.
|
||||
Other(&'a str),
|
||||
}
|
||||
|
||||
/// Split a metadata line into a field and its value, sharing the anchoring rules
|
||||
/// `parse_ticket_field` uses: list marker optional, name matched at the start.
|
||||
fn metadata_row(line: &str) -> MetadataRow<'_> {
|
||||
let body = metadata_field_body(line);
|
||||
let Some(rest) = body.strip_prefix("**") else {
|
||||
return MetadataRow::Other(line);
|
||||
};
|
||||
let Some(close) = rest.find("**:") else {
|
||||
return MetadataRow::Other(line);
|
||||
};
|
||||
|
||||
MetadataRow::Field {
|
||||
name: &rest[..close],
|
||||
value: rest[close + "**:".len()..].trim(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The value cell for a field, styled per the colour guideline.
|
||||
fn metadata_value_cell(name: &str, value: &str, colored: bool) -> String {
|
||||
if name == "Priority" {
|
||||
// Reads as a glyph, while the file keeps storing the number.
|
||||
let (glyph, colour) = priority_mark(priority_from_value(value));
|
||||
return format!("{} {}", paint(glyph, colour, colored), value);
|
||||
}
|
||||
|
||||
let content = line;
|
||||
let open_pos = match content.find("**") {
|
||||
Some(p) => p,
|
||||
None => return content.to_string(),
|
||||
};
|
||||
if is_unknown_value(value) {
|
||||
return paint(value, "grey", colored);
|
||||
}
|
||||
|
||||
let after_open = open_pos + 2;
|
||||
let remaining = &content[after_open..];
|
||||
let close_pos = match remaining.find("**") {
|
||||
Some(p) => p,
|
||||
None => return content.to_string(),
|
||||
};
|
||||
value.to_string()
|
||||
}
|
||||
|
||||
let field_name = &content[after_open..after_open + close_pos];
|
||||
let after_field = &content[after_open + close_pos + 2..];
|
||||
/// Render the Metadata section as two aligned columns.
|
||||
///
|
||||
/// 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 {
|
||||
// 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
|
||||
.iter()
|
||||
.position(|line| !line.trim().is_empty())
|
||||
.unwrap_or(lines.len());
|
||||
let rows: Vec<MetadataRow> = lines[start..].iter().map(|line| metadata_row(line)).collect();
|
||||
|
||||
let colored_field = color_text(field_name, "red");
|
||||
let value_text = after_field.strip_prefix(": ").map(|s| s.trim()).unwrap_or(after_field);
|
||||
let after_field_colored = if is_unknown_value(value_text) {
|
||||
color_text(after_field, "grey")
|
||||
} else {
|
||||
after_field.to_string()
|
||||
};
|
||||
// Measured on the raw names, in characters, and padded before anything is
|
||||
// styled. Measuring a coloured name counts its escape sequences towards its
|
||||
// width, which is what tilts a table when colour is on and not when it is off.
|
||||
let field_width = rows
|
||||
.iter()
|
||||
.filter_map(|row| match row {
|
||||
MetadataRow::Field { name, .. } => Some(name.chars().count()),
|
||||
MetadataRow::Other(_) => None,
|
||||
})
|
||||
.max()
|
||||
.unwrap_or(0);
|
||||
|
||||
format!(
|
||||
"{}{}{}",
|
||||
&content[..open_pos],
|
||||
colored_field,
|
||||
after_field_colored
|
||||
)
|
||||
let mut result = String::new();
|
||||
for row in &rows {
|
||||
match row {
|
||||
MetadataRow::Field { name, value } => {
|
||||
result.push_str(&paint(name, "red", colored));
|
||||
result.push_str(&" ".repeat(field_width - name.chars().count()));
|
||||
result.push_str(METADATA_GUTTER);
|
||||
result.push_str(&metadata_value_cell(name, value, colored));
|
||||
}
|
||||
MetadataRow::Other(text) => result.push_str(&colorize_line(text)),
|
||||
}
|
||||
result.push('\n');
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
pub fn is_unknown_value(value: &str) -> bool {
|
||||
@@ -434,33 +511,61 @@ fn is_delimiter(chars: &[char], at: usize) -> bool {
|
||||
chars.get(at) == Some(&'*') && chars.get(at + 1) == Some(&'*')
|
||||
}
|
||||
|
||||
pub fn parse_ticket_field(content: &str, field: &str) -> String {
|
||||
let pattern = format!("**{}**:", field);
|
||||
const METADATA_HEADING: &str = "## Metadata";
|
||||
|
||||
fn is_metadata_heading(line: &str) -> bool {
|
||||
line.trim_end() == METADATA_HEADING
|
||||
}
|
||||
|
||||
/// The lines of the Metadata section, or nothing when the heading is absent.
|
||||
///
|
||||
/// Field lookup has to be anchored here. Prose above the section is free text, so a
|
||||
/// description quoting a field marker would otherwise shadow the real value below it.
|
||||
fn metadata_lines(content: &str) -> impl Iterator<Item = &str> {
|
||||
content
|
||||
.lines()
|
||||
.find(|line| line.contains(&pattern))
|
||||
.map(|line| {
|
||||
line.splitn(2, &pattern)
|
||||
.nth(1)
|
||||
.unwrap_or("_Not set_")
|
||||
.trim()
|
||||
.to_string()
|
||||
})
|
||||
.unwrap_or("_Not set_".to_string())
|
||||
.skip_while(|line| !is_metadata_heading(line))
|
||||
.skip(1)
|
||||
.take_while(|line| !line.starts_with("## "))
|
||||
}
|
||||
|
||||
/// A metadata line without its list marker, so lookup can match on a prefix rather
|
||||
/// than searching the whole line.
|
||||
fn metadata_field_body(line: &str) -> &str {
|
||||
let line = line.trim_start();
|
||||
line.strip_prefix("- ").unwrap_or(line)
|
||||
}
|
||||
|
||||
pub fn parse_ticket_field(content: &str, field: &str) -> String {
|
||||
let prefix = format!("**{}**:", field);
|
||||
metadata_lines(content)
|
||||
.find_map(|line| metadata_field_body(line).strip_prefix(&prefix))
|
||||
.map(|value| value.trim().to_string())
|
||||
.unwrap_or_else(|| "_Not set_".to_string())
|
||||
}
|
||||
|
||||
fn is_status_line(line: &str) -> bool {
|
||||
let body = metadata_field_body(line);
|
||||
// The second spelling is what earlier versions wrote, repair it on the way through.
|
||||
line.starts_with("- **Status**:") || line.starts_with("- **-Status**:")
|
||||
body.starts_with("**Status**:") || body.starts_with("**-Status**:")
|
||||
}
|
||||
|
||||
// Rewrite the Status field in the Metadata section, leaving every other line untouched.
|
||||
//
|
||||
// Scoped to the section for the same reason as parse_ticket_field: a description line
|
||||
// shaped like the Status field would otherwise be rewritten in its place, corrupting
|
||||
// the prose and leaving the real metadata stale.
|
||||
pub fn set_status_field(content: &str, target_status: &str, title: &str) -> Result<String> {
|
||||
let mut updated = String::with_capacity(content.len());
|
||||
let mut in_metadata = false;
|
||||
let mut found = false;
|
||||
|
||||
for line in content.lines() {
|
||||
if !found && is_status_line(line) {
|
||||
if line.starts_with("## ") {
|
||||
in_metadata = is_metadata_heading(line);
|
||||
}
|
||||
|
||||
if in_metadata && !found && is_status_line(line) {
|
||||
updated.push_str("- **Status**: ");
|
||||
updated.push_str(target_status);
|
||||
found = true;
|
||||
@@ -496,36 +601,139 @@ pub fn status_dirs() -> Vec<&'static str> {
|
||||
vec!["backlog", "committed", "reviewing", "done"]
|
||||
}
|
||||
|
||||
pub type TicketItem = (String, String, String, String, String);
|
||||
/// Lowest and highest level a ticket can carry. 1 is the most urgent, which is
|
||||
/// what the `p1` to `p3` tags this replaced already meant.
|
||||
pub const PRIORITY_RANGE: std::ops::RangeInclusive<u8> = 1..=5;
|
||||
|
||||
/// A ticket's priority as it comes off disk.
|
||||
///
|
||||
/// Three states, not two: a value outside the range has to stay distinguishable
|
||||
/// from no value at all, or a typo silently reads as "no priority".
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Priority {
|
||||
Level(u8),
|
||||
Unset,
|
||||
Invalid,
|
||||
}
|
||||
|
||||
impl Priority {
|
||||
/// Sort weight. Levels first in order, then anything wrong, then anything
|
||||
/// absent, so a typo surfaces above the long tail of unset tickets.
|
||||
pub fn rank(&self) -> u8 {
|
||||
match self {
|
||||
Priority::Level(level) => *level,
|
||||
Priority::Invalid => u8::MAX - 1,
|
||||
Priority::Unset => u8::MAX,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A priority from the value alone, for callers that already have it in hand.
|
||||
pub fn priority_from_value(raw: &str) -> Priority {
|
||||
let raw = raw.trim();
|
||||
|
||||
if is_unknown_value(raw) {
|
||||
return Priority::Unset;
|
||||
}
|
||||
|
||||
match raw.parse::<u8>() {
|
||||
Ok(level) if PRIORITY_RANGE.contains(&level) => Priority::Level(level),
|
||||
_ => Priority::Invalid,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse_priority(content: &str) -> Priority {
|
||||
priority_from_value(&parse_ticket_field(content, "Priority"))
|
||||
}
|
||||
|
||||
pub struct TicketItem {
|
||||
pub title: String,
|
||||
pub owner: String,
|
||||
pub due: String,
|
||||
pub id: String,
|
||||
pub created: String,
|
||||
pub priority: Priority,
|
||||
}
|
||||
|
||||
/// Grey for a value that is not set, per the colour guideline.
|
||||
///
|
||||
/// `show` already did this through `colorize_metadata`, so the listing was the
|
||||
/// one place that ignored the rule.
|
||||
fn dim_if_unset(value: &str) -> String {
|
||||
/// `show` already did this in its metadata rendering, so the listing was the one
|
||||
/// place that ignored the rule.
|
||||
fn dim_if_unset(value: &str, colored: bool) -> String {
|
||||
if is_unknown_value(value) {
|
||||
color_text(value, "grey")
|
||||
paint(value, "grey", colored)
|
||||
} else {
|
||||
value.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn display_ticket_items(items: &Vec<TicketItem>) {
|
||||
for (title, owner, due, uuid, ts) in items {
|
||||
let uuid_colored = color_text(uuid, "red");
|
||||
let owner = dim_if_unset(owner);
|
||||
let due = dim_if_unset(due);
|
||||
/// The mark and colour for a level, from one place.
|
||||
///
|
||||
/// A two-segment meter that empties as the level rises, so the level is legible
|
||||
/// from shape alone: colour is off whenever output is piped, and NO_COLOR turns it
|
||||
/// off in a terminal too, so colour accentuates and never encodes.
|
||||
///
|
||||
/// Only three glyphs, the ones frig uses for its status indicators and which are
|
||||
/// therefore known to render here. The quadrant circles this first used are in a
|
||||
/// quarter as many fonts, so terminals substituted them from a fallback font that
|
||||
/// draws them oversized. Two cells of a three-level ramp gives five steps of ink,
|
||||
/// 2, 1.5, 1, 0.5, 0, without leaving that safe set.
|
||||
///
|
||||
/// The number counts up while the mark empties out, because 1 is the most urgent.
|
||||
/// That is the convention every tracker uses and what the p1 tags this replaced
|
||||
/// already meant.
|
||||
pub fn priority_mark(priority: Priority) -> (&'static str, &'static str) {
|
||||
match priority {
|
||||
Priority::Level(1) => ("\u{25cf}\u{25cf}", "brightred"),
|
||||
Priority::Level(2) => ("\u{25cf}\u{25d0}", "red"),
|
||||
Priority::Level(3) => ("\u{25cf}\u{25cb}", "orange"),
|
||||
Priority::Level(4) => ("\u{25d0}\u{25cb}", "cyan"),
|
||||
Priority::Level(5) => ("\u{25cb}\u{25cb}", "grey"),
|
||||
// Unreachable while Level is only built by parse_priority, which checks
|
||||
// the range, but a level added later should not silently render blank.
|
||||
Priority::Level(_) | Priority::Invalid => ("??", "brightred"),
|
||||
Priority::Unset => ("\u{b7}\u{b7}", "grey"),
|
||||
}
|
||||
}
|
||||
|
||||
if ts.is_empty() {
|
||||
println!(
|
||||
" ({}) {} | Owner: {} | Due: {}",
|
||||
uuid_colored, title, owner, due
|
||||
);
|
||||
} else {
|
||||
let ts_colored = color_text(ts, "cyan");
|
||||
/// The legend, for help text. Nothing else in a listing explains the glyphs.
|
||||
pub fn priority_legend() -> String {
|
||||
let levels = PRIORITY_RANGE
|
||||
.map(|level| {
|
||||
let (glyph, _) = priority_mark(Priority::Level(level));
|
||||
format!("{} {}", glyph, level)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
|
||||
let (unset, _) = priority_mark(Priority::Unset);
|
||||
format!("Priority: {levels} {unset} unset 1 is most urgent")
|
||||
}
|
||||
|
||||
fn show_priority(priority: Priority, colored: bool) -> String {
|
||||
let (glyph, colour) = priority_mark(priority);
|
||||
paint(glyph, colour, colored)
|
||||
}
|
||||
|
||||
pub fn display_ticket_items(items: &[TicketItem]) {
|
||||
let colored = should_use_colors();
|
||||
|
||||
for item in items {
|
||||
let id = paint(&item.id, "red", colored);
|
||||
let owner = dim_if_unset(&item.owner, colored);
|
||||
let due = dim_if_unset(&item.due, colored);
|
||||
let priority = show_priority(item.priority, colored);
|
||||
|
||||
if item.created.is_empty() {
|
||||
println!(
|
||||
" {} ({}) {} | Owner: {} | Due: {}",
|
||||
ts_colored, uuid_colored, title, owner, due
|
||||
priority, id, item.title, owner, due
|
||||
);
|
||||
} else {
|
||||
let created = paint(&item.created, "cyan", colored);
|
||||
println!(
|
||||
" {} {} ({}) {} | Owner: {} | Due: {}",
|
||||
priority, created, id, item.title, owner, due
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -547,19 +755,25 @@ pub fn collect_ticket_items(status_path: impl AsRef<Path>) -> Result<Vec<TicketI
|
||||
let due = parse_ticket_field(&content, "Due");
|
||||
let filename = e.path().file_stem()?.to_string_lossy().to_string();
|
||||
let created_at = parse_ticket_field(&content, "Created At");
|
||||
let short_date = format_created_at(&created_at);
|
||||
|
||||
Some((
|
||||
Some(TicketItem {
|
||||
title,
|
||||
owner,
|
||||
due,
|
||||
short_id(&filename).to_string(),
|
||||
short_date,
|
||||
))
|
||||
id: short_id(&filename).to_string(),
|
||||
created: format_created_at(&created_at),
|
||||
priority: parse_priority(&content),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
items.sort_by(|a, b| a.0.to_lowercase().cmp(&b.0.to_lowercase()));
|
||||
// Priority first, title as the tiebreak, which is what the sort used to be.
|
||||
items.sort_by(|a, b| {
|
||||
a.priority
|
||||
.rank()
|
||||
.cmp(&b.priority.rank())
|
||||
.then_with(|| a.title.to_lowercase().cmp(&b.title.to_lowercase()))
|
||||
});
|
||||
Ok(items)
|
||||
}
|
||||
|
||||
@@ -598,21 +812,433 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn unset_values_are_dimmed_and_set_ones_are_not() {
|
||||
// Colour is off in a test process, so this asserts the decision, not the escape
|
||||
// Both paths, now that the colour decision is a parameter: with colour off the
|
||||
// text has to come back untouched, with it on only the unset values get wrapped
|
||||
for unset in ["_Not set_", "_None_"] {
|
||||
assert!(is_unknown_value(unset), "{unset} should count as unset");
|
||||
assert_eq!(dim_if_unset(unset), unset);
|
||||
assert_eq!(dim_if_unset(unset, false), unset);
|
||||
assert_eq!(dim_if_unset(unset, true), paint(unset, "grey", true));
|
||||
}
|
||||
|
||||
for set in ["alice", "2026-12-31", "bug,frontend"] {
|
||||
assert!(!is_unknown_value(set));
|
||||
assert_eq!(dim_if_unset(set), set);
|
||||
assert_eq!(dim_if_unset(set, false), set);
|
||||
assert_eq!(dim_if_unset(set, true), set);
|
||||
}
|
||||
}
|
||||
|
||||
fn ticket_with_priority(raw: &str) -> String {
|
||||
format!("# T\n\n## Metadata\n\n- **Priority**: {}\n", raw)
|
||||
}
|
||||
|
||||
/// A ticket whose prose quotes the field markers it also carries as metadata,
|
||||
/// as a list so the quoted lines start with the marker. This repo files tickets
|
||||
/// about the metadata format, so it is the normal case here rather than a corner.
|
||||
fn ticket_shadowing_its_own_metadata() -> String {
|
||||
"# Shadow\n\
|
||||
\n\
|
||||
## Description\n\
|
||||
The current format is:\n\
|
||||
- **Owner**: nobody\n\
|
||||
- **Status**: backlog\n\
|
||||
\n\
|
||||
## Metadata\n\
|
||||
\n\
|
||||
- **ID**: real-id\n\
|
||||
- **Owner**: alice\n\
|
||||
- **Status**: backlog\n"
|
||||
.to_string()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prose_quoting_a_field_marker_does_not_shadow_the_metadata() {
|
||||
let content = ticket_shadowing_its_own_metadata();
|
||||
assert_eq!(parse_ticket_field(&content, "Owner"), "alice");
|
||||
assert_eq!(parse_ticket_field(&content, "ID"), "real-id");
|
||||
assert_eq!(parse_ticket_field(&content, "Status"), "backlog");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_field_only_mentioned_in_prose_reads_as_unset() {
|
||||
let content = "# T\n\n## Description\n- **Due**: 2026-12-31\n\n## Metadata\n\n- **ID**: x\n";
|
||||
assert_eq!(parse_ticket_field(content, "Due"), "_Not set_");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_field_lookup_needs_the_metadata_heading() {
|
||||
// No section, no fields: there is nothing to anchor to.
|
||||
assert_eq!(
|
||||
parse_ticket_field("# T\n\n- **Owner**: alice\n", "Owner"),
|
||||
"_Not set_"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_field_lookup_stops_at_the_next_section() {
|
||||
let content = "# T\n\n## Metadata\n\n- **ID**: x\n\n## Notes\n\n- **Owner**: alice\n";
|
||||
assert_eq!(parse_ticket_field(content, "Owner"), "_Not set_");
|
||||
assert_eq!(parse_ticket_field(content, "ID"), "x");
|
||||
}
|
||||
|
||||
/// Matching on a prefix, not a substring: a field name inside another field's
|
||||
/// value is not that field.
|
||||
#[test]
|
||||
fn a_field_marker_inside_another_value_is_not_matched() {
|
||||
let content = "# T\n\n## Metadata\n\n- **Tags**: mentions **Owner**: bob\n";
|
||||
assert_eq!(parse_ticket_field(content, "Owner"), "_Not set_");
|
||||
assert_eq!(parse_ticket_field(content, "Tags"), "mentions **Owner**: bob");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn setting_the_status_leaves_prose_that_looks_like_metadata_alone() {
|
||||
let content = ticket_shadowing_its_own_metadata();
|
||||
let updated = set_status_field(&content, "committed", "Shadow").unwrap();
|
||||
|
||||
assert!(
|
||||
updated.contains("## Description\nThe current format is:\n- **Owner**: nobody\n- **Status**: backlog\n"),
|
||||
"the description was rewritten:\n{updated}"
|
||||
);
|
||||
assert_eq!(parse_ticket_field(&updated, "Status"), "committed");
|
||||
assert_eq!(updated.matches("**Status**: committed").count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn setting_the_status_needs_the_field_in_the_metadata_section() {
|
||||
// A Status line above the section is prose, so this is a ticket without the field.
|
||||
let content = "# T\n\n## Description\n- **Status**: backlog\n\n## Metadata\n\n- **ID**: x\n";
|
||||
assert!(set_status_field(content, "committed", "T").is_err());
|
||||
}
|
||||
|
||||
/// SGR escapes removed, so a rendered cell can be measured as it lands on screen.
|
||||
/// Test-only: production never measures a styled string, which is the point.
|
||||
fn unstyled(text: &str) -> String {
|
||||
let mut out = String::new();
|
||||
let mut chars = text.chars();
|
||||
|
||||
while let Some(c) = chars.next() {
|
||||
if c != '\x1b' {
|
||||
out.push(c);
|
||||
continue;
|
||||
}
|
||||
// Drop everything up to and including the 'm' that closes the sequence.
|
||||
for c in chars.by_ref() {
|
||||
if c == 'm' {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_metadata_table_aligns_values_in_one_column() {
|
||||
// The leading blank line is what the ticket template writes under the heading.
|
||||
let rendered = render_metadata_table(
|
||||
&[
|
||||
"",
|
||||
"- **ID**: abc",
|
||||
"- **Created At**: 2026-08-20",
|
||||
"- **Owner**: alice",
|
||||
],
|
||||
false,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
rendered,
|
||||
"ID abc\n\
|
||||
Created At 2026-08-20\n\
|
||||
Owner alice\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_field_name_widens_the_column_for_every_row() {
|
||||
let rendered =
|
||||
render_metadata_table(&["- **ID**: abc", "- **Handled By Team**: ops"], false);
|
||||
|
||||
assert_eq!(
|
||||
rendered,
|
||||
"ID abc\n\
|
||||
Handled By Team ops\n"
|
||||
);
|
||||
}
|
||||
|
||||
/// The trap the ticket names: field names are coloured, unset values are greyed
|
||||
/// and Priority carries a mark, so measuring the styled text would tilt the table
|
||||
/// with colour on and not with it off.
|
||||
#[test]
|
||||
fn colour_does_not_change_the_alignment() {
|
||||
let lines = [
|
||||
"- **ID**: abc",
|
||||
"- **Priority**: 2",
|
||||
"- **Due**: _Not set_",
|
||||
"- **Owner**: Ansho Rei",
|
||||
];
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
#[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);
|
||||
|
||||
assert_eq!(
|
||||
rendered,
|
||||
"Créé à oui\n\
|
||||
ID abc\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_non_ascii_value_leaves_the_column_alone() {
|
||||
let lines = ["- **Owner**: 日本語", "- **ID**: abc"];
|
||||
let rendered = render_metadata_table(&lines, false);
|
||||
|
||||
assert_eq!(
|
||||
rendered,
|
||||
"Owner 日本語\n\
|
||||
ID abc\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_field_the_tool_does_not_know_still_gets_a_row() {
|
||||
let rendered = render_metadata_table(&["- **ID**: abc", "- **Sprint**: 14"], false);
|
||||
|
||||
assert!(rendered.contains("Sprint 14"), "{rendered:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_that_is_not_a_field_is_carried_through() {
|
||||
let rendered =
|
||||
render_metadata_table(&["- **ID**: abc", "a hand written note"], false);
|
||||
|
||||
assert_eq!(
|
||||
rendered,
|
||||
"ID abc\n\
|
||||
a hand written note\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_priority_cell_carries_the_mark_and_the_stored_number() {
|
||||
let rendered = render_metadata_table(&["- **Priority**: 2"], false);
|
||||
let (glyph, _) = priority_mark(Priority::Level(2));
|
||||
|
||||
assert_eq!(rendered, format!("Priority {glyph} 2\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unset_priority_reads_as_unset_in_the_table() {
|
||||
let rendered = render_metadata_table(&["- **Priority**: _Not set_"], false);
|
||||
let (glyph, _) = priority_mark(Priority::Unset);
|
||||
|
||||
assert_eq!(rendered, format!("Priority {glyph} _Not set_\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_section_rule_matches_the_width_of_its_name() {
|
||||
let rendered = content_trim_colored("# T\n\n## Description\nbody\n");
|
||||
|
||||
// Eleven characters, not fourteen: the rule used to span "## Description"
|
||||
assert!(
|
||||
rendered.starts_with("Description\n───────────\n"),
|
||||
"{rendered:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_non_ascii_section_name_is_not_over_drawn() {
|
||||
let rendered = content_trim_colored("# T\n\n## Résumé\nbody\n");
|
||||
|
||||
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");
|
||||
|
||||
assert!(!rendered.contains("Only Once"), "{rendered:?}");
|
||||
// And no gap where it was
|
||||
assert!(rendered.starts_with("Description"), "{rendered:?}");
|
||||
}
|
||||
|
||||
#[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);
|
||||
|
||||
assert_eq!(rendered, "Metadata\n────────\n\nID abc\nOwner alice\n");
|
||||
}
|
||||
|
||||
#[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);
|
||||
|
||||
assert!(rendered.contains("ID abc"), "{rendered:?}");
|
||||
assert!(rendered.contains("Notes\n─────\n"), "{rendered:?}");
|
||||
assert!(rendered.ends_with("after\n"), "{rendered:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_level_in_range_parses() {
|
||||
for level in 1..=5u8 {
|
||||
let content = ticket_with_priority(&level.to_string());
|
||||
assert_eq!(parse_priority(&content), Priority::Level(level));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_or_unset_level_is_unset() {
|
||||
assert_eq!(parse_priority("# T\n\n## Metadata\n"), Priority::Unset);
|
||||
assert_eq!(parse_priority(&ticket_with_priority("_Not set_")), Priority::Unset);
|
||||
assert_eq!(parse_priority(&ticket_with_priority("_None_")), Priority::Unset);
|
||||
}
|
||||
|
||||
/// Distinct from unset on purpose: a typo must not read as "no priority".
|
||||
#[test]
|
||||
fn an_out_of_range_or_unparseable_level_is_invalid() {
|
||||
for raw in ["0", "6", "42", "high", "-1", "1.5", "999999999999"] {
|
||||
assert_eq!(
|
||||
parse_priority(&ticket_with_priority(raw)),
|
||||
Priority::Invalid,
|
||||
"for {raw:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn levels_sort_ahead_of_invalid_which_sorts_ahead_of_unset() {
|
||||
let mut ranks = [Priority::Unset, Priority::Level(5), Priority::Invalid, Priority::Level(1)]
|
||||
.map(|p| p.rank());
|
||||
ranks.sort();
|
||||
assert_eq!(
|
||||
ranks,
|
||||
[
|
||||
Priority::Level(1).rank(),
|
||||
Priority::Level(5).rank(),
|
||||
Priority::Invalid.rank(),
|
||||
Priority::Unset.rank()
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_level_gets_its_own_glyph_and_colour() {
|
||||
let marks: Vec<_> = PRIORITY_RANGE
|
||||
.map(|level| priority_mark(Priority::Level(level)))
|
||||
.collect();
|
||||
|
||||
let glyphs: std::collections::HashSet<_> = marks.iter().map(|(g, _)| *g).collect();
|
||||
assert_eq!(glyphs.len(), marks.len(), "two levels share a glyph");
|
||||
|
||||
let colours: std::collections::HashSet<_> = marks.iter().map(|(_, c)| *c).collect();
|
||||
assert_eq!(colours.len(), marks.len(), "two levels share a colour");
|
||||
}
|
||||
|
||||
/// The glyph has to carry the level with colour off, which is how every pipe
|
||||
/// and every opencode tool reads it.
|
||||
#[test]
|
||||
fn the_glyph_alone_distinguishes_every_state() {
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
for state in PRIORITY_RANGE.map(Priority::Level).chain([Priority::Unset, Priority::Invalid]) {
|
||||
let (glyph, _) = priority_mark(state);
|
||||
assert!(seen.insert(glyph), "{glyph} is used for more than one state");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_fullest_mark_is_the_most_urgent() {
|
||||
assert_eq!(priority_mark(Priority::Level(1)).0, "\u{25cf}\u{25cf}");
|
||||
assert_eq!(priority_mark(Priority::Level(5)).0, "\u{25cb}\u{25cb}");
|
||||
}
|
||||
|
||||
/// Every mark is the same width, or the column stops lining up.
|
||||
#[test]
|
||||
fn every_mark_is_the_same_width() {
|
||||
let widths: std::collections::HashSet<usize> = PRIORITY_RANGE
|
||||
.map(Priority::Level)
|
||||
.chain([Priority::Unset, Priority::Invalid])
|
||||
.map(|p| priority_mark(p).0.chars().count())
|
||||
.collect();
|
||||
assert_eq!(widths, std::collections::HashSet::from([2]));
|
||||
}
|
||||
|
||||
/// The marks are built only from what frig already renders in this terminal:
|
||||
/// the quadrant circles are in a quarter as many fonts and got substituted
|
||||
/// from a fallback font that drew them oversized.
|
||||
#[test]
|
||||
fn marks_use_only_the_glyphs_known_to_render() {
|
||||
let allowed = ['\u{25cf}', '\u{25d0}', '\u{25cb}', '\u{b7}', '?'];
|
||||
for state in PRIORITY_RANGE
|
||||
.map(Priority::Level)
|
||||
.chain([Priority::Unset, Priority::Invalid])
|
||||
{
|
||||
for ch in priority_mark(state).0.chars() {
|
||||
assert!(allowed.contains(&ch), "{ch:?} is outside the safe set");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_meter_empties_as_the_level_rises() {
|
||||
let ink = |p: Priority| -> f32 {
|
||||
priority_mark(p)
|
||||
.0
|
||||
.chars()
|
||||
.map(|c| match c {
|
||||
'\u{25cf}' => 1.0,
|
||||
'\u{25d0}' => 0.5,
|
||||
_ => 0.0,
|
||||
})
|
||||
.sum()
|
||||
};
|
||||
let mut previous = f32::MAX;
|
||||
for level in PRIORITY_RANGE {
|
||||
let current = ink(Priority::Level(level));
|
||||
assert!(current < previous, "level {level} does not empty further");
|
||||
previous = current;
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_invalid_level_is_marked_wrong_not_unset() {
|
||||
assert_eq!(priority_mark(Priority::Invalid).0, "??");
|
||||
assert_ne!(
|
||||
priority_mark(Priority::Invalid),
|
||||
priority_mark(Priority::Unset)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_legend_covers_every_level_and_says_which_way_it_runs() {
|
||||
let legend = priority_legend();
|
||||
for level in PRIORITY_RANGE {
|
||||
let (glyph, _) = priority_mark(Priority::Level(level));
|
||||
assert!(legend.contains(glyph), "{glyph} missing from the legend");
|
||||
assert!(legend.contains(&level.to_string()));
|
||||
}
|
||||
assert!(legend.contains("most urgent"), "direction not spelled out");
|
||||
}
|
||||
|
||||
/// Green means title; a priority must not borrow it.
|
||||
#[test]
|
||||
fn the_ramp_avoids_green() {
|
||||
for level in PRIORITY_RANGE {
|
||||
assert_ne!(priority_mark(Priority::Level(level)).1, "green");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_colour_the_code_asks_for_exists() {
|
||||
for colour in ["red", "cyan", "orange", "green", "grey", "magenta"] {
|
||||
for colour in ["red", "cyan", "orange", "green", "grey", "magenta", "brightred"] {
|
||||
assert!(!get_color(colour).is_empty(), "{colour} is not defined");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
use assert_fs::TempDir;
|
||||
use assert_fs::fixture::{PathChild, PathCreateDir};
|
||||
use std::fs;
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
const BIN_NAME: &str = env!("CARGO_BIN_EXE_worklane");
|
||||
|
||||
/// What a truncated pipe costs: the process dies by signal rather than returning a
|
||||
/// code, so a shell reports 128 + 13. Asserted here so the README and the code stay
|
||||
/// honest about what `pipefail` sees.
|
||||
const SIGPIPE: i32 = 13;
|
||||
|
||||
/// A pipe holds 64 KiB on Linux before a write blocks. Below that the whole listing
|
||||
/// lands in the buffer, the writer never notices the reader is gone, and a test
|
||||
/// proves nothing. Every ticket here is one `ls` row of roughly a hundred bytes.
|
||||
const TICKETS: usize = 1200;
|
||||
|
||||
fn setup_crowded_board(temp: &TempDir) -> std::path::PathBuf {
|
||||
let worklane = temp.child(".worklane");
|
||||
worklane.create_dir_all().unwrap();
|
||||
|
||||
for dir in ["backlog", "committed", "reviewing", "done"] {
|
||||
worklane.child(dir).create_dir_all().unwrap();
|
||||
}
|
||||
|
||||
let backlog = worklane.path().join("backlog");
|
||||
for i in 0..TICKETS {
|
||||
let id = format!("{:08x}-0000-4000-8000-000000000000", i);
|
||||
let title = format!("A ticket with a title long enough to fill a row {}", i);
|
||||
fs::write(
|
||||
backlog.join(format!("{}_ticket-{}.md", id, i)),
|
||||
format!(
|
||||
"# {}\n\n## Metadata\n\n\
|
||||
- **ID**: {}\n\
|
||||
- **Owner**: someone with a name\n\
|
||||
- **Status**: backlog\n",
|
||||
title, id
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
temp.path().to_path_buf()
|
||||
}
|
||||
|
||||
fn panic_text(stderr: &str) -> bool {
|
||||
stderr.contains("panicked")
|
||||
|| stderr.contains("failed printing to stdout")
|
||||
|| stderr.contains("Broken pipe")
|
||||
}
|
||||
|
||||
/// The reader closed before the writer finished: dropping the read end here is the
|
||||
/// same thing `head` does when it has seen enough, without the timing luck.
|
||||
fn run_with_stdout_dropped(dir: &std::path::Path, args: &[&str]) -> std::process::Output {
|
||||
let mut child = Command::new(BIN_NAME)
|
||||
.args(args)
|
||||
.current_dir(dir)
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
|
||||
drop(child.stdout.take().unwrap());
|
||||
child.wait_with_output().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ls_says_nothing_when_the_reader_goes_away() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let dir = setup_crowded_board(&temp);
|
||||
|
||||
let output = run_with_stdout_dropped(&dir, &["ls", "backlog"]);
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
|
||||
assert!(!panic_text(&stderr), "stderr was {stderr:?}");
|
||||
assert_ne!(output.status.code(), Some(101), "panicked instead of dying");
|
||||
assert_eq!(
|
||||
output.status.signal(),
|
||||
Some(SIGPIPE),
|
||||
"expected death by SIGPIPE, got {:?}",
|
||||
output.status
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn show_says_nothing_when_the_reader_goes_away() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let dir = setup_crowded_board(&temp);
|
||||
|
||||
// A ticket carrying more comments than a pipe will hold, since the comment list
|
||||
// is the longest thing show prints and the last thing it reaches.
|
||||
let comments = temp
|
||||
.path()
|
||||
.join(".worklane")
|
||||
.join("comments")
|
||||
.join("00000000-0000-4000-8000-000000000000");
|
||||
fs::create_dir_all(&comments).unwrap();
|
||||
for i in 0..800 {
|
||||
fs::write(
|
||||
comments.join(format!("2026082{}_120000_{:06}.md", i % 10, i)),
|
||||
format!(
|
||||
"**Comment**\nA comment body long enough to be worth buffering, number {}.\n\n\
|
||||
**Author**: someone\n**Time**: 2026-08-20 12:00:00\n",
|
||||
i
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
let output = run_with_stdout_dropped(&dir, &["show", "00000000-0000-4000"]);
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
|
||||
assert!(!panic_text(&stderr), "stderr was {stderr:?}");
|
||||
assert_ne!(output.status.code(), Some(101), "panicked instead of dying");
|
||||
assert_eq!(
|
||||
output.status.signal(),
|
||||
Some(SIGPIPE),
|
||||
"expected death by SIGPIPE, got {:?}",
|
||||
output.status
|
||||
);
|
||||
}
|
||||
|
||||
/// The real invocation, through a shell into `head`, which is how this was found.
|
||||
/// Whether the writer gets far enough to notice is up to the scheduler, so this
|
||||
/// asserts only what must hold either way: `head` gets its lines and nothing
|
||||
/// alarming reaches stderr.
|
||||
#[test]
|
||||
fn a_shell_pipeline_into_head_prints_lines_and_not_a_panic() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let dir = setup_crowded_board(&temp);
|
||||
|
||||
let output = Command::new("sh")
|
||||
.arg("-c")
|
||||
.arg(format!("{} ls backlog | head -3", BIN_NAME))
|
||||
.current_dir(&dir)
|
||||
.output()
|
||||
.unwrap();
|
||||
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
|
||||
assert_eq!(stdout.lines().count(), 3, "stdout was {stdout:?}");
|
||||
assert!(!panic_text(&stderr), "stderr was {stderr:?}");
|
||||
}
|
||||
|
||||
/// The reset must not touch anything else: a real failure still returns its code.
|
||||
#[test]
|
||||
fn real_exit_codes_are_unchanged() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let dir = setup_crowded_board(&temp);
|
||||
|
||||
let ok = Command::new(BIN_NAME)
|
||||
.args(["ls", "backlog"])
|
||||
.current_dir(&dir)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert_eq!(ok.status.code(), Some(0));
|
||||
|
||||
let missing = Command::new(BIN_NAME)
|
||||
.args(["show", "no-such-ticket-anywhere"])
|
||||
.current_dir(&dir)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert_eq!(missing.status.code(), Some(1));
|
||||
|
||||
let misuse = Command::new(BIN_NAME)
|
||||
.arg("--bogus")
|
||||
.current_dir(&dir)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert_eq!(misuse.status.code(), Some(2));
|
||||
}
|
||||
@@ -199,3 +199,184 @@ fn add_file_has_uuid_prefix() {
|
||||
assert_eq!(parts[0].len(), 36);
|
||||
assert_eq!(parts[0].chars().filter(|c| c.is_ascii_hexdigit()).count(), 32);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_writes_the_priority_field() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
setup_worklane(&temp);
|
||||
|
||||
Command::cargo_bin(BIN_NAME)
|
||||
.unwrap()
|
||||
.current_dir(&temp.path())
|
||||
.args(["add", "--title", "Urgent thing", "--priority", "1"])
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
let files: Vec<_> = fs::read_dir(temp.child(".worklane").join("backlog"))
|
||||
.unwrap()
|
||||
.filter_map(|e| e.ok())
|
||||
.collect();
|
||||
let content = fs::read_to_string(files[0].path()).unwrap();
|
||||
assert!(content.contains("- **Priority**: 1"), "was {content:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_leaves_priority_unset_when_omitted() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
setup_worklane(&temp);
|
||||
|
||||
Command::cargo_bin(BIN_NAME)
|
||||
.unwrap()
|
||||
.current_dir(&temp.path())
|
||||
.args(["add", "--title", "Whenever"])
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
let files: Vec<_> = fs::read_dir(temp.child(".worklane").join("backlog"))
|
||||
.unwrap()
|
||||
.filter_map(|e| e.ok())
|
||||
.collect();
|
||||
let content = fs::read_to_string(files[0].path()).unwrap();
|
||||
assert!(content.contains("- **Priority**: _Not set_"), "was {content:?}");
|
||||
}
|
||||
|
||||
/// Rejected at parse time, so no ticket is written at all.
|
||||
#[test]
|
||||
fn add_rejects_a_level_outside_the_range() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = setup_worklane(&temp);
|
||||
|
||||
// The `=` form, so a negative value reaches the validator instead of being
|
||||
// read as a flag.
|
||||
for bad in ["0", "6", "high", "-1"] {
|
||||
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
|
||||
cmd.current_dir(&temp.path())
|
||||
.args(["add", "--title", "Bad level", &format!("--priority={bad}")])
|
||||
.assert()
|
||||
.failure();
|
||||
|
||||
let stderr = String::from_utf8(cmd.assert().get_output().stderr.clone()).unwrap();
|
||||
assert!(stderr.contains("priority must be"), "for {bad}: {stderr}");
|
||||
}
|
||||
|
||||
let count = fs::read_dir(worklane.join("backlog")).unwrap().count();
|
||||
assert_eq!(count, 0, "a ticket was written despite a bad level");
|
||||
}
|
||||
|
||||
/// Ticket text quotes flag names constantly, and the space form is what both a
|
||||
/// person and the opencode wrapper produce. Every one of these used to be refused
|
||||
/// with "unexpected argument found", writing no ticket at all.
|
||||
#[test]
|
||||
fn add_accepts_prose_values_that_begin_with_a_hyphen() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = setup_worklane(&temp);
|
||||
|
||||
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
|
||||
cmd.current_dir(&temp.path())
|
||||
.args(["add", "--title", "-t is a flag name"])
|
||||
.args(["--description", "-x does nothing"])
|
||||
.args(["--acceptance", "--print should be supported"])
|
||||
.args(["--plan", "-f skips the check"])
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
let content = only_ticket(&worklane);
|
||||
|
||||
// Stored verbatim, hyphens and all
|
||||
assert!(content.contains("# -t is a flag name"), "was {content:?}");
|
||||
assert!(content.contains("-x does nothing"), "was {content:?}");
|
||||
assert!(
|
||||
content.contains("- [ ] --print should be supported"),
|
||||
"was {content:?}"
|
||||
);
|
||||
assert!(content.contains("1. -f skips the check"), "was {content:?}");
|
||||
}
|
||||
|
||||
/// The docs and the habit both use it, and it reaches the parser as one token, so
|
||||
/// it has to keep working alongside the space form.
|
||||
#[test]
|
||||
fn add_still_accepts_the_equals_form() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = setup_worklane(&temp);
|
||||
|
||||
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
|
||||
cmd.current_dir(&temp.path())
|
||||
.args(["add", "--title=-x equals form"])
|
||||
.args(["--acceptance=--print via equals"])
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
let content = only_ticket(&worklane);
|
||||
assert!(content.contains("# -x equals form"), "was {content:?}");
|
||||
assert!(
|
||||
content.contains("- [ ] --print via equals"),
|
||||
"was {content:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// Never silently dropped: a value that is nothing but hyphens is content.
|
||||
#[test]
|
||||
fn add_stores_a_title_that_is_only_hyphens() {
|
||||
for bare in ["-", "--", "---"] {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = setup_worklane(&temp);
|
||||
|
||||
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
|
||||
cmd.current_dir(&temp.path())
|
||||
.args(["add", "--title", bare])
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
let content = only_ticket(&worklane);
|
||||
assert!(
|
||||
content.starts_with(&format!("# {}\n", bare)),
|
||||
"for {bare:?}: {content:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The other half of the trade. These arguments were deliberately left alone, so a
|
||||
/// mistyped flag there is still a usage error rather than stored text.
|
||||
#[test]
|
||||
fn add_still_rejects_a_mistyped_flag_on_a_non_prose_argument() {
|
||||
for flag in ["--due", "--priority", "--tags", "--owner"] {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = setup_worklane(&temp);
|
||||
|
||||
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
|
||||
cmd.current_dir(&temp.path())
|
||||
.args(["add", "--title", "Mistyped", flag, "--bogus"])
|
||||
.assert()
|
||||
.failure();
|
||||
|
||||
let count = fs::read_dir(worklane.join("backlog")).unwrap().count();
|
||||
assert_eq!(count, 0, "{flag} wrote a ticket anyway");
|
||||
}
|
||||
}
|
||||
|
||||
/// `add` has no positionals, so a bare `--` ends the options and whatever follows
|
||||
/// has nowhere to go. Recorded because clap's separator and a hyphen-leading value
|
||||
/// are easy to confuse.
|
||||
#[test]
|
||||
fn add_rejects_arguments_after_a_bare_separator() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = setup_worklane(&temp);
|
||||
|
||||
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
|
||||
cmd.current_dir(&temp.path())
|
||||
.args(["add", "--title", "Sep", "--", "--title", "second"])
|
||||
.assert()
|
||||
.failure();
|
||||
|
||||
let count = fs::read_dir(worklane.join("backlog")).unwrap().count();
|
||||
assert_eq!(count, 0);
|
||||
}
|
||||
|
||||
fn only_ticket(worklane: &PathBuf) -> String {
|
||||
let files: Vec<_> = fs::read_dir(worklane.join("backlog"))
|
||||
.unwrap()
|
||||
.filter_map(|e| e.ok())
|
||||
.collect();
|
||||
assert_eq!(files.len(), 1, "expected exactly one ticket");
|
||||
fs::read_to_string(files[0].path()).unwrap()
|
||||
}
|
||||
|
||||
@@ -250,3 +250,92 @@ fn comments_added_back_to_back_are_both_kept() {
|
||||
let third = stdout.find("third comment").expect("third comment missing");
|
||||
assert!(first < second && second < third, "comments out of order");
|
||||
}
|
||||
|
||||
/// The body is a positional, and the case that motivated this: a review comment
|
||||
/// quoting a flag name used to be refused outright.
|
||||
#[test]
|
||||
fn comment_accepts_a_body_that_begins_with_a_hyphen() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = setup_worklane(&temp);
|
||||
let uuid = create_ticket(&worklane, "backlog", "Hyphen body");
|
||||
|
||||
for body in ["--print is the flag I mean", "-f skips the check", "-"] {
|
||||
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
|
||||
cmd.current_dir(&temp.path())
|
||||
.args(["comment", &uuid, body])
|
||||
.assert()
|
||||
.success();
|
||||
}
|
||||
|
||||
let bodies: String = fs::read_dir(worklane.join("comments").join(&uuid))
|
||||
.unwrap()
|
||||
.filter_map(|e| e.ok())
|
||||
.map(|e| fs::read_to_string(e.path()).unwrap())
|
||||
.collect();
|
||||
|
||||
for body in ["--print is the flag I mean", "-f skips the check"] {
|
||||
assert!(bodies.contains(body), "{body:?} missing from {bodies:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The ticket positional was deliberately left alone, so a hyphen-leading search
|
||||
/// term is still a usage error. A bare separator is the way through, and it is the
|
||||
/// only way through for `comment` since the body follows in the same position.
|
||||
#[test]
|
||||
fn comment_needs_a_separator_for_a_hyphen_leading_ticket() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = setup_worklane(&temp);
|
||||
create_ticket(&worklane, "backlog", "-leading");
|
||||
|
||||
let mut without = Command::cargo_bin(BIN_NAME).unwrap();
|
||||
without
|
||||
.current_dir(&temp.path())
|
||||
.args(["comment", "-leading", "a body"])
|
||||
.assert()
|
||||
.failure();
|
||||
|
||||
let mut with = Command::cargo_bin(BIN_NAME).unwrap();
|
||||
with.current_dir(&temp.path())
|
||||
.args(["comment", "--", "-leading", "a body"])
|
||||
.assert()
|
||||
.success();
|
||||
}
|
||||
|
||||
/// The one shape `allow_hyphen_values` does not reach: a lone `--` in a positional
|
||||
/// is clap's end-of-options marker, consumed before any value is assigned. So a
|
||||
/// comment body of exactly `--` needs its own separator in front of it.
|
||||
///
|
||||
/// Not a silent drop either way, which is what matters: without the separator the
|
||||
/// body is reported missing and nothing is written.
|
||||
#[test]
|
||||
fn a_bare_double_hyphen_body_needs_a_separator() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = setup_worklane(&temp);
|
||||
let uuid = create_ticket(&worklane, "backlog", "Bare separator");
|
||||
|
||||
let mut without = Command::cargo_bin(BIN_NAME).unwrap();
|
||||
let assert = without
|
||||
.current_dir(&temp.path())
|
||||
.args(["comment", &uuid, "--"])
|
||||
.assert()
|
||||
.failure();
|
||||
let stderr = String::from_utf8(assert.get_output().stderr.clone()).unwrap();
|
||||
assert!(stderr.contains("<BODY>"), "unclear error: {stderr}");
|
||||
assert!(
|
||||
!worklane.join("comments").join(&uuid).exists(),
|
||||
"a comment was written despite the error"
|
||||
);
|
||||
|
||||
let mut with = Command::cargo_bin(BIN_NAME).unwrap();
|
||||
with.current_dir(&temp.path())
|
||||
.args(["comment", &uuid, "--", "--"])
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
let stored: String = fs::read_dir(worklane.join("comments").join(&uuid))
|
||||
.unwrap()
|
||||
.filter_map(|e| e.ok())
|
||||
.map(|e| fs::read_to_string(e.path()).unwrap())
|
||||
.collect();
|
||||
assert!(stored.contains("**Comment**\n--\n"), "was {stored:?}");
|
||||
}
|
||||
|
||||
@@ -216,3 +216,83 @@ fn ls_survives_a_malformed_created_at() {
|
||||
// Unparseable, so the timestamp column is dropped rather than printed raw
|
||||
assert!(!stdout.contains("日本語"));
|
||||
}
|
||||
|
||||
fn create_ticket_with_priority(worklane_dir: &std::path::PathBuf, title: &str, priority: &str) {
|
||||
let slug: String = title.to_lowercase().replace(' ', "-");
|
||||
let body = format!(
|
||||
"# {}\n\n## Metadata\n\n- **ID**: 00000000-0000-0000-0000-00000000000{}\n\
|
||||
- **Priority**: {}\n- **Tags**: test\n- **Due**: _Not set_\n\
|
||||
- **Owner**: alice\n- **Status**: backlog\n",
|
||||
title,
|
||||
slug.len() % 10,
|
||||
priority
|
||||
);
|
||||
let filename = format!("0000000{}-0000-0000-0000-000000000001_{}.md", slug.len() % 10, slug);
|
||||
fs::write(worklane_dir.join("backlog").join(filename), body).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ls_sorts_by_priority_then_title() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = setup_worklane(&temp);
|
||||
|
||||
create_ticket_with_priority(&worklane, "Zebra urgent", "1");
|
||||
create_ticket_with_priority(&worklane, "Apple later", "4");
|
||||
create_ticket_with_priority(&worklane, "Middle one", "2");
|
||||
create_ticket(&worklane, "backlog", "No priority at all", "alice", "_Not set_");
|
||||
|
||||
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
|
||||
cmd.current_dir(&temp.path()).arg("ls").arg("backlog");
|
||||
let stdout = get_stdout(&mut cmd);
|
||||
|
||||
let at = |needle: &str| stdout.find(needle).unwrap_or_else(|| panic!("{needle} missing"));
|
||||
assert!(at("Zebra urgent") < at("Middle one"), "priority 1 must lead");
|
||||
assert!(at("Middle one") < at("Apple later"), "2 before 4");
|
||||
// Unset sorts last even though its title would come first alphabetically
|
||||
assert!(at("Apple later") < at("No priority at all"), "unset must trail");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ls_filters_by_priority_and_composes_with_status() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = setup_worklane(&temp);
|
||||
|
||||
create_ticket_with_priority(&worklane, "Urgent one", "1");
|
||||
create_ticket_with_priority(&worklane, "Lower one", "3");
|
||||
|
||||
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
|
||||
cmd.current_dir(&temp.path())
|
||||
.args(["ls", "backlog", "--priority", "1"]);
|
||||
let stdout = get_stdout(&mut cmd);
|
||||
assert!(stdout.contains("Urgent one"));
|
||||
assert!(!stdout.contains("Lower one"), "filter let a level 3 through");
|
||||
|
||||
// Same filter without a status, through the grouped listing
|
||||
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
|
||||
cmd.current_dir(&temp.path()).args(["ls", "--priority", "3"]);
|
||||
let stdout = get_stdout(&mut cmd);
|
||||
assert!(stdout.contains("Lower one"));
|
||||
assert!(!stdout.contains("Urgent one"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ls_shows_a_mark_for_the_level() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = setup_worklane(&temp);
|
||||
|
||||
create_ticket_with_priority(&worklane, "Top level", "1");
|
||||
create_ticket_with_priority(&worklane, "Bottom level", "5");
|
||||
create_ticket(&worklane, "backlog", "Nothing set", "alice", "_Not set_");
|
||||
|
||||
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
|
||||
cmd.current_dir(&temp.path()).arg("ls").arg("backlog");
|
||||
let stdout = get_stdout(&mut cmd);
|
||||
|
||||
// Piped, so no escapes: the glyph is carrying the level by itself
|
||||
assert!(!stdout.contains('\u{1b}'));
|
||||
assert!(stdout.contains("\u{25cf}\u{25cf} "), "no full meter for level 1 in {stdout:?}");
|
||||
assert!(stdout.contains("\u{25cb}\u{25cb} "), "no empty meter for level 5");
|
||||
assert!(stdout.contains("\u{b7}\u{b7} "), "no unset mark");
|
||||
// The raw number is not what the listing shows
|
||||
assert!(!stdout.contains(" 1 "), "the digit leaked into the row");
|
||||
}
|
||||
|
||||
+171
@@ -431,3 +431,174 @@ fn mv_fails_when_status_field_is_missing() {
|
||||
assert!(worklane.join("backlog").join(filename).exists());
|
||||
assert!(!worklane.join("committed").join(filename).exists());
|
||||
}
|
||||
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
fn chmod(path: &std::path::Path, mode: u32) {
|
||||
let mut perms = fs::metadata(path).unwrap().permissions();
|
||||
perms.set_mode(mode);
|
||||
fs::set_permissions(path, perms).unwrap();
|
||||
}
|
||||
|
||||
fn md_files(dir: &std::path::Path) -> Vec<String> {
|
||||
match fs::read_dir(dir) {
|
||||
Ok(entries) => entries
|
||||
.filter_map(|e| e.ok())
|
||||
.map(|e| e.file_name().into_string().unwrap())
|
||||
.filter(|name| name.ends_with(".md"))
|
||||
.collect(),
|
||||
Err(_) => vec![],
|
||||
}
|
||||
}
|
||||
|
||||
/// Nothing is staged in a status directory, so nothing can be left behind that the
|
||||
/// listing would read as a ticket.
|
||||
fn stray_files(worklane: &std::path::Path) -> Vec<String> {
|
||||
let mut stray: Vec<String> = fs::read_dir(worklane)
|
||||
.unwrap()
|
||||
.filter_map(|e| e.ok())
|
||||
.map(|e| e.file_name().into_string().unwrap())
|
||||
.filter(|name| !["backlog", "committed", "reviewing", "done", "comments"].contains(&name.as_str()))
|
||||
.collect();
|
||||
|
||||
for dir in ["backlog", "committed", "reviewing", "done"] {
|
||||
stray.extend(
|
||||
fs::read_dir(worklane.join(dir))
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|e| e.ok())
|
||||
.map(|e| e.file_name().into_string().unwrap())
|
||||
.filter(|name| !name.ends_with(".md")),
|
||||
);
|
||||
}
|
||||
|
||||
stray
|
||||
}
|
||||
|
||||
/// The bug this fixes. The old order renamed first and wrote second, so a write
|
||||
/// that failed left the ticket in its new directory still claiming the old status.
|
||||
/// A read-only ticket file is the cheapest way to make the write fail.
|
||||
#[test]
|
||||
fn mv_never_leaves_stale_content_in_the_target_directory() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = setup_worklane(&temp);
|
||||
|
||||
let filename = create_ticket(
|
||||
&worklane,
|
||||
"backlog",
|
||||
"Read Only",
|
||||
"A description.",
|
||||
"abc123def456789012345678901234567890",
|
||||
"alice",
|
||||
"2026-12-31",
|
||||
"test",
|
||||
);
|
||||
|
||||
let source = worklane.join("backlog").join(&filename);
|
||||
chmod(&source, 0o444);
|
||||
|
||||
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
|
||||
cmd.current_dir(&temp.path())
|
||||
.args(["mv", "abc123def4567", "--status", "committed"])
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
// Wherever it ended up, its Status must agree with the directory it is in
|
||||
let moved = worklane.join("committed").join(&filename);
|
||||
assert!(moved.exists(), "ticket did not move");
|
||||
let content = fs::read_to_string(&moved).unwrap();
|
||||
assert!(
|
||||
content.contains("- **Status**: committed"),
|
||||
"stale status: {content:?}"
|
||||
);
|
||||
assert!(!content.contains("- **Status**: backlog"), "{content:?}");
|
||||
|
||||
assert_eq!(md_files(&worklane.join("backlog")).len(), 0);
|
||||
assert_eq!(stray_files(&worklane), Vec::<String>::new());
|
||||
}
|
||||
|
||||
/// The other criterion: one directory or the other, never both. An unwritable
|
||||
/// target directory fails the move at the last step, which is the step that would
|
||||
/// have to be reordered to break this.
|
||||
#[test]
|
||||
fn mv_leaves_the_ticket_in_one_place_when_the_move_fails() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = setup_worklane(&temp);
|
||||
|
||||
let filename = create_ticket(
|
||||
&worklane,
|
||||
"backlog",
|
||||
"Blocked Move",
|
||||
"A description.",
|
||||
"abc123def456789012345678901234567890",
|
||||
"alice",
|
||||
"2026-12-31",
|
||||
"test",
|
||||
);
|
||||
|
||||
let target = worklane.join("committed");
|
||||
chmod(&target, 0o555);
|
||||
|
||||
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
|
||||
let assert = cmd
|
||||
.current_dir(&temp.path())
|
||||
.args(["mv", "abc123def4567", "--status", "committed"])
|
||||
.assert()
|
||||
.failure();
|
||||
|
||||
let stderr = String::from_utf8(assert.get_output().stderr.clone()).unwrap();
|
||||
// Named, not a bare io error
|
||||
assert!(stderr.contains("Blocked Move"), "{stderr}");
|
||||
|
||||
assert_eq!(
|
||||
md_files(&worklane.join("backlog")),
|
||||
vec![filename.clone()],
|
||||
"the ticket left its own directory"
|
||||
);
|
||||
assert_eq!(md_files(&target).len(), 0, "the ticket is in both places");
|
||||
assert_eq!(stray_files(&worklane), Vec::<String>::new());
|
||||
|
||||
// The documented worst case: still in its old directory, carrying a Status one
|
||||
// move ahead because the content was written before the move was attempted.
|
||||
let left = fs::read_to_string(worklane.join("backlog").join(&filename)).unwrap();
|
||||
assert!(left.contains("- **Status**: committed"), "{left:?}");
|
||||
|
||||
// And the state is recoverable, because the directory is what decides the
|
||||
// current status, so a retry moves it rather than refusing.
|
||||
chmod(&target, 0o755);
|
||||
|
||||
let mut retry = Command::cargo_bin(BIN_NAME).unwrap();
|
||||
retry
|
||||
.current_dir(&temp.path())
|
||||
.args(["mv", "abc123def4567", "--status", "committed"])
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
assert_eq!(md_files(&target), vec![filename]);
|
||||
assert_eq!(md_files(&worklane.join("backlog")).len(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mv_leaves_nothing_behind_on_success() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = setup_worklane(&temp);
|
||||
|
||||
create_ticket(
|
||||
&worklane,
|
||||
"backlog",
|
||||
"Clean Move",
|
||||
"A description.",
|
||||
"abc123def456789012345678901234567890",
|
||||
"alice",
|
||||
"2026-12-31",
|
||||
"test",
|
||||
);
|
||||
|
||||
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
|
||||
cmd.current_dir(&temp.path())
|
||||
.args(["mv", "abc123def4567", "--status", "committed"])
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
assert_eq!(stray_files(&worklane), Vec::<String>::new());
|
||||
}
|
||||
|
||||
@@ -393,3 +393,95 @@ fn show_searches_across_all_statuses() {
|
||||
assert!(stdout.contains("Committed Task"));
|
||||
assert!(stdout.contains("This is in committed."));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn show_renders_the_priority_mark_beside_the_number() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = setup_worklane(&temp);
|
||||
|
||||
let filename = "abc123def456789012345678901234567890_prio.md";
|
||||
fs::write(
|
||||
worklane.join("backlog").join(filename),
|
||||
"# Prio Ticket\n\n## Metadata\n\n- **ID**: abc123def456789012345678901234567890\n\
|
||||
- **Priority**: 2\n- **Status**: backlog\n",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
|
||||
cmd.current_dir(&temp.path()).arg("show").arg("Prio");
|
||||
let stdout = get_stdout(&mut cmd);
|
||||
|
||||
// Mark for the eye, number still there for the file's sake
|
||||
assert!(stdout.contains("\u{25cf}\u{25d0}"), "no mark in {stdout:?}");
|
||||
assert!(stdout.contains("Priority"));
|
||||
assert!(stdout.contains('2'));
|
||||
|
||||
// And the file itself is untouched
|
||||
let content = fs::read_to_string(worklane.join("backlog").join(filename)).unwrap();
|
||||
assert!(content.contains("- **Priority**: 2"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn show_prints_the_title_once() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = setup_worklane(&temp);
|
||||
|
||||
create_ticket(
|
||||
&worklane,
|
||||
"backlog",
|
||||
"Once Only",
|
||||
"A description that does not name the title.",
|
||||
"abc123def456789012345678901234567890",
|
||||
"alice",
|
||||
"2026-12-31",
|
||||
"test",
|
||||
);
|
||||
|
||||
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
|
||||
cmd.current_dir(&temp.path()).arg("show").arg("Once Only");
|
||||
let stdout = get_stdout(&mut cmd);
|
||||
|
||||
assert_eq!(
|
||||
stdout.matches("Once Only").count(),
|
||||
1,
|
||||
"title repeated in {stdout:?}"
|
||||
);
|
||||
// The rule under it is still the width of the title
|
||||
assert!(stdout.contains("Once Only\n─────────\n"), "{stdout:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn show_renders_the_metadata_as_an_aligned_table() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = setup_worklane(&temp);
|
||||
|
||||
let filename = "abc123def456789012345678901234567890_table.md";
|
||||
fs::write(
|
||||
worklane.join("backlog").join(filename),
|
||||
"# Table Ticket\n\n## Metadata\n\n\
|
||||
- **ID**: abc123def456789012345678901234567890\n\
|
||||
- **Created At**: 2026-08-20 15:51:01\n\
|
||||
- **Owner**: alice\n\
|
||||
- **Status**: backlog\n",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
|
||||
cmd.current_dir(&temp.path()).arg("show").arg("Table");
|
||||
let stdout = get_stdout(&mut cmd);
|
||||
|
||||
// Every value starts in the same column, sized by the longest field name
|
||||
assert!(
|
||||
stdout.contains(
|
||||
"ID abc123def456789012345678901234567890\n\
|
||||
Created At 2026-08-20 15:51:01\n\
|
||||
Owner alice\n\
|
||||
Status backlog\n"
|
||||
),
|
||||
"{stdout:?}"
|
||||
);
|
||||
|
||||
// Display only: the file is still the markdown list it was
|
||||
let content = fs::read_to_string(worklane.join("backlog").join(filename)).unwrap();
|
||||
assert!(content.contains("- **Owner**: alice"));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user