greengate 5.3.0

Opinionated git hooks that judge what you are committing, not what is on disk
//! greengate 4.0's first run in a repository greengate 3.x used, through
//! the real binary: refused while 3.x's parked changes are there, then the
//! state and keys moved once, `doctor` clean, and a `migrate --reverse`
//! that the next command does not undo (plan "greengate 4.0 renames its
//! data names", Phase 2).

use crate::common::Repo;

fn config(repo: &Repo, key: &str) -> String {
    String::from_utf8_lossy(&repo.git(&["config", "--get-all", key]).stdout).into_owned()
}

#[test]
fn a_3x_repository_is_moved_once_and_a_reverse_holds() {
    let repo = Repo::new();
    std::fs::write(
        repo.path(".git/amont-bypasses"),
        "amont-bypass-v1\n1 abc x\n",
    )
    .unwrap();
    repo.git(&["config", "amont.timeout", "700"]);
    std::fs::create_dir_all(repo.path(".git/amont-held")).unwrap();

    // 3.x's parked changes: refused, nothing moved, the way out named.
    let refused = repo.run(&["list"]);
    assert_eq!(refused.code, 1, "{}", refused.stderr);
    assert!(refused.stderr.contains("amont-held"), "{}", refused.stderr);
    assert!(refused.stderr.contains("restore"), "{}", refused.stderr);
    assert!(repo.path(".git/amont-bypasses").is_file());
    assert_eq!(config(&repo, "amont.timeout"), "700\n");

    // `restore` is not held back by the migration, and finds the old store.
    let restored = repo.run(&["restore"]);
    assert_eq!(restored.code, 0, "{}{}", restored.stdout, restored.stderr);
    assert!(
        !repo.path(".git/amont-held").exists(),
        "restore took the 3.x store"
    );

    // The first command moves everything, once.
    let listed = repo.run(&["list"]);
    assert_eq!(listed.code, 0, "{}", listed.stderr);
    assert_eq!(
        std::fs::read_to_string(repo.path(".git/greengate-bypasses")).unwrap(),
        "greengate-bypass-v1\n1 abc x\n"
    );
    assert!(!repo.path(".git/amont-bypasses").exists());
    assert_eq!(config(&repo, "greengate.timeout"), "700\n");
    assert_eq!(config(&repo, "amont.timeout"), "");
    assert!(repo.path(".git/greengate-migrated").is_file());

    let doctor = repo.run(&["doctor"]);
    assert!(
        !doctor.stdout.contains("state:") && !doctor.stdout.contains("local config:"),
        "{}",
        doctor.stdout
    );

    // Back to 3.x's names, and the next 4.0 command leaves them.
    let reversed = repo.run(&["migrate", "--reverse"]);
    assert_eq!(reversed.code, 0, "{}", reversed.stderr);
    assert_eq!(
        std::fs::read_to_string(repo.path(".git/amont-bypasses")).unwrap(),
        "amont-bypass-v1\n1 abc x\n"
    );
    assert_eq!(config(&repo, "amont.timeout"), "700\n");
    let again = repo.run(&["list"]);
    assert_eq!(again.code, 0, "{}", again.stderr);
    assert!(
        repo.path(".git/amont-bypasses").is_file(),
        "a reverse is not undone"
    );
    let holding = repo.run(&["doctor"]);
    assert_eq!(holding.code, 1, "{}", holding.stderr);
    assert!(
        holding.stdout.contains("reversed: this repository"),
        "doctor says why 4.0 leaves it: {}",
        holding.stdout
    );

    // Until `migrate` is asked for by name.
    let forward = repo.run(&["migrate"]);
    assert_eq!(forward.code, 0, "{}", forward.stderr);
    assert!(forward.stderr.contains("moved"), "{}", forward.stderr);
    assert!(repo.path(".git/greengate-bypasses").is_file());
}

#[test]
fn a_dry_run_moves_nothing() {
    let repo = Repo::new();
    std::fs::write(repo.path(".git/amont-bypasses"), "amont-bypass-v1\n").unwrap();
    let out = repo.run(&["land", "--dry-run"]);
    assert!(
        repo.path(".git/amont-bypasses").is_file(),
        "a dry run promised to change nothing: {}",
        out.stderr
    );
    assert!(!repo.path(".git/greengate-migrated").exists());
}

/// `repo`'s binary with a config home and global git config of its own,
/// so a test of the global half sees no other test's marker.
fn own_home(repo: &Repo, args: &[&str]) -> std::process::Output {
    let mut cmd = crate::common::amont_cmd();
    cmd.args(args)
        .current_dir(&repo.dir)
        .env("XDG_CONFIG_HOME", repo.path("own-config"))
        .env("GIT_CONFIG_GLOBAL", repo.path("own-gitconfig"))
        .stdin(std::process::Stdio::null());
    cmd.output().expect("run greengate")
}

fn global(repo: &Repo, key: &str) -> String {
    let out = std::process::Command::new("git")
        .args(["config", "--file"])
        .arg(repo.path("own-gitconfig"))
        .args(["--get-all", key])
        .output()
        .expect("git config --file");
    String::from_utf8_lossy(&out.stdout).into_owned()
}

#[test]
fn a_global_reverse_holds_until_migrate_global() {
    let repo = Repo::new();
    std::fs::write(repo.path("own-gitconfig"), "[amont]\n\thostSlots = 3\n").unwrap();
    let first = own_home(&repo, &["list"]);
    assert!(
        first.status.success(),
        "{}",
        String::from_utf8_lossy(&first.stderr)
    );
    assert_eq!(global(&repo, "greengate.hostSlots"), "3\n");

    let back = own_home(&repo, &["migrate", "--reverse", "--global"]);
    assert!(
        back.status.success(),
        "{}",
        String::from_utf8_lossy(&back.stderr)
    );
    assert_eq!(global(&repo, "amont.hostSlots"), "3\n");
    let again = own_home(&repo, &["list"]);
    assert!(again.status.success());
    assert_eq!(
        global(&repo, "amont.hostSlots"),
        "3\n",
        "a global reverse is not undone"
    );

    let forward = own_home(&repo, &["migrate", "--global"]);
    assert!(
        forward.status.success(),
        "{}",
        String::from_utf8_lossy(&forward.stderr)
    );
    assert_eq!(global(&repo, "greengate.hostSlots"), "3\n");
}

#[test]
fn doctor_names_a_3x_variable_left_set() {
    let repo = Repo::new();
    let out = crate::common::amont_cmd()
        .arg("doctor")
        .current_dir(&repo.dir)
        .env("AMONT_TIMEOUT", "5")
        .env("GIT_CONFIG_GLOBAL", repo.path("fake-gitconfig"))
        .output()
        .expect("run doctor");
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert_eq!(out.status.code(), Some(1), "{stdout}");
    assert!(
        stdout.contains("AMONT_TIMEOUT") && stdout.contains("GREENGATE_TIMEOUT"),
        "{stdout}"
    );
}

/// A kubeconfig left at 3.x's path logs in as the old namespace's runner:
/// doctor names it and the two commands that fix it.
#[test]
fn doctor_names_a_3x_kubeconfig() {
    let repo = Repo::new();
    let global = repo.path("fake-gitconfig");
    let set = std::process::Command::new("git")
        .args(["config", "--file"])
        .arg(&global)
        .args([
            "greengate.cluster.kubeconfig",
            "/home/me/.config/amont/kube/homelab.yaml",
        ])
        .status()
        .expect("git config");
    assert!(set.success());
    let out = crate::common::amont_cmd()
        .arg("doctor")
        .current_dir(&repo.dir)
        .env("GIT_CONFIG_GLOBAL", &global)
        .output()
        .expect("run doctor");
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert_eq!(out.status.code(), Some(1), "{stdout}");
    assert!(
        stdout.contains("cluster: greengate.cluster.kubeconfig is greengate 3.x's")
            && stdout.contains("greengate-gates-kubeconfig.sh")
            && stdout.contains("~/.config/greengate/kube/homelab.yaml"),
        "{stdout}"
    );
}

/// Only the old signing key exists: doctor names the rename in one line.
/// A scratch HOME, never the real one; with the new key beside it, or with
/// neither, the line is not said.
#[test]
fn doctor_names_the_signing_key_move() {
    let repo = Repo::new();
    let home = repo.path("home");
    std::fs::create_dir_all(home.join(".ssh")).unwrap();
    let doctor = |home: &std::path::Path| {
        let out = crate::common::amont_cmd()
            .arg("doctor")
            .current_dir(&repo.dir)
            .env("HOME", home)
            .env("GIT_CONFIG_GLOBAL", repo.path("fake-gitconfig"))
            .output()
            .expect("run doctor");
        (
            out.status.code(),
            String::from_utf8_lossy(&out.stdout).into_owned(),
        )
    };
    let (_, none) = doctor(&home);
    assert!(!none.contains("signing key"), "{none}");
    std::fs::write(home.join(".ssh/amont-attest"), "k").unwrap();
    let (code, only_old) = doctor(&home);
    assert_eq!(code, Some(1), "{only_old}");
    let line = only_old
        .lines()
        .find(|l| l.contains("signing key"))
        .unwrap_or_else(|| panic!("no key line: {only_old}"));
    assert!(
        line.contains("mv ~/.ssh/amont-attest ~/.ssh/greengate-attest"),
        "{line}"
    );
    std::fs::write(home.join(".ssh/greengate-attest"), "k").unwrap();
    let (_, both) = doctor(&home);
    assert!(!both.contains("signing key"), "{both}");
}

/// A signer block an older greengate filed under the old local notes name is
/// named by doctor (nothing reads it now); the green local ref is not.
#[test]
fn doctor_names_an_old_local_signer_ref() {
    let repo = Repo::new();
    repo.stage("a.txt", "x\n");
    repo.commit("chore: a");
    let tip = String::from_utf8_lossy(&repo.git(&["rev-parse", "HEAD"]).stdout)
        .trim()
        .to_string();
    let doctor = || {
        let out = crate::common::amont_cmd()
            .arg("doctor")
            .current_dir(&repo.dir)
            .env("HOME", repo.path("home"))
            .env("GIT_CONFIG_GLOBAL", repo.path("fake-gitconfig"))
            .output()
            .expect("run doctor");
        String::from_utf8_lossy(&out.stdout).into_owned()
    };
    repo.git(&[
        "update-ref",
        "refs/notes/attest-local/greengate-attest",
        &tip,
    ]);
    assert!(!doctor().contains("local notes"), "{}", doctor());
    repo.git(&["update-ref", "refs/notes/attest-local/amont-attest", &tip]);
    let said = doctor();
    let line = said
        .lines()
        .find(|l| l.contains("local notes"))
        .unwrap_or_else(|| panic!("no line: {said}"));
    assert!(
        line.contains("refs/notes/attest-local/amont-attest")
            && line.contains("git update-ref -d refs/notes/attest-local/amont-attest"),
        "{line}"
    );
}

/// Doctor names the host sizing and where it came from, on stderr, without
/// changing its leftover-names stdout or exit code.
#[test]
fn doctor_names_the_host_sizing_and_its_source() {
    let repo = Repo::new();
    let out = crate::common::amont_cmd()
        .arg("doctor")
        .current_dir(&repo.dir)
        .env("GREENGATE_HOST_CORES", "4")
        .env("GREENGATE_HOST_SLOTS", "2")
        .env("GIT_CONFIG_GLOBAL", repo.path("fake-gitconfig"))
        .output()
        .expect("run doctor");
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("host cores: 4, ") && stderr.contains("(GREENGATE_HOST_CORES)"),
        "{stderr}"
    );
    assert!(
        stderr.contains("host slots: 2 (GREENGATE_HOST_SLOTS)"),
        "{stderr}"
    );
    assert!(stderr.lines().all(|l| l.len() <= 80), "{stderr}");
    assert!(!String::from_utf8_lossy(&out.stdout).contains("host slots"));
}

/// A host with no `greengate.*` key gets no warning: git's exit 1 is no rows.
#[test]
fn doctor_says_nothing_about_git_on_a_host_with_no_keys() {
    let repo = Repo::new();
    let out = crate::common::amont_cmd()
        .arg("doctor")
        .current_dir(&repo.dir)
        .env("GIT_CONFIG_GLOBAL", repo.path("empty-gitconfig"))
        .env("GIT_CONFIG_NOSYSTEM", "1")
        .env_remove("GREENGATE_HOST_CORES")
        .env_remove("GREENGATE_HOST_SLOTS")
        .output()
        .expect("run doctor");
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(stderr.contains("host slots: auto (detected)"), "{stderr}");
    assert!(!stderr.contains("warning"), "{stderr}");
}

#[test]
fn asking_for_help_moves_nothing() {
    let repo = Repo::new();
    std::fs::write(repo.path(".git/amont-bypasses"), "amont-bypass-v1\n").unwrap();
    for args in [["list", "--help"], ["list", "--bogus"]] {
        repo.run(&args);
        assert!(
            repo.path(".git/amont-bypasses").is_file(),
            "{args:?} moved the 3.x state"
        );
    }
    assert!(!repo.path(".git/greengate-migrated").exists());
}

#[test]
fn a_refusal_keeps_its_lines_and_the_rm_line_pastes() {
    let repo = Repo::new();
    std::fs::create_dir_all(repo.path(".git/amont")).unwrap();
    let pending = repo.path(".git/amont/cluster-pending");
    std::fs::write(&pending, "not json").unwrap();
    let out = repo.run(&["list"]);
    assert_eq!(out.code, 1, "{}", out.stderr);
    assert!(!out.stderr.contains("\\x0a"), "{}", out.stderr);
    // One line is the `rm` command alone, naming the pending file: the
    // path is spelled as the binary resolved it (`/private/var` on macOS,
    // a short `RUNNER~1` name on Windows), so its tail is what is compared.
    let tail = std::path::Path::new(".git")
        .join("amont")
        .join("cluster-pending");
    let tail = tail.to_string_lossy();
    assert!(
        out.stderr.lines().any(|line| line.starts_with("  rm ")
            && line.ends_with(&*tail)
            && !line["  rm ".len()..].contains(' ')),
        "no line is the `rm` command alone:\n{}",
        out.stderr
    );
}