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
This commit is contained in:
2026-04-05 23:02:14 +02:00
parent 3da214ae4c
commit 3c9cb8bd73
17 changed files with 436 additions and 168 deletions

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,20 +32,58 @@ 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> {
@@ -100,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)]
@@ -117,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
@@ -174,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)]
@@ -197,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();
@@ -214,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();
@@ -233,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());
@@ -244,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]
@@ -259,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())
@@ -278,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())
@@ -297,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())
@@ -316,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())
@@ -329,13 +404,19 @@ 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]
@@ -345,10 +426,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())
@@ -357,7 +438,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())
@@ -366,11 +447,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)]