1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
//! Thin abstraction over jj operations.
//!
//! All jj interaction goes through [`JjBackend`]. The [`ShellBackend`] impl
//! shells out to the `jj` binary. A future `LibBackend` could use jj-lib
//! directly without changing anything upstream of this module.
use std::{
path::{Path, PathBuf},
process::Command,
};
use crate::errors::{ReleaseError, Result};
use jj_release_changelog::CommitInfo;
/// Everything jj-release needs from the VCS layer.
pub trait JjBackend {
/// Return `(change_id, description)` pairs for every commit matched by
/// `revset`, newest-first.
///
/// # Errors
///
/// Returns an error if the `revset` expression is syntactically invalid or
/// if the underlying command execution fails.
fn log_commits(&self, revset: &str) -> Result<Vec<CommitInfo>>;
/// Create a new commit on top of `@` with the given message.
/// Returns the new commit's change id.
///
/// # Errors
///
/// Returns an error if there are unresolved conflicts or if the commit
/// creation fails.
fn new_commit(&self, message: &str) -> Result<String>;
/// Create (or move) a tag to the given revision.
/// # Errors
///
/// Returns an error if the target revision does not exist or if tag
/// creation fails.
fn create_tag(&self, tag: &str, revision: &str) -> Result<()>;
/// Move a bookmark to the given revision.
///
/// # Errors
///
/// Returns an error if the bookmark or revision can't be resolved, or
/// if the update fails.
fn set_bookmark(&self, name: &str, revision: &str) -> Result<()>;
/// Push bookmark(s) and tags to `origin`.
///
/// # Errors
///
/// Returns an error if network operations fail, authentication fails,
/// or the remote rejects the push.
fn git_push(&self, bookmark: Option<&str>, tag: Option<&str>) -> Result<()>;
/// Export jj state to the colocated git repo (needed before raw git ops).
///
/// # Errors
///
/// Returns an error if the export fails due to workspace state or
/// command execution failure.
fn git_export(&self) -> Result<()>;
/// List all local tag names.
///
/// # Errors
///
/// Returns an error if the underlying command fails to retrieve tags.
fn list_tags(&self, revset: &str) -> Result<Vec<String>>;
/// Verify that `user.name` and `user.email` are configured in jj.
/// Called before any mutations to fail fast with a clear message.
///
/// # Errors
///
/// Returns an error if either `user.name` or `user.email` is not set,
/// with a hint on how to fix it.
fn check_identity(&self) -> Result<()>;
/// Return commits that modified files under `path`, filtered by `revset`.
///
/// # Errors
///
/// This function will return an error in the following situations:
/// * The provided `revset` string is invalid or malformed.
/// * Querying the underlying version control backend for commit logs fails.
fn log_commits_for_path(&self, revset: &str, path: &str) -> Result<Vec<CommitInfo>>;
/// Committer date of `rev` as `YYYY-MM-DD`.
///
/// # Errors
///
/// Returns an error if the revision doesn't exist or `jj` fails.
fn commit_date(&self, rev: &str) -> Result<String> {
let _ = rev;
Ok(jiff::Zoned::now().date().to_string())
}
/// Check if a tag already exists.
///
/// # Errors
///
/// Returns an error if the underlying command fails.
fn tag_exists(&self, tag: &str) -> Result<bool>;
}
// Shell implementation
/// Shells out to the `jj` binary found on `$PATH`.
pub struct ShellBackend {
/// Repo root (where `.jj/` lives).
root: PathBuf,
/// Path to the `jj` binary.
jj_bin: PathBuf,
}
impl ShellBackend {
/// Creates a new backend instance rooted at the specified path,
/// locating the jj binary on the system PATH.
///
/// # Errors
///
/// Returns an error if the jj executable is not found on the system PATH.
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,
})
}
/// Run `jj <args>` from the repo root, return stdout as a String.
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())
}
/// Run `jj <args>` and discard stdout (for mutation commands).
fn run_silent(&self, args: &[&str]) -> Result<()> {
self.run(args).map(|_| ())
}
}
impl JjBackend for ShellBackend {
fn log_commits(&self, revset: &str) -> Result<Vec<CommitInfo>> {
// Use a separator that won't appear in commit messages.
// Format: <change_id>\x1f<description>\x1e
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> {
// `jj describe` snapshots whatever is currently on disk into @ and
// sets the message, so edits made before this call (e.g. Cargo.toml)
// are captured in the commit rather than left as working-copy changes.
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<()> {
// Push the bookmark first.
if let Some(bookmark) = bookmark {
self.run_silent(&["git", "push", "--bookmark", bookmark])?;
}
// Push the tag by name, --tag is mutually exclusive with --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, revset: &str) -> Result<Vec<String>> {
let raw = self.run(&[
"log",
"-r",
revset,
"--no-graph",
"-T",
r#"tags.join("\n") ++ "\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, // jj log accepts a path filter as a positional argument
])?;
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 commit_date(&self, rev: &str) -> Result<String> {
let out = self.run(&[
"log",
"-r",
rev,
"--no-graph",
"-T",
r#"committer.timestamp().format("%Y-%m-%d")"#,
])?;
Ok(out.trim().to_owned())
}
fn tag_exists(&self, tag: &str) -> Result<bool> {
// Attempt to log the exact tag. If jj exits successfully, the tag exists.
// We use Command directly here to avoid the automatic error translation in `self.run()`.
let out = Command::new(&self.jj_bin)
.args(["log", "--no-graph", "-r", tag])
.current_dir(&self.root)
.output()
.map_err(|e| ReleaseError::Message(format!("failed to spawn jj: {e}")))?;
Ok(out.status.success())
}
}
/// Locate the repo root by walking up from `start` until we find `.jj/`.
///
/// # Errors
///
/// Returns an error if no .jj/ directory is found between the starting path
/// and the filesystem root.
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();
// No .jj directory, should error
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());
}
}
}