Port every jeans command and view to Rust
src/jj.rs passes --config snapshot.auto-update-stale=true to every jj call,
because finishing a task from its workspace leaves the main workspace stale
and the Ruby version only worked where the user's config set it.
Task: Port every jeans command and view to Rust
Done looks like: the Rust binary behaves like the Ruby bin/jeans at alpha-channel 150a86206e57 for every command and view (init, add, claim, done, release, describe, ready, status, team-size, log, tree, board, watch, --color, NO_COLOR, --goal resolution, file lock, legacy-goal refusal). The parity recipe passes, and Rust integration tests running real jj in temp repos cover every case in jeans_test.rb. `just all` green. Split this as needed.
Assisted-by: Claude Opus 5.5 via Claude Code
diff --git a/Cargo.lock b/Cargo.lock
index 5404ecb..b9683f2 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2,6 +2,213 @@
# It is not intended for manual editing.
version = 4
+[[package]]
+name = "autocfg"
+version = "1.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
+
+[[package]]
+name = "bitflags"
+version = "2.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
+
+[[package]]
+name = "camino"
+version = "1.2.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bbbad30e4b4c14a39e3cc8aed085a12a327257c316619c93581e017bc52be591"
+
+[[package]]
+name = "cfg-if"
+version = "1.0.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
+
+[[package]]
+name = "errno"
+version = "0.3.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776"
+dependencies = [
+ "libc",
+ "windows-sys",
+]
+
+[[package]]
+name = "fastrand"
+version = "2.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
+
+[[package]]
+name = "fs-err"
+version = "3.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b5c95b673b8f6f7235229ae11c5642d81b04c2e64c1e2fb417bc0cf73ca45f29"
+dependencies = [
+ "autocfg",
+]
+
+[[package]]
+name = "getrandom"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "r-efi",
+]
+
[[package]]
name = "jeans"
version = "0.1.0"
+dependencies = [
+ "camino",
+ "fs-err",
+ "signal-hook",
+ "tempfile",
+ "thiserror",
+]
+
+[[package]]
+name = "libc"
+version = "0.2.191"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
+
+[[package]]
+name = "linux-raw-sys"
+version = "0.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
+
+[[package]]
+name = "once_cell"
+version = "1.21.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
+
+[[package]]
+name = "proc-macro2"
+version = "1.0.107"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "quote"
+version = "1.0.47"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "r-efi"
+version = "6.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
+
+[[package]]
+name = "rustix"
+version = "1.1.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa"
+dependencies = [
+ "bitflags",
+ "errno",
+ "libc",
+ "linux-raw-sys",
+ "windows-sys",
+]
+
+[[package]]
+name = "signal-hook"
+version = "0.4.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "49f7447afd772ca79ad17ae0a3972a6b0df0cb4b80990fd82707593e9e012a74"
+dependencies = [
+ "libc",
+ "signal-hook-registry",
+]
+
+[[package]]
+name = "signal-hook-registry"
+version = "1.4.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"
+dependencies = [
+ "errno",
+ "libc",
+]
+
+[[package]]
+name = "syn"
+version = "3.0.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "tempfile"
+version = "3.27.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
+dependencies = [
+ "fastrand",
+ "getrandom",
+ "once_cell",
+ "rustix",
+ "windows-sys",
+]
+
+[[package]]
+name = "thiserror"
+version = "2.0.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"
+dependencies = [
+ "thiserror-impl",
+]
+
+[[package]]
+name = "thiserror-impl"
+version = "2.0.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "unicode-ident"
+version = "1.0.27"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
+
+[[package]]
+name = "windows-link"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
+
+[[package]]
+name = "windows-sys"
+version = "0.61.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
+dependencies = [
+ "windows-link",
+]
diff --git a/Cargo.toml b/Cargo.toml
index b27e7d6..ee91152 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -8,6 +8,13 @@ name = "jeans"
path = "src/bin/jeans/main.rs"
[dependencies]
+camino = "*"
+fs-err = "*"
+signal-hook = "*"
+thiserror = "*"
+
+[dev-dependencies]
+tempfile = "*"
[lints.clippy]
self_named_module_files = "warn"
diff --git a/justfile b/justfile
index c17a453..921430b 100644
--- a/justfile
+++ b/justfile
@@ -10,7 +10,6 @@ coverage:
./bin/coverage
# Runs the Ruby suite from the original plugin against the Rust binary.
-# Expected to fail until the port lands.
parity:
cargo build --quiet
JEANS="$PWD/target/debug/jeans" ruby test/jeans_test.rb
diff --git a/src/bin/jeans/main.rs b/src/bin/jeans/main.rs
index f8c5f01..0fee1db 100644
--- a/src/bin/jeans/main.rs
+++ b/src/bin/jeans/main.rs
@@ -1,3 +1,3 @@
-fn main() {
- print!("{}", jeans::USAGE);
+fn main() -> std::process::ExitCode {
+ jeans::run(std::env::args_os().skip(1).collect())
}
diff --git a/src/cli.rs b/src/cli.rs
new file mode 100644
index 0000000..3fd5d16
--- /dev/null
+++ b/src/cli.rs
@@ -0,0 +1,283 @@
+use std::ffi::OsString;
+use std::io::IsTerminal as _;
+use std::io::Write;
+use std::process::ExitCode;
+use std::sync::Arc;
+use std::sync::atomic::AtomicBool;
+
+use crate::Error;
+use crate::Result;
+use crate::USAGE;
+use crate::color_enabled;
+use crate::graph::Jeans;
+use crate::init::Init;
+use crate::init::init;
+
+/// Runs the jeans command in ARGS (without the program name), printing its
+/// output, and returns the exit status.
+pub fn run(args: Vec<OsString>) -> ExitCode {
+ let stdout = std::io::stdout();
+ match dispatch(args, &mut stdout.lock()) {
+ Ok(Exit::Success) => ExitCode::SUCCESS,
+ Ok(Exit::Usage) => {
+ eprint!("{USAGE}");
+ ExitCode::FAILURE
+ }
+ Err(e) => {
+ eprintln!("jeans: {e}");
+ ExitCode::FAILURE
+ }
+ }
+}
+
+enum Exit {
+ Success,
+ Usage,
+}
+
+/// The flags every command accepts, wherever they sit among its arguments.
+#[derive(Default)]
+struct Opts {
+ body: Option<String>,
+ team: Option<i64>,
+ home: Option<String>,
+ before: Option<String>,
+ after: Vec<String>,
+ depth: Option<i64>,
+ color: Option<String>,
+ goal: Option<String>,
+}
+
+fn dispatch(args: Vec<OsString>, out: &mut impl Write) -> Result<Exit> {
+ let mut args = args
+ .into_iter()
+ .map(|arg| {
+ arg.into_string()
+ .map_err(|arg| Error::msg(format!("{} isn't UTF-8", arg.display())))
+ })
+ .collect::<Result<Vec<_>>>()?
+ .into_iter();
+ let command = args.next().unwrap_or_default();
+ let (opts, args) = parse(args)?;
+ let color = color_enabled(
+ opts.color.as_deref().unwrap_or("auto"),
+ std::io::stdout().is_terminal(),
+ std::env::var_os("NO_COLOR").as_deref(),
+ );
+ let goal = opts.goal.as_deref();
+ let jeans = |hint: Option<&str>| Jeans::new(color, true, goal, hint);
+ let arg = |i: usize| args.get(i).map(String::as_str);
+ let required = |what: &str| arg(0).ok_or_else(|| Error::msg(format!("{command} needs {what}")));
+ // Past the end of --depth's range, nothing is deep enough to collapse.
+ let depth = opts.depth.and_then(|d| usize::try_from(d).ok());
+
+ match command.as_str() {
+ "init" => {
+ let id = init(&Init {
+ title: required("TITLE")?,
+ goal,
+ body: opts.body.as_deref(),
+ team_size: opts.team.unwrap_or(3),
+ home: opts.home.as_deref(),
+ })?;
+ puts(out, &id)?;
+ }
+ "add" => {
+ let before = opts.before.as_deref();
+ let id = jeans(before)?.add(
+ required("TITLE")?,
+ opts.body.as_deref(),
+ before,
+ &opts.after,
+ )?;
+ puts(out, &id)?;
+ }
+ "ready" => puts_lines(out, &jeans(None)?.ready()?)?,
+ "log" => puts(out, &jeans(arg(1))?.log(arg(0), arg(1))?)?,
+ "status" => puts(out, &jeans(None)?.log(None, None)?)?,
+ "tree" => puts(out, &jeans(arg(0))?.tree(arg(0), depth)?)?,
+ "board" => puts(out, &jeans(arg(0))?.board(arg(0))?)?,
+ "watch" => {
+ let stop = Arc::new(AtomicBool::new(false));
+ signal_hook::flag::register(signal_hook::consts::SIGINT, Arc::clone(&stop))?;
+ let jeans = Jeans::new(color, false, goal, arg(1))?;
+ jeans.watch(arg(0).unwrap_or("tree"), arg(1), depth, &stop, out)?;
+ }
+ "show" => {
+ let task = required("TASK")?;
+ puts(out, &jeans(Some(task))?.show(task)?)?;
+ }
+ "describe" => {
+ let task = required("TASK")?;
+ let message = opts
+ .body
+ .as_deref()
+ .ok_or_else(|| Error::msg("describe needs -m MESSAGE"))?;
+ jeans(Some(task))?.describe(task, message)?;
+ }
+ "claim" => {
+ let task = required("TASK")?;
+ puts(out, &jeans(Some(task))?.claim(task)?)?;
+ }
+ "done" => {
+ let task = required("TASK")?;
+ puts(out, &jeans(Some(task))?.done(task, opts.body.as_deref())?)?;
+ }
+ "release" => {
+ let task = required("TASK")?;
+ puts(out, &jeans(Some(task))?.release(task)?)?;
+ }
+ "team-size" => puts(out, &jeans(None)?.team_size()?.to_string())?,
+ _ => return Ok(Exit::Usage),
+ }
+ Ok(Exit::Success)
+}
+
+/// Splits ARGS into flags and positional arguments the way Ruby's
+/// OptionParser does: flags anywhere, values attached or as the next
+/// argument, and everything after `--` positional.
+fn parse(mut args: impl Iterator<Item = String>) -> Result<(Opts, Vec<String>)> {
+ let mut opts = Opts::default();
+ let mut positional = Vec::new();
+ while let Some(arg) = args.next() {
+ let (flag, attached) = if arg == "--" {
+ positional.extend(args.by_ref());
+ break;
+ } else if let Some(long) = arg.strip_prefix("--") {
+ match long.split_once('=') {
+ Some((name, value)) => (format!("--{name}"), Some(value.to_owned())),
+ None => (arg.clone(), None),
+ }
+ } else if let Some(value) = arg.strip_prefix("-m") {
+ (
+ "-m".to_owned(),
+ Some(value).filter(|v| !v.is_empty()).map(str::to_owned),
+ )
+ } else if arg.starts_with('-') && arg != "-" {
+ return Err(Error::msg(format!("invalid option: {arg}")));
+ } else {
+ positional.push(arg);
+ continue;
+ };
+
+ let known = [
+ "-m", "--team", "--home", "--before", "--after", "--depth", "--color", "--goal",
+ ];
+ if !known.contains(&flag.as_str()) {
+ return Err(Error::msg(format!("invalid option: {flag}")));
+ }
+ let value = attached
+ .or_else(|| args.next())
+ .ok_or_else(|| Error::msg(format!("missing argument: {flag}")))?;
+ let invalid = || Error::msg(format!("invalid argument: {flag} {value}"));
+ match flag.as_str() {
+ "-m" => opts.body = Some(value),
+ "--team" => opts.team = Some(value.parse().map_err(|_| invalid())?),
+ "--home" => opts.home = Some(value),
+ "--before" => opts.before = Some(value),
+ "--after" => opts.after.push(value),
+ "--depth" => opts.depth = Some(value.parse().map_err(|_| invalid())?),
+ "--color" if ["always", "never", "auto"].contains(&value.as_str()) => {
+ opts.color = Some(value);
+ }
+ "--color" => return Err(invalid()),
+ _ => opts.goal = Some(value),
+ }
+ }
+ Ok((opts, positional))
+}
+
+/// Prints TEXT and a newline, unless TEXT already ends with one.
+fn puts(out: &mut impl Write, text: &str) -> Result<()> {
+ if text.ends_with('\n') {
+ write!(out, "{text}")?;
+ } else {
+ writeln!(out, "{text}")?;
+ }
+ Ok(())
+}
+
+/// Prints each line, or a blank line for none, like Ruby's `puts []`.
+fn puts_lines(out: &mut impl Write, lines: &[String]) -> Result<()> {
+ if lines.is_empty() {
+ writeln!(out)?;
+ }
+ for line in lines {
+ puts(out, line)?;
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn parsed(args: &[&str]) -> Result<(Opts, Vec<String>)> {
+ parse(args.iter().map(|a| (*a).to_owned()))
+ }
+
+ fn error(args: &[&str]) -> String {
+ parsed(args).err().unwrap().to_string()
+ }
+
+ #[test]
+ fn flags_go_anywhere() {
+ let (opts, args) = parsed(&[
+ "a",
+ "--depth",
+ "2",
+ "-m",
+ "- one",
+ "--after=x",
+ "--after",
+ "y",
+ "b",
+ "--",
+ "--c",
+ ])
+ .unwrap();
+ assert_eq!(args, ["a", "b", "--c"]);
+ assert_eq!(opts.depth, Some(2));
+ assert_eq!(opts.body.as_deref(), Some("- one"));
+ assert_eq!(opts.after, ["x", "y"]);
+ }
+
+ #[test]
+ fn every_flag_sets_its_option() {
+ let (opts, args) = parsed(&[
+ "-mbody", "--team", "4", "--home", "h", "--before", "t", "--color", "never", "--goal",
+ "g", "-",
+ ])
+ .unwrap();
+ assert_eq!(args, ["-"]);
+ assert_eq!(opts.body.as_deref(), Some("body"));
+ assert_eq!(opts.team, Some(4));
+ assert_eq!(opts.home.as_deref(), Some("h"));
+ assert_eq!(opts.before.as_deref(), Some("t"));
+ assert_eq!(opts.color.as_deref(), Some("never"));
+ assert_eq!(opts.goal.as_deref(), Some("g"));
+ }
+
+ #[test]
+ fn bad_flags_are_errors() {
+ assert_eq!(error(&["-x"]), "invalid option: -x");
+ assert_eq!(error(&["--nope"]), "invalid option: --nope");
+ assert_eq!(error(&["--team"]), "missing argument: --team");
+ assert_eq!(error(&["--team", "x"]), "invalid argument: --team x");
+ assert_eq!(error(&["--depth=x"]), "invalid argument: --depth x");
+ assert_eq!(
+ error(&["--color", "sometimes"]),
+ "invalid argument: --color sometimes"
+ );
+ }
+
+ #[test]
+ fn puts_adds_a_missing_newline() {
+ let mut out = Vec::new();
+ puts(&mut out, "a").unwrap();
+ puts(&mut out, "b\n").unwrap();
+ puts_lines(&mut out, &[]).unwrap();
+ puts_lines(&mut out, &["c".to_owned()]).unwrap();
+ assert_eq!(String::from_utf8(out).unwrap(), "a\nb\n\nc\n");
+ }
+}
diff --git a/src/color.rs b/src/color.rs
new file mode 100644
index 0000000..0277daa
--- /dev/null
+++ b/src/color.rs
@@ -0,0 +1,66 @@
+use std::ffi::OsStr;
+
+/// Whether `--color WHEN` colors the output, given whether stdout is a
+/// terminal and the value of NO_COLOR.
+pub fn color_enabled(when: &str, is_tty: bool, no_color: Option<&OsStr>) -> bool {
+ match when {
+ "always" => true,
+ "never" => false,
+ _ => is_tty && no_color.is_none_or(OsStr::is_empty),
+ }
+}
+
+/// What a piece of output is colored as.
+#[derive(Clone, Copy)]
+pub(crate) enum Paint {
+ Id,
+ Ready,
+ Claimed,
+ Blocked,
+ Done,
+}
+
+impl Paint {
+ fn code(self) -> &'static str {
+ match self {
+ Self::Ready => "32",
+ Self::Claimed => "33",
+ Self::Blocked => "31",
+ Self::Done => "90",
+ Self::Id => "35",
+ }
+ }
+}
+
+pub(crate) fn paint(color: bool, text: &str, key: Paint) -> String {
+ if color && !text.is_empty() {
+ format!("\x1b[{}m{text}\x1b[0m", key.code())
+ } else {
+ text.to_owned()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn auto_colors_only_a_terminal_without_no_color() {
+ assert!(color_enabled("auto", true, None));
+ assert!(color_enabled("auto", true, Some(OsStr::new(""))));
+ assert!(!color_enabled("auto", true, Some(OsStr::new("1"))));
+ assert!(!color_enabled("auto", false, None));
+ }
+
+ #[test]
+ fn always_and_never_ignore_the_terminal() {
+ assert!(color_enabled("always", false, Some(OsStr::new("1"))));
+ assert!(!color_enabled("never", true, None));
+ }
+
+ #[test]
+ fn empty_text_stays_plain() {
+ assert_eq!(paint(true, "", Paint::Id), "");
+ assert_eq!(paint(true, "x", Paint::Id), "\x1b[35mx\x1b[0m");
+ }
+}
diff --git a/src/commands.rs b/src/commands.rs
new file mode 100644
index 0000000..c42d80c
--- /dev/null
+++ b/src/commands.rs
@@ -0,0 +1,348 @@
+use crate::Error;
+use crate::Result;
+use crate::graph::Jeans;
+use crate::graph::State;
+use crate::graph::ids_revset;
+use crate::init::created_id;
+use crate::init::done_bookmark;
+use crate::init::goal_bookmark;
+use crate::jj::jj_allow_failure;
+use crate::message::finished_message;
+use crate::message::message;
+
+impl Jeans {
+ /// Inserts a task before BEFORE (default: the goal) and after each of
+ /// AFTER (default: trunk), and returns its change ID.
+ pub(crate) fn add(
+ &self,
+ title: &str,
+ body: Option<&str>,
+ before: Option<&str>,
+ after: &[String],
+ ) -> Result<String> {
+ self.locked(|| {
+ if self.goal.is_none() {
+ return Err(Error::msg(
+ "there's no goal to add to; run `jeans init` first",
+ ));
+ }
+ let before = self.resolve(before.unwrap_or(&self.goal_revset))?;
+ if self.done_ids()?.contains(&before) {
+ return Err(Error::msg(format!(
+ "{before} is done; add follow-up work before a task that isn't"
+ )));
+ }
+ self.guard_scope(&before, true)?;
+
+ let after = if after.is_empty() {
+ vec!["trunk()".to_owned()]
+ } else {
+ after
+ .iter()
+ .map(|rev| self.resolve(rev))
+ .collect::<Result<_>>()?
+ };
+ let message = message(title, body);
+ let mut args = vec!["new", "--no-edit"];
+ for parent in &after {
+ args.extend(["-A", parent]);
+ }
+ args.extend(["-B", &before, "-m", &message]);
+ let new = self.jj_in(&self.main, &args)?;
+ created_id(&new.stderr, &self.main, self.snapshot)
+ })
+ }
+
+ /// Replaces a task's description.
+ pub(crate) fn describe(&self, rev: &str, message: &str) -> Result<()> {
+ self.locked(|| {
+ let id = self.resolve(rev)?;
+ self.guard_scope(&id, false)?;
+ self.jj(&["describe", "-r", &id, "-m", message])?;
+ Ok(())
+ })
+ }
+
+ /// Makes a ready task's workspace and returns its path.
+ pub(crate) fn claim(&self, rev: &str) -> Result<String> {
+ self.locked(|| {
+ let id = self.resolve(rev)?;
+ let state = self.state(&id)?;
+ if state != State::Ready {
+ return Err(Error::msg(format!("{id} is {}, not ready", state.name())));
+ }
+ let path = self.workspace_path(&id);
+ self.jj(&[
+ "workspace",
+ "add",
+ path.as_str(),
+ "--name",
+ &Self::workspace_name(&id),
+ "-r",
+ &id,
+ ])?;
+ Ok(path.into_string())
+ })
+ }
+
+ /// Squashes a task's workspace in, puts MESSAGE above its spec, and
+ /// moves it under the done node.
+ pub(crate) fn done(&self, rev: &str, message: Option<&str>) -> Result<String> {
+ let message = message.filter(|m| !m.trim().is_empty()).ok_or_else(|| {
+ Error::msg("done needs -m MESSAGE, a commit message for the finished work")
+ })?;
+ self.finish(rev, |id| self.integrate_finished(id, message))
+ }
+
+ /// Squashes a task's workspace in and drops it, leaving the task undone.
+ pub(crate) fn release(&self, rev: &str) -> Result<String> {
+ self.finish(rev, |_| Ok(()))
+ }
+
+ fn integrate_finished(&self, id: &str, message: &str) -> Result<()> {
+ let conflicted = self.tasks()?.into_iter().any(|t| t.id == id && t.conflict);
+ if conflicted {
+ return Err(Error::msg(format!(
+ "{id} has conflicts; resolve them in its workspace first"
+ )));
+ }
+
+ let goal_ids = self.log_ids(&self.goal_revset)?;
+ let finishing_goal = self
+ .goal
+ .as_ref()
+ .filter(|_| goal_ids.iter().any(|g| g == id));
+ let spec = self.jj(&["log", "--no-graph", "-r", id, "-T", "description"])?;
+ self.jj(&[
+ "describe",
+ "-r",
+ id,
+ "-m",
+ &finished_message(message, &spec),
+ ])?;
+
+ let heads = self.log_ids(&format!(
+ "heads(parents({}) ~ ::trunk() | {id})",
+ self.done_node
+ ))?;
+ let superseded = self.superseded_resolutions(&heads, id)?;
+ // -s, not -r: -r would drop the done node from the integration node above it.
+ let mut rebase = vec!["rebase", "-s", &self.done_node];
+ for head in heads.iter().filter(|h| !superseded.contains(h)) {
+ rebase.extend(["-o", head]);
+ }
+ self.jj(&rebase)?;
+ if !superseded.is_empty() {
+ let mut abandon = vec!["abandon"];
+ abandon.extend(superseded.iter().map(String::as_str));
+ self.jj(&abandon)?;
+ }
+
+ let resolution = self.add_resolution_task()?;
+ if let Some(resolution) = &resolution {
+ eprintln!("the finished tasks conflict; added resolution task {resolution}");
+ }
+ if let Some(goal) = finishing_goal {
+ // The goal takes the done node's place as a parent of the
+ // integration node.
+ let node = self.resolve(&self.done_node)?;
+ self.jj(&[
+ "bookmark",
+ "delete",
+ &goal_bookmark(goal),
+ &done_bookmark(goal),
+ ])?;
+ self.jj(&["abandon", &node])?;
+ }
+ if resolution.is_none() {
+ self.warn_integration_conflicts()?;
+ }
+ Ok(())
+ }
+
+ fn finish(&self, rev: &str, work: impl FnOnce(&str) -> Result<()>) -> Result<String> {
+ self.locked(|| {
+ let id = self.resolve(rev)?;
+ let ws = self.workspace_path(&id);
+ if !self.claimed()?.contains(&id) {
+ return Err(Error::msg(format!("{id} isn't claimed")));
+ }
+
+ self.jj_in(&ws, &["workspace", "update-stale"])?;
+ let wc_args = [
+ "log",
+ "--no-graph",
+ "-r",
+ "@",
+ "-T",
+ r#"empty ++ " " ++ conflict"#,
+ ];
+ let wc = self.jj_in(&ws, &wc_args)?;
+ let (empty, conflict) = wc.stdout.split_once(' ').unwrap_or_default();
+ if conflict == "true" {
+ return Err(Error::msg(format!(
+ "the working copy in {ws} has conflicts; resolve them first"
+ )));
+ }
+ if empty != "true" {
+ self.jj_in(&ws, &["squash", "--from", "@", "--into", &id, "-u"])?;
+ }
+
+ work(&id)?;
+
+ let name = Self::workspace_name(&id);
+ let leftover = self.jj(&[
+ "log",
+ "--no-graph",
+ "-r",
+ &format!("{name}@"),
+ "-T",
+ "commit_id",
+ ])?;
+ self.jj(&["workspace", "forget", &name])?;
+ let abandon = ["abandon", leftover.trim()];
+ jj_allow_failure(Some(&self.main), self.snapshot, &abandon)?;
+ match fs_err::remove_dir_all(&ws) {
+ Err(e) if e.kind() != std::io::ErrorKind::NotFound => return Err(e.into()), // cov-excl-line
+ _ => {}
+ }
+ Ok(id)
+ })
+ }
+
+ /// A claimed task's scope belongs to the developer on it, who runs jeans
+ /// from inside its workspace. That developer in turn changes only its
+ /// own subtree; work it finds elsewhere is the stakeholder's to add.
+ fn guard_scope(&self, id: &str, own_subtree: bool) -> Result<()> {
+ if let Some(current) = self.current_task()? {
+ let allowed = if own_subtree {
+ self.log_ids(&format!("::{current} & ({})", self.tasks_revset))?
+ } else {
+ vec![current.clone()]
+ };
+ if allowed.iter().any(|a| a == id) {
+ return Ok(());
+ }
+ return Err(Error::msg(format!(
+ "{id} is outside your task {current}; report it to the stakeholder instead"
+ )));
+ }
+ if self.claimed()?.iter().any(|c| c == id) {
+ return Err(Error::msg(format!(
+ "{id} is claimed; only the developer in {} can change it",
+ self.workspace_path(id)
+ )));
+ }
+ Ok(())
+ }
+
+ /// A resolution task is redundant once another done task integrates all
+ /// of its parents, and merging it with that task conflicts again even
+ /// when both resolved the same way. Leave one a developer is still on
+ /// until it finishes.
+ fn superseded_resolutions(&self, heads: &[String], finishing: &str) -> Result<Vec<String>> {
+ let resolutions =
+ self.log_ids(&format!("({}) ~ ::{}", self.tasks_revset, self.goal_revset))?;
+ let taken = self.claimed()?;
+ let mut superseded = Vec::new();
+ for head in heads {
+ if !resolutions.contains(head) || (head != finishing && taken.contains(head)) {
+ continue;
+ }
+ let others: Vec<&str> = heads
+ .iter()
+ .filter(|h| *h != head)
+ .map(String::as_str)
+ .collect();
+ let uncovered =
+ self.log_ids(&format!("parents({head}) ~ ::({})", ids_revset(&others)))?;
+ if uncovered.is_empty() {
+ superseded.push(head.clone());
+ }
+ }
+ Ok(superseded)
+ }
+
+ /// Adds a task to resolve the done node's conflicts. A conflicted parent
+ /// is an unresolved resolution task, whose own resolution will be checked
+ /// again when it's done.
+ fn add_resolution_task(&self) -> Result<Option<String>> {
+ let conflicted =
+ self.jj(&["log", "--no-graph", "-r", &self.done_node, "-T", "conflict"])?;
+ if conflicted != "true" {
+ return Ok(None);
+ }
+ let parents_revset = format!("parents({})", self.done_node);
+ if !self
+ .log_ids(&format!("{parents_revset} & conflicts()"))?
+ .is_empty()
+ {
+ return Ok(None);
+ }
+
+ let parents = self.log_ids(&parents_revset)?;
+ let parent_refs: Vec<&str> = parents.iter().map(String::as_str).collect();
+ let titles = self.jj(&[
+ "log",
+ "--no-graph",
+ "-r",
+ &ids_revset(&parent_refs),
+ "-T",
+ r#"description.first_line() ++ "\n""#,
+ ])?;
+ let list = ["resolve", "--list", "-r", &self.done_node];
+ let files = jj_allow_failure(Some(&self.main), self.snapshot, &list)?.stdout;
+ let message = message(
+ &format!(
+ "Resolve conflicts between {}",
+ titles.lines().collect::<Vec<_>>().join(", ")
+ ),
+ Some(&format!(
+ "These finished tasks conflict when merged:\n\n{}",
+ files.trim_end()
+ )),
+ );
+ let mut args = vec!["new", "--no-edit"];
+ for parent in &parent_refs {
+ args.extend(["-A", parent]);
+ }
+ args.extend(["-B", &self.done_node, "-m", &message]);
+ let new = self.jj_in(&self.main, &args)?;
+ created_id(&new.stderr, &self.main, self.snapshot).map(Some)
+ }
+
+ /// The finished work merged cleanly, but conflicts with the integration
+ /// node's other parents.
+ fn warn_integration_conflicts(&self) -> Result<()> {
+ let conflicted =
+ self.jj(&["log", "--no-graph", "-r", &self.integrate, "-T", "conflict"])?;
+ if conflicted == "true" {
+ eprintln!(
+ "{} has conflicts between the finished tasks and its other parents",
+ self.integrate
+ );
+ }
+ Ok(())
+ }
+
+ pub(crate) fn state(&self, id: &str) -> Result<State> {
+ self.tasks()?
+ .into_iter()
+ .find(|t| t.id == id)
+ .map(|t| t.state)
+ .ok_or_else(|| Error::msg(format!("{id} isn't a task")))
+ }
+
+ /// Runs WORK holding the home directory's lock, so concurrent jeans
+ /// commands change the graph one at a time.
+ fn locked<T>(&self, work: impl FnOnce() -> Result<T>) -> Result<T> {
+ let lock = fs_err::OpenOptions::new()
+ .read(true)
+ .write(true)
+ .create(true)
+ .truncate(false)
+ .open(self.home.join("lock"))?;
+ lock.file().lock()?;
+ work()
+ }
+}
diff --git a/src/error.rs b/src/error.rs
new file mode 100644
index 0000000..e884662
--- /dev/null
+++ b/src/error.rs
@@ -0,0 +1,20 @@
+/// Everything that stops a jeans command. The CLI prints it after `jeans: `.
+#[derive(Debug, thiserror::Error)]
+pub enum Error {
+ #[error("{0}")]
+ Message(String),
+ #[error(transparent)]
+ Io(#[from] std::io::Error),
+ #[error("jj printed output that isn't UTF-8: {0}")]
+ Utf8(#[from] std::string::FromUtf8Error),
+ #[error("{} isn't a UTF-8 path", .0.as_path().display())]
+ Path(#[from] camino::FromPathBufError),
+}
+
+pub type Result<T> = std::result::Result<T, Error>;
+
+impl Error {
+ pub(crate) fn msg(message: impl Into<String>) -> Self {
+ Self::Message(message.into())
+ }
+}
diff --git a/src/graph.rs b/src/graph.rs
new file mode 100644
index 0000000..1e791bb
--- /dev/null
+++ b/src/graph.rs
@@ -0,0 +1,359 @@
+use camino::Utf8Path;
+use camino::Utf8PathBuf;
+use std::collections::HashSet;
+
+use crate::Error;
+use crate::Result;
+use crate::color::Paint;
+use crate::color::paint;
+use crate::init::bookmark_revset;
+use crate::init::done_bookmark;
+use crate::init::goal_bookmark;
+use crate::init::goals;
+use crate::jj;
+use crate::message::short;
+
+const LEGACY_GOAL: &str = "jeans-goal";
+const WORKSPACE_PREFIX: &str = "jeans-";
+
+/// A repo's jeans setup and the goal a command works on.
+pub(crate) struct Jeans {
+ pub(crate) color: bool,
+ pub(crate) snapshot: bool,
+ pub(crate) main: Utf8PathBuf,
+ pub(crate) home: Utf8PathBuf,
+ pub(crate) integrate: String,
+ pub(crate) goal: Option<String>,
+ pub(crate) goal_revset: String,
+ /// A task is done once it's an ancestor of the done node. The node is a
+ /// parent of the integration node, so the human's checkout holds all the
+ /// finished work.
+ pub(crate) done_node: String,
+ /// Conflict resolution tasks hang under the done node, outside the goal.
+ pub(crate) tasks_revset: String,
+}
+
+/// A task commit: one between trunk and the goal or the done node.
+pub(crate) struct Task {
+ pub(crate) id: String,
+ pub(crate) parents: Vec<String>,
+ pub(crate) conflict: bool,
+ pub(crate) title: String,
+ pub(crate) state: State,
+}
+
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+pub(crate) enum State {
+ Ready,
+ Claimed,
+ Blocked,
+ Done,
+}
+
+pub(crate) const STATES: [State; 4] = [State::Ready, State::Claimed, State::Blocked, State::Done];
+
+impl State {
+ pub(crate) fn name(self) -> &'static str {
+ match self {
+ Self::Ready => "ready",
+ Self::Claimed => "claimed",
+ Self::Blocked => "blocked",
+ Self::Done => "done",
+ }
+ }
+
+ pub(crate) fn paint(self) -> Paint {
+ match self {
+ Self::Ready => Paint::Ready,
+ Self::Claimed => Paint::Claimed,
+ Self::Blocked => Paint::Blocked,
+ Self::Done => Paint::Done,
+ }
+ }
+}
+
+impl Jeans {
+ /// GOAL is the --goal flag. Without it, the goal is the one that HINT, a
+ /// task from the command line, feeds; else the one the current
+ /// workspace's task feeds; else the repo's only goal.
+ pub(crate) fn new(
+ color: bool,
+ snapshot: bool,
+ goal: Option<&str>,
+ hint: Option<&str>,
+ ) -> Result<Self> {
+ let main = Utf8PathBuf::from(config(None, snapshot, "jeans.main")?);
+ let home = Utf8PathBuf::from(config(Some(&main), snapshot, "jeans.home")?);
+ let mut jeans = Self {
+ color,
+ snapshot,
+ main,
+ home,
+ integrate: String::new(),
+ goal: None,
+ goal_revset: "none()".to_owned(),
+ done_node: "none()".to_owned(),
+ tasks_revset: String::new(),
+ };
+ if jeans.legacy()? {
+ return Err(Error::msg(format!(
+ "{LEGACY_GOAL} is a goal from an older jeans; \
+ see \"Upgrading a goal from before named goals\" in the README"
+ )));
+ }
+ jeans.integrate = jeans.config("jeans.integrate")?;
+ jeans.goal = jeans.pick_goal(goal, hint)?;
+ if let Some(goal) = &jeans.goal {
+ jeans.goal_revset = bookmark_revset(&goal_bookmark(goal));
+ jeans.done_node = bookmark_revset(&done_bookmark(goal));
+ }
+ jeans.tasks_revset = format!(
+ "(trunk()..({} | {})) ~ {}",
+ jeans.goal_revset, jeans.done_node, jeans.done_node
+ );
+ Ok(jeans)
+ }
+
+ pub(crate) fn team_size(&self) -> Result<i64> {
+ let size = self.config("jeans.team-size")?;
+ size.parse()
+ .map_err(|_| Error::msg(format!("jeans.team-size is {size}, not a number")))
+ }
+
+ /// Every task in jj log order, each with its state.
+ pub(crate) fn tasks(&self) -> Result<Vec<Task>> {
+ let template = [
+ "change_id",
+ r#"parents.map(|p| p.change_id()).join(",")"#,
+ "conflict",
+ "description.first_line()",
+ ]
+ .join(r#" ++ "\t" ++ "#)
+ + r#" ++ "\n""#;
+ let out = self.jj(&[
+ "log",
+ "--no-graph",
+ "-r",
+ &self.tasks_revset,
+ "-T",
+ &template,
+ ])?;
+ let done = self.done_ids()?;
+ let taken = self.claimed()?;
+
+ let mut tasks: Vec<Task> = Vec::new();
+ for line in out.lines() {
+ let mut fields = line.splitn(4, '\t');
+ let mut field = || fields.next().unwrap_or_default().to_owned();
+ let id = field();
+ let parents = field();
+ let conflict = field() == "true";
+ let title = field();
+ tasks.push(Task {
+ state: if done.contains(&id) {
+ State::Done
+ } else {
+ State::Ready
+ },
+ parents: parents
+ .split(',')
+ .filter(|p| !p.is_empty())
+ .map(str::to_owned)
+ .collect(),
+ id,
+ conflict,
+ title,
+ });
+ }
+
+ let unfinished: HashSet<String> = tasks
+ .iter()
+ .filter(|t| t.state != State::Done)
+ .map(|t| t.id.clone())
+ .collect();
+ for task in &mut tasks {
+ if task.state == State::Done {
+ continue;
+ }
+ task.state = if taken.contains(&task.id) {
+ State::Claimed
+ } else if task.parents.iter().any(|p| unfinished.contains(p)) {
+ State::Blocked
+ } else {
+ State::Ready
+ };
+ }
+ Ok(tasks)
+ }
+
+ /// The IDs of the claimed tasks, from their workspace names.
+ pub(crate) fn claimed(&self) -> Result<Vec<String>> {
+ let out = self.jj(&["workspace", "list", "-T", r#"name ++ "\n""#])?;
+ Ok(out
+ .lines()
+ .filter_map(|name| name.strip_prefix(WORKSPACE_PREFIX))
+ .map(str::to_owned)
+ .collect())
+ }
+
+ pub(crate) fn state_label(&self, state: State) -> String {
+ paint(self.color, &format!("[{}]", state.name()), state.paint())
+ }
+
+ pub(crate) fn paint(&self, text: &str, key: Paint) -> String {
+ paint(self.color, text, key)
+ }
+
+ pub(crate) fn resolve(&self, rev: &str) -> Result<String> {
+ let out = self.jj(&["log", "--no-graph", "-r", rev, "-T", r#"change_id ++ "\n""#])?;
+ match out.lines().collect::<Vec<_>>().as_slice() {
+ [id] => Ok((*id).to_owned()),
+ ids => Err(Error::msg(format!(
+ "{rev} resolves to {} commits",
+ ids.len()
+ ))),
+ }
+ }
+
+ /// The task whose workspace jeans is running in, if any.
+ pub(crate) fn current_task(&self) -> Result<Option<String>> {
+ let root = jj::jj(None, self.snapshot, &["root"])?.stdout;
+ let here = fs_err::canonicalize(root.trim())?;
+ for id in self.claimed()? {
+ let path = self.workspace_path(&id);
+ if path.exists() && fs_err::canonicalize(&path)? == here {
+ return Ok(Some(id));
+ }
+ }
+ Ok(None)
+ }
+
+ pub(crate) fn done_ids(&self) -> Result<HashSet<String>> {
+ Ok(self
+ .log_ids(&format!(
+ "::{} & ({}) ~ conflicts()",
+ self.done_node, self.tasks_revset
+ ))?
+ .into_iter()
+ .collect())
+ }
+
+ pub(crate) fn log_ids(&self, revset: &str) -> Result<Vec<String>> {
+ let out = self.jj(&[
+ "log",
+ "--no-graph",
+ "-r",
+ revset,
+ "-T",
+ r#"change_id ++ "\n""#,
+ ])?;
+ Ok(out.lines().map(str::to_owned).collect())
+ }
+
+ pub(crate) fn workspace_name(id: &str) -> String {
+ format!("{WORKSPACE_PREFIX}{id}")
+ }
+
+ pub(crate) fn workspace_path(&self, id: &str) -> Utf8PathBuf {
+ self.home.join(id)
+ }
+
+ /// Runs jj in the main repo and returns its stdout.
+ pub(crate) fn jj(&self, args: &[&str]) -> Result<String> {
+ Ok(jj::jj(Some(&self.main), self.snapshot, args)?.stdout)
+ }
+
+ pub(crate) fn jj_in(&self, repo: &Utf8Path, args: &[&str]) -> Result<jj::Output> {
+ jj::jj(Some(repo), self.snapshot, args)
+ }
+
+ fn config(&self, key: &str) -> Result<String> {
+ config(Some(&self.main), self.snapshot, key)
+ }
+
+ /// A goal still in progress whose done node is the main workspace's
+ /// working copy.
+ fn legacy(&self) -> Result<bool> {
+ if self.config("jeans.workspace").is_err() {
+ return Ok(false);
+ }
+ Ok(!self.log_ids(&bookmark_revset(LEGACY_GOAL))?.is_empty())
+ }
+
+ fn pick_goal(&self, name: Option<&str>, hint: Option<&str>) -> Result<Option<String>> {
+ let names = goals(&self.main, self.snapshot)?;
+ if let Some(name) = name {
+ if !names.iter().any(|n| n == name) {
+ return Err(Error::msg(format!(
+ "there's no goal named {name}; the goals are {}",
+ list(&names)
+ )));
+ }
+ return Ok(Some(name.to_owned()));
+ }
+
+ let hint = hint.map(|rev| self.resolve(rev)).transpose()?;
+ let current = self.current_task()?;
+ for task in hint.iter().chain(current.iter()) {
+ let mut owners = Vec::new();
+ for name in &names {
+ if !self
+ .log_ids(&format!("{task} & ::{}", goal_heads(name)))?
+ .is_empty()
+ {
+ owners.push(name.clone());
+ }
+ }
+ if owners.len() > 1 {
+ return Err(Error::msg(format!(
+ "{} feeds goals {}; pick one with --goal NAME",
+ short(task, 8),
+ list(&owners)
+ )));
+ }
+ if let Some(owner) = owners.pop() {
+ return Ok(Some(owner));
+ }
+ }
+ if names.len() > 1 {
+ return Err(Error::msg(format!(
+ "this repo has goals {}; pick one with --goal NAME",
+ list(&names)
+ )));
+ }
+ Ok(names.into_iter().next())
+ }
+}
+
+pub(crate) fn ids_revset(ids: &[&str]) -> String {
+ if ids.is_empty() {
+ "none()".to_owned()
+ } else {
+ ids.join(" | ")
+ }
+}
+
+fn config(repo: Option<&Utf8Path>, snapshot: bool, key: &str) -> Result<String> {
+ match jj::jj(repo, snapshot, &["config", "get", key]) {
+ Ok(out) => Ok(out.stdout.trim().to_owned()),
+ Err(_) => Err(Error::msg(format!(
+ "{key} isn't set; run `jeans init` in the repository first"
+ ))),
+ }
+}
+
+fn goal_heads(name: &str) -> String {
+ format!(
+ "({} | {})",
+ bookmark_revset(&goal_bookmark(name)),
+ bookmark_revset(&done_bookmark(name))
+ )
+}
+
+fn list(names: &[String]) -> String {
+ if names.is_empty() {
+ "none".to_owned()
+ } else {
+ names.join(", ")
+ }
+}
diff --git a/src/init.rs b/src/init.rs
new file mode 100644
index 0000000..90e7fec
--- /dev/null
+++ b/src/init.rs
@@ -0,0 +1,151 @@
+use camino::Utf8Path;
+use camino::Utf8PathBuf;
+
+use crate::Error;
+use crate::Result;
+use crate::jj::jj;
+use crate::message::created_commit;
+use crate::message::message;
+
+/// Each goal NAME has the bookmarks jeans/NAME/goal and jeans/NAME/done.
+const GOALS: &str = "glob:jeans/*/goal";
+const MEGAMERGE: &str = r#"bookmarks(exact:"mm")"#;
+
+/// What `jeans init` needs to make a goal.
+pub(crate) struct Init<'a> {
+ pub(crate) title: &'a str,
+ pub(crate) goal: Option<&'a str>,
+ pub(crate) body: Option<&'a str>,
+ pub(crate) team_size: i64,
+ pub(crate) home: Option<&'a str>,
+}
+
+/// Makes the goal commit and its done node, and returns the goal's change ID.
+pub(crate) fn init(init: &Init<'_>) -> Result<String> {
+ let goal = init.goal.filter(|g| is_goal_name(g)).ok_or_else(|| {
+ Error::msg("init needs --goal NAME, made of letters, digits, '.', '_', and '-'")
+ })?;
+
+ let root = Utf8PathBuf::from(jj(None, true, &["root"])?.stdout.trim());
+ let run = |args: &[&str]| jj(Some(&root), true, args);
+ if goals(&root, true)?.iter().any(|g| g == goal) {
+ return Err(Error::msg(format!(
+ "this repo already has a goal named {goal}"
+ )));
+ }
+
+ let home = match init.home {
+ Some(home) => Utf8PathBuf::from(home),
+ None => root.with_file_name(format!("{}.jeans", root.file_name().unwrap_or_default())),
+ };
+ let home = Utf8PathBuf::try_from(std::path::absolute(&home)?)?;
+ fs_err::create_dir_all(&home)?;
+ let team_size = init.team_size.to_string();
+ for (key, value) in [
+ ("jeans.main", root.as_str()),
+ ("jeans.home", home.as_str()),
+ ("jeans.team-size", &team_size),
+ ] {
+ run(&["config", "set", "--repo", key, value])?;
+ }
+
+ let goal_message = message(init.title, init.body);
+ let new = run(&["new", "--no-edit", "trunk()", "-m", &goal_message])?;
+ let id = created_id(&new.stderr, &root, true)?;
+ run(&["bookmark", "create", &goal_bookmark(goal), "-r", &id])?;
+
+ let integrate = integration_node(&root)?;
+ run(&["config", "set", "--repo", "jeans.integrate", &integrate])?;
+ // Branching from the trunk the integration node already holds keeps newer
+ // trunk commits out of it until finished tasks bring them in.
+ let base = format!("heads(::({integrate}) & ::trunk())");
+ let done_message = format!("Finished tasks for: {}", init.title);
+ let new = run(&[
+ "new",
+ "--no-edit",
+ "-A",
+ &base,
+ "-B",
+ &integrate,
+ "-m",
+ &done_message,
+ ])?;
+ let done = created_id(&new.stderr, &root, true)?;
+ run(&["bookmark", "create", &done_bookmark(goal), "-r", &done])?;
+ Ok(id)
+}
+
+/// The names of the repo's goals, in bookmark order.
+pub(crate) fn goals(repo: &Utf8Path, snapshot: bool) -> Result<Vec<String>> {
+ let args = ["bookmark", "list", GOALS, "-T", r#"name ++ "\n""#];
+ let out = jj(Some(repo), snapshot, &args)?;
+ let mut names: Vec<String> = Vec::new();
+ for line in out.stdout.lines() {
+ let name = line.strip_prefix("jeans/").unwrap_or(line);
+ let name = name.strip_suffix("/goal").unwrap_or(name);
+ if !names.iter().any(|n| n == name) {
+ names.push(name.to_owned());
+ }
+ }
+ Ok(names)
+}
+
+/// The full change ID of the commit jj's stderr says it created.
+pub(crate) fn created_id(stderr: &str, repo: &Utf8Path, snapshot: bool) -> Result<String> {
+ let Some(short) = created_commit(stderr) else {
+ // cov-excl-start
+ return Err(Error::msg(format!(
+ "couldn't find the new commit in:\n{stderr}"
+ )));
+ // cov-excl-stop
+ };
+ let args = ["log", "--no-graph", "-r", short, "-T", "change_id"];
+ let out = jj(Some(repo), snapshot, &args)?;
+ Ok(out.stdout.trim().to_owned())
+}
+
+pub(crate) fn goal_bookmark(name: &str) -> String {
+ format!("jeans/{name}/goal")
+}
+
+pub(crate) fn done_bookmark(name: &str) -> String {
+ format!("jeans/{name}/done")
+}
+
+/// Matches nothing once the bookmark is gone, where a bare name would fail.
+pub(crate) fn bookmark_revset(bookmark: &str) -> String {
+ format!(r#"bookmarks(exact:"{bookmark}")"#)
+}
+
+/// Finished work goes into the megamerge when there is one, and otherwise
+/// under the main workspace's working copy.
+fn integration_node(root: &Utf8Path) -> Result<String> {
+ let run = |args: &[&str]| jj(Some(root), true, args);
+ let mm = run(&["log", "--no-graph", "-r", MEGAMERGE, "-T", "change_id"])?;
+ if !mm.stdout.trim().is_empty() {
+ return Ok(MEGAMERGE.to_owned());
+ }
+ let current = r#"if(target.current_working_copy(), name ++ "\n")"#;
+ let workspace = run(&["workspace", "list", "-T", current])?;
+ Ok(format!("{}@", workspace.stdout.trim()))
+}
+
+/// Letters, digits, '.', '_', and '-', starting with a letter or digit.
+fn is_goal_name(name: &str) -> bool {
+ let mut chars = name.chars();
+ chars.next().is_some_and(|c| c.is_ascii_alphanumeric())
+ && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn goal_names_start_with_a_letter_or_digit() {
+ assert!(is_goal_name("a1._-"));
+ assert!(!is_goal_name(""));
+ assert!(!is_goal_name("-a"));
+ assert!(!is_goal_name("a/b"));
+ }
+}
diff --git a/src/jj.rs b/src/jj.rs
new file mode 100644
index 0000000..a1e5188
--- /dev/null
+++ b/src/jj.rs
@@ -0,0 +1,62 @@
+use camino::Utf8Path;
+use std::process::Command;
+
+use crate::Error;
+use crate::Result;
+
+/// What a jj command printed.
+pub(crate) struct Output {
+ pub(crate) stdout: String,
+ pub(crate) stderr: String,
+}
+
+/// Runs jj, failing with its stderr when it exits non-zero.
+///
+/// Without `snapshot`, jj leaves the working copy alone, so read-only
+/// commands record no operation.
+pub(crate) fn jj(repo: Option<&Utf8Path>, snapshot: bool, args: &[&str]) -> Result<Output> {
+ let (output, success, flags) = run(repo, snapshot, args)?;
+ if success {
+ Ok(output)
+ } else {
+ Err(Error::msg(format!(
+ "{flags}{} failed:\n{}",
+ args.join(" "),
+ output.stderr
+ )))
+ }
+}
+
+/// Runs jj and returns its output whether or not it succeeded.
+pub(crate) fn jj_allow_failure(
+ repo: Option<&Utf8Path>,
+ snapshot: bool,
+ args: &[&str],
+) -> Result<Output> {
+ Ok(run(repo, snapshot, args)?.0)
+}
+
+fn run(repo: Option<&Utf8Path>, snapshot: bool, args: &[&str]) -> Result<(Output, bool, String)> {
+ let mut flags = Vec::new();
+ if !snapshot {
+ flags.push("--ignore-working-copy");
+ }
+ if let Some(repo) = repo {
+ flags.extend(["-R", repo.as_str()]);
+ }
+ // Finishing a task from its workspace rewrites the main working copy, so
+ // the main workspace is stale on its next command unless jj updates it.
+ let out = Command::new("jj")
+ .args(["--no-pager", "--color=never"])
+ .args(["--config", "snapshot.auto-update-stale=true"])
+ .args(&flags)
+ .args(args)
+ .output()?;
+ let output = Output {
+ stdout: String::from_utf8(out.stdout)?,
+ stderr: String::from_utf8(out.stderr)?,
+ };
+ // Matches the Ruby error text: the flags after --color, then the args.
+ let flags = flags.iter().map(|f| format!("{f} ")).collect();
+ Ok((output, out.status.success(), flags))
+}
diff --git a/src/lib.rs b/src/lib.rs
index 038a28a..cfeaaeb 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -9,49 +9,20 @@
)
)]
-/// The command list `jeans` prints when run with no arguments.
-pub const USAGE: &str = "\
-usage: jeans <command> [args] [--goal NAME] [--color WHEN]
+mod cli;
+mod color;
+mod commands;
+mod error;
+mod graph;
+mod init;
+mod jj;
+mod message;
+mod usage;
+mod views;
- init TITLE --goal NAME [-m BODY] [--team N] [--home DIR]
- add TITLE [-m BODY] [--before TASK] [--after TASK]...
- ready
- log [VIEW]
- status
- tree [TASK] [--depth N]
- board [TASK]
- watch [tree|board] [TASK] [--depth N]
- show TASK
- describe TASK -m MESSAGE
- claim TASK
- done TASK -m MESSAGE
- release TASK
- team-size
-";
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn usage_lists_every_command() {
- for command in [
- "init",
- "add",
- "ready",
- "log",
- "status",
- "tree",
- "board",
- "watch",
- "show",
- "describe",
- "claim",
- "done",
- "release",
- "team-size",
- ] {
- assert!(USAGE.contains(&format!(" {command}")), "missing {command}");
- }
- }
-}
+pub use cli::run;
+pub use color::color_enabled;
+pub use error::Error;
+pub use error::Result;
+pub use message::finished_message;
+pub use usage::USAGE;
diff --git a/src/message.rs b/src/message.rs
new file mode 100644
index 0000000..20a495b
--- /dev/null
+++ b/src/message.rs
@@ -0,0 +1,166 @@
+/// A commit message: the title, then the body as its own paragraph.
+pub(crate) fn message(title: &str, body: Option<&str>) -> String {
+ match body {
+ Some(body) => format!("{title}\n\n{body}"),
+ None => title.to_owned(),
+ }
+}
+
+/// The finished task's description. The commit message leads and its
+/// trailers stay last, so they still parse as trailers, with the task's
+/// spec kept between them under a `Task:` line.
+pub fn finished_message(message: &str, spec: &str) -> String {
+ let mut paragraphs = paragraphs(message.trim());
+ let trailers = match paragraphs.as_slice() {
+ [_, .., last] if is_trailers(last) => paragraphs.pop(),
+ _ => None,
+ };
+ let (title, body) = match spec.trim().split_once('\n') {
+ Some((title, body)) => (title, Some(body)),
+ None => (spec.trim(), None),
+ };
+ let mut parts: Vec<String> = paragraphs.into_iter().map(str::to_owned).collect();
+ parts.push(format!("Task: {title}"));
+ parts.extend(body.map(|body| indent(body.trim())));
+ parts.extend(trailers.map(str::to_owned));
+ parts.join("\n\n")
+}
+
+// Splits trimmed text on runs of two or more newlines.
+fn paragraphs(text: &str) -> Vec<&str> {
+ let mut pieces = Vec::new();
+ if text.is_empty() {
+ return pieces;
+ }
+ let mut rest = text;
+ while let Some(start) = rest.find("\n\n") {
+ let (piece, tail) = rest.split_at(start);
+ pieces.push(piece);
+ rest = tail.trim_start_matches('\n');
+ }
+ pieces.push(rest);
+ pieces
+}
+
+fn is_trailers(paragraph: &str) -> bool {
+ let mut lines = paragraph.lines();
+ lines.next().is_some_and(is_trailer) && lines.all(|l| is_trailer(l) || is_continuation(l))
+}
+
+/// `Key: value`, where the key is letters, digits, and dashes.
+fn is_trailer(line: &str) -> bool {
+ let key_end = line
+ .find(|c: char| !(c.is_ascii_alphanumeric() || c == '-'))
+ .unwrap_or(line.len());
+ key_end > 0
+ && line
+ .get(key_end..)
+ .and_then(|rest| rest.strip_prefix(": "))
+ .and_then(|value| value.chars().next())
+ .is_some_and(|c| !c.is_whitespace())
+}
+
+/// A wrapped trailer value: indented, then text.
+fn is_continuation(line: &str) -> bool {
+ let text = line.trim_start();
+ text.len() < line.len() && text.chars().next().is_some_and(|c| !c.is_whitespace())
+}
+
+fn indent(text: &str) -> String {
+ text.split_inclusive('\n')
+ .map(|line| {
+ if line.trim().is_empty() {
+ "\n".to_owned()
+ } else {
+ format!(" {line}")
+ }
+ })
+ .collect()
+}
+
+/// The short ID in jj's "Created new commit" line.
+pub(crate) fn created_commit(stderr: &str) -> Option<&str> {
+ let (_, rest) = stderr.split_once("Created new commit ")?;
+ let end = rest
+ .find(|c: char| !(c.is_alphanumeric() || c == '_'))
+ .unwrap_or(rest.len());
+ rest.get(..end).filter(|id| !id.is_empty())
+}
+
+/// The first `len` characters of a change ID.
+pub(crate) fn short(id: &str, len: usize) -> &str {
+ id.get(..len).unwrap_or(id)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn message_puts_the_body_after_a_blank_line() {
+ assert_eq!(message("T", None), "T");
+ assert_eq!(message("T", Some("b")), "T\n\nb");
+ }
+
+ #[test]
+ fn finished_message_keeps_trailers_last() {
+ assert_eq!(
+ finished_message(
+ "area: do A\n\nBecause.\n\nAssisted-by: Claude\nSigned-off-by: Someone\n",
+ "A\n\n- one\n- two\n\nthen three\n"
+ ),
+ "area: do A\n\nBecause.\n\nTask: A\n\n - one\n - two\n\n then three\n\nAssisted-by: Claude\nSigned-off-by: Someone"
+ );
+ }
+
+ #[test]
+ fn an_empty_message_leaves_only_the_spec() {
+ assert_eq!(finished_message("", "A"), "Task: A");
+ }
+
+ #[test]
+ fn a_lone_paragraph_is_never_trailers() {
+ assert_eq!(
+ finished_message("Key: value", "A\n"),
+ "Key: value\n\nTask: A"
+ );
+ }
+
+ #[test]
+ fn trailers_may_wrap() {
+ assert_eq!(
+ finished_message("do A\n\nKey: one\n two\n\n\n", "A"),
+ "do A\n\nTask: A\n\nKey: one\n two"
+ );
+ }
+
+ #[test]
+ fn a_list_isnt_trailers() {
+ assert_eq!(
+ finished_message("do A\n\n- a list\n wrapped", "A\n"),
+ "do A\n\n- a list\n wrapped\n\nTask: A"
+ );
+ assert!(!is_trailer("Key:value"));
+ assert!(!is_trailer(": value"));
+ assert!(!is_trailer("Key: value"));
+ assert!(!is_continuation("text"));
+ assert!(!is_continuation(" "));
+ }
+
+ #[test]
+ fn created_commit_finds_the_short_id() {
+ assert_eq!(
+ created_commit("Created new commit abcd 1234 (empty) T\n"),
+ Some("abcd")
+ );
+ assert_eq!(created_commit("Created new commit abcd"), Some("abcd"));
+ assert_eq!(created_commit("Created new commit x"), None);
+ assert_eq!(created_commit("nothing"), None);
+ }
+
+ #[test]
+ fn short_truncates_only_long_ids() {
+ assert_eq!(short("abcdefghij", 8), "abcdefgh");
+ assert_eq!(short("abc", 8), "abc");
+ }
+}
diff --git a/src/usage.rs b/src/usage.rs
new file mode 100644
index 0000000..8928669
--- /dev/null
+++ b/src/usage.rs
@@ -0,0 +1,63 @@
+/// The command list `jeans` prints when it doesn't know the command.
+pub const USAGE: &str = "\
+usage: jeans <command> [args] [--goal NAME] [--color WHEN]
+
+ init TITLE --goal NAME [-m BODY] [--team N] [--home DIR]
+ make the goal commit
+ add TITLE [-m BODY] [--before TASK] [--after TASK]...
+ insert a task before TASK (default: the goal)
+ ready list ready task IDs
+ log [VIEW] jj log of the tasks, each with its state; VIEW is one of
+ ready, claimed, blocked, done, open (not done),
+ under TASK (TASK and what feeds it),
+ path TASK (TASK up to the goal), or a revset
+ status same as log with no VIEW
+ tree [TASK] [--depth N] an outline from TASK (default: the goal) down,
+ collapsing done subtrees and anything past N levels
+ board [TASK] one section per state, for TASK and what feeds it
+ watch [tree|board] [TASK] [--depth N] redraw tree (the default) or board whenever the graph changes
+ show TASK a task's state, workspace, and description
+ describe TASK -m MESSAGE replace a task's description
+ claim TASK make TASK's workspace; prints its path
+ done TASK -m MESSAGE squash the workspace in, prepend MESSAGE to the
+ task's description, mark done, drop it
+ release TASK squash the workspace in and drop it, not done
+ team-size how many developers may run at once
+
+--goal NAME picks the goal. Without it, a command uses the goal its TASK
+feeds, then the goal the current workspace's task feeds, then the repo's
+only goal.
+
+--color WHEN is always, never, or auto (the default), which colors output
+only when it goes to a terminal and NO_COLOR is unset.
+";
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn usage_lists_every_command() {
+ for command in [
+ "init",
+ "add",
+ "ready",
+ "log",
+ "status",
+ "tree",
+ "board",
+ "watch",
+ "show",
+ "describe",
+ "claim",
+ "done",
+ "release",
+ "team-size",
+ ] {
+ assert!(
+ USAGE.contains(&format!("\n {command}")),
+ "missing {command}"
+ );
+ }
+ }
+}
diff --git a/src/views.rs b/src/views.rs
new file mode 100644
index 0000000..61598e4
--- /dev/null
+++ b/src/views.rs
@@ -0,0 +1,291 @@
+use std::collections::HashMap;
+use std::collections::HashSet;
+use std::sync::Arc;
+use std::sync::atomic::AtomicBool;
+use std::sync::atomic::Ordering;
+use std::time::Duration;
+use std::time::Instant;
+
+use crate::Error;
+use crate::Result;
+use crate::color::Paint;
+use crate::graph::Jeans;
+use crate::graph::STATES;
+use crate::graph::State;
+use crate::graph::Task;
+use crate::graph::ids_revset;
+use crate::message::short;
+
+const LOG_TEMPLATE: &str = r#"change_id.short(12) ++ " " ++ description.first_line() ++ "\n""#;
+
+impl Jeans {
+ pub(crate) fn ready(&self) -> Result<Vec<String>> {
+ Ok(self
+ .tasks()?
+ .into_iter()
+ .filter(|t| t.state == State::Ready)
+ .map(|t| t.id)
+ .collect())
+ }
+
+ /// `jj log` of the tasks in VIEW, each ID followed by its state.
+ pub(crate) fn log(&self, view: Option<&str>, task: Option<&str>) -> Result<String> {
+ let tasks = self.tasks()?;
+ let ids_in = |keep: &dyn Fn(State) -> bool| {
+ let ids: Vec<&str> = tasks
+ .iter()
+ .filter(|t| keep(t.state))
+ .map(|t| t.id.as_str())
+ .collect();
+ ids_revset(&ids)
+ };
+ let revset = match view {
+ None => format!("{} | trunk()", self.tasks_revset),
+ Some("open") => ids_in(&|s| s != State::Done),
+ Some("under") => format!(
+ "::{} & ({})",
+ self.resolve_view_task(task)?,
+ self.tasks_revset
+ ),
+ Some("path") => format!("{}::{}", self.resolve_view_task(task)?, self.goal_revset),
+ Some(view) => match STATES.into_iter().find(|s| s.name() == view) {
+ Some(state) => ids_in(&|s| s == state),
+ None => format!("({view}) & ({})", self.tasks_revset),
+ },
+ };
+ let out = self.jj(&["log", "-r", &revset, "-T", LOG_TEMPLATE])?;
+ Ok(self.label_ids(&out, &tasks))
+ }
+
+ /// An outline with the goal at the root, followed by any resolution
+ /// tasks under the done node. Each task sits under the tasks it feeds. A
+ /// task feeding more than one other task is printed once and referenced
+ /// after. Everything feeding a done task is done too, so its subtree
+ /// collapses to a count.
+ pub(crate) fn tree(&self, root: Option<&str>, depth: Option<usize>) -> Result<String> {
+ let tasks = self.tasks()?;
+ let roots = match root {
+ Some(root) => vec![self.resolve(root)?],
+ None => {
+ let mut roots = self.log_ids(&self.goal_revset)?;
+ roots.extend(self.log_ids(&format!(
+ "heads(({}) ~ ::{})",
+ self.tasks_revset, self.goal_revset
+ ))?);
+ roots
+ }
+ };
+ let mut tree = Tree {
+ jeans: self,
+ by_id: tasks.iter().map(|t| (t.id.as_str(), t)).collect(),
+ depth,
+ lines: Vec::new(),
+ seen: HashSet::new(),
+ };
+ for id in &roots {
+ tree.visit(id, "", "", 0)?;
+ }
+ Ok(tree.lines.join("\n"))
+ }
+
+ /// One section per state, for ROOT and what feeds it.
+ pub(crate) fn board(&self, root: Option<&str>) -> Result<String> {
+ let tasks = self.tasks()?;
+ let by_id: HashMap<&str, &Task> = tasks.iter().map(|t| (t.id.as_str(), t)).collect();
+ let scope = match root {
+ Some(root) => {
+ let under = format!("::{} & ({})", self.resolve(root)?, self.tasks_revset);
+ self.log_ids(&under)?
+ }
+ None => tasks.iter().map(|t| t.id.clone()).collect(),
+ };
+ let mut sections = Vec::new();
+ for state in STATES {
+ let mut section = Vec::new();
+ for task in scope.iter().filter_map(|id| by_id.get(id.as_str())) {
+ if task.state == state {
+ section.push(format!(
+ " {} {}",
+ self.paint(short(&task.id, 8), Paint::Id),
+ task.title
+ ));
+ }
+ }
+ let heading = format!("{} ({})", state.name().to_uppercase(), section.len());
+ section.insert(0, self.paint(&heading, state.paint()));
+ sections.push(section.join("\n"));
+ }
+ Ok(sections.join("\n\n"))
+ }
+
+ /// Redraws VIEW whenever jj records an operation, until `stop` is set.
+ pub(crate) fn watch(
+ &self,
+ view: &str,
+ task: Option<&str>,
+ depth: Option<usize>,
+ stop: &Arc<AtomicBool>,
+ out: &mut impl std::io::Write,
+ ) -> Result<()> {
+ if view != "tree" && view != "board" {
+ return Err(Error::msg(format!("watch shows tree or board, not {view}")));
+ }
+ let interval = Duration::from_secs(1);
+ let mut last = None;
+ while !stop.load(Ordering::Relaxed) {
+ // A terminal's ^C also kills the jj child mid-call, which is no error.
+ if let Err(e) = self.redraw(view, task, depth, &mut last, out)
+ && !stop.load(Ordering::Relaxed)
+ {
+ return Err(e);
+ }
+ let deadline = Instant::now()
+ .checked_add(interval)
+ .unwrap_or_else(Instant::now);
+ while !stop.load(Ordering::Relaxed) && Instant::now() < deadline {
+ std::thread::sleep(Duration::from_millis(50));
+ }
+ }
+ Ok(())
+ }
+
+ /// Draws VIEW unless jj's latest operation is still LAST.
+ fn redraw(
+ &self,
+ view: &str,
+ task: Option<&str>,
+ depth: Option<usize>,
+ last: &mut Option<String>,
+ out: &mut impl std::io::Write,
+ ) -> Result<()> {
+ let op = self.jj(&["op", "log", "-n1", "--no-graph", "-T", "id"])?;
+ if last.as_ref() != Some(&op) {
+ let frame = if view == "board" {
+ self.board(task)?
+ } else {
+ self.tree(task, depth)?
+ };
+ writeln!(out, "\x1b[H\x1b[2J{frame}")?;
+ out.flush()?;
+ *last = Some(op);
+ }
+ Ok(())
+ }
+
+ /// A task's state, workspace, and description.
+ pub(crate) fn show(&self, rev: &str) -> Result<String> {
+ let id = self.resolve(rev)?;
+ let state = self.state(&id)?;
+ let description = self.jj(&["log", "--no-graph", "-r", &id, "-T", "description"])?;
+ Ok(format!(
+ "{}\n{}\n{description}",
+ self.paint(state.name(), state.paint()),
+ self.workspace_path(&id)
+ ))
+ }
+
+ fn resolve_view_task(&self, task: Option<&str>) -> Result<String> {
+ self.resolve(task.ok_or_else(|| Error::msg("log under and log path need TASK"))?)
+ }
+
+ /// Follows each task ID in jj's log output with the task's state.
+ fn label_ids(&self, out: &str, tasks: &[Task]) -> String {
+ let is_word = |c: char| c.is_alphanumeric() || c == '_';
+ let mut labeled = String::with_capacity(out.len());
+ let mut rest = out;
+ while let Some(start) = rest.find(is_word) {
+ let (before, from_word) = rest.split_at(start);
+ let end = from_word.find(|c| !is_word(c)).unwrap_or(from_word.len());
+ let (word, after) = from_word.split_at(end);
+ labeled.push_str(before);
+ if word.len() == 12 && word.bytes().all(|b| (b'k'..=b'z').contains(&b)) {
+ labeled.push_str(&self.paint(word, Paint::Id));
+ if let Some(task) = tasks.iter().find(|t| t.id.starts_with(word)) {
+ labeled.push(' ');
+ labeled.push_str(&self.state_label(task.state));
+ }
+ } else {
+ labeled.push_str(word);
+ }
+ rest = after;
+ }
+ labeled.push_str(rest);
+ labeled
+ }
+}
+
+struct Tree<'a> {
+ jeans: &'a Jeans,
+ by_id: HashMap<&'a str, &'a Task>,
+ depth: Option<usize>,
+ lines: Vec<String>,
+ seen: HashSet<String>,
+}
+
+impl<'a> Tree<'a> {
+ fn visit(&mut self, id: &str, lead: &str, branch: &str, level: usize) -> Result<()> {
+ let task = self.task(id)?;
+ let label = format!(
+ "{lead}{branch}{} {} {}",
+ self.jeans.paint(short(id, 8), Paint::Id),
+ task.title,
+ self.jeans.state_label(task.state)
+ );
+ let children = self.subtasks(task);
+ if self.seen.contains(id) {
+ self.lines.push(format!("{label} (see above)"));
+ } else if !children.is_empty() && (task.state == State::Done || Some(level) == self.depth) {
+ let mut below = HashSet::new();
+ self.count(task, &mut below);
+ let kind = if task.state == State::Done {
+ "done"
+ } else {
+ "more"
+ };
+ self.lines
+ .push(format!("{label} (+{} {kind})", below.len()));
+ } else {
+ self.lines.push(label);
+ self.seen.insert(id.to_owned());
+ let child_lead = match branch {
+ "├── " => format!("{lead}│ "),
+ "└── " => format!("{lead} "),
+ _ => lead.to_owned(),
+ };
+ let last = children.len().saturating_sub(1);
+ for (i, child) in children.iter().enumerate() {
+ let branch = if i == last {
+ "└── "
+ } else {
+ "├── "
+ };
+ self.visit(child, &child_lead, branch, level.saturating_add(1))?;
+ }
+ }
+ Ok(())
+ }
+
+ fn task(&self, id: &str) -> Result<&'a Task> {
+ self.by_id
+ .get(id)
+ .copied()
+ .ok_or_else(|| Error::msg(format!("{id} isn't a task")))
+ }
+
+ fn subtasks(&self, task: &Task) -> Vec<String> {
+ task.parents
+ .iter()
+ .filter(|p| self.by_id.contains_key(p.as_str()))
+ .cloned()
+ .collect()
+ }
+
+ fn count(&self, task: &Task, below: &mut HashSet<String>) {
+ for child in self.subtasks(task) {
+ if let Some(child_task) = self.by_id.get(child.as_str()).copied() {
+ self.count(child_task, below);
+ }
+ below.insert(child);
+ }
+ }
+}
diff --git a/tests/cli.rs b/tests/cli.rs
index 961a3c0..75abb30 100644
--- a/tests/cli.rs
+++ b/tests/cli.rs
@@ -1,10 +1,54 @@
-#![allow(clippy::unwrap_used)]
+#![allow(
+ clippy::unwrap_used,
+ clippy::panic,
+ clippy::indexing_slicing,
+ clippy::arithmetic_side_effects
+)]
-use std::process::Command;
+mod support;
+
+use std::ffi::OsStr;
+use std::os::unix::ffi::OsStrExt as _;
+
+use support::Sandbox;
+
+#[test]
+fn an_unknown_command_prints_the_command_list() {
+ let s = Sandbox::new();
+ for args in [&[][..], &["nope"][..]] {
+ let out = s.run_in(&s.repo, args);
+ assert!(!out.status.success());
+ assert_eq!(out.stdout, b"");
+ assert_eq!(String::from_utf8(out.stderr).unwrap(), jeans::USAGE);
+ }
+}
+
+#[test]
+fn commands_name_their_missing_arguments() {
+ let s = Sandbox::new();
+ assert_eq!(s.jeans_fails(["show"]), "jeans: show needs TASK");
+ assert_eq!(
+ s.jeans_fails(["init", "--goal", "x"]),
+ "jeans: init needs TITLE"
+ );
+ assert_eq!(
+ s.jeans_fails(["describe", &s.goal]),
+ "jeans: describe needs -m MESSAGE"
+ );
+ assert_eq!(
+ s.jeans_fails(["tree", "--depth"]),
+ "jeans: missing argument: --depth"
+ );
+}
#[test]
-fn no_arguments_prints_the_command_list() {
- let out = Command::new(env!("CARGO_BIN_EXE_jeans")).output().unwrap();
- assert!(out.status.success());
- assert_eq!(String::from_utf8(out.stdout).unwrap(), jeans::USAGE);
+fn arguments_must_be_utf8() {
+ let s = Sandbox::new();
+ let out = s.run_in(&s.repo, [OsStr::new("show"), OsStr::from_bytes(b"\xff")]);
+ assert!(!out.status.success());
+ assert!(
+ String::from_utf8(out.stderr)
+ .unwrap()
+ .contains("isn't UTF-8")
+ );
}
diff --git a/tests/edges.rs b/tests/edges.rs
new file mode 100644
index 0000000..04369fe
--- /dev/null
+++ b/tests/edges.rs
@@ -0,0 +1,243 @@
+//! Cases the Ruby suite doesn't cover: setup errors, odd revsets, and the
+//! less common paths through done.
+
+#![allow(
+ clippy::unwrap_used,
+ clippy::panic,
+ clippy::indexing_slicing,
+ clippy::arithmetic_side_effects
+)]
+
+mod support;
+
+use support::DONE;
+use support::Sandbox;
+use support::ids_in;
+
+#[test]
+fn an_uninitialized_repo_says_to_run_init() {
+ let s = Sandbox::bare("repo");
+ assert_eq!(
+ s.jeans_fails(["ready"]),
+ "jeans: jeans.main isn't set; run `jeans init` in the repository first"
+ );
+}
+
+#[test]
+fn init_defaults_home_beside_the_repo() {
+ let s = Sandbox::bare("repo");
+ s.jeans(["init", "T", "--goal", "g", "-m", "the body"]);
+ assert!(s.tmp.join("repo.jeans").is_dir());
+ assert_eq!(s.jeans(["team-size"]), "3");
+ assert_eq!(s.title(r#"bookmarks(exact:"jeans/g/goal")"#), "T");
+ assert_eq!(
+ s.description(r#"bookmarks(exact:"jeans/g/goal")"#),
+ "T\n\nthe body\n"
+ );
+}
+
+#[test]
+fn a_goal_from_an_older_jeans_is_refused() {
+ let s = Sandbox::new();
+ s.sh(["config", "set", "--repo", "jeans.workspace", "default"]);
+ assert_eq!(s.ready(), std::slice::from_ref(&s.goal));
+
+ s.sh(["bookmark", "create", "jeans-goal", "-r", "@"]);
+ assert!(
+ s.jeans_fails(["ready"])
+ .contains("jeans-goal is a goal from an older jeans")
+ );
+}
+
+#[test]
+fn a_team_size_must_be_a_number() {
+ let s = Sandbox::new();
+ s.sh(["config", "set", "--repo", "jeans.team-size", "lots"]);
+ assert_eq!(
+ s.jeans_fails(["team-size"]),
+ "jeans: jeans.team-size is lots, not a number"
+ );
+}
+
+#[test]
+fn a_finished_goal_leaves_nothing_to_add_to() {
+ let s = Sandbox::new();
+ s.claim(&s.goal);
+ s.finish(&s.goal);
+ assert_eq!(
+ s.jeans_fails(["add", "A"]),
+ "jeans: there's no goal to add to; run `jeans init` first"
+ );
+ assert!(
+ s.jeans_fails(["ready", "--goal", "nope"])
+ .ends_with("the goals are none")
+ );
+}
+
+#[test]
+fn revsets_must_name_one_task() {
+ let s = Sandbox::new();
+ s.jeans(["add", "A"]);
+ assert!(s.jeans_fails(["show", "all()"]).contains("resolves to"));
+ assert!(s.jeans_fails(["show", "nope("]).contains("failed:"));
+ assert!(s.jeans_fails(["show", "root()"]).ends_with("isn't a task"));
+ assert!(s.jeans_fails(["tree", "root()"]).ends_with("isn't a task"));
+ assert!(s.jeans_fails(["show", "@"]).ends_with("isn't a task"));
+ assert!(s.jeans_fails(["log", "under"]).contains("need TASK"));
+}
+
+#[test]
+fn log_views_pick_tasks_by_state() {
+ let s = Sandbox::new();
+ let a = s.jeans(["add", "A"]);
+ let b = s.jeans(["add", "B"]);
+ s.claim(&b);
+
+ let ids = |view: &[&str]| {
+ let mut ids = ids_in(&s.jeans(view));
+ ids.sort();
+ ids
+ };
+ let mut open = vec![
+ s.goal[..12].to_owned(),
+ a[..12].to_owned(),
+ b[..12].to_owned(),
+ ];
+ open.sort();
+ assert_eq!(ids(&["log", "open"]), open);
+ assert_eq!(ids(&["log", "claimed"]), [b[..12].to_owned()]);
+ assert_eq!(ids(&["log", "done"]), Vec::<String>::new());
+ // Status adds trunk, which isn't a task and gets no state.
+ let status = s.jeans(["status"]);
+ assert!(status.contains(&format!("{} [ready] A", &a[..12])));
+ assert!(status.contains("zzzzzzzzzzzz"));
+ assert!(!status.contains("zzzzzzzzzzzz ["));
+}
+
+#[test]
+fn a_task_feeding_two_goals_needs_goal() {
+ let s = Sandbox::new();
+ let home = s.tmp.join("jeans");
+ s.jeans([
+ "init".as_ref(),
+ "other".as_ref(),
+ "--goal".as_ref(),
+ "other".as_ref(),
+ "--home".as_ref(),
+ home.as_os_str(),
+ ]);
+ let a = s.jeans(["add", "A", "--goal", "thing"]);
+ s.jeans(["add", "B", "--goal", "other", "--after", &a]);
+ assert!(
+ s.jeans_fails(["show", &a])
+ .contains("feeds goals other, thing; pick one with --goal NAME")
+ );
+ assert_eq!(
+ s.jeans(["show", &a, "--goal", "thing"]).lines().next(),
+ Some("ready")
+ );
+}
+
+#[test]
+fn only_a_claimed_task_can_be_released() {
+ let s = Sandbox::new();
+ let a = s.jeans(["add", "A"]);
+ assert_eq!(
+ s.jeans_fails(["release", &a]),
+ format!("jeans: {a} isn't claimed")
+ );
+}
+
+#[test]
+fn a_conflicted_workspace_must_be_resolved_before_finishing() {
+ let s = Sandbox::new();
+ let a = s.jeans(["add", "A"]);
+ let ws = s.claim(&a);
+ fs_err::write(ws.join("same.txt"), "workspace\n").unwrap();
+ s.sh_in(&ws, ["status"]);
+
+ // Rewrite the task under the workspace so its working copy conflicts.
+ s.sh(["new", "--no-edit", &a, "-m", "fixup"]);
+ let fixup = s.change_id(r#"description(exact:"fixup\n")"#);
+ let fixup_ws = s.tmp.join("fixup");
+ s.sh([
+ "workspace".as_ref(),
+ "add".as_ref(),
+ fixup_ws.as_os_str(),
+ "-r".as_ref(),
+ fixup.as_ref(),
+ ]);
+ fs_err::write(fixup_ws.join("same.txt"), "main\n").unwrap();
+ s.sh_in(&fixup_ws, ["squash", "--from", "@", "--into", &a, "-u"]);
+
+ assert!(
+ s.jeans_fails(["done", &a, "-m", "A"])
+ .contains("has conflicts; resolve them first")
+ );
+}
+
+#[test]
+fn a_new_task_under_a_conflicted_resolution_adds_no_second_one() {
+ let s = Sandbox::new();
+ let a = s.jeans(["add", "A"]);
+ let b = s.jeans(["add", "B"]);
+ let c = s.jeans(["add", "C"]);
+ for task in [&a, &b] {
+ fs_err::write(s.claim(task).join("same.txt"), format!("{task}\n")).unwrap();
+ s.finish(task);
+ }
+ let resolution = s.parents(DONE);
+ assert_eq!(resolution.len(), 1);
+
+ fs_err::write(s.claim(&c).join("c.txt"), "c\n").unwrap();
+ let out = s.run_in(&s.repo, ["done", &c, "-m", "C"]);
+ assert!(out.status.success());
+ assert!(
+ !String::from_utf8(out.stderr)
+ .unwrap()
+ .contains("added resolution task")
+ );
+ let mut parents = s.parents(DONE);
+ parents.sort();
+ let mut expected = vec![resolution[0].clone(), c];
+ expected.sort();
+ assert_eq!(parents, expected);
+}
+
+#[test]
+fn finished_work_that_conflicts_with_the_checkout_is_reported() {
+ let s = Sandbox::new();
+ fs_err::write(s.repo.join("same.txt"), "checkout\n").unwrap();
+ s.sh(["status"]);
+ let a = s.jeans(["add", "A"]);
+ fs_err::write(s.claim(&a).join("same.txt"), "task\n").unwrap();
+
+ let out = s.run_in(&s.repo, ["done", &a, "-m", "A"]);
+ assert!(out.status.success());
+ assert!(
+ String::from_utf8(out.stderr)
+ .unwrap()
+ .contains("default@ has conflicts between the finished tasks and its other parents")
+ );
+}
+
+#[test]
+fn a_task_left_conflicted_under_its_workspace_cant_be_done() {
+ let s = Sandbox::new();
+ let a = s.jeans(["add", "A"]);
+ let b = s.jeans(["add", "B"]);
+ for task in [&a, &b] {
+ fs_err::write(s.claim(task).join("same.txt"), format!("{task}\n")).unwrap();
+ s.finish(task);
+ }
+ let resolution = s.parents(DONE).remove(0);
+
+ // Resolving in a commit above the task leaves the task itself conflicted.
+ let ws = s.claim(&resolution);
+ fs_err::write(ws.join("same.txt"), "both\n").unwrap();
+ s.sh_in(&ws, ["commit", "-m", "resolve"]);
+ assert_eq!(
+ s.jeans_fails(["done", &resolution, "-m", "resolve"]),
+ format!("jeans: {resolution} has conflicts; resolve them in its workspace first")
+ );
+}
diff --git a/tests/jeans.rs b/tests/jeans.rs
new file mode 100644
index 0000000..4ba7ba5
--- /dev/null
+++ b/tests/jeans.rs
@@ -0,0 +1,630 @@
+//! The cases from the Ruby plugin's jeans_test.rb, run against the Rust
+//! binary with real jj in temp repos.
+
+#![allow(
+ clippy::unwrap_used,
+ clippy::panic,
+ clippy::indexing_slicing,
+ clippy::arithmetic_side_effects
+)]
+
+mod support;
+
+use std::io::Read as _;
+use std::process::Stdio;
+use std::sync::mpsc;
+use std::time::Duration;
+use std::time::Instant;
+
+use support::DONE;
+use support::JEANS;
+use support::Sandbox;
+use support::ids_in;
+use support::lines;
+use support::short;
+use support::sorted;
+
+#[test]
+fn goal_alone_is_ready() {
+ let s = Sandbox::new();
+ assert_eq!(s.ready(), std::slice::from_ref(&s.goal));
+ assert_eq!(s.jeans(["team-size"]), "2");
+}
+
+#[test]
+fn subtasks_block_their_parent() {
+ let s = Sandbox::new();
+ let a = s.jeans(["add", "A"]);
+ let b = s.jeans(["add", "B"]);
+
+ assert_eq!(sorted(s.ready()), sorted(vec![a.clone(), b.clone()]));
+ assert_eq!(sorted(s.parents(&s.goal)), sorted(vec![a, b]));
+}
+
+#[test]
+fn split_a_task_into_siblings_and_a_dependency() {
+ let s = Sandbox::new();
+ let a = s.jeans(["add", "A"]);
+ let a1 = s.jeans(["add", "A.1", "--before", &a]);
+ let a2 = s.jeans(["add", "A.2", "--before", &a, "--after", &a1]);
+
+ assert_eq!(s.parents(&a), std::slice::from_ref(&a2));
+ assert_eq!(s.parents(&a2), std::slice::from_ref(&a1));
+ assert_eq!(s.ready(), [a1]);
+}
+
+#[test]
+fn only_the_claiming_developer_changes_a_claimed_task() {
+ let s = Sandbox::new();
+ let a = s.jeans(["add", "A"]);
+ let ws = s.claim(&a);
+
+ assert!(
+ s.jeans_fails(["add", "A.1", "--before", &a])
+ .contains("is claimed")
+ );
+ assert!(
+ s.jeans_fails(["describe", &a, "-m", "A, rescoped"])
+ .contains("is claimed")
+ );
+
+ let a1 = s.jeans_in(&ws, ["add", "A.1", "--before", &a]);
+ s.jeans_in(&ws, ["add", "A.1.1", "--before", &a1]);
+ s.jeans_in(&ws, ["describe", &a, "-m", "A, rescoped"]);
+
+ let out = s.run_in(&ws, ["add", "found a bug"]);
+ assert!(!out.status.success());
+ assert!(
+ String::from_utf8(out.stderr)
+ .unwrap()
+ .contains("outside your task")
+ );
+ let out = s.run_in(&ws, ["describe", &a1, "-m", "nope"]);
+ assert!(
+ String::from_utf8(out.stderr)
+ .unwrap()
+ .contains("outside your task")
+ );
+}
+
+#[test]
+fn done_keeps_the_spec_between_message_and_trailers() {
+ let s = Sandbox::new();
+ let a = s.jeans(["add", "A", "-m", "- one\n- two\n\nthen three"]);
+ s.claim(&a);
+ s.jeans([
+ "done",
+ &a,
+ "-m",
+ "area: do A\n\nBecause.\n\nAssisted-by: Claude\nSigned-off-by: Someone",
+ ]);
+
+ assert_eq!(
+ s.description(&a),
+ "area: do A\n\nBecause.\n\nTask: A\n\n - one\n - two\n\n then three\n\nAssisted-by: Claude\nSigned-off-by: Someone\n"
+ );
+ let trailer = r#"trailers.filter(|t| t.key() == "Assisted-by").map(|t| t.value()).join(",")"#;
+ assert_eq!(
+ s.sh(["log", "--no-graph", "-r", &a, "-T", trailer]),
+ "Claude"
+ );
+}
+
+#[test]
+fn done_leaves_a_last_paragraph_that_isnt_trailers() {
+ let s = Sandbox::new();
+ let a = s.jeans(["add", "A"]);
+ s.claim(&a);
+ s.jeans(["done", &a, "-m", "do A\n\n- a list\n wrapped"]);
+
+ assert_eq!(
+ s.description(&a),
+ "do A\n\n- a list\n wrapped\n\nTask: A\n"
+ );
+}
+
+#[test]
+fn done_needs_a_message() {
+ let s = Sandbox::new();
+ let a = s.jeans(["add", "A"]);
+ let ws = s.claim(&a);
+ fs_err::write(ws.join("a.txt"), "hello\n").unwrap();
+
+ assert!(
+ s.jeans_fails(["done", &a])
+ .contains("done needs -m MESSAGE")
+ );
+ assert!(
+ s.jeans_fails(["done", &a, "-m", " "])
+ .contains("done needs -m MESSAGE")
+ );
+ assert_eq!(first_line(&s.jeans(["show", &a])), "claimed");
+ assert_eq!(s.description(&a), "A\n");
+}
+
+#[test]
+fn describe_rewrites_a_task() {
+ let s = Sandbox::new();
+ let a = s.jeans(["add", "A"]);
+ s.jeans(["describe", &a, "-m", "A, but answered"]);
+ assert!(s.jeans(["show", &a]).contains("A, but answered"));
+}
+
+#[test]
+fn claim_work_done() {
+ let s = Sandbox::new();
+ let a = s.jeans(["add", "A"]);
+ let ws = s.claim(&a);
+ assert!(s.jeans(["show", &a]).contains("claimed"));
+ assert!(!s.jeans(["ready"]).contains(&a));
+ assert_eq!(
+ s.jeans_fails(["claim", &a]),
+ format!("jeans: {a} is claimed, not ready")
+ );
+
+ fs_err::write(ws.join("a.txt"), "hello\n").unwrap();
+ s.finish(&a);
+
+ assert!(!ws.exists());
+ assert_eq!(first_line(&s.jeans(["show", &a])), "done");
+ assert_eq!(s.description(&a), "A\n\nTask: A\n");
+ assert_eq!(s.parents(DONE), std::slice::from_ref(&a));
+ assert_eq!(
+ fs_err::read_to_string(s.repo.join("a.txt")).unwrap(),
+ "hello\n"
+ );
+ assert!(
+ s.jeans_fails(["add", "late", "--before", &a])
+ .contains("is done")
+ );
+ assert_eq!(s.sh(["file", "list", "-r", &a]).trim(), "a.txt");
+ assert_eq!(s.ready(), std::slice::from_ref(&s.goal));
+ assert_eq!(s.sh(["workspace", "list"]).lines().count(), 1);
+ let stray = format!("heads(all()) ~ (@ | {})", s.goal);
+ assert_eq!(
+ s.sh(["log", "--no-graph", "-r", &stray, "-T", "change_id"]),
+ ""
+ );
+}
+
+#[test]
+fn done_goal_leaves_a_plain_commit() {
+ let s = Sandbox::new();
+ let a = s.jeans(["add", "A"]);
+ s.claim(&a);
+ s.finish(&a);
+ s.claim(&s.goal);
+ s.jeans(["done", &s.goal, "-m", "thing: ship it\n\nBuilt A."]);
+
+ assert_eq!(
+ s.sh(["bookmark", "list", "jeans/thing/goal", "jeans/thing/done"]),
+ ""
+ );
+ assert_eq!(
+ s.description(&s.goal),
+ "thing: ship it\n\nBuilt A.\n\nTask: ship the thing\n"
+ );
+ assert_eq!(s.parents("@"), std::slice::from_ref(&s.goal));
+ let home = s.tmp.join("jeans");
+ let next = s.jeans([
+ "init".as_ref(),
+ "the next thing".as_ref(),
+ "--goal".as_ref(),
+ "thing".as_ref(),
+ "--home".as_ref(),
+ home.as_os_str(),
+ ]);
+ assert_ne!(next, s.goal);
+}
+
+#[test]
+fn finished_work_goes_into_the_megamerge() {
+ let mut s = Sandbox::bare("repo");
+ s.repo = s.use_repo("megamerge");
+ let mut branches = Vec::new();
+ for name in ["x", "y"] {
+ s.sh(["new", "root()", "-m", name]);
+ fs_err::write(s.repo.join(format!("{name}.txt")), format!("{name}\n")).unwrap();
+ branches.push(s.change_id("@"));
+ }
+ s.sh(["new", &branches[0], &branches[1], "-m", "mm"]);
+ s.sh(["bookmark", "create", "mm", "-r", "@"]);
+ s.sh(["new"]);
+ let home = s.tmp.join("megamerge.jeans");
+ let goal = s.jeans([
+ "init".as_ref(),
+ "ship the thing".as_ref(),
+ "--goal".as_ref(),
+ "thing".as_ref(),
+ "--home".as_ref(),
+ home.as_os_str(),
+ ]);
+ let done = s.change_id(DONE);
+ let with = |last: &str| {
+ sorted(vec![
+ branches[0].clone(),
+ branches[1].clone(),
+ last.to_owned(),
+ ])
+ };
+ assert_eq!(sorted(s.parents("mm")), with(&done));
+
+ let a = s.jeans(["add", "A"]);
+ fs_err::write(s.claim(&a).join("a.txt"), "hello\n").unwrap();
+ s.finish(&a);
+
+ assert_eq!(s.parents(DONE), [a]);
+ assert_eq!(sorted(s.parents("mm")), with(&done));
+ assert_eq!(s.parents("@"), [s.change_id("mm")]);
+ assert_eq!(
+ fs_err::read_to_string(s.repo.join("a.txt")).unwrap(),
+ "hello\n"
+ );
+
+ s.claim(&goal);
+ s.finish(&goal);
+ assert_eq!(sorted(s.parents("mm")), with(&goal));
+ assert_eq!(
+ s.sh(["bookmark", "list", "jeans/thing/goal", "jeans/thing/done"]),
+ ""
+ );
+}
+
+#[test]
+fn goals_keep_their_own_tasks() {
+ let s = Sandbox::new();
+ let other_done = r#"bookmarks(exact:"jeans/other/done")"#;
+ let home = s.tmp.join("jeans");
+ s.jeans([
+ "init".as_ref(),
+ "another thing".as_ref(),
+ "--goal".as_ref(),
+ "other".as_ref(),
+ "--home".as_ref(),
+ home.as_os_str(),
+ ]);
+ assert!(
+ s.jeans_fails(["init", "again", "--goal", "other"])
+ .contains("already has a goal named other")
+ );
+ assert!(
+ s.jeans_fails(["init", "unnamed"])
+ .contains("init needs --goal NAME")
+ );
+ assert!(
+ s.jeans_fails(["ready"])
+ .contains("has goals other, thing; pick one with --goal NAME")
+ );
+ assert!(
+ s.jeans_fails(["ready", "--goal", "nope"])
+ .contains("no goal named nope; the goals are other, thing")
+ );
+
+ let a = s.jeans(["add", "A", "--goal", "thing"]);
+ let b = s.jeans(["add", "B", "--goal", "other"]);
+ assert_eq!(
+ lines(&s.jeans(["ready", "--goal", "thing"])),
+ std::slice::from_ref(&a)
+ );
+ assert_eq!(lines(&s.jeans(["ready", "--goal", "other"])), [b]);
+
+ let ws = s.claim(&a);
+ let a1 = s.jeans_in(&ws, ["add", "A.1", "--before", &a]);
+ s.jeans_in(&ws, ["release", &a]);
+ fs_err::write(s.claim(&a1).join("a1.txt"), "hello\n").unwrap();
+ s.finish(&a1);
+
+ assert_eq!(first_line(&s.jeans(["show", &a1])), "done");
+ assert_eq!(s.parents(DONE), std::slice::from_ref(&a1));
+ assert!(!s.parents(other_done).contains(&a1));
+ assert_eq!(
+ sorted(s.parents("@")),
+ sorted(vec![s.change_id(DONE), s.change_id(other_done)])
+ );
+ assert_eq!(
+ fs_err::read_to_string(s.repo.join("a1.txt")).unwrap(),
+ "hello\n"
+ );
+}
+
+#[test]
+fn release_keeps_work_without_finishing() {
+ let s = Sandbox::new();
+ let a = s.jeans(["add", "A"]);
+ let ws = s.claim(&a);
+ fs_err::write(ws.join("partial.txt"), "wip\n").unwrap();
+ s.jeans(["release", &a]);
+
+ assert_eq!(s.ready(), std::slice::from_ref(&a));
+ assert_eq!(s.sh(["file", "list", "-r", &a]).trim(), "partial.txt");
+}
+
+#[test]
+fn works_from_inside_a_workspace() {
+ let s = Sandbox::new();
+ let a = s.jeans(["add", "A"]);
+ let ws = s.claim(&a);
+ let a1 = s.jeans_in(&ws, ["add", "A.1", "--before", &a]);
+ s.jeans_in(&ws, ["release", &a]);
+
+ assert_eq!(s.ready(), [a1]);
+}
+
+#[test]
+fn integration_supersedes_an_untaken_resolution_task() {
+ let s = Sandbox::new();
+ for task in [s.jeans(["add", "A"]), s.jeans(["add", "B"])] {
+ fs_err::write(s.claim(&task).join("same.txt"), format!("{task}\n")).unwrap();
+ s.finish(&task);
+ }
+ let resolution = s.parents(DONE).remove(0);
+
+ fs_err::write(s.claim(&s.goal).join("same.txt"), "both\n").unwrap();
+ s.finish(&s.goal);
+
+ assert_eq!(s.parents("@"), std::slice::from_ref(&s.goal));
+ let present = format!("present({resolution})");
+ assert_eq!(
+ s.sh(["log", "--no-graph", "-r", &present, "-T", "change_id"]),
+ ""
+ );
+ assert_eq!(
+ fs_err::read_to_string(s.repo.join("same.txt")).unwrap(),
+ "both\n"
+ );
+}
+
+#[test]
+fn conflicts_in_the_done_node_get_a_resolution_task() {
+ let s = Sandbox::new();
+ let a = s.jeans(["add", "A"]);
+ let b = s.jeans(["add", "B"]);
+ for task in [&a, &b] {
+ fs_err::write(s.claim(task).join("same.txt"), format!("{task}\n")).unwrap();
+ s.finish(task);
+ }
+
+ assert_eq!(
+ s.sh(["log", "--no-graph", "-r", "@", "-T", "conflict"]),
+ "true"
+ );
+ let resolutions = s.parents(DONE);
+ assert_eq!(resolutions.len(), 1);
+ let resolution = resolutions[0].clone();
+ let description = s.description(&resolution);
+ assert!(
+ description.starts_with("Resolve conflicts between A, B\n")
+ || description.starts_with("Resolve conflicts between B, A\n"),
+ "{description}"
+ );
+ assert_eq!(
+ sorted(s.ready()),
+ sorted(vec![s.goal.clone(), resolution.clone()])
+ );
+ assert!(
+ s.jeans(["tree"])
+ .contains(&format!("{} Resolve conflicts", short(&resolution, 8)))
+ );
+
+ for task in [&resolution, &s.goal] {
+ let ws = s.claim(task);
+ let title = s.title(task);
+ assert!(
+ s.jeans_fails(["done", task, "-m", &title])
+ .contains("has conflicts")
+ );
+ fs_err::write(ws.join("same.txt"), "both\n").unwrap();
+ s.finish(task);
+ }
+
+ assert_eq!(
+ s.sh(["log", "--no-graph", "-r", "@", "-T", "conflict"]),
+ "false"
+ );
+ assert_eq!(
+ fs_err::read_to_string(s.repo.join("same.txt")).unwrap(),
+ "both\n"
+ );
+ assert_eq!(s.jeans(["ready"]), "");
+}
+
+#[test]
+fn views() {
+ let s = Sandbox::new();
+ let a = s.jeans(["add", "A"]);
+ let a1 = s.jeans(["add", "A.1", "--before", &a]);
+ let b = s.jeans(["add", "B"]);
+ s.claim(&b);
+ let (g8, a8, a18, b8) = (short(&s.goal, 8), short(&a, 8), short(&a1, 8), short(&b, 8));
+
+ assert_eq!(
+ s.jeans(["tree"]),
+ format!(
+ "{g8} ship the thing [blocked]\n├── {a8} A [blocked]\n│ └── {a18} A.1 [ready]\n└── {b8} B [claimed]"
+ )
+ );
+ assert_eq!(
+ s.jeans(["tree", &a, "--depth", "0"]),
+ format!("{a8} A [blocked] (+1 more)")
+ );
+ let scoped = s.jeans(["board", &a]);
+ assert!(scoped.contains(a18));
+ assert!(!scoped.contains(b8));
+
+ assert_eq!(
+ s.jeans(["board"]),
+ format!(
+ "READY (1)\n {a18} A.1\n\nCLAIMED (1)\n {b8} B\n\nBLOCKED (2)\n {g8} ship the thing\n {a8} A\n\nDONE (0)"
+ )
+ );
+
+ let ready = s.jeans(["log", "ready"]);
+ assert!(ready.contains(&format!("{} [ready] A.1", short(&a1, 12))));
+ assert!(!ready.contains(short(&b, 12)));
+ assert_eq!(
+ ids_in(&s.jeans(["log", "under", &a])),
+ [short(&a, 12), short(&a1, 12)]
+ );
+ assert_eq!(
+ ids_in(&s.jeans(["log", "path", &a1])),
+ [short(&s.goal, 12), short(&a, 12), short(&a1, 12)]
+ );
+ assert_eq!(
+ ids_in(&s.jeans(["log", "description(exact:\"B\n\")"])),
+ [short(&b, 12)]
+ );
+
+ for task in [&a1, &a] {
+ s.claim(task);
+ s.finish(task);
+ }
+ assert!(
+ s.jeans(["tree"])
+ .contains(&format!("{a8} A [done] (+1 done)"))
+ );
+}
+
+#[test]
+fn color_changes_only_escape_codes() {
+ let s = Sandbox::new();
+ let a = s.jeans(["add", "A"]);
+ s.jeans(["add", "A.1", "--before", &a]);
+ let b = s.jeans(["add", "B"]);
+ s.claim(&b);
+
+ for view in [vec!["tree"], vec!["board"], vec!["log"], vec!["show", &a]] {
+ let colored = s.jeans(view.iter().copied().chain(["--color", "always"]));
+ assert!(colored.contains("\x1b["), "{} has no color", view[0]);
+ assert_eq!(
+ s.jeans(&view),
+ strip_color(&colored),
+ "{} differs beyond color",
+ view[0]
+ );
+ }
+ assert!(
+ s.jeans(["tree", "--color", "always"])
+ .contains("\x1b[32m[ready]\x1b[0m")
+ );
+ assert!(!s.jeans(["tree"]).contains("\x1b["));
+}
+
+#[test]
+fn watch_redraws_when_the_graph_changes() {
+ let s = Sandbox::new();
+ let a = s.jeans(["add", "A"]);
+ let mut watch = Watch::start(&s, &["watch"]);
+ watch.read_until(&format!("{} A [ready]", short(&a, 8)));
+ let op_log = ["op", "log", "-n1", "--no-graph", "-T", "id"];
+ let op = s.sh(op_log);
+ std::thread::sleep(Duration::from_secs(2));
+ assert_eq!(s.sh(op_log), op, "watching added an operation");
+
+ let b = s.jeans(["add", "B"]);
+ watch.read_until(&format!("{} B [ready]", short(&b, 8)));
+ watch.interrupt();
+
+ let mut board = Watch::start(&s, &["watch", "board"]);
+ board.read_until("READY (2)");
+ board.interrupt();
+
+ assert!(s.jeans_fails(["watch", "log"]).contains("tree or board"));
+ assert!(
+ s.jeans_fails(["watch", "tree", "root()"])
+ .ends_with("isn't a task")
+ );
+}
+
+#[test]
+fn concurrent_done_leaves_no_divergence() {
+ let s = Sandbox::new();
+ let tasks: Vec<String> = (0..3).map(|i| s.jeans(["add", &format!("T{i}")])).collect();
+ for task in &tasks {
+ fs_err::write(s.claim(task).join(format!("{task}.txt")), "x\n").unwrap();
+ }
+ std::thread::scope(|scope| {
+ for task in &tasks {
+ let s = &s;
+ scope.spawn(move || s.finish(task));
+ }
+ });
+
+ assert_eq!(s.ready(), std::slice::from_ref(&s.goal));
+ assert!(!s.sh(["log", "-r", "all()"]).contains("divergent"));
+}
+
+fn first_line(text: &str) -> &str {
+ text.lines().next().unwrap_or_default().trim()
+}
+
+fn strip_color(text: &str) -> String {
+ let mut plain = String::new();
+ let mut rest = text;
+ while let Some(start) = rest.find("\x1b[") {
+ plain.push_str(&rest[..start]);
+ let end = rest[start..].find('m').unwrap();
+ rest = &rest[start + end + 1..];
+ }
+ plain.push_str(rest);
+ plain
+}
+
+/// A `jeans watch` child whose stdout arrives on a channel.
+struct Watch {
+ child: std::process::Child,
+ chunks: mpsc::Receiver<String>,
+ seen: String,
+}
+
+impl Watch {
+ fn start(s: &Sandbox, args: &[&str]) -> Self {
+ let mut child = s
+ .command(JEANS, &s.repo)
+ .args(args)
+ .stdout(Stdio::piped())
+ .spawn()
+ .unwrap();
+ let mut stdout = child.stdout.take().unwrap();
+ let (tx, chunks) = mpsc::channel();
+ std::thread::spawn(move || {
+ let mut buf = [0; 4096];
+ // The test only searches the frames for ASCII labels.
+ #[allow(clippy::disallowed_methods)]
+ while let Ok(n @ 1..) = stdout.read(&mut buf) {
+ if tx
+ .send(String::from_utf8_lossy(&buf[..n]).into_owned())
+ .is_err()
+ {
+ break;
+ }
+ }
+ });
+ Self {
+ child,
+ chunks,
+ seen: String::new(),
+ }
+ }
+
+ fn read_until(&mut self, text: &str) {
+ let deadline = Instant::now() + Duration::from_secs(10);
+ while !self.seen.contains(text) {
+ let left = deadline.saturating_duration_since(Instant::now());
+ match self.chunks.recv_timeout(left) {
+ Ok(chunk) => self.seen.push_str(&chunk),
+ Err(_) => panic!("never printed {text:?}; got:\n{}", self.seen),
+ }
+ }
+ }
+
+ /// Stops the watch the way a human does, with ^C, so it exits cleanly.
+ fn interrupt(mut self) {
+ let pid = self.child.id().to_string();
+ let status = std::process::Command::new("kill")
+ .args(["-INT", &pid])
+ .status()
+ .unwrap();
+ assert!(status.success());
+ assert!(self.child.wait().unwrap().success());
+ }
+}
diff --git a/tests/support/mod.rs b/tests/support/mod.rs
new file mode 100644
index 0000000..4673b91
--- /dev/null
+++ b/tests/support/mod.rs
@@ -0,0 +1,214 @@
+//! A temp repo with a goal, and helpers that run jeans and jj in it.
+
+#![allow(dead_code)]
+
+use std::ffi::OsStr;
+use std::path::Path;
+use std::path::PathBuf;
+use std::process::Command;
+use std::process::Output;
+
+pub const JEANS: &str = env!("CARGO_BIN_EXE_jeans");
+pub const DONE: &str = r#"bookmarks(exact:"jeans/thing/done")"#;
+
+pub struct Sandbox {
+ // Held for its Drop, which removes the directory.
+ _tmp: tempfile::TempDir,
+ pub tmp: PathBuf,
+ pub repo: PathBuf,
+ pub config: PathBuf,
+ pub goal: String,
+}
+
+impl Sandbox {
+ /// A repo at `repo` whose goal "thing" has a team size of 2.
+ pub fn new() -> Self {
+ let mut sandbox = Self::bare("repo");
+ let home = sandbox.tmp.join("jeans");
+ sandbox.goal = sandbox.jeans([
+ OsStr::new("init"),
+ OsStr::new("ship the thing"),
+ OsStr::new("--goal"),
+ OsStr::new("thing"),
+ OsStr::new("--team"),
+ OsStr::new("2"),
+ OsStr::new("--home"),
+ home.as_os_str(),
+ ]);
+ sandbox
+ }
+
+ /// An empty jj repo at NAME, with no goal yet.
+ pub fn bare(name: &str) -> Self {
+ let tmp_dir = tempfile::tempdir().unwrap();
+ // Canonical, so paths jeans prints compare equal on macOS's /private/var.
+ let tmp = tmp_dir.path().canonicalize().unwrap();
+ // Keeps the developer's own jj config, like a trunk() alias, out of the tests.
+ let config = tmp.join("jj-config.toml");
+ fs_err::write(
+ &config,
+ "user.name = \"Test\"\nuser.email = \"test@example.com\"\n",
+ )
+ .unwrap();
+ let sandbox = Self {
+ _tmp: tmp_dir,
+ repo: tmp.join(name),
+ tmp,
+ config,
+ goal: String::new(),
+ };
+ sandbox.use_repo(name);
+ sandbox
+ }
+
+ /// Makes and switches to a fresh jj repo at NAME.
+ pub fn use_repo(&self, name: &str) -> PathBuf {
+ let repo = self.tmp.join(name);
+ fs_err::create_dir_all(&repo).unwrap();
+ self.sh_in(&repo, ["git", "init", "."]);
+ repo
+ }
+
+ pub fn command(&self, program: &str, dir: &Path) -> Command {
+ let mut command = Command::new(program);
+ command
+ .current_dir(dir)
+ .env("JJ_CONFIG", &self.config)
+ .env_remove("NO_COLOR");
+ command
+ }
+
+ pub fn run_in<I, S>(&self, dir: &Path, args: I) -> Output
+ where
+ I: IntoIterator<Item = S>,
+ S: AsRef<OsStr>,
+ {
+ self.command(JEANS, dir).args(args).output().unwrap()
+ }
+
+ /// Runs jeans in the repo, asserts it succeeded, and returns its stdout
+ /// stripped.
+ pub fn jeans<I, S>(&self, args: I) -> String
+ where
+ I: IntoIterator<Item = S>,
+ S: AsRef<OsStr>,
+ {
+ self.jeans_in(&self.repo, args)
+ }
+
+ pub fn jeans_in<I, S>(&self, dir: &Path, args: I) -> String
+ where
+ I: IntoIterator<Item = S>,
+ S: AsRef<OsStr>,
+ {
+ let args: Vec<_> = args.into_iter().map(|a| a.as_ref().to_owned()).collect();
+ let out = self.run_in(dir, &args);
+ assert!(
+ out.status.success(),
+ "jeans {args:?} failed: {}",
+ String::from_utf8(out.stderr).unwrap()
+ );
+ String::from_utf8(out.stdout).unwrap().trim().to_owned()
+ }
+
+ /// Runs jeans in the repo, asserts it failed, and returns its stderr
+ /// stripped.
+ pub fn jeans_fails<I, S>(&self, args: I) -> String
+ where
+ I: IntoIterator<Item = S>,
+ S: AsRef<OsStr>,
+ {
+ let out = self.run_in(&self.repo, args);
+ assert!(!out.status.success(), "jeans succeeded: {out:?}");
+ String::from_utf8(out.stderr).unwrap().trim().to_owned()
+ }
+
+ /// Runs jj in the repo and returns its stdout.
+ pub fn sh<I, S>(&self, args: I) -> String
+ where
+ I: IntoIterator<Item = S>,
+ S: AsRef<OsStr>,
+ {
+ self.sh_in(&self.repo, args)
+ }
+
+ pub fn sh_in<I, S>(&self, dir: &Path, args: I) -> String
+ where
+ I: IntoIterator<Item = S>,
+ S: AsRef<OsStr>,
+ {
+ let out = self.command("jj", dir).args(args).output().unwrap();
+ assert!(
+ out.status.success(),
+ "jj failed: {}",
+ String::from_utf8(out.stderr).unwrap()
+ );
+ String::from_utf8(out.stdout).unwrap()
+ }
+
+ pub fn claim(&self, task: &str) -> PathBuf {
+ PathBuf::from(self.jeans(["claim", task]))
+ }
+
+ /// Reusing the task's title as the commit title keeps the views' labels
+ /// stable.
+ pub fn finish(&self, task: &str) {
+ let title = self.title(task);
+ self.jeans(["done", task, "-m", &title]);
+ }
+
+ pub fn title(&self, rev: &str) -> String {
+ self.sh([
+ "log",
+ "--no-graph",
+ "-r",
+ rev,
+ "-T",
+ "description.first_line()",
+ ])
+ }
+
+ pub fn description(&self, rev: &str) -> String {
+ self.sh(["log", "--no-graph", "-r", rev, "-T", "description"])
+ }
+
+ pub fn change_id(&self, rev: &str) -> String {
+ self.sh(["log", "--no-graph", "-r", rev, "-T", "change_id"])
+ }
+
+ pub fn parents(&self, rev: &str) -> Vec<String> {
+ lines(&self.sh([
+ "log",
+ "--no-graph",
+ "-r",
+ &format!("parents({rev})"),
+ "-T",
+ r#"change_id ++ "\n""#,
+ ]))
+ }
+
+ pub fn ready(&self) -> Vec<String> {
+ lines(&self.jeans(["ready"]))
+ }
+}
+
+pub fn lines(text: &str) -> Vec<String> {
+ text.lines().map(str::to_owned).collect()
+}
+
+pub fn sorted(mut items: Vec<String>) -> Vec<String> {
+ items.sort();
+ items
+}
+
+pub fn short(id: &str, len: usize) -> &str {
+ &id[..len]
+}
+
+/// The 12-character change IDs in TEXT, in order.
+pub fn ids_in(text: &str) -> Vec<String> {
+ text.split(|c: char| !c.is_ascii_alphanumeric())
+ .filter(|w| w.len() == 12 && w.bytes().all(|b| (b'k'..=b'z').contains(&b)))
+ .map(str::to_owned)
+ .collect()
+}