GITv
master
host.rs171 lines, 6.5 KB
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
//! Helpers shared by both packages' integration tests: isolated git, scratch folders, and a
//! stand-in for ssh that runs `gitv serve`. Each package's `tests/common/mod.rs` includes this
//! file; the web tests add their own server and HTTP client.

#![allow(dead_code)]

use std::fs;
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use std::process::{Command, Output, Stdio};
use std::sync::LazyLock;

/// The `gitv` binary. A test can only be told where its own package's binaries are, so the
/// web tests find it beside their own executable, where a workspace build puts it.
pub static GITV: LazyLock<String> = LazyLock::new(|| binary(option_env!("CARGO_BIN_EXE_gitv"), "gitv"));
/// The `gitv-web` binary, found the same way.
pub static GITV_WEB: LazyLock<String> = LazyLock::new(|| binary(option_env!("CARGO_BIN_EXE_gitv-web"), "gitv-web"));

fn binary(own: Option<&str>, name: &str) -> String {
    if let Some(path) = own {
        return path.to_string();
    }
    // The binaries sit in target/<profile>. Test executables are somewhere below it: in
    // target/<profile>/deps, or deeper in newer Cargo's build directory layout. So look in each
    // folder above this test for a file with the binary's name.
    let exe = std::env::current_exe().unwrap();
    exe.ancestors()
        .skip(1)
        .map(|dir| dir.join(name))
        .find(|path| path.is_file())
        .map(|path| path.to_string_lossy().into_owned())
        .unwrap_or_else(|| {
            panic!("{name} isn't built near {}; run the tests from the workspace root with `cargo test`", exe.display())
        })
}
/// The hostname every test installation is configured with.
pub const TEST_HOST: &str = "git.example.test";
/// A configuration file that doesn't exist, so the machine's own /etc/gitv/gitv.conf never applies.
pub const NO_CONFIG: &str = "/nonexistent/gitv.conf";

/// A fresh, empty directory under Cargo's per-target temporary directory.
pub fn scratch(name: &str) -> PathBuf {
    let dir = Path::new(env!("CARGO_TARGET_TMPDIR")).join(name);
    let _ = fs::remove_dir_all(&dir);
    fs::create_dir_all(&dir).unwrap();
    dir
}

/// Git with no user or system config and a fixed identity and clock, so runs are repeatable.
pub fn git_cmd(dir: &Path) -> Command {
    let mut command = Command::new("git");
    command
        .current_dir(dir)
        .env("HOME", dir)
        .env("GIT_CONFIG_NOSYSTEM", "1")
        .env("GIT_CONFIG_GLOBAL", "/dev/null")
        .env("GIT_AUTHOR_NAME", "Ada Lovelace")
        .env("GIT_AUTHOR_EMAIL", "ada@example.com")
        .env("GIT_COMMITTER_NAME", "Ada Lovelace")
        .env("GIT_COMMITTER_EMAIL", "ada@example.com")
        .env("GIT_AUTHOR_DATE", "2026-01-02T03:04:05Z")
        .env("GIT_COMMITTER_DATE", "2026-01-02T03:04:05Z")
        .env("GIT_SSH_VARIANT", "simple")
        .stdin(Stdio::null());
    command
}

/// Run git in `dir`, panic with its output on failure, and return trimmed stdout.
pub fn git(dir: &Path, args: &[&str]) -> String {
    let output = git_cmd(dir).args(args).output().unwrap();
    assert!(output.status.success(), "git {args:?} failed: {}", String::from_utf8_lossy(&output.stderr));
    String::from_utf8_lossy(&output.stdout).trim().to_string()
}

/// A GITv installation in a scratch directory: repositories, a keys file, and a fake `ssh`
/// that hands git's command to `gitv serve` as an owner's key would.
pub struct Host {
    pub dir: PathBuf,
    pub repos: PathBuf,
    pub keys: PathBuf,
}

impl Host {
    pub fn new(name: &str) -> Host {
        let dir = scratch(name);
        let repos = dir.join("repos");
        fs::create_dir_all(&repos).unwrap();
        let keys = dir.join("authorized_keys");
        let host = Host { dir, repos, keys };
        // With GIT_SSH_VARIANT=simple git runs: <ssh> <owner>@host <command>.
        let script = format!(
            "#!/bin/sh\nowner=${{1%%@*}}\nSSH_ORIGINAL_COMMAND=\"$2\" GITV_REPOS='{}' GITV_LOG='{}' GITV_HOST={TEST_HOST} GITV_CONFIG={NO_CONFIG} exec '{}' serve \"$owner\"\n",
            host.repos.display(),
            host.log().display(),
            *GITV
        );
        let ssh = host.ssh_script();
        fs::write(&ssh, script).unwrap();
        fs::set_permissions(&ssh, fs::Permissions::from_mode(0o755)).unwrap();
        host
    }

    /// Where `gitv` writes its operator log in tests.
    pub fn log(&self) -> PathBuf {
        self.dir.join("operator.log")
    }

    /// The operator log so far, empty if nothing was logged.
    pub fn logged(&self) -> String {
        fs::read_to_string(self.log()).unwrap_or_default()
    }

    pub fn ssh_script(&self) -> PathBuf {
        self.dir.join("fake-ssh")
    }

    /// `ssh git@host <command>` as `owner`'s key.
    pub fn ssh(&self, owner: &str, command: &str) -> Output {
        Command::new(&*GITV)
            .args(["serve", owner])
            .env("SSH_ORIGINAL_COMMAND", command)
            .env("GITV_HOST", TEST_HOST)
            .env("GITV_CONFIG", NO_CONFIG)
            .env("GITV_REPOS", &self.repos)
            .env("GITV_LOG", self.log())
            .stdin(Stdio::null())
            .output()
            .unwrap()
    }

    /// `gitv <args>` as the administrator, pointed at this host.
    pub fn admin(&self, args: &[&str]) -> Output {
        Command::new(&*GITV)
            .args(args)
            .env("GITV_HOST", TEST_HOST)
            .env("GITV_CONFIG", NO_CONFIG)
            .env("GITV_REPOS", &self.repos)
            .env("GITV_KEYS", &self.keys)
            .env("GITV_LOG", self.log())
            .stdin(Stdio::null())
            .output()
            .unwrap()
    }

    /// Git in `dir`, with remotes reached through this host's fake ssh.
    pub fn git(&self, dir: &Path, args: &[&str]) -> Output {
        git_cmd(dir).env("GIT_SSH_COMMAND", self.ssh_script()).args(args).output().unwrap()
    }

    pub fn repo(&self, owner: &str, name: &str) -> PathBuf {
        self.repos.join(owner).join(format!("{name}.git"))
    }
}

pub fn stdout(output: &Output) -> String {
    String::from_utf8_lossy(&output.stdout).into_owned()
}

pub fn stderr(output: &Output) -> String {
    String::from_utf8_lossy(&output.stderr).into_owned()
}

/// A syntactically valid OpenSSH Ed25519 public key built from `seed`.
pub fn ed25519_key(seed: u8) -> String {
    use base64::Engine;
    let mut blob = 11u32.to_be_bytes().to_vec();
    blob.extend_from_slice(b"ssh-ed25519");
    blob.extend_from_slice(&32u32.to_be_bytes());
    blob.extend_from_slice(&[seed; 32]);
    format!("ssh-ed25519 {} test@example\n", base64::engine::general_purpose::STANDARD.encode(blob))
}