Compare commits

...
1 Commits
13 changed files with 1200 additions and 32 deletions
+63
View File
@@ -8,6 +8,7 @@
- `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/history.rs` - the history log: the path, the kinds, the reader, the writer, the card's counter and the block `show` and the board both render
- `src/board.rs` - the shared-board layout: the machine config, the boards directory, the `.worklane.toml` pointer and the `init` decision table that decides which layout a project is on
- `src/tui.rs` - board state, the change digest, and the ratatui draw
- `src/split.rs` - one pure function turning a typed line into arguments the way a shell does, plus what the half-typed line is still inside and where the cursor sits among them
- `src/clipboard.rs` - the OSC 52 write and the base64 it carries, the board's only way out to the clipboard
@@ -52,6 +53,68 @@ rule and the argument traps are written down. Read it before working a ticket in
repo. Do not restate any of it in this file: a second copy is a copy that goes stale,
and this file is for what someone changing worklane's own code needs.
## Shared Boards
- **A project's board is on one of two layouts, and `src/board.rs` is the whole of the
second one.** The local layout is the `.worklane` directory a project has always had.
The shared layout answers `.worklane` being gitignored and not a git repo so a clone
elsewhere has no board: the project commits a `.worklane.toml` naming its board by
uuid, one boards repo is cloned once per machine, and `.worklane` in the project
becomes a *symlink* into it. The symlink is the point: with no `.worklane` directory
`cat .worklane/backlog/*.md` and `ls .worklane/reviewing` would stop working, and that
is the belief the whole file format exists to serve. Because the link is transparent,
`find_worklane_dir` gains no resolution code at all (c6a61b4 AC 14).
- **The machine config lives at `$XDG_CONFIG_HOME/worklane/config.toml`** (default
`~/.config`, empty counts as unset). It carries a `[boards]` section holding the *url*
of the boards repo and an optional `dir` overriding where the boards directory sits —
the config is *this machine's* answer, and the pointer carries no server address, so a
client repo never holds an internal hostname. The boards directory itself defaults to
`$XDG_DATA_HOME/worklane/boards` (`~/.local/share` without it).
- **The pointer is `.worklane.toml`, committed at the project root:**
`[worklane] board = "<uuid>"`, and nothing else. Read and written by `read_pointer` /
`write_pointer`. `write_pointer` leaves a pointer that already names the same board
alone — it is a committed file and rewriting it writes nothing new, which is what keeps
"init symlinks it and creates nothing" true for a fresh clone.
- **A board directory is `<uuid>_<slug>`, named after the ticket files.** The slug is
`util::slug` of the project's directory name, and resolution (`resolve_board`) is a
uuid prefix match, the bargain the ticket filenames already make: the directory stays
readable to `ls`, identity is stable, and renaming a board breaks no committed pointer.
- **The decision table is `decide_init`, one match.** The reason it is a table rather
than a fallback is that no branch may fall through into creating a board, so each row
returns its own outcome. The rows:
- no pointer, no `[boards]` config → local `.worklane`, exactly as `init` always made
it (AC 12);
- no pointer, config present → create the board, write the pointer, symlink `.worklane`
to it (AC 4);
- pointer present, board found → symlink it and create nothing (AC 5);
- pointer present, board absent → refuse. A committed pointer is proof the board exists
somewhere, so a missing board is an unsynced machine, and creating a second board
there produces two boards with one name and a manual merge — the worst outcome in the
design. The refusal says so and names `init --create` as the only way to make one
(AC 6/7). The fetch-and-look-again half of the ticket is deferred: nothing pulls the
boards repo yet, and the refusal names it rather than doing it. **`--create` is the
`create` field on `Command::Init`**, the escape hatch under that row;
- the boards directory itself missing → a distinct refusal saying the boards repo is
not cloned here (AC 8);
- the correct symlink already in place → no change, nothing written (AC 9);
- a symlink to a *different* board → refuse rather than repoint it: changing what a
project is on without asking is how two machines come to disagree about the work
(AC 10);
- a symlink that dangles → refuse rather than replace it without asking;
- a real `.worklane` directory under a pointer → refuse and name the adopt path
(aa80db4), never walk over it (AC 11).
- **The three symlink states are told apart by `classify_worklane`:** `Absent`,
`RealDir`, `Symlink`, `Dangling` and `NotADirectory`. The `Symlink` comparison is
canonicalized, the `Dangling` one is lexical (a dangling link cannot be canonicalized)
and checks for the relative spelling this tool writes or the absolute board path.
- **The symlink target is relative** to the link's own parent, so it uses no home
directory path and the link is portable in that limited sense; an absolute target
appearing anywhere is how a home directory leaks into a write. Because a relative
target depends on how deep a repo sits, `init` still runs once per project per machine,
which is the price of transparent access.
- **Everything under `.worklane` is layout-agnostic.** `create_board_contents` makes the
same status directories, `campaigns/` and `tags.md` for a local and a shared board,
and every reader below `find_worklane_dir` works through the link unchanged.
## Testing
- **Run `make check` before committing**: `cargo fmt --check`, then `cargo clippy --all-targets -- -D warnings`, then `cargo test`, cheapest first. That is the whole of the enforcement, and it is deliberate rather than a stopgap: this repo has no CI and does not want any, and a git hook is a per-clone opt-in the way `blame.ignoreRevsFile` is, so neither can be relied on. What was missing was one name to type, so the two rules below are a command and not a memory. `-D warnings` is what makes clippy's opinion an exit code; a warning printed into a wall of cargo output is unread, not clean. The completion checks are inside `cargo test` rather than a target of their own, since a second thing to remember is the problem this solves
- Run one suite: `cargo test`
Generated
+63 -1
View File
@@ -896,6 +896,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
dependencies = [
"serde_core",
"serde_derive",
]
[[package]]
@@ -931,6 +932,15 @@ dependencies = [
"zmij",
]
[[package]]
name = "serde_spanned"
version = "0.6.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3"
dependencies = [
"serde",
]
[[package]]
name = "shlex"
version = "1.3.0"
@@ -1055,6 +1065,47 @@ version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f50febec83f5ee1df3015341d8bd429f2d1cc62bcba7ea2076759d315084683"
[[package]]
name = "toml"
version = "0.8.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362"
dependencies = [
"serde",
"serde_spanned",
"toml_datetime",
"toml_edit",
]
[[package]]
name = "toml_datetime"
version = "0.6.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c"
dependencies = [
"serde",
]
[[package]]
name = "toml_edit"
version = "0.22.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a"
dependencies = [
"indexmap",
"serde",
"serde_spanned",
"toml_datetime",
"toml_write",
"winnow",
]
[[package]]
name = "toml_write"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801"
[[package]]
name = "unicode-ident"
version = "1.0.24"
@@ -1407,6 +1458,15 @@ version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
[[package]]
name = "winnow"
version = "0.7.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945"
dependencies = [
"memchr",
]
[[package]]
name = "wit-bindgen"
version = "0.51.0"
@@ -1503,7 +1563,7 @@ dependencies = [
[[package]]
name = "worklane"
version = "0.32.21"
version = "0.33.0"
dependencies = [
"anyhow",
"assert_cmd",
@@ -1514,7 +1574,9 @@ dependencies = [
"crossterm",
"libc",
"ratatui",
"serde",
"tempfile",
"toml",
"uuid",
]
+3 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "worklane"
version = "0.32.21"
version = "0.33.0"
edition = "2024"
[dependencies]
@@ -15,6 +15,8 @@ libc = "0.2"
ratatui = { version = "0.29", features = ["unstable-rendered-line-info"] }
crossterm = "0.28"
clap_complete = "4.6.9"
serde = { version = "1", features = ["derive"] }
toml = "0.8"
[dev-dependencies]
assert_cmd = "2"
+30 -1
View File
@@ -6,7 +6,7 @@ Worklane is a local Kanban flow for agentic software development.
| Command | Description |
|---------|-------------|
| `worklane` or `worklane tui [path...]` | Opens the board: one column per status, redrawn when the tree changes. Read only. Opens with done and discarded hidden, their counts in the footer; `d` rotates hide both, show done, show both, and back around. Arrows or `hjkl` to move, `enter` for detail, `pgup`/`pgdn` to scroll an open ticket or the campaign frame, whichever the selection is on, with a page indicator on its border while there is more of it than fits, `/` to jump to the first ticket whose id or title matches, `y` to copy the selected ticket's short id to the clipboard, `c` to pick a campaign and filter the columns to its members, `q` to close whatever is open and then to quit. A card carries its campaign beside its tags, marked `~` and bold, and a comment count in its bottom right corner, the number then `❞` in cyan, before the criteria count and absent entirely when nobody has commented; while one is selected a frame above the columns names it, shows three rows of its description and says how far it has got, and `q` on its border gives the whole board back; up from the top card of a column moves the selection to that frame, where the scroll keys page through the description, `enter` gives it half the board and takes the rows back again, and down returns to the column it came from, leaving the frame at whatever height it was. Each path opens the first `.worklane` at or above it, the working directory by default. Several paths are monitored together, as a tab per project plus an `all` tab that merges them, with `tab` and `shift+tab` between them |
| `worklane init` | Creates `.worklane/` with backlog, committed, reviewing, done, discarded directories |
| `worklane init` | Creates `.worklane/` with backlog, committed, reviewing, done, discarded directories. On a machine with a boards config, or in a project that already carries a `.worklane.toml`, it puts the project on the shared layout instead: the board lives in a boards directory under the machine's data dir and `.worklane` becomes a symlink into it. `--create` makes a new board under a pointer that names a missing one, the only way to do so. See Shared Boards |
| `worklane add` | Creates a ticket in backlog with `--title`, `--description`, `--acceptance`, `--plan`, `--tags`, `--due`, `--owner`, `--priority` flags. `--due` takes `YYYY-MM-DD` and refuses anything else at parse time |
| `worklane ls [status]` | Lists tickets, each column in its own order: the backlog by due date, soonest first, then priority then title, with an undated ticket below every dated one; committed and reviewing by when the ticket entered them, oldest first; done and discarded newest first. Optional positional status, and `--priority <1-5>`, `--tag <tag>` and `--campaign <campaign>`, which compose in any combination. `--tag` matches a whole value of the comma-separated Tags field, case sensitively, so `--tag bug` does not list a ticket tagged `bugfix` or one tagged `Bug`. `--ids` prints one ticket per line as its short id, a tab and its title, unstyled, done included, for a script or a completion |
| `worklane show <id>` | Shows ticket by UUID prefix (4+ chars), title substring, or filename substring. A campaign is addressed the same way, plus its exact codename, which wins over all three. Ends with the ticket's history: every comment on it and every change to its status, owner or tags, oldest first, each naming who made it |
@@ -70,6 +70,35 @@ installed binary to be current**: an older one without `--ids` completes nothing
`tui` is the one command whose argument is a path, so it is the one place fish still offers
directories.
## Shared Boards
A board exists on exactly one machine: `.worklane` is gitignored and not itself a git repo, so cloning
a project elsewhere gives you no board. The shared layout answers that: one boards repo is cloned once
per machine to `~/.local/share/worklane/boards`, holding a directory per board named `uuid_slug` after
the ticket filename convention; the project commits a `.worklane.toml` naming its board by uuid; and
`.worklane` in the project becomes a symlink into it. The symlink is what keeps every other tool
working — with no `.worklane` directory, `cat .worklane/backlog/*.md` stops.
The boards repo url lives in the machine config at `~/.config/worklane/config.toml`, so a client repo
never carries a hostname. The pointer names the board, not the server.
`init` decides where a project is on by the following table, and `--create` is the only way to make a
board under a pointer that names a missing one:
| pointer | boards repo | `.worklane` | outcome |
|---|---|---|---|
| none | irrelevant | none | local `.worklane`, as always |
| none | on this machine (config) | none | create the board, write the pointer, symlink |
| present | board found | none | symlink, and nothing is created |
| present | board absent | none | refuse: an unsynced machine, fetch and look again |
| present | repo not cloned | any | refuse, saying the repo is not cloned here |
| present | board found | link to it | no change, nothing written |
| present | board found | link to another | refuse rather than repoint |
| present | board found | dangling link | refuse rather than replace |
| present | board found | real directory | refuse, and name the adopt path |
Resolution is a uuid prefix match, so renaming a board's slug breaks no committed pointer.
## Exit codes
| Code | Meaning |
|------|---------|
+13
View File
@@ -202,6 +202,19 @@ resolve as a ticket. `--clear` replaces both arguments with the ticket alone.
`worklane init` creates `.worklane/` with the five status directories and the campaigns
directory beside them, for a repo that has no board yet.
**A board can be shared across machines.** `.worklane` is gitignored and not itself a git
repo, so a clone elsewhere has no board. The shared layout keeps one boards repo cloned
once per machine, a committed `.worklane.toml` in the project naming its board, and
`.worklane` as a symlink into the boards directory — transparent to every command. Where
to run `init` decides the layout: a project whose machine carries a boards config, or
whose repo already shows a `.worklane.toml`, lands on the shared board, and everything
else gets the ordinary local `.worklane`. A pointer whose board is missing is an unsynced
machine and `init` refuses rather than creating a second board that would have to be
merged by hand; `worklane init --create` is the deliberate exception for a genuinely new
board. You only need the layout in mind when a `.worklane.toml` appears in a repo you
are working in: it says the board is another machine's, and a missing one means pull the
boards repo, not that the board never existed.
## Relating tickets
```
+615
View File
@@ -0,0 +1,615 @@
//! Shared boards: the `.worklane.toml` pointer, the machine config, the boards
//! directory and the symlink that makes a shared board transparent.
//!
//! A board exists on exactly one machine: `.worklane` is gitignored and not itself a
//! git repo, so a project cloned elsewhere has no board. The shared layout answers that
//! with a boards repo cloned once per machine, holding one directory per board named
//! `<uuid>_<slug>` after the ticket filename convention. The project carries a
//! committed `.worklane.toml` naming its board by uuid, and `.worklane` in the project
//! becomes a *symlink* into the boards directory. A symlink rather than resolving the
//! pointer inside the CLI, because with no `.worklane` directory `cat
//! .worklane/backlog/*.md` and `ls .worklane/reviewing` would stop working, and that is
//! the belief the whole file format exists to serve. The symlink keeps every other tool
//! working and `find_worklane_dir` needs no resolution code, because it already follows
//! a link.
//!
//! The pointer names the board, not the server: the boards repo url lives in the
//! machine config, so a client repo never carries an internal hostname for anyone with
//! access to it to read.
use anyhow::{Result, anyhow};
use std::fs;
use std::path::{Path, PathBuf};
use crate::util::slug;
/// The one file that decides whether this project's board is shared or local.
const POINTER_FILE: &str = ".worklane.toml";
/// Where the machine-level config lives, under `$XDG_CONFIG_HOME`, or `~/.config`
/// without it, the same resolution `install::tools_root` follows.
fn config_path() -> PathBuf {
xdg_config().join("worklane/config.toml")
}
/// The boards directory, under `$XDG_DATA_HOME`, or `~/.local/share` without it.
///
/// The ticket's spelling is `~/.local/share/worklane/boards`.
fn default_boards_dir() -> PathBuf {
xdg_data().join("worklane/boards")
}
/// `$XDG_CONFIG_HOME` or `~/.config`, the convention `install::tools_root` already
/// follows. An empty value counts as unset, like `NO_COLOR` in `colors_wanted`.
fn xdg_config() -> PathBuf {
match std::env::var_os("XDG_CONFIG_HOME") {
Some(value) if !value.is_empty() => PathBuf::from(value),
_ => home().join(".config"),
}
}
/// `$XDG_DATA_HOME` or `~/.local/share`.
fn xdg_data() -> PathBuf {
match std::env::var_os("XDG_DATA_HOME") {
Some(value) if !value.is_empty() => PathBuf::from(value),
_ => home().join(".local/share"),
}
}
fn home() -> PathBuf {
std::env::var_os("HOME").map(PathBuf::from).unwrap_or_default()
}
/// The machine's boards configuration, `None` when neither the file nor a `[boards]`
/// section exists.
///
/// Holding the boards repo url and the board directory path. The directory defaults
/// under `$XDG_DATA_HOME` but is overridable here.
pub fn read_config() -> Result<Option<MachineConfig>> {
let path = config_path();
let text = match fs::read_to_string(&path) {
Ok(text) => text,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(error) => {
return Err(anyhow!("Could not read the machine config {}: {error}", path.display()));
}
};
let parsed: ConfigFile = toml::from_str(&text).map_err(|error| {
anyhow!("Could not parse the machine config {}: {error}", path.display())
})?;
Ok(parsed.boards.option())
}
/// The effective boards directory, config override or default.
pub fn boards_dir() -> Result<PathBuf> {
Ok(read_config()?
.and_then(|config| config.boards_dir)
.unwrap_or_else(default_boards_dir))
}
#[derive(Default)]
pub struct MachineConfig {
/// The boards repo url. Read and held so the config carries it (the pointer names
/// the board, the machine names the server), and not yet read anywhere further:
/// the fetch that would use it is deferred.
#[allow(dead_code)]
pub url: Option<String>,
pub boards_dir: Option<PathBuf>,
}
#[derive(serde::Deserialize, Default)]
struct ConfigFile {
#[serde(default)]
boards: BoardsSection,
}
#[derive(serde::Deserialize, Default)]
struct BoardsSection {
#[serde(default)]
url: Option<String>,
#[serde(default)]
dir: Option<PathBuf>,
}
impl BoardsSection {
/// `None` when the section is absent or entirely empty, which is what makes "this
/// machine uses shared boards" a property of the config rather than of an empty
/// file.
fn option(self) -> Option<MachineConfig> {
let BoardsSection { url, dir } = self;
if url.is_none() && dir.is_none() {
None
} else {
Some(MachineConfig { url, boards_dir: dir })
}
}
}
/// The committed pointer in a project: `.worklane.toml`, naming the board by uuid.
pub struct Pointer {
pub board: String,
}
/// Where the pointer lives, at the project root beside `.worklane`.
pub fn pointer_path(project: &Path) -> PathBuf {
project.join(POINTER_FILE)
}
/// The pointer a project carries, `None` when there is none or it names nothing.
pub fn read_pointer(project: &Path) -> Result<Option<Pointer>> {
let path = pointer_path(project);
let text = match fs::read_to_string(&path) {
Ok(text) => text,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(error) => {
return Err(anyhow!("Could not read the board pointer {}: {error}", path.display()));
}
};
let parsed: PointerFile = toml::from_str(&text).map_err(|error| {
anyhow!("Could not parse the board pointer {}: {error}", path.display())
})?;
Ok(parsed
.worklane
.board
.filter(|board| !board.trim().is_empty())
.map(|board| Pointer { board }))
}
#[derive(serde::Deserialize, Default)]
struct PointerFile {
#[serde(default)]
worklane: PointerSection,
}
#[derive(serde::Deserialize, Default)]
struct PointerSection {
#[serde(default)]
board: Option<String>,
}
/// Write `.worklane.toml` naming `uuid`, creating or replacing the pointer.
///
/// A pointer that already names the same board is left alone: it is a committed file,
/// and rewriting what is already committed writes nothing new.
pub fn write_pointer(project: &Path, uuid: &str) -> Result<PathBuf> {
let path = pointer_path(project);
let text = format!("[worklane]\nboard = \"{uuid}\"\n");
match fs::read_to_string(&path) {
Ok(existing) if existing == text => return Ok(path),
Ok(_) => {}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => {
return Err(anyhow!("Could not read the board pointer {}: {error}", path.display()));
}
}
fs::write(&path, text).map_err(|error| {
anyhow!("Could not write the board pointer {}: {}", path.display(), error)
})?;
Ok(path)
}
/// A board directory's name for a fresh board, `<uuid>_<slug>` after the ticket
/// filename convention.
pub fn board_dir_name(uuid: &str, title: &str) -> String {
format!("{uuid}_{}", slug(title))
}
/// An existing board directory's uuid, the segment before the first underscore.
fn dir_uuid(name: &str) -> &str {
name.split('_').next().unwrap_or(name)
}
/// The board directory in `boards` that `search` names, by uuid prefix, `None` when
/// nothing matches.
///
/// A uuid prefix rather than the full pointer value, so renaming a board's slug breaks
/// no committed pointer, the bargain the ticket filenames already make. Matches only
/// the uuid, never the slug: a directory named `_my-board` carries no uuid to match.
pub fn resolve_board(boards: &Path, search: &str) -> Result<Option<PathBuf>> {
let search = search.to_lowercase();
let matches = match fs::read_dir(boards) {
Ok(entries) => entries
.filter_map(|entry| entry.ok())
.filter(|entry| entry.file_type().is_ok_and(|t| t.is_dir()))
.map(|entry| entry.path())
.filter(|path| {
path.file_name()
.and_then(|name| name.to_str())
.map(|name| dir_uuid(name).to_lowercase().starts_with(&search))
.unwrap_or(false)
})
.collect::<Vec<_>>(),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(error) => {
return Err(anyhow!(
"Could not read the boards directory {}: {error}",
boards.display()
));
}
};
match matches.len() {
0 => Ok(None),
1 => Ok(Some(matches.into_iter().next().unwrap())),
_ => Err(anyhow!(
"'{search}' is ambiguous across {} boards in {}",
matches.len(),
boards.display()
)),
}
}
/// What `init` decided, for the handler to say.
pub enum Init {
/// `.worklane` was already a board for this project, so nothing was written.
AlreadyInitialized(PathBuf),
/// A local `.worklane`, the layout every project had before the shared one.
CreatedLocal(PathBuf),
/// A shared board: pointer written, board directory made, `.worklane` symlinked to
/// it.
CreatedShared {
pointer: PathBuf,
board: PathBuf,
link: PathBuf,
},
/// A deliberate refusal with a reason: the caller looked and decided not to change
/// what a pointer or an existing `.worklane` commits to.
Refused(String),
}
/// The decision table for `init`, one match so no branch can fall through into
/// creating a board.
///
/// `dir` is the canonical project root. `create` is `--create`, the only way to make a
/// board under a pointer that names a missing one.
pub fn decide_init(dir: &Path, create: bool) -> Result<Init> {
let worklane_dir = dir.join(".worklane");
let pointer = read_pointer(dir)?;
match pointer {
// No pointer: this project has never been put on the shared layout.
None => init_no_pointer(dir, &worklane_dir),
Some(pointer) => init_with_pointer(dir, &worklane_dir, &pointer, create),
}
}
fn init_no_pointer(dir: &Path, worklane_dir: &Path) -> Result<Init> {
match classify_worklane(worklane_dir) {
Worklane::Absent => {}
// An existing board of the local layout, or a shared one reached through a link
// whose pointer is missing; either way it is a board already.
Worklane::RealDir => return Ok(Init::AlreadyInitialized(worklane_dir.to_path_buf())),
Worklane::Symlink(_) | Worklane::Dangling(_) => {
return Ok(Init::AlreadyInitialized(worklane_dir.to_path_buf()));
}
Worklane::NotADirectory => {
return Ok(Init::Refused(format!(
"{} is not a directory; refusing to replace what is there.",
worklane_dir.display()
)));
}
}
// The machine config decides the layout. A `[boards]` section means a shared board
// here; none means the local layout, exactly as worklane always created it.
if read_config()?.is_some() {
let boards = boards_dir()?;
let uuid = uuid::Uuid::new_v4().to_string();
let board = boards.join(board_dir_name(&uuid, &project_title(dir)));
fs::create_dir_all(&board).map_err(|error| {
anyhow!("Could not create the board directory {}: {error}", board.display())
})?;
create_board_contents(&board)?;
let link = symlink_board(&board, worklane_dir)?;
let pointer = write_pointer(dir, &uuid)?;
return Ok(Init::CreatedShared { pointer, board, link });
}
Ok(Init::CreatedLocal(create_local(worklane_dir)?))
}
fn init_with_pointer(
dir: &Path,
worklane_dir: &Path,
pointer: &Pointer,
create: bool,
) -> Result<Init> {
let boards = boards_dir()?;
// The boards repo itself must be here: a committed pointer is proof the board
// exists somewhere, and a missing repo is an unsynced machine, not a missing board.
if !boards.is_dir() {
return Ok(Init::Refused(format!(
"The boards directory {} does not exist.\n\
This project names board {} in {},\n\
so its board lives in a boards repo that is not cloned here.\n\
Clone the boards repo (or run `worklane init --create` to make a new one).",
boards.display(),
pointer.board,
pointer_path(dir).display(),
)));
}
let resolved = resolve_board(&boards, &pointer.board)?;
// An existing `.worklane` must not be repointed or walked over. This is where a
// project that predates the shared layout, or one that points at the wrong board,
// is caught.
match classify_worklane(worklane_dir) {
Worklane::Absent => {}
Worklane::RealDir => {
return Ok(Init::Refused(format!(
"{} is a real directory, not the shared board {} names.\n\
This may be a board from before the shared layout, which worklane can \
adopt later (see the migration); refusing to walk over it. Remove it \
first, then run `worklane init` to link the board {} names.",
worklane_dir.display(),
pointer_path(dir).display(),
pointer_path(dir).display(),
)));
}
Worklane::Symlink(target) => {
// A link to exactly the board the pointer names is the layout already in
// place; a link to anything else is not to be repointed.
let board_named = resolved
.as_deref()
.and_then(|board| same(&target, board).then_some(board));
return match board_named {
Some(_) => Ok(Init::AlreadyInitialized(worklane_dir.to_path_buf())),
None => Ok(Init::Refused(format!(
"{} already links to {}, and not to the board {} names.\n\
Refusing to repoint it: changing what a project is on without \
asking is how two machines come to disagree about where the work is.\n\
Remove {} and run `worklane init` again to link {}.",
worklane_dir.display(),
target.display(),
pointer_path(dir).display(),
worklane_dir.display(),
resolved
.map(|p| p.display().to_string())
.unwrap_or_else(|| pointer.board.clone()),
))),
};
}
Worklane::Dangling(target) => {
// A link that resolves nowhere: if it is spelled as the board the pointer
// names — the relative form this tool writes, or the absolute board path —
// the board is out of this machine and the missing-board answer is the
// right one; anything else is not to be replaced without asking. Compared
// lexically, since a dangling link cannot be canonicalized.
let points_at_board = resolved.as_deref().is_some_and(|board| {
let base = worklane_dir.parent().unwrap_or(Path::new(""));
target == relative_path(base, board) || target == board
});
if points_at_board {
return Ok(missing_board(pointer, &boards));
}
return Ok(Init::Refused(format!(
"{} is a link to {}, which does not exist; refusing to replace it \
without asking.",
worklane_dir.display(),
target.display(),
)));
}
Worklane::NotADirectory => {
return Ok(Init::Refused(format!(
"{} is not a directory; refusing to replace what is there.",
worklane_dir.display()
)));
}
}
match resolved {
Some(board) => {
let link = symlink_board(&board, worklane_dir)?;
Ok(Init::CreatedShared {
pointer: pointer_path(dir),
board,
link,
})
}
None => {
if create {
let board = boards.join(board_dir_name(&pointer.board, &project_title(dir)));
fs::create_dir_all(&board).map_err(|error| {
anyhow!("Could not create the board directory {}: {error}", board.display())
})?;
create_board_contents(&board)?;
let link = symlink_board(&board, worklane_dir)?;
Ok(Init::CreatedShared {
pointer: pointer_path(dir),
board,
link,
})
} else {
Ok(missing_board(pointer, &boards))
}
}
}
}
/// The missing-board refusal, shared by the dangling-symlink-to-the-board and the
/// nothing-linking cases, so the board's being out of this machine is told once.
fn missing_board(pointer: &Pointer, boards: &Path) -> Init {
Init::Refused(format!(
"The boards directory {} holds no board for {}.\n\
The boards repo may need pulling; run a fetch there and try again.\n\
To deliberately start a new board under this pointer, run `worklane init --create`.",
boards.display(),
pointer.board,
))
}
/// The slug a newly created board takes: the project directory's name, so a board is
/// named after the project it lives in. Sharing a name keeps a reader looking at the
/// boards directory able to tell which project a board belongs to.
fn project_title(dir: &Path) -> String {
dir.file_name()
.map(|name| name.to_string_lossy().to_string())
.unwrap_or_default()
}
/// Classify an existing `.worklane` entry, distinguishing a real directory from a link
/// that resolves and a link that dangles, so each is answered differently.
enum Worklane {
/// Nothing at that path.
Absent,
/// A directory, not a link: a local board, or one that predates the shared layout.
RealDir,
/// A link that resolves to a directory, carrying the resolved target.
Symlink(PathBuf),
/// A link that resolves to nothing, carrying the target it names.
Dangling(PathBuf),
/// There, and neither a directory nor a link to one.
NotADirectory,
}
/// The four-way answer `init` needs from a `.worklane` path.
fn classify_worklane(path: &Path) -> Worklane {
let entry = match fs::symlink_metadata(path) {
Ok(entry) => entry,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Worklane::Absent,
Err(_) => return Worklane::NotADirectory,
};
if !entry.is_symlink() {
return match entry.is_dir() {
true => Worklane::RealDir,
false => Worklane::NotADirectory,
};
}
let target = fs::read_link(path).unwrap_or_else(|_| path.to_path_buf());
match fs::metadata(path) {
Ok(resolved) if resolved.is_dir() => {
Worklane::Symlink(fs::canonicalize(path).unwrap_or(path.to_path_buf()))
}
Ok(_) => Worklane::NotADirectory,
Err(_) => Worklane::Dangling(target),
}
}
/// Whether two paths are the same directory, through canonicalization and following
/// links.
fn same(a: &Path, b: &Path) -> bool {
match (fs::canonicalize(a), fs::canonicalize(b)) {
(Ok(a), Ok(b)) => a == b,
_ => false,
}
}
/// Symlink `worklane_dir` to `board`, the one way `.worklane` becomes a board reached
/// through a link.
///
/// The target is made relative to the link's own parent so the link is portable (it
/// uses no home directory path), and the link's parent directory is created since the
/// project may not exist as a directory yet.
fn symlink_board(board: &Path, worklane_dir: &Path) -> Result<PathBuf> {
if let Some(parent) = worklane_dir.parent() {
fs::create_dir_all(parent)
.map_err(|error| anyhow!("Could not create {}: {error}", parent.display()))?;
}
let target = relative_path(worklane_dir.parent().unwrap_or(Path::new("")), board);
make_symlink(&target, worklane_dir)?;
Ok(worklane_dir.to_path_buf())
}
/// A relative path from `base` (a directory) to `target`.
fn relative_path(base: &Path, target: &Path) -> PathBuf {
let base = base.to_path_buf();
let target = target.to_path_buf();
// The common prefix gives how far up `base` the link must climb. When they share a
// root device but no component they have no common ancestor expressible in a
// relative path, and the absolute target is the honest answer.
let common = base
.components()
.zip(target.components())
.take_while(|(a, b)| a == b)
.count();
let mut result = PathBuf::new();
for _ in common..base.components().count() {
result.push("..");
}
for component in target.components().skip(common) {
result.push(component);
}
result
}
/// Create a symlink at `link` to `target`, refusing to replace a different file or link.
fn make_symlink(target: &Path, link: &Path) -> Result<()> {
match fs::symlink_metadata(link) {
// Nothing there: place it.
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => {
return Err(anyhow!("Could not inspect {} before linking: {error}", link.display()));
}
Ok(_) => {
return Err(anyhow!(
"{} already exists; refusing to replace what is there",
link.display()
));
}
}
#[cfg(unix)]
std::os::unix::fs::symlink(target, link).map_err(|error| {
anyhow!("Could not symlink {} to {}: {error}", link.display(), target.display())
})?;
#[cfg(not(unix))]
{
let _ = (target, link);
return Err(anyhow!(
"shared boards need symlinks, which this platform does not support"
));
}
Ok(())
}
/// The local board layout, as `init` always created it: the status directories, the
/// campaigns directory and the tag vocabulary.
///
/// Shared boards call the same helper on their directory. Returns the worklane
/// directory for the message.
fn create_local(worklane_dir: &Path) -> Result<PathBuf> {
fs::create_dir_all(worklane_dir)
.map_err(|error| anyhow!("Could not create {}: {error}", worklane_dir.display()))?;
create_board_contents(worklane_dir)?;
Ok(worklane_dir.to_path_buf())
}
/// The contents every board gets, whatever layout holds it.
fn create_board_contents(worklane_dir: &Path) -> Result<()> {
for folder in crate::util::status_dirs() {
fs::create_dir_all(worklane_dir.join(folder)).map_err(|error| {
anyhow!("Could not create {}: {error}", worklane_dir.join(folder).display())
})?;
}
fs::create_dir_all(crate::campaign::campaigns_dir(worklane_dir)).map_err(|error| {
anyhow!(
"Could not create {}: {error}",
crate::campaign::campaigns_dir(worklane_dir).display()
)
})?;
fs::write(
crate::tag::tags_path(worklane_dir),
crate::tag::TagIndex::default().render(),
)
.map_err(|error| {
anyhow!(
"Could not write {}: {error}",
crate::tag::tags_path(worklane_dir).display()
)
})?;
Ok(())
}
+5 -1
View File
@@ -220,7 +220,11 @@ const PROSE: bool = true;
#[derive(clap::Subcommand)]
pub enum Command {
/// Initialize worklane in the current project
Init,
Init {
/// Create a board even where a committed pointer names one that is not here
#[arg(long)]
create: bool,
},
/// Add a new ticket to the backlog
Add(AddArgs),
+16 -24
View File
@@ -15,34 +15,26 @@ use crate::install;
use crate::tag::{TAGS_FILE, TagIndex, tags_path};
use crate::util::*;
pub fn cmd_init(start: &Path, sink: &mut Sink) -> Result<()> {
pub fn cmd_init(create: bool, start: &Path, sink: &mut Sink) -> Result<()> {
let dir = start.canonicalize().unwrap_or_else(|_| start.to_path_buf());
let worklane_dir = dir.join(".worklane");
if worklane_dir.exists() {
sink.writeln(&format!("worklane already initialized in: {}", worklane_dir.display()))?;
return Ok(());
match crate::board::decide_init(&dir, create)? {
crate::board::Init::AlreadyInitialized(worklane_dir) => {
sink.writeln(&format!("worklane already initialized in: {}", worklane_dir.display()))?;
}
crate::board::Init::CreatedLocal(worklane_dir) => {
sink.writeln(&format!("Initialized worklane in: {}", worklane_dir.display()))?;
}
crate::board::Init::CreatedShared { pointer, board, link } => {
sink.writeln(&format!("Initialized shared worklane in: {}", board.display()))?;
sink.writeln(&format!("Board pointer: {}", pointer.display()))?;
sink.writeln(&format!("Linked {} to it", link.display()))?;
}
crate::board::Init::Refused(reason) => {
return Err(anyhow!("{reason}"));
}
}
fs::create_dir_all(&worklane_dir)?;
for folder in status_dirs() {
fs::create_dir_all(worklane_dir.join(folder))?;
}
// Beside the status directories, not among them: a campaign has no status. Created
// here for a new board, and on demand by `campaign add` for a board that predates
// campaigns, which is why `status_dirs()` is untouched.
fs::create_dir_all(campaigns_dir(&worklane_dir))?;
// The tag vocabulary, beside both for the same reason, and written empty rather than
// left for the first `tags add` to make. An empty file explains itself when it is
// opened, which is the point of the preamble, and a board that has one from the start
// has one file shape rather than two. `fs::write` and not `write_then_replace`: the
// directory was made three lines ago, so there is nothing here to truncate.
fs::write(tags_path(&worklane_dir), TagIndex::default().render())?;
sink.writeln(&format!("Initialized worklane in: {}", worklane_dir.display()))?;
Ok(())
}
+2 -1
View File
@@ -3,6 +3,7 @@ use std::path::Path;
use anyhow::Result;
use clap::Parser;
mod board;
mod campaign;
mod clipboard;
mod command;
@@ -88,7 +89,7 @@ pub fn dispatch(command: &Command, start: &Path, sink: &mut Sink) -> Result<()>
// Reachable only from the prompt, since `main` takes this arm before it gets
// here. A board is not something a board can open.
Command::Tui { .. } => Err(anyhow::anyhow!("`tui` opens a board, and you are on one")),
Command::Init => cmd_init(start, sink),
Command::Init { create } => cmd_init(*create, start, sink),
Command::Add(args) => cmd_add(args, start, sink),
Command::Ls(args) => {
let worklane_dir = find_worklane_dir(start)?;
+11 -1
View File
@@ -247,7 +247,17 @@ fn nothing_is_created_without_a_title() {
fn init_creates_the_campaigns_directory() {
let temp = TempDir::new().unwrap();
let out = run(&temp, &["init"]);
// Isolated HOME and XDG so `init` cannot decide on a real machine's boards config:
// the board has to be local no matter whose machine runs the suite.
let mut init = Command::cargo_bin(BIN_NAME).unwrap();
let out = init
.current_dir(temp.path())
.env("HOME", temp.path())
.env("XDG_CONFIG_HOME", temp.path().join("config"))
.env("XDG_DATA_HOME", temp.path().join("data"))
.arg("init")
.output()
.unwrap();
assert!(out.status.success(), "{}", stderr(&out));
assert!(temp.child(".worklane").child("campaigns").path().is_dir());
+9 -1
View File
@@ -75,7 +75,15 @@ fn fish_is_offered_every_status() {
fn board() -> (assert_fs::TempDir, String, String) {
let temp = assert_fs::TempDir::new().unwrap();
let mut init = Command::cargo_bin(BIN_NAME).unwrap();
init.current_dir(temp.path()).arg("init").assert().success();
// Isolated HOME and XDG so `init` cannot decide on a real machine's boards config:
// the board has to be local no matter whose machine runs the suite.
init.current_dir(temp.path())
.env("HOME", temp.path())
.env("XDG_CONFIG_HOME", temp.path().join("config"))
.env("XDG_DATA_HOME", temp.path().join("data"))
.arg("init")
.assert()
.success();
let mut add = Command::cargo_bin(BIN_NAME).unwrap();
add.current_dir(temp.path())
+359
View File
@@ -0,0 +1,359 @@
//! `worklane init` and the shared-board decision table (c6a61b4).
//!
//! A project is on one of two layouts: the local `.worklane` directory every project
//! always had, or the shared one where the project carries a committed `.worklane.toml`,
//! the board lives in a machine-level boards directory, and `.worklane` is a symlink
//! into it. The machine config decides the default, and the pointer decides where the
//! project already is. The tests below walk the whole table: one per row, the three
//! symlink states, and the standalone path.
//!
//! Every test runs on an isolated machine: `HOME` and the XDG variables point into the
//! temp directory, so the suite can never read or write a real config or boards
//! directory, and a `find_worklane_dir` walk from the project can never climb into one.
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");
/// A project with no pointer and no board, ready for `init` to decide on.
fn project(temp: &TempDir) -> PathBuf {
temp.child("project").create_dir_all().unwrap();
temp.child("project").path().to_path_buf()
}
fn run(project: &Path, machine: &TempDir, args: &[&str]) -> std::process::Output {
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
cmd.current_dir(project)
.env("HOME", machine.path())
.env("XDG_CONFIG_HOME", machine.path().join(".config"))
.env("XDG_DATA_HOME", machine.path().join(".local/share"))
.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()
}
/// The boards directory of a machine, under its data dir.
fn boards_dir(machine: &TempDir) -> PathBuf {
machine.path().join(".local/share/worklane/boards")
}
/// The board a pointer names when the machine holds it.
fn board_path(machine: &TempDir, uuid: &str, slug: &str) -> PathBuf {
boards_dir(machine).join(format!("{uuid}_{slug}"))
}
/// The machine config, without which a no-pointer project stays on the local layout.
///
/// Carries only the boards repo url; the boards directory defaults under the machine's
/// data dir, which is where these tests put it.
fn with_boards_config(machine: &TempDir) {
let config = machine.path().join(".config/worklane/config.toml");
fs::create_dir_all(config.parent().unwrap()).unwrap();
fs::write(config, "[boards]\nurl = \"git@example:worklane/boards\"\n").unwrap();
}
/// The committed pointer naming a board by uuid. This is the only thing that puts a
/// project on the shared layout.
fn write_pointer(project: &Path, uuid: &str) {
fs::write(project.join(".worklane.toml"), format!("[worklane]\nboard = \"{uuid}\"\n")).unwrap();
}
/// A board directory in the machine's boards repo, named `<uuid>_<slug>`.
fn with_board(machine: &TempDir, uuid: &str, slug: &str) -> PathBuf {
let board = board_path(machine, uuid, slug);
fs::create_dir_all(&board).unwrap();
board
}
/// The relative spelling init gives a `.worklane` symlink, used to build the states a
/// project can already be in.
fn link_target(project: &Path, board: &Path) -> String {
let base = project;
let common = base
.components()
.zip(board.components())
.take_while(|(a, b)| a == b)
.count();
let mut up = String::new();
for _ in common..base.components().count() {
up.push_str("../");
}
let mut rest = String::new();
for component in board.components().skip(common) {
rest.push_str(&component.as_os_str().to_string_lossy());
rest.push('/');
}
format!("{up}{rest}").trim_end_matches('/').to_string()
}
fn symlink_to(project: &Path, target: &str) {
std::os::unix::fs::symlink(target, project.join(".worklane")).unwrap();
}
fn boards_of(machine: &TempDir) -> Vec<PathBuf> {
fs::read_dir(boards_dir(machine))
.unwrap()
.map(|entry| entry.unwrap().path())
.collect()
}
/// The standalone path, and the reason it has to stay: every project written before the
/// shared layout existed, and every project whose machine has no boards config, must
/// still get exactly the board `init` always made.
#[test]
fn no_pointer_no_config_and_no_boards_repo_makes_a_local_board() {
let machine = TempDir::new().unwrap();
let project = project(&machine);
let out = run(&project, &machine, &["init"]);
assert!(out.status.success(), "{}", stderr(&out));
assert_eq!(
stdout(&out),
format!("Initialized worklane in: {}\n", project.join(".worklane").display())
);
assert!(
fs::symlink_metadata(project.join(".worklane")).unwrap().is_dir(),
".worklane must be a real directory"
);
assert!(!project.join(".worklane.toml").exists(), "no pointer on a local board");
for dir in [
"backlog",
"committed",
"reviewing",
"done",
"discarded",
"campaigns",
] {
assert!(project.join(".worklane").join(dir).is_dir(), "local board missing {dir}");
}
}
/// The pointer is committed and carries only the board by uuid, nowhere for a home
/// directory or a server address to hide.
#[test]
fn a_shared_init_commits_a_pointer_carrying_only_the_uuid() {
let machine = TempDir::new().unwrap();
let project = project(&machine);
with_boards_config(&machine);
let out = run(&project, &machine, &["init"]);
assert!(out.status.success(), "{}", stderr(&out));
let output = stdout(&out);
assert!(output.contains("Initialized shared worklane in: "), "{output}");
assert!(output.contains("Board pointer: "), "{output}");
assert!(
output.contains(&format!("Linked {} to it", project.join(".worklane").display())),
"{output}"
);
let board = output
.lines()
.next()
.unwrap()
.trim_start_matches("Initialized shared worklane in: ")
.to_string();
let uuid = Path::new(&board)
.file_name()
.unwrap()
.to_str()
.unwrap()
.split('_')
.next()
.unwrap();
let pointer = fs::read_to_string(project.join(".worklane.toml")).unwrap();
assert_eq!(pointer, format!("[worklane]\nboard = \"{uuid}\"\n"));
assert!(
!pointer.contains(machine.path().to_str().unwrap()),
"no home path in the pointer"
);
assert!(!pointer.contains("git@"), "no server address in the pointer");
}
/// A pointer whose board is present is the state a fresh clone is in: `.worklane` is
/// missing and nothing else is. init links it and creates nothing.
#[test]
fn pointer_with_the_board_present_symlinks_it_and_creates_nothing() {
let machine = TempDir::new().unwrap();
let project = project(&machine);
with_boards_config(&machine);
write_pointer(&project, "12345678-1234-1234-1234-1234567890ab");
let board = with_board(&machine, "12345678-1234-1234-1234-1234567890ab", "project");
let before = fs::read_to_string(project.join(".worklane.toml")).unwrap();
let out = run(&project, &machine, &["init"]);
assert!(out.status.success(), "{}", stderr(&out));
assert!(
stdout(&out).contains(&format!("Linked {} to it", project.join(".worklane").display()))
);
assert_eq!(
fs::canonicalize(project.join(".worklane")).unwrap(),
fs::canonicalize(&board).unwrap()
);
assert_eq!(fs::read_to_string(project.join(".worklane.toml")).unwrap(), before);
assert_eq!(boards_of(&machine).len(), 1, "no second board was created");
}
/// A pointer whose board is absent is an unsynced machine, and creating a second board
/// there is the worst outcome in the design. init refuses, and `--create` is the only
/// way to make one.
#[test]
fn pointer_with_the_board_absent_refuses_and_create_is_the_only_way() {
let machine = TempDir::new().unwrap();
let project = project(&machine);
with_boards_config(&machine);
write_pointer(&project, "abcd5678-abcd-4bcd-abcd-abcdabcdabcd");
with_board(&machine, "12345678-1234-1234-1234-1234567890ab", "other");
let out = run(&project, &machine, &["init"]);
assert!(!out.status.success());
let err = stderr(&out);
assert!(
err.contains("holds no board for abcd5678-abcd-4bcd-abcd-abcdabcdabcd."),
"{err}"
);
assert!(err.contains("`worklane init --create`"), "{err}");
assert!(!project.join(".worklane").exists(), "nothing was linked");
assert_eq!(boards_of(&machine).len(), 1, "no board was created");
let out = run(&project, &machine, &["init", "--create"]);
assert!(out.status.success(), "{}", stderr(&out));
assert_eq!(
fs::canonicalize(project.join(".worklane")).unwrap(),
fs::canonicalize(board_path(&machine, "abcd5678-abcd-4bcd-abcd-abcdabcdabcd", "project"))
.unwrap()
);
}
/// The boards directory itself is gone: that is an uncloned boards repo, not a missing
/// board, and the two must be told apart.
#[test]
fn boards_repo_missing_is_said_as_such() {
let machine = TempDir::new().unwrap();
let project = project(&machine);
with_boards_config(&machine);
write_pointer(&project, "12345678-1234-1234-1234-1234567890ab");
let out = run(&project, &machine, &["init"]);
assert!(!out.status.success());
let err = stderr(&out);
assert!(err.contains("does not exist"), "{err}");
assert!(err.contains("boards repo that is not cloned here"), "{err}");
}
/// The correct symlink in place is the layout already there: init reports no change and
/// writes nothing.
#[test]
fn correct_symlink_already_in_place_reports_no_change() {
let machine = TempDir::new().unwrap();
let project = project(&machine);
with_boards_config(&machine);
let board = with_board(&machine, "12345678-1234-1234-1234-1234567890ab", "project");
write_pointer(&project, "12345678-1234-1234-1234-1234567890ab");
symlink_to(&project, &link_target(&project, &board));
let before = fs::read_to_string(project.join(".worklane.toml")).unwrap();
let out = run(&project, &machine, &["init"]);
assert!(out.status.success(), "{}", stderr(&out));
assert!(stdout(&out).starts_with("worklane already initialized in: "));
assert_eq!(fs::read_to_string(project.join(".worklane.toml")).unwrap(), before);
assert_eq!(boards_of(&machine).len(), 1, "nothing was written");
}
/// A symlink pointing at a different board is a project on the wrong board, and changing
/// what a project is on without asking is how two machines disagree about the work.
#[test]
fn symlink_to_a_different_board_refuses_rather_than_repointing() {
let machine = TempDir::new().unwrap();
let project = project(&machine);
with_boards_config(&machine);
with_board(&machine, "12345678-1234-1234-1234-1234567890ab", "project");
let other = with_board(&machine, "99999999-9999-4999-8999-999999999999", "other");
write_pointer(&project, "12345678-1234-1234-1234-1234567890ab");
let other_target = link_target(&project, &other);
symlink_to(&project, &other_target);
let out = run(&project, &machine, &["init"]);
assert!(!out.status.success());
let err = stderr(&out);
assert!(err.contains("already links to"), "{err}");
assert!(err.contains("not to the board"), "{err}");
assert_eq!(
fs::read_link(project.join(".worklane")).unwrap(),
PathBuf::from(&other_target)
);
}
/// A symlink that resolves to nothing is neither the layout init places nor a board: it
/// is not replaced without asking.
#[test]
fn symlink_that_dangles_is_not_replaced() {
let machine = TempDir::new().unwrap();
let project = project(&machine);
with_boards_config(&machine);
with_board(&machine, "12345678-1234-1234-1234-1234567890ab", "project");
write_pointer(&project, "12345678-1234-1234-1234-1234567890ab");
symlink_to(&project, "nowhere-anyone-knows");
let out = run(&project, &machine, &["init"]);
assert!(!out.status.success());
let err = stderr(&out);
assert!(err.contains("nowhere-anyone-knows, which does not exist"), "{err}");
assert_eq!(
fs::read_link(project.join(".worklane")).unwrap(),
PathBuf::from("nowhere-anyone-knows")
);
}
/// A real `.worklane` directory under a pointer is a board from before the shared
/// layout, and it is never walked over; the refusal names the adopt path.
#[test]
fn real_worklane_directory_under_a_pointer_refuses_and_names_the_adopt_path() {
let machine = TempDir::new().unwrap();
let project = project(&machine);
with_boards_config(&machine);
write_pointer(&project, "12345678-1234-1234-1234-1234567890ab");
with_board(&machine, "12345678-1234-1234-1234-1234567890ab", "project");
fs::create_dir_all(project.join(".worklane").join("backlog")).unwrap();
fs::write(project.join(".worklane").join("backlog").join("b.md"), "# anything\n").unwrap();
let out = run(&project, &machine, &["init"]);
assert!(!out.status.success());
let err = stderr(&out);
assert!(err.contains("is a real directory"), "{err}");
assert!(err.contains("adopt"), "{err}");
assert!(
project.join(".worklane").join("backlog").join("b.md").is_file(),
"the pre-existing board was left intact"
);
}
/// The slug, and only the slug, may change: resolution is a uuid prefix match, so
/// renaming a board breaks no committed pointer.
#[test]
fn renaming_a_board_slug_breaks_no_pointer() {
let machine = TempDir::new().unwrap();
let project = project(&machine);
with_boards_config(&machine);
write_pointer(&project, "12345678-1234-1234-1234-1234567890ab");
let renamed = with_board(&machine, "12345678-1234-1234-1234-1234567890ab", "new-name");
let out = run(&project, &machine, &["init"]);
assert!(out.status.success(), "{}", stderr(&out));
assert_eq!(
fs::canonicalize(project.join(".worklane")).unwrap(),
fs::canonicalize(&renamed).unwrap()
);
}
+11 -1
View File
@@ -397,7 +397,17 @@ fn the_file_is_created_on_a_board_that_predates_it() {
#[test]
fn init_writes_the_vocabulary_beside_the_status_directories() {
let temp = TempDir::new().unwrap();
let out = run(&temp, &["init"]);
// Isolated HOME and XDG so `init` cannot decide on a real machine's boards config:
// the board has to be local no matter whose machine runs the suite.
let mut out = Command::cargo_bin(BIN_NAME).unwrap();
let out = out
.current_dir(temp.path())
.env("HOME", temp.path())
.env("XDG_CONFIG_HOME", temp.path().join("config"))
.env("XDG_DATA_HOME", temp.path().join("data"))
.arg("init")
.output()
.unwrap();
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
let file = vocabulary(&temp);