aboutsummaryrefslogtreecommitdiff
path: root/tests/cli.rs
blob: 5098b9db24319eea26b6006158da9879615ff290 (plain)
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
use std::fs;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};

use serde_json::Value;
use tempfile::TempDir;

#[test]
fn sync_initial() {
    let fixture = fixture();

    let output = treeimp(&fixture.workspace, &["sync"]);
    assert_success(&output, "sync");
    assert_eq!(String::from_utf8_lossy(&output.stdout), "local: updated\n");
    assert_eq!(
        read_files(&fixture.workspace.join("vendor/local")),
        vec![("message.txt".to_owned(), "first\n".to_owned())]
    );

    let lock: Value = serde_json::from_slice(
        &fs::read(fixture.workspace.join("treeimp.lock")).expect("read lock file"),
    )
    .expect("decode lock file");
    assert_eq!(
        lock,
        serde_json::json!({
            "local": {
                "commit": fixture.initial_commit,
                "date": "2024-01-01T00:00:00Z"
            }
        })
    );
}

#[test]
fn sync_unchanged() {
    let fixture = fixture();
    assert_success(&treeimp(&fixture.workspace, &["sync"]), "initial sync");
    let lock_path = fixture.workspace.join("treeimp.lock");
    let initial_lock = fs::read(&lock_path).expect("read initial lock file");

    let output = treeimp(&fixture.workspace, &["sync"]);
    assert_success(&output, "unchanged sync");
    assert_eq!(
        String::from_utf8_lossy(&output.stdout),
        "local: unchanged\n"
    );
    assert_eq!(
        fs::read(lock_path).expect("read unchanged lock file"),
        initial_lock
    );
}

#[test]
fn sync_changed() {
    let fixture = fixture();
    assert_success(&treeimp(&fixture.workspace, &["sync"]), "initial sync");
    fs::write(fixture.upstream.join("source/message.txt"), "second\n").expect("update source file");
    let updated_commit = commit(&fixture.upstream, "update source", "2024-01-03T00:00:00Z");

    let output = treeimp(&fixture.workspace, &["sync"]);
    assert_success(&output, "updated sync");
    assert_eq!(String::from_utf8_lossy(&output.stdout), "local: updated\n");
    assert_eq!(
        read_files(&fixture.workspace.join("vendor/local")),
        vec![("message.txt".to_owned(), "second\n".to_owned())]
    );
    let lock: Value = serde_json::from_slice(
        &fs::read(fixture.workspace.join("treeimp.lock")).expect("read updated lock file"),
    )
    .expect("decode updated lock file");
    assert_eq!(
        lock,
        serde_json::json!({
            "local": {
                "commit": updated_commit,
                "date": "2024-01-03T00:00:00Z"
            }
        })
    );
}

struct Fixture {
    _temporary: TempDir,
    upstream: PathBuf,
    workspace: PathBuf,
    initial_commit: String,
}

fn fixture() -> Fixture {
    let temporary = TempDir::new().expect("create temporary directory");
    let upstream = temporary.path().join("upstream");
    let workspace = temporary.path().join("workspace");
    fs::create_dir_all(upstream.join("source")).expect("create upstream source directory");
    fs::create_dir(&workspace).expect("create workspace");

    git(&upstream, &["init", "--quiet", "--initial-branch=main"]);
    fs::write(upstream.join("source/message.txt"), "first\n").expect("write source file");
    let initial_commit = commit(&upstream, "initial source", "2024-01-01T00:00:00Z");

    fs::write(upstream.join("unrelated.txt"), "not imported\n").expect("write unrelated file");
    let _ = commit(&upstream, "unrelated change", "2024-01-02T00:00:00Z");

    let url = serde_json::to_string(
        upstream
            .to_str()
            .expect("temporary repository path is valid UTF-8"),
    )
    .expect("encode repository path");
    fs::write(
        workspace.join("treeimp.nix"),
        format!(
            r#"{{
  local = {{
    url = {url};
    ref = "main";
    source = "source";
    destination = "vendor/local";
    transform = source: source;
  }};
}}
"#,
        ),
    )
    .expect("write treeimp config");

    Fixture {
        _temporary: temporary,
        upstream,
        workspace,
        initial_commit,
    }
}

fn read_files(root: &Path) -> Vec<(String, String)> {
    fn visit(root: &Path, directory: &Path, files: &mut Vec<(String, String)>) {
        for entry in fs::read_dir(directory).expect("read directory") {
            let path = entry.expect("read directory entry").path();
            if path.is_dir() {
                visit(root, &path, files);
                continue;
            }
            let relative = path
                .strip_prefix(root)
                .expect("file is below root")
                .to_str()
                .expect("relative path is valid UTF-8")
                .to_owned();
            let contents = fs::read_to_string(&path).expect("read file");
            files.push((relative, contents));
        }
    }

    let mut files = Vec::new();
    visit(root, root, &mut files);
    files.sort_by(|(left, _), (right, _)| left.cmp(right));
    files
}

fn git(repository: &Path, arguments: &[&str]) -> String {
    let output = Command::new("git")
        .current_dir(repository)
        .args(arguments)
        .output()
        .expect("run Git");
    assert_success(&output, &format!("git {}", arguments.join(" ")));
    String::from_utf8(output.stdout)
        .expect("Git output is UTF-8")
        .trim()
        .to_owned()
}

fn commit(repository: &Path, message: &str, date: &str) -> String {
    git(repository, &["add", "."]);
    let output = Command::new("git")
        .current_dir(repository)
        .args(["commit", "--quiet", "-m", message])
        .env("GIT_AUTHOR_NAME", "Treeimp Test")
        .env("GIT_AUTHOR_EMAIL", "treeimp@example.invalid")
        .env("GIT_COMMITTER_NAME", "Treeimp Test")
        .env("GIT_COMMITTER_EMAIL", "treeimp@example.invalid")
        .env("GIT_AUTHOR_DATE", date)
        .env("GIT_COMMITTER_DATE", date)
        .output()
        .expect("commit changes");
    assert_success(&output, "git commit");
    git(repository, &["rev-parse", "HEAD"])
}

fn treeimp(workspace: &Path, arguments: &[&str]) -> Output {
    let nix_directory = workspace.join(".nix");
    let store_directory = nix_directory.join("store");
    let state_directory = nix_directory.join("state");
    fs::create_dir_all(&store_directory).expect("create private Nix store directory");
    fs::create_dir_all(&state_directory).expect("create private Nix state directory");

    Command::new(env!("CARGO_BIN_EXE_treeimp"))
        .current_dir(workspace)
        .args(arguments)
        // Make it work when run from a Nix build sandbox.
        .env("NIX_REMOTE", "local")
        .env("NIX_STORE_DIR", store_directory)
        .env("NIX_STATE_DIR", state_directory)
        .output()
        .expect("run treeimp")
}

fn assert_success(output: &Output, operation: &str) {
    assert!(
        output.status.success(),
        "{operation} failed with {}\nstdout:\n{}\nstderr:\n{}",
        output.status,
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr),
    );
}