use std::{
path::{Path, PathBuf},
process::Command,
};
use crate::commits::CommitInfo;
use crate::errors::{ReleaseError, Result};
pub trait JjBackend {
fn log_commits(&self, revset: &str) -> Result<Vec<CommitInfo>>;
fn new_commit(&self, message: &str) -> Result<String>;
fn create_tag(&self, tag: &str, revision: &str) -> Result<()>;
fn set_bookmark(&self, name: &str, revision: &str) -> Result<()>;
fn git_push(&self, bookmark: Option<&str>, tag: Option<&str>) -> Result<()>;
fn git_export(&self) -> Result<()>;
fn list_tags(&self) -> Result<Vec<String>>;
fn check_identity(&self) -> Result<()>;
fn log_commits_for_path(&self, revset: &str, path: &str) -> Result<Vec<CommitInfo>>;
}
pub struct ShellBackend {
root: PathBuf,
jj_bin: PathBuf,
}
impl ShellBackend {
pub fn new(root: impl AsRef<Path>) -> Result<Self> {
let jj_bin = which::which("jj").map_err(|_| ReleaseError::MissingTool("jj".into()))?;
Ok(Self {
root: root.as_ref().to_path_buf(),
jj_bin,
})
}
fn run(&self, args: &[&str]) -> Result<String> {
let out = Command::new(&self.jj_bin)
.args(args)
.arg("--no-pager")
.current_dir(&self.root)
.output()
.map_err(|e| {
ReleaseError::Message(format!("failed to spawn jj {}: {e}", args.join(" ")))
})?;
if !out.status.success() {
let stderr = String::from_utf8_lossy(&out.stderr);
return Err(ReleaseError::Message(format!(
"jj {} failed:\n{stderr}",
args.join(" ")
)));
}
Ok(String::from_utf8_lossy(&out.stdout).into_owned())
}
fn run_silent(&self, args: &[&str]) -> Result<()> {
self.run(args).map(|_| ())
}
}
impl JjBackend for ShellBackend {
fn log_commits(&self, revset: &str) -> Result<Vec<CommitInfo>> {
let raw = self.run(&[
"log",
"--no-graph",
"-r",
revset,
"-T",
r#"change_id ++ "\x1f" ++ description ++ "\x1e""#,
])?;
let mut commits = Vec::new();
for record in raw.split('\x1e') {
let record = record.trim();
if record.is_empty() {
continue;
}
let (change_id, description) = record.split_once('\x1f').ok_or_else(|| {
ReleaseError::Message(format!("unexpected log format: {record:?}"))
})?;
commits.push(CommitInfo {
change_id: change_id.trim().to_owned(),
description: description.trim().to_owned(),
});
}
Ok(commits)
}
fn new_commit(&self, message: &str) -> Result<String> {
self.run_silent(&["describe", "-m", message])?;
let id = self.run(&["log", "--no-graph", "-r", "@", "-T", r#"change_id ++ "\n""#])?;
Ok(id.trim().to_owned())
}
fn create_tag(&self, tag: &str, revision: &str) -> Result<()> {
self.run_silent(&["tag", "set", tag, "-r", revision, "--allow-move"])
}
fn set_bookmark(&self, name: &str, revision: &str) -> Result<()> {
self.run_silent(&["bookmark", "set", name, "--revision", revision])
}
fn git_push(&self, bookmark: Option<&str>, tag: Option<&str>) -> Result<()> {
if let Some(bookmark) = bookmark {
self.run_silent(&["git", "push", "--bookmark", bookmark])?;
}
if let Some(tag) = tag {
self.run_silent(&["git", "push", "--tag", tag])?;
}
Ok(())
}
fn git_export(&self) -> Result<()> {
self.run_silent(&["git", "export"])
}
fn list_tags(&self) -> Result<Vec<String>> {
let raw = self.run(&["tag", "list", "--template", r#"name ++ "\n""#])?;
Ok(raw
.lines()
.map(|l| l.trim().to_owned())
.filter(|l| !l.is_empty())
.collect())
}
fn check_identity(&self) -> Result<()> {
self.run(&["config", "get", "user.email"]).map_err(|_| {
ReleaseError::Message(
"jj user.email not set, run: jj config set --user user.email 'you@example.com'"
.into(),
)
})?;
self.run(&["config", "get", "user.name"]).map_err(|_| {
ReleaseError::Message(
"jj user.name not set, run: jj config set --user user.name 'Your Name'".into(),
)
})?;
Ok(())
}
fn log_commits_for_path(&self, revset: &str, path: &str) -> Result<Vec<CommitInfo>> {
let raw = self.run(&[
"log",
"--no-graph",
"-r",
revset,
"-T",
r#"change_id ++ "\x1f" ++ description ++ "\x1e""#,
path, ])?;
let mut commits = Vec::new();
for record in raw.split('\x1e') {
let record = record.trim();
if record.is_empty() {
continue;
}
let (change_id, description) = record.split_once('\x1f').ok_or_else(|| {
ReleaseError::Message(format!("unexpected log format: {record:?}"))
})?;
commits.push(CommitInfo {
change_id: change_id.trim().to_owned(),
description: description.trim().to_owned(),
});
}
Ok(commits)
}
}
pub fn find_repo_root(start: &Path) -> Result<PathBuf> {
let mut dir = start.to_path_buf();
loop {
if dir.join(".jj").exists() {
return Ok(dir);
}
if !dir.pop() {
return Err(ReleaseError::Message(format!(
"not inside a jj repository (no .jj/ found from {})",
start.display()
)));
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
use tempfile::tempdir;
#[test]
fn find_repo_root_finds_jj_dir() {
let dir = tempdir().unwrap();
fs::create_dir(dir.path().join(".jj")).unwrap();
let found = find_repo_root(dir.path()).unwrap();
assert_eq!(found, dir.path());
}
#[test]
fn find_repo_root_walks_up() {
let dir = tempdir().unwrap();
fs::create_dir(dir.path().join(".jj")).unwrap();
let subdir = dir.path().join("a").join("b").join("c");
fs::create_dir_all(&subdir).unwrap();
let found = find_repo_root(&subdir).unwrap();
assert_eq!(found, dir.path());
}
#[test]
fn find_repo_root_errors_when_not_found() {
let dir = tempdir().unwrap();
assert!(find_repo_root(dir.path()).is_err());
}
#[test]
fn shell_backend_errors_without_jj() {
if which::which("jj").is_ok() {
let dir = tempdir().unwrap();
assert!(ShellBackend::new(dir.path()).is_ok());
}
}
}