(c6a61b4) Resolve a board through a pointer file and a shared boards repo, and bump to 0.33.0

This commit is contained in:
Ansho Rei
2026-09-01 17:41:05 +02:00
parent 3892afe819
commit f877e6dbf2
13 changed files with 1200 additions and 32 deletions
+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)?;