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
use camino::Utf8Path;
use std::process::Command;

use crate::Error;
use crate::Result;

/// What a jj command printed.
pub(crate) struct Output {
    pub(crate) stdout: String,
    pub(crate) stderr: String,
}

/// Runs jj, failing with its stderr when it exits non-zero.
///
/// Without `snapshot`, jj leaves the working copy alone, so read-only
/// commands record no operation.
pub(crate) fn jj(repo: Option<&Utf8Path>, snapshot: bool, args: &[&str]) -> Result<Output> {
    let (output, success, flags) = run(repo, snapshot, args)?;
    if success {
        Ok(output)
    } else {
        Err(Error::msg(format!(
            "{flags}{} failed:\n{}",
            args.join(" "),
            output.stderr
        )))
    }
}

/// Runs jj and returns its output whether or not it succeeded.
pub(crate) fn jj_allow_failure(
    repo: Option<&Utf8Path>,
    snapshot: bool,
    args: &[&str],
) -> Result<Output> {
    Ok(run(repo, snapshot, args)?.0)
}

fn run(repo: Option<&Utf8Path>, snapshot: bool, args: &[&str]) -> Result<(Output, bool, String)> {
    let mut flags = Vec::new();
    if !snapshot {
        flags.push("--ignore-working-copy");
    }
    if let Some(repo) = repo {
        flags.extend(["-R", repo.as_str()]);
    }
    // Finishing a task from its workspace rewrites the main working copy, so
    // the main workspace is stale on its next command unless jj updates it.
    let out = Command::new("jj")
        .args(["--no-pager", "--color=never"])
        .args(["--config", "snapshot.auto-update-stale=true"])
        .args(&flags)
        .args(args)
        .output()?;
    let output = Output {
        stdout: String::from_utf8(out.stdout)?,
        stderr: String::from_utf8(out.stderr)?,
    };
    // Matches the Ruby error text: the flags after --color, then the args.
    let flags = flags.iter().map(|f| format!("{f} ")).collect();
    Ok((output, out.status.success(), flags))
}