10 Commits

Author SHA1 Message Date
9a6b94276b chore(deps): RUSTSEC-2026-0097 mitigation
All checks were successful
Publish Docker Images / coverage-and-sonar (push) Successful in 16m23s
2026-04-22 01:18:12 +02:00
c5814ab480 feat(cli): add jj-lib version to version output 2026-04-22 01:18:12 +02:00
1bab78cb20 feat: set message for multiple revsets
Allows to set the revision message of multiple revisions by passing
them as arguments. This only supports simple revisions, such as `@`,
`@-`, `xs`, and so on. Comple revisions such as `@..@-` are not
supported.

Fixes: #5
2026-04-22 01:18:12 +02:00
e965a728a1 refactor(prompter): simplify commit type selection 2026-04-22 01:18:12 +02:00
95e6250a60 fix(scope): no new string allocation to count characters 2026-04-22 01:18:12 +02:00
518d2916b9 feat(errors): preserve jj-emitted errors when loading config 2026-04-22 01:18:12 +02:00
a88f839798 refactor(BreakingChange): rename method ignore to is_absent
Method `ignore` did not carry its meaning well by the way it is named.
This commit renames it to `is_absent` to clearly state this method
returns whether we have a breaking change.
2026-04-22 01:18:12 +02:00
51cf5bae4e refactor(workflow): remove unnecessary async declarations 2026-04-22 01:18:12 +02:00
825127dbdb refactor(nix): simplify package declaration 2026-04-22 01:18:12 +02:00
CI Bot
a5b2bc41aa chore(release): bump version to 1.0.1-dev [skip ci] 2026-03-25 15:06:26 +00:00
22 changed files with 882 additions and 355 deletions

301
Cargo.lock generated
View File

@@ -203,6 +203,18 @@ version = "1.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33"
[[package]]
name = "cargo-lock"
version = "11.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "63585cdf8572aa7adf0e30a253f988f2b77233bfac1973d52efb6dd53a75920e"
dependencies = [
"semver",
"serde",
"toml",
"url",
]
[[package]]
name = "cc"
version = "1.2.56"
@@ -237,8 +249,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c673075a2e0e5f4a1dde27ce9dee1ea4558c7ffe648f576438a20ca1d2acc4b0"
dependencies = [
"iana-time-zone",
"js-sys",
"num-traits",
"serde",
"wasm-bindgen",
"windows-link",
]
@@ -463,6 +477,17 @@ dependencies = [
"subtle",
]
[[package]]
name = "displaydoc"
version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "doc-comment"
version = "0.3.4"
@@ -591,6 +616,15 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
[[package]]
name = "form_urlencoded"
version = "1.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"
dependencies = [
"percent-encoding",
]
[[package]]
name = "futures"
version = "0.3.32"
@@ -1518,12 +1552,115 @@ dependencies = [
"cc",
]
[[package]]
name = "icu_collections"
version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2984d1cd16c883d7935b9e07e44071dca8d917fd52ecc02c04d5fa0b5a3f191c"
dependencies = [
"displaydoc",
"potential_utf",
"utf8_iter",
"yoke",
"zerofrom",
"zerovec",
]
[[package]]
name = "icu_locale_core"
version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "92219b62b3e2b4d88ac5119f8904c10f8f61bf7e95b640d25ba3075e6cac2c29"
dependencies = [
"displaydoc",
"litemap",
"tinystr",
"writeable",
"zerovec",
]
[[package]]
name = "icu_normalizer"
version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c56e5ee99d6e3d33bd91c5d85458b6005a22140021cc324cea84dd0e72cff3b4"
dependencies = [
"icu_collections",
"icu_normalizer_data",
"icu_properties",
"icu_provider",
"smallvec",
"zerovec",
]
[[package]]
name = "icu_normalizer_data"
version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da3be0ae77ea334f4da67c12f149704f19f81d1adf7c51cf482943e84a2bad38"
[[package]]
name = "icu_properties"
version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bee3b67d0ea5c2cca5003417989af8996f8604e34fb9ddf96208a033901e70de"
dependencies = [
"icu_collections",
"icu_locale_core",
"icu_properties_data",
"icu_provider",
"zerotrie",
"zerovec",
]
[[package]]
name = "icu_properties_data"
version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e2bbb201e0c04f7b4b3e14382af113e17ba4f63e2c9d2ee626b720cbce54a14"
[[package]]
name = "icu_provider"
version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "139c4cf31c8b5f33d7e199446eff9c1e02decfc2f0eec2c8d71f65befa45b421"
dependencies = [
"displaydoc",
"icu_locale_core",
"writeable",
"yoke",
"zerofrom",
"zerotrie",
"zerovec",
]
[[package]]
name = "id-arena"
version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
[[package]]
name = "idna"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de"
dependencies = [
"idna_adapter",
"smallvec",
"utf8_iter",
]
[[package]]
name = "idna_adapter"
version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3acae9609540aa318d1bc588455225fb2085b9ed0c4f6bd0d9d5bcd86f1a0344"
dependencies = [
"icu_normalizer",
"icu_properties",
]
[[package]]
name = "ignore"
version = "0.4.25"
@@ -1650,11 +1787,13 @@ dependencies = [
[[package]]
name = "jj-cz"
version = "1.0.0"
version = "1.0.1-dev"
dependencies = [
"assert_cmd",
"assert_fs",
"async-trait",
"cargo-lock",
"chrono",
"clap",
"etcetera",
"git-conventional",
@@ -1806,6 +1945,12 @@ version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
[[package]]
name = "litemap"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0"
[[package]]
name = "litrs"
version = "1.0.0"
@@ -2043,6 +2188,15 @@ dependencies = [
"portable-atomic",
]
[[package]]
name = "potential_utf"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0103b1cef7ec0cf76490e969665504990193874ea05c85ff9bab8b911d0a0564"
dependencies = [
"zerovec",
]
[[package]]
name = "ppv-lite86"
version = "0.2.21"
@@ -2150,9 +2304,9 @@ checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
[[package]]
name = "rand"
version = "0.10.0"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bc266eb313df6c5c09c1c7b1fbe2510961e5bcd3add930c1e31f7ed9da0feff8"
checksum = "d2e8e8bcc7961af1fdac401278c6a831614941f6164ee3bf4ce61b7edb162207"
dependencies = [
"chacha20",
"getrandom",
@@ -2316,6 +2470,10 @@ name = "semver"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d767eb0aabc880b29956c35734170f26ed551a859dbd361d140cdbeca61ab1e2"
dependencies = [
"serde",
"serde_core",
]
[[package]]
name = "serde"
@@ -2500,6 +2658,17 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "synstructure"
version = "0.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "tempfile"
version = "3.27.0"
@@ -2559,6 +2728,16 @@ dependencies = [
"cfg-if",
]
[[package]]
name = "tinystr"
version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c8323304221c2a851516f22236c5722a72eaa19749016521d6dff0824447d96d"
dependencies = [
"displaydoc",
"zerovec",
]
[[package]]
name = "tinyvec"
version = "1.10.0"
@@ -2596,6 +2775,21 @@ dependencies = [
"syn",
]
[[package]]
name = "toml"
version = "0.9.12+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf92845e79fc2e2def6a5d828f0801e29a2f8acc037becc5ab08595c7d5e9863"
dependencies = [
"indexmap",
"serde_core",
"serde_spanned",
"toml_datetime",
"toml_parser",
"toml_writer",
"winnow",
]
[[package]]
name = "toml_datetime"
version = "0.7.5+spec-1.1.0"
@@ -2738,6 +2932,24 @@ version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"
[[package]]
name = "url"
version = "2.5.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"
dependencies = [
"form_urlencoded",
"idna",
"percent-encoding",
"serde",
]
[[package]]
name = "utf8_iter"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
[[package]]
name = "utf8parse"
version = "0.2.2"
@@ -3151,6 +3363,35 @@ dependencies = [
"wasmparser",
]
[[package]]
name = "writeable"
version = "0.6.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4"
[[package]]
name = "yoke"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "abe8c5fda708d9ca3df187cae8bfb9ceda00dd96231bed36e445a1a48e66f9ca"
dependencies = [
"stable_deref_trait",
"yoke-derive",
"zerofrom",
]
[[package]]
name = "yoke-derive"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e"
dependencies = [
"proc-macro2",
"quote",
"syn",
"synstructure",
]
[[package]]
name = "zerocopy"
version = "0.8.42"
@@ -3171,6 +3412,60 @@ dependencies = [
"syn",
]
[[package]]
name = "zerofrom"
version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "69faa1f2a1ea75661980b013019ed6687ed0e83d069bc1114e2cc74c6c04c4df"
dependencies = [
"zerofrom-derive",
]
[[package]]
name = "zerofrom-derive"
version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1"
dependencies = [
"proc-macro2",
"quote",
"syn",
"synstructure",
]
[[package]]
name = "zerotrie"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0f9152d31db0792fa83f70fb2f83148effb5c1f5b8c7686c3459e361d9bc20bf"
dependencies = [
"displaydoc",
"yoke",
"zerofrom",
]
[[package]]
name = "zerovec"
version = "0.11.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "90f911cbc359ab6af17377d242225f4d75119aec87ea711a880987b18cd7b239"
dependencies = [
"yoke",
"zerofrom",
"zerovec-derive",
]
[[package]]
name = "zerovec-derive"
version = "0.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "zlib-rs"
version = "0.6.3"

View File

@@ -1,6 +1,6 @@
[package]
name = "jj-cz"
version = "1.0.0"
version = "1.0.1-dev"
description = "Conventional commits for Jujutsu"
edition = "2024"
publish = true
@@ -33,6 +33,7 @@ thiserror = "2.0.18"
tokio = { version = "1.49.0", features = ["macros", "rt-multi-thread"] }
textwrap = "0.16.2"
unicode-width = "0.2.2"
chrono = "0.4.44"
[dev-dependencies]
assert_cmd = "2.1.2"
@@ -49,6 +50,9 @@ codegen-units = 1
panic = "abort"
strip = true
[build-dependencies]
cargo-lock = "11"
[package.metadata.git-cliff.changelog]
body = """
{% if version %}\

View File

@@ -24,6 +24,16 @@ jj-cz
The tool detects whether you're in a Jujutsu repository, guides you
through the commit message, and applies it to your current change.
You can also set the revision message of a few revisions at once, or
target a single revision other than the current one.
```sh
jj-cz @- xs develop
```
No explicit revision is simply the equivalent of `jj-cz @`, like
`jj desc`.
## Requirements
- A Jujutsu repository
@@ -41,8 +51,44 @@ what `jj-cz` alone would be good for without `jj`.
| 130 | Interrupted |
## Installation
### From crates.io
Simply run the following command:
You can install jj-cz with Cargo by building it from source.
```
cargo install jj-cz
```
Done! `jj-cz` is now available!
### With Nix Flakes
Notice how theres a `flake.nix` file? This means you can run the
project using this repository as one of your flakes inputs. In fact,
thats how I install it in my own NixOS configuration! Add this
repository to your configuration:
```nix
{
inputs = {
nixpkgs.url = "github:nixos/nixpkgs?ref=nixos-unstable";
jj-cz = {
url = "git+https://labs.phundrak.com/phundrak/jj-cz";
inputs.nixpkgs.follows = "nixpkgs";
};
};
}
```
And tadah! you can now install
`inputs.jj-cz.packages.${pkgs.stdenv.hostPlatform.system}.default`
among your other packages. Take a look at my
[`jujutsu.nix`](https://labs.phundrak.com/phundrak/nix-config/src/branch/main/users/modules/dev/vcs/jujutsu.nix)
module if you need some inspiration.
### From source
You can also install `jj-cz` with Cargo by building it from source.
Just make sure Rust is available on your machine (duh!).
```sh
cargo install --path .

13
build.rs Normal file
View File

@@ -0,0 +1,13 @@
use cargo_lock::Lockfile;
fn main() {
let lockfile = Lockfile::load("Cargo.lock").expect("Cargo.lock not found");
let version = lockfile
.packages
.iter()
.find(|p| p.name.as_str() == "jj-lib")
.map(|p| p.version.to_string())
.unwrap_or_else(|| "unknown".to_string());
println!("cargo:rustc-env=JJ_LIB_VERSION={version}");
println!("cargo:rerun-if-changed=Cargo.lock");
}

View File

@@ -41,36 +41,22 @@
};
in {
formatter = alejandra.defaultPackage.${system};
packages =
(import ./nix/package.nix {inherit pkgs rustPlatform;})
// {
windows = let
mingwPkgs = pkgs.pkgsCross.mingwW64;
rustWindows = pkgs.rust-bin.stable.latest.default.override {
targets = ["x86_64-pc-windows-gnu"];
};
rustPlatformWindows = mingwPkgs.makeRustPlatform {
cargo = rustWindows;
rustc = rustWindows;
};
cargoToml = builtins.fromTOML (builtins.readFile ./Cargo.toml);
in
rustPlatformWindows.buildRustPackage {
pname = cargoToml.package.name;
version = cargoToml.package.version;
src = pkgs.lib.cleanSource ./.;
cargoLock.lockFile = ./Cargo.lock;
nativeBuildInputs = [pkgs.upx];
doCheck = false;
meta = {
description = "Conventional commits for Jujutsu";
homepage = "https://labs.phundrak.com/phundrak/jj-cz";
};
postBuild = ''
${pkgs.upx}/bin/upx target/*/release/jj-cz.exe
'';
};
packages = let
nativeRustVersion = pkgs.rust-bin.stable.latest.default;
nativeRustPlatform = pkgs.makeRustPlatform {
cargo = nativeRustVersion;
rustc = nativeRustVersion;
};
mingwPkgs = pkgs.pkgsCross.mingwW64;
windowsRustVersion = pkgs.rust-bin.stable.latest.default.override {
targets = ["x86_64-pc-windows-gnu"];
};
windowsRustPlatform = mingwPkgs.makeRustPlatform {
cargo = windowsRustVersion;
rustc = windowsRustVersion;
};
in
import ./nix/package.nix {inherit pkgs nativeRustPlatform windowsRustPlatform;};
devShell = import ./nix/shell.nix {
inherit inputs pkgs rustVersion;
};

View File

@@ -1,26 +1,33 @@
{
pkgs,
rustPlatform,
nativeRustPlatform,
windowsRustPlatform,
...
}: let
cargoToml = fromTOML (builtins.readFile ../Cargo.toml);
name = cargoToml.package.name;
version = cargoToml.package.version;
rustBuild = rustPlatform.buildRustPackage {
buildArgs = {
pname = name;
inherit version;
src = pkgs.lib.cleanSource ../.;
cargoLock.lockFile = ../Cargo.lock;
nativeBuildInputs = [pkgs.upx];
useNextest = true;
meta = {
description = "Conventional commits for Jujutsu";
homepage = "https://labs.phundrak.com/phundrak/jj-cz";
inherit (cargoToml.package) description homepage;
};
postBuild = ''
${pkgs.upx}/bin/upx target/*/release/${name}
'';
};
nativeBuild =
nativeRustPlatform.buildRustPackage buildArgs
// {
postBuild = "${pkgs.upx}/bin/upx target/*/release/${name}";
};
windowsBuild =
windowsRustPlatform.buildRustPackage buildArgs
// {
postBuild = "${pkgs.upx}/bin/upx target/*/release/${name}.exe";
};
in {
default = rustBuild;
default = nativeBuild;
windows = windowsBuild;
}

View File

@@ -7,11 +7,26 @@ use clap::Parser;
#[derive(Debug, Parser)]
#[command(
name = "jj-cz",
version,
version = concat!(env!("CARGO_PKG_VERSION"), " (jj-lib ", env!("JJ_LIB_VERSION") ,")"),
about = "Interactive conventional commit tool for Jujutsu",
long_about = "Guides you through creating a properly formatted conventional \
commit message and applies it to the current change in your \
Jujutsu repository.\n\n\
This tool requires an interactive terminal (TTY)."
)]
pub struct Cli;
pub struct Cli {
/// The revision(s) whose description to edit (default: @)
#[arg(value_name = "REVSETS")]
revsets: Vec<String>,
}
impl Cli {
/// Returns the revsets to operate on, defaulting to `["@"]` if none provided
pub fn revsets(&self) -> Vec<&str> {
if self.revsets.is_empty() {
vec!["@"]
} else {
self.revsets.iter().map(|s| s.as_str()).collect()
}
}
}

View File

@@ -32,7 +32,7 @@ impl Body {
mod tests {
use super::*;
/// Default produces Body(None) no body
/// Default produces Body(None) - no body
#[test]
fn default_produces_none() {
assert_eq!(Body::default(), Body(None));
@@ -71,7 +71,7 @@ mod tests {
);
}
/// Leading and internal whitespace is preserved users may write
/// Leading and internal whitespace is preserved - users may write
/// indented lists, ASCII art, file trees, etc.
#[test]
fn from_preserves_leading_whitespace() {

View File

@@ -31,7 +31,7 @@ pub enum BreakingChange {
}
impl BreakingChange {
pub fn ignore(&self) -> bool {
pub fn is_absent(&self) -> bool {
matches!(self, BreakingChange::No)
}
@@ -66,7 +66,7 @@ where
mod tests {
use super::*;
/// Empty string produces Yes(None) no footer, only '!' in the header
/// Empty string produces Yes(None) - no footer, only '!' in the header
#[test]
fn from_empty_string_yields_yes_none() {
assert_eq!(BreakingChange::from(String::new()), BreakingChange::Yes);

View File

@@ -6,7 +6,7 @@ impl Description {
/// Soft limit for description length.
///
/// Descriptions over this length are warned about at the prompt layer but
/// are not rejected here the hard limit is the 72-character total first
/// are not rejected here - the hard limit is the 72-character total first
/// line enforced by [`crate::ConventionalCommit`].
pub const MAX_LENGTH: usize = 50;

View File

@@ -10,7 +10,7 @@ pub enum CommitMessageError {
/// The formatted message is not parseable as a conventional commit
///
/// This should never occur in normal use it indicates a bug in the
/// This should never occur in normal use - it indicates a bug in the
/// formatting logic.
#[error("output failed git-conventional validation: {reason}")]
InvalidConventionalFormat { reason: String },
@@ -76,7 +76,7 @@ impl ConventionalCommit {
pub fn first_line_len(&self) -> usize {
self.commit_type.len()
+ self.scope.header_segment_len()
+ if self.breaking_change.ignore() { 0 } else { 1 }
+ if self.breaking_change.is_absent() { 0 } else { 1 }
+ 2 // ": "
+ self.description.len()
}
@@ -932,7 +932,7 @@ mod tests {
/// Breaking change footer does not count toward the 72-character first-line limit
#[test]
fn breaking_change_footer_does_not_count_toward_line_limit() {
// First line is short; the note itself is long should still be accepted.
// First line is short; the note itself is long - should still be accepted.
let long_note = "x".repeat(200);
let result = ConventionalCommit::new(
CommitType::Fix,

View File

@@ -61,7 +61,11 @@ impl Scope {
/// Returns the visible length of the header segment
pub fn header_segment_len(&self) -> usize {
self.header_segment().chars().count()
if self.is_empty() {
0
} else {
self.0.chars().count() + 2
}
}
}

View File

@@ -1,3 +1,5 @@
use jj_lib::revset::{RevsetEvaluationError, RevsetParseError, RevsetResolutionError};
use crate::commit::types::{CommitMessageError, DescriptionError, ScopeError};
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
@@ -18,13 +20,17 @@ pub enum Error {
RepositoryLocked,
#[error("Could not get current directory")]
FailedGettingCurrentDir,
#[error("Could not load Jujutsu configuration")]
FailedReadingConfig,
#[error("Could not load Jujutsu configuration: {context}")]
FailedReadingConfig { context: String },
// Application errors
#[error("Operation cancelled by user")]
Cancelled,
#[error("Non-interactive terminal detected")]
NonInteractive,
#[error("Failed to resolve revision '{revset}': {context}")]
RevsetResolutionError { revset: String, context: String },
#[error("Revision set '{revset}' resolves to multiple commits; specify a single revision")]
MultipleRevisions { revset: String },
}
impl From<ScopeError> for Error {
@@ -46,7 +52,38 @@ impl From<CommitMessageError> for Error {
}
impl From<std::io::Error> for Error {
fn from(_value: std::io::Error) -> Self {
fn from(_: std::io::Error) -> Self {
Self::FailedGettingCurrentDir
}
}
impl<T> From<std::sync::PoisonError<T>> for Error {
fn from(_: std::sync::PoisonError<T>) -> Self {
Self::JjOperation {
context: "internal lock poisoned".to_string(),
}
}
}
impl Error {
pub fn from_revset_parse_error(revset: &str, error: RevsetParseError) -> Self {
Self::RevsetResolutionError {
revset: revset.to_string(),
context: error.to_string(),
}
}
pub fn from_revset_resolution_error(revset: &str, error: RevsetResolutionError) -> Self {
Self::RevsetResolutionError {
revset: revset.to_string(),
context: error.to_string(),
}
}
pub fn from_revset_evaluation_error(revset: &str, error: RevsetEvaluationError) -> Self {
Self::RevsetResolutionError {
revset: revset.to_string(),
context: error.to_string(),
}
}
}

View File

@@ -3,13 +3,24 @@
//! This implementation uses jj-lib 0.39.0 directly for repository detection
//! and commit description, replacing the earlier shell-out approach.
use std::path::{Path, PathBuf};
use std::{
collections::HashMap,
path::{Path, PathBuf},
sync::{Arc, Mutex},
};
use etcetera::BaseStrategy;
use jj_lib::{
backend::CommitId,
config::{ConfigSource, StackedConfig},
ref_name::WorkspaceName,
repo::{Repo, StoreFactories},
fileset::FilesetAliasesMap,
ref_name::WorkspaceNameBuf,
repo::{ReadonlyRepo, Repo, StoreFactories},
repo_path::RepoPathUiConverter,
revset::{
self, RevsetAliasesMap, RevsetDiagnostics, RevsetExtensions, RevsetParseContext,
RevsetWorkspaceContext, SymbolResolver, SymbolResolverExtension,
},
settings::UserSettings,
workspace::{Workspace, default_working_copy_factories},
};
@@ -21,36 +32,80 @@ use crate::jj::JjExecutor;
#[derive(Debug)]
pub struct JjLib {
working_dir: PathBuf,
repo: Mutex<Arc<ReadonlyRepo>>,
workspace_name: WorkspaceNameBuf,
workspace_root: PathBuf,
}
impl JjLib {
/// Create a new JjLib instance using the current working directory
pub fn new() -> Result<Self, Error> {
pub async fn new() -> Result<Self, Error> {
let working_dir = std::env::current_dir()?;
Ok(Self { working_dir })
let (repo, workspace_name, workspace_root) = Self::load_repo(&working_dir).await?;
Ok(Self {
working_dir,
repo: repo.into(),
workspace_name,
workspace_root,
})
}
/// Create a new JjLib instance with a specific working directory
pub fn with_working_dir(path: impl AsRef<Path>) -> Self {
Self {
pub async fn with_working_dir(path: impl AsRef<Path>) -> Result<Self, Error> {
let (repo, workspace_name, workspace_root) = Self::load_repo(path.as_ref()).await?;
Ok(Self {
working_dir: path.as_ref().to_path_buf(),
}
repo: repo.into(),
workspace_name,
workspace_root,
})
}
/// Load the repo from the given working directory
async fn load_repo(
working_dir: &Path,
) -> Result<(Arc<ReadonlyRepo>, WorkspaceNameBuf, PathBuf), Error> {
let settings = Self::load_settings()?;
let store_factories = StoreFactories::default();
let wc_factories = default_working_copy_factories();
let workspace = Workspace::load(&settings, working_dir, &store_factories, &wc_factories)
.map_err(|_| Error::NotARepository)?;
let repo =
workspace
.repo_loader()
.load_at_head()
.await
.map_err(|e| Error::JjOperation {
context: e.to_string(),
})?;
Ok((
repo,
workspace.workspace_name().to_owned(),
workspace.workspace_root().to_path_buf(),
))
}
fn load_settings() -> Result<UserSettings, Error> {
let mut config = StackedConfig::with_defaults();
for path in Self::user_config_paths() {
if path.is_dir() {
config
.load_dir(ConfigSource::User, &path)
.map_err(|_| Error::FailedReadingConfig)?;
config.load_dir(ConfigSource::User, &path).map_err(|e| {
Error::FailedReadingConfig {
context: e.to_string(),
}
})?;
} else if path.exists() {
config
.load_file(ConfigSource::User, path)
.map_err(|_| Error::FailedReadingConfig)?;
config.load_file(ConfigSource::User, path).map_err(|e| {
Error::FailedReadingConfig {
context: e.to_string(),
}
})?;
}
}
UserSettings::from_config(config).map_err(|_| Error::FailedReadingConfig)
UserSettings::from_config(config).map_err(|e| Error::FailedReadingConfig {
context: e.to_string(),
})
}
/// Resolves user config file paths following the same logic as the jj CLI:
@@ -94,6 +149,51 @@ impl JjLib {
paths
}
/// Resolve a revset string to a commit ID
fn get_commit_id(&self, revset: &str) -> Result<CommitId, Error> {
let context = RevsetParseContext {
workspace: Some(RevsetWorkspaceContext {
workspace_name: &self.workspace_name,
path_converter: &RepoPathUiConverter::Fs {
cwd: self.working_dir.clone(),
base: self.workspace_root.clone(),
},
}),
aliases_map: &RevsetAliasesMap::new(),
fileset_aliases_map: &FilesetAliasesMap::new(),
local_variables: HashMap::new(),
user_email: "",
date_pattern_context: chrono::Local::now().into(),
default_ignored_remote: None,
use_glob_by_default: false,
extensions: &RevsetExtensions::default(),
};
let mut diagnostic = RevsetDiagnostics::new();
let repo = self.repo.lock()?.clone();
let symbol_resolver =
SymbolResolver::new(&*repo, &([] as [Box<dyn SymbolResolverExtension>; 0]));
let revision = revset::parse(&mut diagnostic, revset, &context)
.map_err(|e| Error::from_revset_parse_error(revset, e))?
.resolve_user_expression(&*repo, &symbol_resolver)
.map_err(|e| Error::from_revset_resolution_error(revset, e))?
.evaluate(&*repo)
.map_err(|e| Error::from_revset_evaluation_error(revset, e))?;
let mut iter = revision.iter();
let commit_id = iter
.next()
.ok_or(Error::RevsetResolutionError {
revset: revset.to_string(),
context: "No matching revision".to_string(),
})?
.map_err(|e| Error::from_revset_evaluation_error(revset, e))?;
if iter.next().is_some() {
return Err(Error::MultipleRevisions {
revset: revset.to_string(),
});
}
Ok(commit_id)
}
}
#[async_trait::async_trait(?Send)]
@@ -111,49 +211,20 @@ impl JjExecutor for JjLib {
.is_ok())
}
async fn describe(&self, message: &str) -> Result<(), Error> {
let settings = Self::load_settings()?;
let store_factories = StoreFactories::default();
let wc_factories = default_working_copy_factories();
let workspace = Workspace::load(
&settings,
&self.working_dir,
&store_factories,
&wc_factories,
)
.map_err(|_| Error::NotARepository)?;
let repo =
workspace
.repo_loader()
.load_at_head()
.await
.map_err(|e| Error::JjOperation {
context: e.to_string(),
})?;
async fn describe(&self, revset: &str, message: &str) -> Result<(), Error> {
let commit_id = self.get_commit_id(revset)?;
let repo = self.repo.lock()?.clone();
let mut tx = repo.start_transaction();
let wc_commit_id = tx
let commit = tx
.repo()
.view()
.get_wc_commit_id(WorkspaceName::DEFAULT)
.ok_or_else(|| Error::JjOperation {
context: "No working copy commit found".to_string(),
})?
.clone();
let wc_commit =
tx.repo()
.store()
.get_commit(&wc_commit_id)
.map_err(|e| Error::JjOperation {
context: e.to_string(),
})?;
.store()
.get_commit(&commit_id)
.map_err(|e| Error::JjOperation {
context: e.to_string(),
})?;
tx.repo_mut()
.rewrite_commit(&wc_commit)
.rewrite_commit(&commit)
.set_description(message)
.write()
.await
@@ -168,14 +239,28 @@ impl JjExecutor for JjLib {
context: format!("{e:?}"),
})?;
tx.commit("jj-cz: update commit description")
let new_repo = tx
.commit("jj-cz: update commit description")
.await
.map_err(|e| Error::JjOperation {
context: e.to_string(),
})?;
*self.repo.lock()? = new_repo;
Ok(())
}
async fn get_description(&self, revset: &str) -> Result<String, Error> {
let commit_id = self.get_commit_id(revset)?;
let repo = self.repo.lock()?.clone();
let commit = repo
.store()
.get_commit(&commit_id)
.map_err(|e| Error::JjOperation {
context: e.to_string(),
})?;
Ok(commit.description().trim_end().to_string())
}
}
#[cfg(test)]
@@ -191,7 +276,6 @@ mod tests {
.map_err(|e| format!("Failed to init jj repo: {e}"))
}
/// Get the current commit description from a jj repository using jj-lib
async fn get_commit_description(dir: &Path) -> Result<String, String> {
let settings = JjLib::load_settings().map_err(|e| e.to_string())?;
let store_factories = StoreFactories::default();
@@ -208,7 +292,7 @@ mod tests {
let wc_commit_id = repo
.view()
.get_wc_commit_id(WorkspaceName::DEFAULT)
.get_wc_commit_id(jj_lib::ref_name::WorkspaceName::DEFAULT)
.ok_or_else(|| "No working copy commit found".to_string())?
.clone();
@@ -227,7 +311,7 @@ mod tests {
.await
.expect("Failed to init jj repo");
let executor = JjLib::with_working_dir(temp_dir.path());
let executor = JjLib::with_working_dir(temp_dir.path()).await.unwrap();
let result = executor.is_repository().await;
assert!(result.is_ok());
@@ -238,11 +322,8 @@ mod tests {
async fn is_repository_returns_false_outside_jj_repo() {
let temp_dir = assert_fs::TempDir::new().unwrap();
let executor = JjLib::with_working_dir(temp_dir.path());
let result = executor.is_repository().await;
assert!(result.is_ok());
assert!(!result.unwrap());
let executor = JjLib::with_working_dir(temp_dir.path()).await;
assert!(executor.is_err());
}
#[tokio::test]
@@ -253,9 +334,9 @@ mod tests {
.expect("Failed to init jj repo");
let test_message = "test: initial commit";
let executor = JjLib::with_working_dir(temp_dir.path());
let executor = JjLib::with_working_dir(temp_dir.path()).await.unwrap();
let result = executor.describe(test_message).await;
let result = executor.describe("@", test_message).await;
assert!(result.is_ok(), "describe failed: {result:?}");
let actual = get_commit_description(temp_dir.path())
@@ -272,9 +353,9 @@ mod tests {
.expect("Failed to init jj repo");
let test_message = "feat: add feature with special chars !@#$%^&*()";
let executor = JjLib::with_working_dir(temp_dir.path());
let executor = JjLib::with_working_dir(temp_dir.path()).await.unwrap();
let result = executor.describe(test_message).await;
let result = executor.describe("@", test_message).await;
assert!(result.is_ok());
let actual = get_commit_description(temp_dir.path())
@@ -291,9 +372,9 @@ mod tests {
.expect("Failed to init jj repo");
let test_message = "docs: add unicode support 🎉 🚀";
let executor = JjLib::with_working_dir(temp_dir.path());
let executor = JjLib::with_working_dir(temp_dir.path()).await.unwrap();
let result = executor.describe(test_message).await;
let result = executor.describe("@", test_message).await;
assert!(result.is_ok());
let actual = get_commit_description(temp_dir.path())
@@ -310,9 +391,9 @@ mod tests {
.expect("Failed to init jj repo");
let test_message = "feat: add feature\n\nThis is a multiline\ndescription";
let executor = JjLib::with_working_dir(temp_dir.path());
let executor = JjLib::with_working_dir(temp_dir.path()).await.unwrap();
let result = executor.describe(test_message).await;
let result = executor.describe("@", test_message).await;
assert!(result.is_ok());
let actual = get_commit_description(temp_dir.path())
@@ -323,13 +404,21 @@ mod tests {
#[tokio::test]
async fn describe_fails_outside_repo() {
// with_working_dir returns Err when not in a repo
let temp_dir = assert_fs::TempDir::new().unwrap();
let executor = JjLib::with_working_dir(temp_dir.path()).await;
assert!(executor.is_err());
let executor = JjLib::with_working_dir(temp_dir.path());
let result = executor.describe("test: should fail").await;
let valid_dir = assert_fs::TempDir::new().unwrap();
init_jj_repo(valid_dir.path())
.await
.expect("Failed to init jj repo");
let executor = JjLib::with_working_dir(valid_dir.path()).await.unwrap();
let result = executor
.describe("this-bookmark-does-not-exist", "test: should fail")
.await;
assert!(result.is_err());
assert!(matches!(result.unwrap_err(), Error::NotARepository));
}
#[tokio::test]
@@ -339,10 +428,10 @@ mod tests {
.await
.expect("Failed to init jj repo");
let executor = JjLib::with_working_dir(temp_dir.path());
let executor = JjLib::with_working_dir(temp_dir.path()).await.unwrap();
executor
.describe("feat: first commit")
.describe("@", "feat: first commit")
.await
.expect("First describe failed");
let desc1 = get_commit_description(temp_dir.path())
@@ -351,7 +440,7 @@ mod tests {
assert_eq!(desc1, "feat: first commit");
executor
.describe("feat: updated commit")
.describe("@", "feat: updated commit")
.await
.expect("Second describe failed");
let desc2 = get_commit_description(temp_dir.path())
@@ -360,11 +449,87 @@ mod tests {
assert_eq!(desc2, "feat: updated commit");
}
#[test]
fn jj_lib_implements_jj_executor_trait() {
let lib = JjLib::with_working_dir(std::path::Path::new("."));
fn accepts_executor(_: impl JjExecutor) {}
accepts_executor(lib);
#[tokio::test]
async fn get_description_returns_empty_for_fresh_commit() {
let temp_dir = assert_fs::TempDir::new().unwrap();
init_jj_repo(temp_dir.path())
.await
.expect("Failed to init jj repo");
let executor = JjLib::with_working_dir(temp_dir.path()).await.unwrap();
let desc = executor
.get_description("@")
.await
.expect("get_description failed");
assert_eq!(desc, "");
}
#[tokio::test]
async fn get_description_reflects_describe_on_same_executor() {
let temp_dir = assert_fs::TempDir::new().unwrap();
init_jj_repo(temp_dir.path())
.await
.expect("Failed to init jj repo");
let executor = JjLib::with_working_dir(temp_dir.path()).await.unwrap();
let message = "feat: test get_description";
executor
.describe("@", message)
.await
.expect("describe failed");
let desc = executor
.get_description("@")
.await
.expect("get_description failed");
assert_eq!(desc, message);
}
#[tokio::test]
async fn multiple_revisions_error_for_multi_commit_revset() {
let temp_dir = assert_fs::TempDir::new().unwrap();
init_jj_repo(temp_dir.path())
.await
.expect("Failed to init jj repo");
let executor = JjLib::with_working_dir(temp_dir.path()).await.unwrap();
let result = executor.describe("@ | root()", "test").await;
assert!(matches!(result, Err(Error::MultipleRevisions { .. })));
}
#[tokio::test]
async fn empty_revset_returns_resolution_error() {
let temp_dir = assert_fs::TempDir::new().unwrap();
init_jj_repo(temp_dir.path())
.await
.expect("Failed to init jj repo");
let executor = JjLib::with_working_dir(temp_dir.path()).await.unwrap();
let result = executor.describe("none()", "test").await;
assert!(matches!(result, Err(Error::RevsetResolutionError { .. })));
}
#[tokio::test]
async fn invalid_revset_syntax_returns_resolution_error() {
let temp_dir = assert_fs::TempDir::new().unwrap();
init_jj_repo(temp_dir.path())
.await
.expect("Failed to init jj repo");
let executor = JjLib::with_working_dir(temp_dir.path()).await.unwrap();
let result = executor.describe("(((invalid", "test").await;
assert!(matches!(result, Err(Error::RevsetResolutionError { .. })));
}
#[tokio::test]
async fn jj_lib_implements_jj_executor_trait() {
fn assert_implements<T: JjExecutor>() {}
assert_implements::<JjLib>();
}
mod user_config_paths_tests {

View File

@@ -15,6 +15,10 @@ pub struct MockJjExecutor {
is_repo_response: Result<bool, Error>,
/// Response to return from describe()
describe_response: Result<(), Error>,
/// Track described revsets
described_revsets: Mutex<Vec<String>>,
/// Track response to return from get_description()
get_description_response: Result<String, Error>,
/// Track calls to is_repository()
is_repo_called: AtomicBool,
/// Track calls to describe() with the message passed
@@ -26,6 +30,8 @@ impl Default for MockJjExecutor {
Self {
is_repo_response: Ok(true),
describe_response: Ok(()),
described_revsets: Mutex::new(Vec::new()),
get_description_response: Ok(String::new()),
is_repo_called: AtomicBool::new(false),
describe_calls: Mutex::new(Vec::new()),
}
@@ -50,6 +56,12 @@ impl MockJjExecutor {
self
}
/// Configure get_description() to return a specific value
pub fn with_get_description_response(mut self, response: Result<String, Error>) -> Self {
self.get_description_response = response;
self
}
/// Check if is_repository() was called
pub fn was_is_repo_called(&self) -> bool {
self.is_repo_called
@@ -60,6 +72,11 @@ impl MockJjExecutor {
pub fn describe_messages(&self) -> Vec<String> {
self.describe_calls.lock().unwrap().clone()
}
/// Get all revsets visited
pub fn described_revsets(&self) -> Vec<String> {
self.described_revsets.lock().unwrap().clone()
}
}
#[async_trait(?Send)]
@@ -73,7 +90,11 @@ impl JjExecutor for MockJjExecutor {
}
}
async fn describe(&self, message: &str) -> Result<(), Error> {
async fn describe(&self, revset: &str, message: &str) -> Result<(), Error> {
self.described_revsets
.lock()
.unwrap()
.push(revset.to_string());
self.describe_calls
.lock()
.unwrap()
@@ -83,6 +104,10 @@ impl JjExecutor for MockJjExecutor {
Err(e) => Err(e.clone()),
}
}
async fn get_description(&self, _revset: &str) -> Result<String, Error> {
self.get_description_response.clone()
}
}
#[cfg(test)]
@@ -130,7 +155,7 @@ mod tests {
#[tokio::test]
async fn mock_describe_records_message() {
let mock = MockJjExecutor::new();
let result = mock.describe("test message").await;
let result = mock.describe("@", "test message").await;
assert!(result.is_ok());
let messages = mock.describe_messages();
assert_eq!(messages.len(), 1);
@@ -141,8 +166,8 @@ mod tests {
#[tokio::test]
async fn mock_describe_records_multiple_messages() {
let mock = MockJjExecutor::new();
mock.describe("first message").await.unwrap();
mock.describe("second message").await.unwrap();
mock.describe("@", "first message").await.unwrap();
mock.describe("@", "second message").await.unwrap();
let messages = mock.describe_messages();
assert_eq!(messages.len(), 2);
assert_eq!(messages[0], "first message");
@@ -153,7 +178,7 @@ mod tests {
#[tokio::test]
async fn mock_describe_returns_error() {
let mock = MockJjExecutor::new().with_describe_response(Err(Error::RepositoryLocked));
let result = mock.describe("test").await;
let result = mock.describe("@", "test").await;
assert!(result.is_err());
assert!(matches!(result.unwrap_err(), Error::RepositoryLocked));
}
@@ -164,7 +189,7 @@ mod tests {
let mock = MockJjExecutor::new().with_describe_response(Err(Error::JjOperation {
context: "transaction failed".to_string(),
}));
let result = mock.describe("test").await;
let result = mock.describe("@", "test").await;
assert!(result.is_err());
match result.unwrap_err() {
Error::JjOperation { context } => {
@@ -208,7 +233,7 @@ mod tests {
#[tokio::test]
async fn mock_describe_accepts_empty_message() {
let mock = MockJjExecutor::new();
let result = mock.describe("").await;
let result = mock.describe("@", "").await;
assert!(result.is_ok());
assert_eq!(mock.describe_messages()[0], "");
}
@@ -218,7 +243,7 @@ mod tests {
async fn mock_describe_accepts_long_message() {
let mock = MockJjExecutor::new();
let long_message = "a".repeat(1000);
let result = mock.describe(&long_message).await;
let result = mock.describe("@", &long_message).await;
assert!(result.is_ok());
assert_eq!(mock.describe_messages()[0].len(), 1000);
}

View File

@@ -14,7 +14,13 @@ pub trait JjExecutor: Send + Sync {
async fn is_repository(&self) -> Result<bool, Error>;
/// Set the description of the current change
async fn describe(&self, message: &str) -> Result<(), Error>;
///
/// The revset parameter should resolve to a single commit (e.g.,
/// `"@"`, `"xs"`, bookmark name)
async fn describe(&self, revset: &str, message: &str) -> Result<(), Error>;
/// Get the current description of a specific revision
async fn get_description(&self, revset: &str) -> Result<String, Error>;
}
#[cfg(test)]

View File

@@ -1,4 +1,3 @@
mod cli;
mod commit;
mod error;
mod jj;

View File

@@ -21,7 +21,9 @@ fn error_to_exit_code(error: &Error) -> i32 {
Error::InvalidCommitMessage(_) => EXIT_ERROR,
Error::NonInteractive => EXIT_ERROR,
Error::FailedGettingCurrentDir => EXIT_ERROR,
Error::FailedReadingConfig => EXIT_ERROR,
Error::FailedReadingConfig { .. } => EXIT_ERROR,
Error::RevsetResolutionError { .. } => EXIT_ERROR,
Error::MultipleRevisions { .. } => EXIT_ERROR,
}
}
@@ -33,42 +35,38 @@ fn is_interactive_terminal() -> bool {
#[tokio::main]
async fn main() {
// Parse CLI arguments; --help and --version are handled automatically by clap
cli::Cli::parse();
let cli = cli::Cli::parse();
if !is_interactive_terminal() {
eprintln!("❌ Error: jj-cz requires an interactive terminal (TTY)");
eprintln!(" This tool cannot be used in non-interactive mode or when piping input.");
eprintln!(" Use --help for usage information.");
process::exit(EXIT_ERROR);
}
// Create the jj executor
let executor = match JjLib::new() {
let executor = match JjLib::new().await {
Ok(e) => e,
Err(e) => {
eprintln!("❌ Error: {}", e);
process::exit(EXIT_ERROR);
}
};
// Create and run the workflow
let workflow = CommitWorkflow::new(executor);
let result = workflow.run().await;
for revset in cli.revsets() {
let result = workflow.run_for_revset(revset).await;
handle_result(result);
}
// Handle the result
match result {
Ok(()) => {
println!("✅ Commit message applied successfully!");
process::exit(EXIT_SUCCESS);
}
Err(Error::Cancelled) => {
println!("🟡 Operation cancelled by user.");
process::exit(EXIT_CANCELLED);
}
Err(e) => {
eprintln!("❌ Error: {}", e);
process::exit(error_to_exit_code(&e));
fn handle_result(result: Result<(), Error>) {
match result {
Ok(()) => println!("✅ Commit message applied successfully!"),
Err(Error::Cancelled) => {
println!("🟡 Operation cancelled by user.");
process::exit(EXIT_CANCELLED);
}
Err(e) => {
eprintln!("❌ Error: {}", e);
process::exit(error_to_exit_code(&e));
}
}
}
process::exit(EXIT_SUCCESS);
}

View File

@@ -17,7 +17,7 @@ use crate::{
///
/// Implement this trait to supply a custom front-end (interactive TUI, mock,
/// headless, etc.) to [`CommitWorkflow`](super::CommitWorkflow).
pub trait Prompter: Send + Sync {
pub trait Prompter {
/// Prompt the user to select a commit type
fn select_commit_type(&self) -> Result<CommitType, Error>;
@@ -66,67 +66,32 @@ pub struct RealPrompts;
impl Prompter for RealPrompts {
fn select_commit_type(&self) -> Result<CommitType, Error> {
use inquire::Select;
let options: Vec<_> = CommitType::all()
.iter()
.map(|ct| format!("{}: {}", ct, ct.description()))
.collect();
let answer = Select::new("Select commit type:", options)
inquire::Select::new("Select commit type:", CommitType::all().to_vec())
.with_page_size(11)
.with_help_message(
"Use arrow keys to navigate, Enter to select. See https://www.conventionalcommits.org/ for details.",
)
.with_formatter(&|option| format!("{}: {}", option.value.as_str(), option.value.description()))
.prompt()
.map_err(|_| Error::Cancelled)?;
// Extract the commit type from the selected option
let selected_type = answer
.split(':')
.next()
.ok_or_else(|| Error::JjOperation {
context: "Failed to parse selected commit type".to_string(),
})?
.trim();
CommitType::all()
.iter()
.find(|ct| ct.as_str() == selected_type)
.copied()
.ok_or_else(|| Error::JjOperation {
context: format!("Unknown commit type: {}", selected_type),
})
.map_err(|_| Error::Cancelled)
}
fn input_scope(&self) -> Result<Scope, Error> {
use inquire::Text;
let answer = Text::new("Enter scope (optional):")
let answer = inquire::Text::new("Enter scope (optional):")
.with_help_message(
"Scope is optional. If provided, it should be a noun representing the section of code affected (e.g., 'api', 'ui', 'config'). Max 30 characters.",
)
.with_placeholder("Leave empty if no scope")
.prompt_skippable()
.map_err(|_| Error::Cancelled)?;
// Empty input is valid (no scope)
let answer_str = match answer {
Some(s) => s,
None => return Ok(Scope::empty()),
};
if answer_str.trim().is_empty() {
return Ok(Scope::empty());
match answer {
Some(s) if s.trim().is_empty() => Ok(Scope::empty()),
Some(s) => Scope::parse(s.trim()).map_err(|e| Error::InvalidScope(e.to_string())),
None => Ok(Scope::empty()),
}
// Parse and validate the scope
Scope::parse(answer_str.trim()).map_err(|e| Error::InvalidScope(e.to_string()))
}
fn input_description(&self) -> Result<Description, Error> {
use inquire::Text;
loop {
let answer = Text::new("Enter description (required):")
.with_help_message(
@@ -142,7 +107,7 @@ impl Prompter for RealPrompts {
continue;
}
// parse() only fails on empty already handled above
// parse() only fails on empty - already handled above
let Ok(desc) = Description::parse(trimmed) else {
println!("❌ Description cannot be empty. Please provide a description.");
continue;
@@ -180,13 +145,10 @@ impl Prompter for RealPrompts {
}
fn input_body(&self) -> Result<Body, Error> {
use inquire::Editor;
let wants_body = Confirm::new("Add a body?")
.with_default(false)
.prompt()
.map_err(|_| Error::Cancelled)?;
if !wants_body {
return Ok(Body::default());
}
@@ -196,12 +158,11 @@ JJ: Body (optional). Markdown is supported.\n\
JJ: Wrap prose lines at 72 characters where possible.\n\
JJ: Lines starting with \"JJ:\" will be removed.\n";
let raw = Editor::new("Body:")
let raw = inquire::Editor::new("Body:")
.with_predefined_text(template)
.with_file_extension(".md")
.prompt()
.map_err(|_| Error::Cancelled)?;
let stripped: String = raw
.lines()
.filter(|line| !line.starts_with("JJ:"))
@@ -212,16 +173,11 @@ JJ: Lines starting with \"JJ:\" will be removed.\n";
}
fn confirm_apply(&self, message: &str) -> Result<bool, Error> {
use inquire::Confirm;
// Show preview
println!(
"\n📝 Commit Message Preview:\n{}\n",
format_message_box(message)
);
// Get confirmation
Confirm::new("Apply this commit message?")
inquire::Confirm::new("Apply this commit message?")
.with_default(true)
.with_help_message("Select 'No' to cancel and start over")
.prompt()
@@ -313,7 +269,7 @@ mod tests {
}
/// A single CJK character (display width 2) is padded as if it occupies 2 columns,
/// not 1 so the right-hand padding is 70 spaces, not 71
/// not 1 - so the right-hand padding is 70 spaces, not 71
#[test]
fn format_message_box_single_cjk_char() {
let result = format_message_box("");

View File

@@ -54,23 +54,22 @@ impl<J: JjExecutor, P: Prompter> CommitWorkflow<J, P> {
/// - User cancels the workflow
/// - Repository operation fails
/// - Message validation fails
pub async fn run(&self) -> Result<(), Error> {
pub async fn run_for_revset(&self, revset: &str) -> Result<(), Error> {
if !self.executor.is_repository().await? {
return Err(Error::NotARepository);
}
let commit_type = self.type_selection().await?;
// For future reference
let _existing_desc = self.executor.get_description(revset).await.ok();
let commit_type = self.type_selection()?;
loop {
let scope = self.scope_input().await?;
let description = self.description_input().await?;
let breaking_change = self.breaking_change_input().await?;
let body = self.body_input().await?;
match self
.preview_and_confirm(commit_type, scope, description, breaking_change, body)
.await
{
let scope = self.scope_input()?;
let description = self.description_input()?;
let breaking_change = self.breaking_change_input()?;
let body = self.body_input()?;
match self.preview_and_confirm(commit_type, scope, description, breaking_change, body) {
Ok(conventional_commit) => {
self.executor
.describe(&conventional_commit.to_string())
.describe(revset, &conventional_commit.to_string())
.await?;
return Ok(());
}
@@ -86,7 +85,7 @@ impl<J: JjExecutor, P: Prompter> CommitWorkflow<J, P> {
}
/// Prompt user to select a commit type from the 11 available options
async fn type_selection(&self) -> Result<CommitType, Error> {
fn type_selection(&self) -> Result<CommitType, Error> {
self.prompts.select_commit_type()
}
@@ -94,7 +93,7 @@ impl<J: JjExecutor, P: Prompter> CommitWorkflow<J, P> {
///
/// Returns Ok(Scope) with the validated scope, or
/// Error::Cancelled if user cancels
async fn scope_input(&self) -> Result<Scope, Error> {
fn scope_input(&self) -> Result<Scope, Error> {
self.prompts.input_scope()
}
@@ -102,7 +101,7 @@ impl<J: JjExecutor, P: Prompter> CommitWorkflow<J, P> {
///
/// Returns Ok(Description) with the validated description, or
/// Error::Cancelled if user cancels
async fn description_input(&self) -> Result<Description, Error> {
fn description_input(&self) -> Result<Description, Error> {
self.prompts.input_description()
}
@@ -110,12 +109,12 @@ impl<J: JjExecutor, P: Prompter> CommitWorkflow<J, P> {
///
/// Returns Ok(BreakingChange) with the validated breaking change,
/// or Error::Cancel if user cancels
async fn breaking_change_input(&self) -> Result<BreakingChange, Error> {
fn breaking_change_input(&self) -> Result<BreakingChange, Error> {
self.prompts.input_breaking_change()
}
/// Prompt user to optionally add a free-form body via an external editor
async fn body_input(&self) -> Result<Body, Error> {
fn body_input(&self) -> Result<Body, Error> {
self.prompts.input_body()
}
@@ -123,7 +122,7 @@ impl<J: JjExecutor, P: Prompter> CommitWorkflow<J, P> {
///
/// This method also validates that the complete first line
/// doesn't exceed 72 characters
async fn preview_and_confirm(
fn preview_and_confirm(
&self,
commit_type: CommitType,
scope: Scope,
@@ -208,7 +207,7 @@ mod tests {
async fn workflow_returns_not_a_repository() {
let mock = MockJjExecutor::new().with_is_repo_response(Ok(false));
let workflow = CommitWorkflow::new(mock);
let result: Result<(), Error> = workflow.run().await;
let result: Result<(), Error> = workflow.run_for_revset("@").await;
assert!(result.is_err());
assert!(matches!(result.unwrap_err(), Error::NotARepository));
}
@@ -218,52 +217,52 @@ mod tests {
async fn workflow_returns_repository_error() {
let mock = MockJjExecutor::new().with_is_repo_response(Err(Error::NotARepository));
let workflow = CommitWorkflow::new(mock);
let result: Result<(), Error> = workflow.run().await;
let result: Result<(), Error> = workflow.run_for_revset("@").await;
assert!(result.is_err());
assert!(matches!(result.unwrap_err(), Error::NotARepository));
}
/// Test that type_selection returns a valid CommitType
#[tokio::test]
async fn type_selection_returns_valid_type() {
#[test]
fn type_selection_returns_valid_type() {
// Updated to use mock prompts to avoid TUI hanging
let mock_executor = MockJjExecutor::new();
let mock_prompts = MockPrompts::new().with_commit_type(CommitType::Feat);
let workflow = CommitWorkflow::with_prompts(mock_executor, mock_prompts);
// Now we can actually test the method with mock prompts
let result = workflow.type_selection().await;
let result = workflow.type_selection();
assert!(result.is_ok());
assert_eq!(result.unwrap(), CommitType::Feat);
}
/// Test that scope_input returns a valid Scope
#[tokio::test]
async fn scope_input_returns_valid_scope() {
#[test]
fn scope_input_returns_valid_scope() {
let mock_executor = MockJjExecutor::new();
let mock_prompts = MockPrompts::new().with_scope(Scope::parse("test").unwrap());
let workflow = CommitWorkflow::with_prompts(mock_executor, mock_prompts);
let result = workflow.scope_input().await;
let result = workflow.scope_input();
assert!(result.is_ok());
assert_eq!(result.unwrap(), Scope::parse("test").unwrap());
}
/// Test that description_input returns a valid Description
#[tokio::test]
async fn description_input_returns_valid_description() {
#[test]
fn description_input_returns_valid_description() {
let mock_executor = MockJjExecutor::new();
let mock_prompts = MockPrompts::new().with_description(Description::parse("test").unwrap());
let workflow = CommitWorkflow::with_prompts(mock_executor, mock_prompts);
let result = workflow.description_input().await;
let result = workflow.description_input();
assert!(result.is_ok());
assert_eq!(result.unwrap(), Description::parse("test").unwrap());
}
/// Test that preview_and_confirm returns a ConventionalCommit
#[tokio::test]
async fn preview_and_confirm_returns_conventional_commit() {
#[test]
fn preview_and_confirm_returns_conventional_commit() {
let mock_executor = MockJjExecutor::new();
let mock_prompts = MockPrompts::new().with_confirm(true);
let workflow = CommitWorkflow::with_prompts(mock_executor, mock_prompts);
@@ -273,9 +272,8 @@ mod tests {
let description = Description::parse("test description").unwrap();
let breaking_change = BreakingChange::No;
let body = Body::default();
let result = workflow
.preview_and_confirm(commit_type, scope, description, breaking_change, body)
.await;
let result =
workflow.preview_and_confirm(commit_type, scope, description, breaking_change, body);
assert!(result.is_ok());
}
@@ -289,7 +287,7 @@ mod tests {
// Verify the mock behaves as expected
assert!(mock.is_repository().await.is_ok());
assert!(mock.describe("test").await.is_err());
assert!(mock.describe("@", "test").await.is_err());
// Also test with a working mock
let working_mock = MockJjExecutor::new();
@@ -327,7 +325,7 @@ mod tests {
let workflow = CommitWorkflow::with_prompts(mock_executor, mock_prompts);
// Run the workflow - should succeed
let result: Result<(), Error> = workflow.run().await;
let result: Result<(), Error> = workflow.run_for_revset("@").await;
assert!(result.is_ok());
}
@@ -338,7 +336,7 @@ mod tests {
let mock_prompts = MockPrompts::new().with_error(Error::Cancelled);
let workflow = CommitWorkflow::with_prompts(mock_executor, mock_prompts);
let result: Result<(), Error> = workflow.run().await;
let result: Result<(), Error> = workflow.run_for_revset("@").await;
assert!(result.is_err());
assert!(matches!(result.unwrap_err(), Error::Cancelled));
@@ -357,7 +355,7 @@ mod tests {
.with_confirm(false); // User cancels at confirmation
let workflow = CommitWorkflow::with_prompts(mock_executor, mock_prompts);
let result: Result<(), Error> = workflow.run().await;
let result: Result<(), Error> = workflow.run_for_revset("@").await;
assert!(result.is_err());
assert!(matches!(result.unwrap_err(), Error::Cancelled));
@@ -388,7 +386,7 @@ mod tests {
// Clone before moving into workflow so we can inspect emitted messages after
let mock_prompts_handle = mock_prompts.clone();
let workflow = CommitWorkflow::with_prompts(mock_executor, mock_prompts);
let result: Result<(), Error> = workflow.run().await;
let result: Result<(), Error> = workflow.run_for_revset("@").await;
// Should succeed after the retry
assert!(
@@ -425,7 +423,7 @@ mod tests {
));
let workflow = CommitWorkflow::with_prompts(mock_executor, mock_prompts);
let result: Result<(), Error> = workflow.run().await;
let result: Result<(), Error> = workflow.run_for_revset("@").await;
assert!(result.is_err());
assert!(matches!(result.unwrap_err(), Error::InvalidScope(_)));
@@ -444,15 +442,15 @@ mod tests {
));
let workflow = CommitWorkflow::with_prompts(mock_executor, mock_prompts);
let result: Result<(), Error> = workflow.run().await;
let result: Result<(), Error> = workflow.run_for_revset("@").await;
assert!(result.is_err());
assert!(matches!(result.unwrap_err(), Error::InvalidDescription(_)));
}
/// Test that mock prompts track method calls correctly
#[tokio::test]
async fn test_mock_prompts_track_calls() {
#[test]
fn test_mock_prompts_track_calls() {
let mock_executor = MockJjExecutor::new().with_is_repo_response(Ok(true));
let mock_prompts = MockPrompts::new()
.with_commit_type(CommitType::Feat)
@@ -483,7 +481,7 @@ mod tests {
MockJjExecutor::new().with_is_repo_response(Ok(true)),
mock_prompts,
);
let result: Result<(), Error> = workflow.run().await;
let result: Result<(), Error> = workflow.run_for_revset("@").await;
assert!(result.is_ok(), "Failed for commit type: {:?}", commit_type);
}
}
@@ -507,7 +505,7 @@ mod tests {
mock_prompts,
);
{
let result: Result<(), Error> = workflow.run().await;
let result: Result<(), Error> = workflow.run_for_revset("@").await;
assert!(result.is_ok());
}
@@ -525,7 +523,7 @@ mod tests {
mock_prompts,
);
{
let result: Result<(), Error> = workflow.run().await;
let result: Result<(), Error> = workflow.run_for_revset("@").await;
assert!(result.is_ok());
}
}
@@ -552,21 +550,19 @@ mod tests {
/// BreakingChange::No was hard-coded, so a confirmed
/// breaking-change commit was silently applied without the '!'
/// marker.
#[tokio::test]
async fn preview_and_confirm_forwards_breaking_change_yes() {
#[test]
fn preview_and_confirm_forwards_breaking_change_yes() {
let mock_executor = MockJjExecutor::new();
let mock_prompts = MockPrompts::new().with_confirm(true);
let workflow = CommitWorkflow::with_prompts(mock_executor, mock_prompts);
let result = workflow
.preview_and_confirm(
CommitType::Feat,
Scope::empty(),
Description::parse("remove old API").unwrap(),
BreakingChange::Yes,
Body::default(),
)
.await;
let result = workflow.preview_and_confirm(
CommitType::Feat,
Scope::empty(),
Description::parse("remove old API").unwrap(),
BreakingChange::Yes,
Body::default(),
);
assert!(result.is_ok(), "expected Ok, got: {:?}", result);
let message = result.unwrap().to_string();
@@ -580,22 +576,20 @@ mod tests {
/// Preview_and_confirm must forward BreakingChange::WithNote,
/// producing a commit with both the '!' header marker and the
/// BREAKING CHANGE footer.
#[tokio::test]
async fn preview_and_confirm_forwards_breaking_change_with_note() {
#[test]
fn preview_and_confirm_forwards_breaking_change_with_note() {
let mock_executor = MockJjExecutor::new();
let mock_prompts = MockPrompts::new().with_confirm(true);
let workflow = CommitWorkflow::with_prompts(mock_executor, mock_prompts);
let breaking_change: BreakingChange = "removes legacy endpoint".into();
let result = workflow
.preview_and_confirm(
CommitType::Feat,
Scope::empty(),
Description::parse("drop legacy API").unwrap(),
breaking_change,
Body::default(),
)
.await;
let result = workflow.preview_and_confirm(
CommitType::Feat,
Scope::empty(),
Description::parse("drop legacy API").unwrap(),
breaking_change,
Body::default(),
);
assert!(result.is_ok(), "expected Ok, got: {:?}", result);
let message = result.unwrap().to_string();
@@ -629,7 +623,7 @@ mod tests {
.with_confirm(true);
let workflow = CommitWorkflow::with_prompts(mock_executor, mock_prompts);
let result: Result<(), Error> = workflow.run().await;
let result: Result<(), Error> = workflow.run_for_revset("@").await;
assert!(
result.is_ok(),
@@ -655,21 +649,19 @@ mod tests {
///
/// Currently the implementation passes Body::default() instead of the
/// received body, so this test will fail until that is fixed.
#[tokio::test]
async fn preview_and_confirm_forwards_body() {
#[test]
fn preview_and_confirm_forwards_body() {
let mock_executor = MockJjExecutor::new();
let mock_prompts = MockPrompts::new().with_confirm(true);
let workflow = CommitWorkflow::with_prompts(mock_executor, mock_prompts);
let result = workflow
.preview_and_confirm(
CommitType::Feat,
Scope::empty(),
Description::parse("add feature").unwrap(),
BreakingChange::No,
Body::from("This explains the change."),
)
.await;
let result = workflow.preview_and_confirm(
CommitType::Feat,
Scope::empty(),
Description::parse("add feature").unwrap(),
BreakingChange::No,
Body::from("This explains the change."),
);
assert!(result.is_ok(), "expected Ok, got: {:?}", result);
assert!(
@@ -684,21 +676,19 @@ mod tests {
/// preview_and_confirm must forward the body even when a breaking change is present
///
/// Expected format: "type!: desc\n\nbody\n\nBREAKING CHANGE: note"
#[tokio::test]
async fn preview_and_confirm_forwards_body_with_breaking_change() {
#[test]
fn preview_and_confirm_forwards_body_with_breaking_change() {
let mock_executor = MockJjExecutor::new();
let mock_prompts = MockPrompts::new().with_confirm(true);
let workflow = CommitWorkflow::with_prompts(mock_executor, mock_prompts);
let result = workflow
.preview_and_confirm(
CommitType::Feat,
Scope::empty(),
Description::parse("drop legacy API").unwrap(),
"removes legacy endpoint".into(),
Body::from("The endpoint was deprecated in v2."),
)
.await;
let result = workflow.preview_and_confirm(
CommitType::Feat,
Scope::empty(),
Description::parse("drop legacy API").unwrap(),
"removes legacy endpoint".into(),
Body::from("The endpoint was deprecated in v2."),
);
assert!(result.is_ok(), "expected Ok, got: {:?}", result);
let message = result.unwrap().to_string();
@@ -728,7 +718,7 @@ mod tests {
.with_confirm(true);
let workflow = CommitWorkflow::with_prompts(mock_executor, mock_prompts);
let result: Result<(), Error> = workflow.run().await;
let result: Result<(), Error> = workflow.run_for_revset("@").await;
assert!(
result.is_ok(),
@@ -760,7 +750,7 @@ mod tests {
.with_confirm(true);
let workflow = CommitWorkflow::with_prompts(mock_executor, mock_prompts);
let result: Result<(), Error> = workflow.run().await;
let result: Result<(), Error> = workflow.run_for_revset("@").await;
assert!(
result.is_ok(),

View File

@@ -1,28 +1,13 @@
use assert_fs::TempDir;
#[cfg(feature = "test-utils")]
use jj_cz::{Body, BreakingChange, CommitType, Description, MockPrompts, Scope};
use jj_cz::{Body, BreakingChange, CommitType, Description, MockJjExecutor, MockPrompts, Scope};
use jj_cz::{CommitWorkflow, Error, JjLib};
#[cfg(feature = "test-utils")]
use jj_lib::{config::StackedConfig, settings::UserSettings, workspace::Workspace};
/// Helper to initialize a temporary jj repository using jj-lib directly (no CLI required)
#[cfg(feature = "test-utils")]
async fn init_jj_repo(temp_dir: &TempDir) {
let config = StackedConfig::with_defaults();
let settings = UserSettings::from_config(config).expect("Failed to create settings");
Workspace::init_internal_git(&settings, temp_dir.path())
.await
.expect("Failed to initialize jj repository");
}
#[cfg(feature = "test-utils")]
#[tokio::test]
async fn test_happy_path_integration() {
// T037: Happy path integration test
let temp_dir = TempDir::new().unwrap();
init_jj_repo(&temp_dir).await;
// Create mock prompts that simulate a successful workflow
let mock_executor = MockJjExecutor::new();
let mock_prompts = MockPrompts::new()
.with_commit_type(CommitType::Feat)
.with_scope(Scope::empty())
@@ -31,13 +16,9 @@ async fn test_happy_path_integration() {
.with_body(Body::default())
.with_confirm(true);
// Create a mock executor that tracks calls
let executor = JjLib::with_working_dir(temp_dir.path());
let workflow = CommitWorkflow::with_prompts(executor, mock_prompts);
let workflow = CommitWorkflow::with_prompts(mock_executor, mock_prompts);
let result = workflow.run_for_revset("@").await;
let result = workflow.run().await;
// The workflow should complete successfully
assert!(
result.is_ok(),
"Workflow should complete successfully: {:?}",
@@ -47,17 +28,11 @@ async fn test_happy_path_integration() {
#[tokio::test]
async fn test_not_in_repo() {
// T038: Not-in-repo integration test
// T038: Not-in-repo integration test - with_working_dir itself returns the error
let temp_dir = TempDir::new().unwrap();
// Don't initialize jj repo
// Create executor with the temp directory (which is not a jj repo)
let executor = JjLib::with_working_dir(temp_dir.path());
let workflow = CommitWorkflow::new(executor);
let result = JjLib::with_working_dir(temp_dir.path()).await;
let result = workflow.run().await;
// Should fail with NotARepository error
assert!(matches!(result, Err(Error::NotARepository)));
}
@@ -77,9 +52,13 @@ async fn test_cancellation() {
Ok(true)
}
async fn describe(&self, _message: &str) -> Result<(), Error> {
async fn describe(&self, _revset: &str, _message: &str) -> Result<(), Error> {
Err(Error::Cancelled)
}
async fn get_description(&self, _revset: &str) -> Result<String, Error> {
Ok(String::new())
}
}
let executor = CancelMock;
@@ -92,7 +71,7 @@ async fn test_cancellation() {
.with_confirm(true);
let workflow = CommitWorkflow::with_prompts(executor, mock_prompts);
let result = workflow.run().await;
let result = workflow.run_for_revset("@").await;
// Should fail with Cancelled error
assert!(matches!(result, Err(Error::Cancelled)));

View File

@@ -20,7 +20,9 @@ fn test_all_error_variants() {
};
let _repo_locked = Error::RepositoryLocked;
let _failed_dir = Error::FailedGettingCurrentDir;
let _failed_config = Error::FailedReadingConfig;
let _failed_config = Error::FailedReadingConfig {
context: "test".to_string(),
};
// Application errors
let cancelled = Error::Cancelled;