Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

17.5 KB
Raw Blame
//! Tests for git-style custom subcommand dispatch (`wt-<name>`).

use crate::common::{
    mock_commands::{MockConfig, MockResponse},
    setup_home_snapshot_settings, wt_command,
};
// Used only by the `#[cfg(unix)]` non-UTF-8 test below; gate the import to
// match, or it reads as unused on Windows under `-D warnings`.
#[cfg(unix)]
use crate::common::TestRepo;
use ansi_str::AnsiStr;
use insta_cmd::assert_cmd_snapshot;
use std::path::{Path, PathBuf};
use std::process::Command;
use tempfile::TempDir;

/// Prepend `dir` to PATH on the given command.
fn prepend_path(cmd: &mut Command, dir: &Path) {
    let (path_var, current) = std::env::vars_os()
        .find(|(k, _)| k.eq_ignore_ascii_case("PATH"))
        .map(|(k, v)| (k.to_string_lossy().into_owned(), Some(v)))
        .unwrap_or(("PATH".to_string(), None));

    let mut paths: Vec<PathBuf> = current
        .as_deref()
        .map(|p| std::env::split_paths(p).collect())
        .unwrap_or_default();
    paths.insert(0, dir.to_path_buf());
    let new_path = std::env::join_paths(&paths).unwrap();
    cmd.env(path_var, new_path);
}

/// Create a mock `wt-<name>` binary in a temp dir, and return the dir.
fn mock_bin_dir(name: &str, response: MockResponse) -> TempDir {
    let dir = worktrunk::testing::tempdir().unwrap();
    MockConfig::new(name)
        .command("_default", response)
        .write(dir.path());
    dir
}

/// Limit PATH to a supported Git executable, excluding every `wt-*` custom
/// subcommand without bypassing wt's startup requirements. `rev-parse`
/// answers the way real git does outside a repository — exit 128 with the
/// fatal message — so repo-discovery tests exercise "no repository" rather
/// than "git failed" (mock_stub's fallback for an unmatched command is
/// exit 1 with no output), and that fatal line is the one the alias error
/// quotes back.
fn set_git_only_path(cmd: &mut Command) -> TempDir {
    let dir = worktrunk::testing::tempdir().unwrap();
    MockConfig::new("git")
        .version("git version 2.43.0")
        .command(
            "rev-parse",
            MockResponse::exit(128).with_stderr(
                "fatal: not a git repository (or any of the parent directories): .git\n",
            ),
        )
        .write(dir.path());
    cmd.env("PATH", dir.path())
        .env("WORKTRUNK_TEST_MOCK_CONFIG_DIR", dir.path());
    dir
}

#[test]
fn custom_subcommand_runs_wt_prefixed_binary_on_path() {
    // `wt wt-test-extcmd-ok` should find `wt-wt-test-extcmd-ok` on PATH.
    // We use a deliberately unique name so host PATH pollution doesn't match.
    let dir = mock_bin_dir("wt-wt-test-extcmd-ok", MockResponse::output("custom ran\n"));

    let mut cmd = wt_command();
    prepend_path(&mut cmd, dir.path());
    cmd.env("WORKTRUNK_TEST_MOCK_CONFIG_DIR", dir.path());
    cmd.args(["wt-test-extcmd-ok", "arg1", "arg2"]);

    let output = cmd.output().expect("failed to run wt");
    assert!(
        output.status.success(),
        "expected success, stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "custom ran");
}

#[cfg(unix)]
#[test]
fn custom_subcommand_accepts_non_utf8_forwarded_arg() {
    use std::ffi::OsString;
    use std::os::unix::ffi::OsStringExt;
    use std::os::unix::fs::PermissionsExt;

    let dir = worktrunk::testing::tempdir().unwrap();
    let script = dir.path().join("wt-wt-test-extcmd-raw");
    std::fs::write(&script, "#!/bin/sh\nprintf 'custom ran\\n'\n").unwrap();
    let mut perms = std::fs::metadata(&script).unwrap().permissions();
    perms.set_mode(0o755);
    std::fs::set_permissions(&script, perms).unwrap();

    let mut cmd = wt_command();
    prepend_path(&mut cmd, dir.path());
    cmd.arg("wt-test-extcmd-raw")
        .arg(OsString::from_vec(vec![0xff]));

    let output = cmd.output().expect("failed to run wt");
    assert!(
        output.status.success(),
        "expected success, stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "custom ran");
}

#[cfg(unix)]
#[test]
fn custom_subcommand_scrubs_shell_exec_directives_and_preserves_cd() {
    use std::os::unix::fs::PermissionsExt;
    use worktrunk::shell_exec::{
        DIRECTIVE_CD_FILE_ENV_VAR, DIRECTIVE_EXEC_FILE_ENV_VAR, RETIRED_DIRECTIVE_FILE_ENV_VAR,
    };

    let dir = worktrunk::testing::tempdir().unwrap();
    let retired_file = dir.path().join("retired");
    let cd_file = dir.path().join("cd");
    let exec_file = dir.path().join("exec");
    std::fs::write(&retired_file, "").unwrap();
    std::fs::write(&cd_file, "").unwrap();
    std::fs::write(&exec_file, "").unwrap();

    let script = dir.path().join("wt-wt-test-extcmd-directives");
    std::fs::write(
        &script,
        r#"#!/bin/sh
if [ -n "${WORKTRUNK_DIRECTIVE_FILE+x}" ]; then
    printf 'retired write\n' >> "$WORKTRUNK_DIRECTIVE_FILE"
fi
printf 'retired=%s\ncd=%s\nexec=%s\n' "${WORKTRUNK_DIRECTIVE_FILE-unset}" "${WORKTRUNK_DIRECTIVE_CD_FILE-unset}" "${WORKTRUNK_DIRECTIVE_EXEC_FILE-unset}"
"#,
    )
    .unwrap();
    std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();

    let mut cmd = wt_command();
    prepend_path(&mut cmd, dir.path());
    cmd.env(RETIRED_DIRECTIVE_FILE_ENV_VAR, &retired_file)
        .env(DIRECTIVE_CD_FILE_ENV_VAR, &cd_file)
        .env(DIRECTIVE_EXEC_FILE_ENV_VAR, &exec_file)
        .arg("wt-test-extcmd-directives");

    let output = cmd.output().expect("failed to run wt");
    assert!(
        output.status.success(),
        "expected success, stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("retired=unset"), "{stdout}");
    assert!(
        stdout.contains(&format!("cd={}", cd_file.display())),
        "{stdout}"
    );
    assert!(stdout.contains("exec=unset"), "{stdout}");
    assert_eq!(
        std::fs::read_to_string(&retired_file).unwrap(),
        "",
        "the retired directive file must remain untouched"
    );
}

#[test]
fn custom_subcommand_not_found_prints_clap_error() {
    let mut cmd = wt_command();
    let _git_only_path = set_git_only_path(&mut cmd);
    cmd.arg("definitely-not-a-wt-subcommand");

    let output = cmd.output().expect("failed to run wt");
    assert!(!output.status.success(), "expected failure");
    // clap's standard InvalidSubcommand exit code.
    assert_eq!(output.status.code(), Some(2));
    let stderr = String::from_utf8_lossy(&output.stderr)
        .ansi_strip()
        .into_owned();
    assert!(
        stderr.contains("unrecognized subcommand 'definitely-not-a-wt-subcommand'"),
        "stderr should use clap's native error format: {stderr}"
    );
    assert!(
        stderr.contains("Usage:") && stderr.contains("try '--help'"),
        "stderr should include Usage block and --help suggestion: {stderr}"
    );
}

#[test]
fn custom_subcommand_typo_suggests_closest_builtin() {
    let mut cmd = wt_command();
    let _git_only_path = set_git_only_path(&mut cmd);
    cmd.arg("siwtch"); // typo of `switch`

    let output = cmd.output().expect("failed to run wt");
    assert!(!output.status.success());
    let stderr = String::from_utf8_lossy(&output.stderr)
        .ansi_strip()
        .into_owned();
    assert!(
        stderr.contains("tip:") && stderr.contains("similar subcommand"),
        "stderr missing clap's similar-subcommand tip: {stderr}"
    );
    assert!(
        stderr.contains("'switch'"),
        "stderr should suggest 'switch': {stderr}"
    );
}

#[test]
fn custom_subcommand_alias_outside_repo_names_the_alias() {
    // `wt co` outside a git repository, with `co` a user-config alias: alias
    // dispatch ends inside try_alias with the alias-needs-repository error —
    // a configured alias isn't "unrecognized", and the clap-style fallback
    // would suggest the typed name itself.
    let config_dir = worktrunk::testing::tempdir().unwrap();
    let config_path = config_dir.path().join("config.toml");
    std::fs::write(&config_path, "[aliases]\nco = \"echo hi\"\n").unwrap();

    let mut cmd = wt_command();
    let _git_only_path = set_git_only_path(&mut cmd);
    cmd.env("WORKTRUNK_CONFIG_PATH", &config_path);
    cmd.arg("co");

    let settings = setup_home_snapshot_settings(&config_dir);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(cmd);
}

#[test]
fn custom_subcommand_alias_outside_repo_omits_gutter_when_git_says_nothing() {
    // The gutter quotes git's explanation, so a fatal exit that carries no
    // output leaves the alias error and its hint alone — not a blank gutter
    // line where the explanation would have gone.
    let config_dir = worktrunk::testing::tempdir().unwrap();
    let config_path = config_dir.path().join("config.toml");
    std::fs::write(&config_path, "[aliases]\nco = \"echo hi\"\n").unwrap();

    let git_dir = worktrunk::testing::tempdir().unwrap();
    MockConfig::new("git")
        .version("git version 2.43.0")
        .command("rev-parse", MockResponse::exit(128))
        .write(git_dir.path());

    let mut cmd = wt_command();
    cmd.env("PATH", git_dir.path())
        .env("WORKTRUNK_TEST_MOCK_CONFIG_DIR", git_dir.path())
        .env("WORKTRUNK_CONFIG_PATH", &config_path)
        .arg("co");

    let output = cmd.output().expect("failed to run wt");
    assert_eq!(output.status.code(), Some(1));
    let stderr = String::from_utf8_lossy(&output.stderr)
        .ansi_strip()
        .into_owned();
    let lines: Vec<&str> = stderr.lines().collect();
    assert_eq!(
        lines,
        vec![
            "✗ co is an alias, but aliases only run inside a git repository",
            "↳ Run wt inside a repository, or to target one, run wt -C <path> co",
        ],
        "got: {stderr}"
    );
}

#[test]
fn custom_subcommand_alias_propagates_non_fatal_git_failure() {
    // Only a fatal git exit (128) reaches the alias message. A git that fails
    // any other way surfaces as itself, the way it does for every other
    // command, rather than being reported as a repository verdict git never
    // gave.
    let config_dir = worktrunk::testing::tempdir().unwrap();
    let config_path = config_dir.path().join("config.toml");
    std::fs::write(&config_path, "[aliases]\nco = \"echo hi\"\n").unwrap();

    // No `rev-parse` response, so it falls through to mock_stub's default:
    // exit 1 with no output, unlike `set_git_only_path`'s fatal 128.
    let git_dir = worktrunk::testing::tempdir().unwrap();
    MockConfig::new("git")
        .version("git version 2.43.0")
        .write(git_dir.path());

    let mut cmd = wt_command();
    cmd.env("PATH", git_dir.path())
        .env("WORKTRUNK_TEST_MOCK_CONFIG_DIR", git_dir.path())
        .env("WORKTRUNK_CONFIG_PATH", &config_path)
        .arg("co");

    let output = cmd.output().expect("failed to run wt");
    assert!(!output.status.success(), "expected failure");
    let stderr = String::from_utf8_lossy(&output.stderr)
        .ansi_strip()
        .into_owned();
    assert!(
        stderr.contains("git rev-parse --git-common-dir failed (exit code 1)"),
        "git's own failure should surface: {stderr}"
    );
    assert!(
        !stderr.contains("is an alias"),
        "a non-fatal git failure must not be reported as a missing repository: {stderr}"
    );
}

#[test]
fn custom_subcommand_alias_outside_repo_wins_over_path_binary() {
    // Outside a repository the user-config alias still owns its name: dispatch
    // ends in try_alias with the needs-repository error instead of falling
    // through to a colliding `wt-<name>` PATH binary — the same "user config
    // wins over wt-<name> PATH binaries" precedence as in-repo dispatch.
    let config_dir = worktrunk::testing::tempdir().unwrap();
    let config_path = config_dir.path().join("config.toml");
    std::fs::write(
        &config_path,
        "[aliases]\nwt-test-extcmd-alias-shadow = \"echo hi\"\n",
    )
    .unwrap();
    let bin_dir = mock_bin_dir(
        "wt-wt-test-extcmd-alias-shadow",
        MockResponse::output("path binary ran\n"),
    );

    let mut cmd = wt_command();
    // No `set_git_only_path` here: `prepend_path` rebuilds PATH from this
    // process's environment, so a git-only PATH set above it would be
    // discarded. The unique alias name is what keeps host `wt-*` binaries
    // out of the way.
    prepend_path(&mut cmd, bin_dir.path());
    cmd.env("WORKTRUNK_TEST_MOCK_CONFIG_DIR", bin_dir.path());
    cmd.env("WORKTRUNK_CONFIG_PATH", &config_path);
    cmd.arg("wt-test-extcmd-alias-shadow");

    let output = cmd.output().expect("failed to run wt");
    assert!(!output.status.success(), "expected failure");
    assert_eq!(output.status.code(), Some(1));
    let stderr = String::from_utf8_lossy(&output.stderr)
        .ansi_strip()
        .into_owned();
    assert!(
        stderr.contains("wt-test-extcmd-alias-shadow is an alias"),
        "error should name the configured alias: {stderr}"
    );
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        !stdout.contains("path binary ran"),
        "the colliding PATH binary must not run: {stdout}"
    );
}

#[cfg(unix)]
#[test]
fn custom_subcommand_alias_rejects_non_utf8_without_running_path_binary() {
    use std::ffi::OsString;
    use std::os::unix::ffi::OsStringExt;

    let repo = TestRepo::new();
    repo.write_project_config(
        r#"[aliases]
co = "echo hi"
"#,
    );
    let bin_dir = mock_bin_dir("wt-co", MockResponse::output("path binary ran\n"));
    let mut cmd = repo.wt_command();
    prepend_path(&mut cmd, bin_dir.path());
    cmd.env("WORKTRUNK_TEST_MOCK_CONFIG_DIR", bin_dir.path());
    cmd.arg("co").arg(OsString::from_vec(vec![0xff]));

    let settings = crate::common::setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();
    assert_cmd_snapshot!(cmd);
}

#[test]
fn custom_subcommand_nested_suggestion_wins_over_path_lookup() {
    // `wt squash` should suggest `wt step squash` even though `wt-squash` is
    // not on PATH. The nested tip is layered on top of clap's standard
    // unrecognized-subcommand error.
    let mut cmd = wt_command();
    let _git_only_path = set_git_only_path(&mut cmd);
    cmd.arg("squash");

    let output = cmd.output().expect("failed to run wt");
    assert!(!output.status.success());
    assert_eq!(output.status.code(), Some(2));
    let stderr = String::from_utf8_lossy(&output.stderr)
        .ansi_strip()
        .into_owned();
    assert!(
        stderr.contains("wt step squash"),
        "stderr should suggest 'wt step squash': {stderr}"
    );
}

#[test]
fn custom_subcommand_propagates_exit_code() {
    let dir = mock_bin_dir(
        "wt-wt-test-extcmd-fail",
        MockResponse::exit(0).with_exit_code(42),
    );

    let mut cmd = wt_command();
    prepend_path(&mut cmd, dir.path());
    cmd.env("WORKTRUNK_TEST_MOCK_CONFIG_DIR", dir.path());
    cmd.arg("wt-test-extcmd-fail");

    let output = cmd.output().expect("failed to run wt");
    assert_eq!(
        output.status.code(),
        Some(42),
        "expected exit code 42, stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    // When the custom command fails, wt should NOT add its own error line —
    // the child already reported whatever it needed to.
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        !stderr.contains("exited with status"),
        "wt should not decorate child failures: {stderr}"
    );
}

#[test]
fn custom_subcommand_respects_global_dash_c_flag() {
    // `wt -C <dir> foo` should run `wt-foo` with `<dir>` as its cwd. We verify
    // by reading argv, not cwd, because MockResponse doesn't reflect cwd —
    // instead we run `pwd` via a shell wrapper using the `file` response. Too
    // fiddly; simpler: use a unique temp dir as cwd and have the mock emit
    // `$PWD` via its stderr field. Alas, MockResponse just emits literals.
    //
    // Instead: point `-C` at a sentinel dir, and have the mock exit 0. The
    // assertion is indirect — if wt fails to chdir to the dir (because it
    // doesn't exist from the parent's cwd), the child will still run because
    // we pass an absolute path. So we verify by confirming the child ran and
    // exited cleanly even though the parent's cwd is unrelated.
    let target_dir = worktrunk::testing::tempdir().unwrap();
    let dir = mock_bin_dir("wt-wt-test-extcmd-cwd", MockResponse::output("ok\n"));

    let mut cmd = wt_command();
    prepend_path(&mut cmd, dir.path());
    cmd.env("WORKTRUNK_TEST_MOCK_CONFIG_DIR", dir.path());
    cmd.current_dir(std::env::temp_dir());
    cmd.args([
        "-C",
        target_dir.path().to_str().unwrap(),
        "wt-test-extcmd-cwd",
    ]);

    let output = cmd.output().expect("failed to run wt");
    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
}

#[test]
fn custom_subcommand_passes_help_flag_through() {
    // `wt foo --help` should hand `--help` to `wt-foo`, not to wt itself.
    // The mock playback has no built-in `--help` handler, so if `--help` reaches
    // it the mock falls through to `_default` (which we set to exit 0).
    let dir = mock_bin_dir(
        "wt-wt-test-extcmd-help",
        MockResponse::output("child got help\n"),
    );

    let mut cmd = wt_command();
    prepend_path(&mut cmd, dir.path());
    cmd.env("WORKTRUNK_TEST_MOCK_CONFIG_DIR", dir.path());
    cmd.args(["wt-test-extcmd-help", "--help"]);

    let output = cmd.output().expect("failed to run wt");
    assert!(output.status.success());
    assert_eq!(
        String::from_utf8_lossy(&output.stdout).trim(),
        "child got help",
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
}