timefs 0.1.0

Mount a Git repository as a read-only filesystem.
Documentation
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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
use std::ffi::{OsStr, OsString};
use std::fs;
use std::io::Read;
use std::os::unix::ffi::{OsStrExt, OsStringExt};
use std::os::unix::fs::{symlink, PermissionsExt};
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Output, Stdio};
use std::thread;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

pub struct MountedTimefs {
    mountpoint: PathBuf,
    child: Option<Child>,
}

pub struct MountRunResult {
    pub stderr: String,
}

impl MountedTimefs {
    pub fn mount(repo: &Path, cli_args: &[&str], mount_args: &[&str]) -> Self {
        let mountpoint = create_temp_dir("timefs-it-mount");
        let child = Command::new(timefs_binary())
            .args(cli_args)
            .arg("mount")
            .arg(repo)
            .arg(&mountpoint)
            .args(mount_args)
            .stdout(Stdio::null())
            .stderr(Stdio::piped())
            .spawn()
            .expect("timefs mount should spawn");

        let mut mount = Self {
            mountpoint,
            child: Some(child),
        };
        mount.wait_until_ready(b"now");
        mount
    }

    pub fn path(&self) -> &Path {
        &self.mountpoint
    }

    pub fn finish(mut self) -> MountRunResult {
        self.unmount();
        MountRunResult {
            stderr: self.wait_for_exit("mount process should exit after explicit unmount"),
        }
    }

    fn wait_until_ready(&mut self, expected_name: &[u8]) {
        for _ in 0..120 {
            if let Ok(entries) = fs::read_dir(&self.mountpoint) {
                let names: Vec<Vec<u8>> = entries
                    .filter_map(Result::ok)
                    .map(|entry| entry.file_name().into_vec())
                    .collect();
                if names.iter().any(|name| name == expected_name) {
                    return;
                }
            }

            if let Some(child) = self.child.as_mut() {
                if let Some(status) = child
                    .try_wait()
                    .expect("mount child status should be readable")
                {
                    panic!(
                        "mount process exited early with status {}: {}",
                        status,
                        child_stderr(child)
                    );
                }
            }

            thread::sleep(Duration::from_millis(50));
        }

        panic!(
            "mountpoint did not become ready at {}",
            self.mountpoint.display()
        );
    }

    fn unmount(&self) {
        run_timefs(["unmount", self.mountpoint.to_string_lossy().as_ref()]);
    }

    fn wait_for_exit(&mut self, message: &str) -> String {
        let Some(mut child) = self.child.take() else {
            return String::new();
        };
        let status = child.wait().expect("mount child status should be readable");
        let stderr = child_stderr(&mut child);
        assert!(status.success(), "{message}: {stderr}");
        wait_for_mount_cleared(&self.mountpoint);
        stderr
    }
}

impl Drop for MountedTimefs {
    fn drop(&mut self) {
        if self.child.is_none() {
            return;
        }

        self.unmount();
        let _ = self.wait_for_exit("mount process should exit during drop cleanup");
    }
}

pub fn with_mounted_timefs<T, F>(
    repo: &Path,
    cli_args: &[&str],
    mount_args: &[&str],
    body: F,
) -> (T, MountRunResult)
where
    F: FnOnce(&MountedTimefs) -> T,
{
    let mount = MountedTimefs::mount(repo, cli_args, mount_args);
    let value = body(&mount);
    let result = mount.finish();
    (value, result)
}

pub struct RepositoryFixture {
    root: PathBuf,
}

impl RepositoryFixture {
    pub fn new(prefix: &str) -> Self {
        let root = unique_temp_path(prefix);
        fs::create_dir_all(&root).expect("fixture directory creation should succeed");
        let fixture = Self { root };
        fixture.git(["init", "-b", "main"]);
        fixture.git(["config", "user.name", "Timefs Tests"]);
        fixture.git(["config", "user.email", "timefs-tests@example.com"]);
        fixture
    }

    pub fn path(&self) -> &Path {
        &self.root
    }

    pub fn git<I, S>(&self, args: I) -> Output
    where
        I: IntoIterator<Item = S>,
        S: AsRef<OsStr>,
    {
        run_git_in(&self.root, args)
    }

    #[allow(dead_code)]
    pub fn git_with_options<A, B, S1, S2>(&self, options: A, args: B) -> Output
    where
        A: IntoIterator<Item = S1>,
        B: IntoIterator<Item = S2>,
        S1: AsRef<OsStr>,
        S2: AsRef<OsStr>,
    {
        let output = Command::new("git")
            .args(options)
            .args(args)
            .current_dir(&self.root)
            .output()
            .expect("git should be executable in tests");

        if output.status.success() {
            output
        } else {
            panic!(
                "git command failed with status {}: {}",
                output.status,
                String::from_utf8_lossy(&output.stderr)
            );
        }
    }

    pub fn git_ls_tree_recursive(&self, rev: &str) -> Vec<GitEntry> {
        parse_ls_tree_entries(&self.git(["ls-tree", "-r", "-z", rev]).stdout)
    }

    pub fn git_show_path(&self, rev: &str, path: &[u8]) -> Vec<u8> {
        let spec = format!("{rev}:{}", String::from_utf8_lossy(path));
        self.git(["show", spec.as_str()]).stdout
    }

    #[allow(dead_code)]
    pub fn git_rev_parse(&self, spec: &str) -> String {
        String::from_utf8(self.git(["rev-parse", spec]).stdout)
            .expect("rev-parse output should be valid UTF-8")
            .trim()
            .to_owned()
    }

    #[allow(dead_code)]
    pub fn git_rev_parse_short(&self, spec: &str) -> String {
        String::from_utf8(self.git(["rev-parse", "--short", spec]).stdout)
            .expect("short rev-parse output should be valid UTF-8")
            .trim()
            .to_owned()
    }

    #[allow(dead_code)]
    pub fn remove_worktree_entries(&self) {
        let entries = fs::read_dir(&self.root).expect("fixture directory should be readable");
        for entry in entries.filter_map(Result::ok) {
            if entry.file_name() == OsStr::new(".git") {
                continue;
            }
            let path = entry.path();
            let file_type = entry
                .file_type()
                .expect("fixture file type should be readable");
            if file_type.is_dir() {
                fs::remove_dir_all(&path).expect("fixture subtree removal should succeed");
            } else {
                fs::remove_file(&path).expect("fixture file removal should succeed");
            }
        }
    }
}

impl Drop for RepositoryFixture {
    fn drop(&mut self) {
        let _ = fs::remove_dir_all(&self.root);
    }
}

#[derive(Debug)]
pub struct GitEntry {
    pub mode: u32,
    pub kind: String,
    pub path: Vec<u8>,
}

pub fn assert_revision_tree_matches_git(fixture: &RepositoryFixture, mount_root: &Path, rev: &str) {
    let git_entries = fixture.git_ls_tree_recursive(rev);
    let mount_paths = collect_mount_leaf_paths(mount_root);
    assert_eq!(
        mount_paths,
        git_entries
            .iter()
            .map(|entry| entry.path.clone())
            .collect::<Vec<_>>()
    );

    for entry in &git_entries {
        let mounted_path = mount_root.join(OsString::from_vec(entry.path.clone()));
        match entry.kind.as_str() {
            "blob" if entry.mode == 0o120000 => {
                let target = fs::read_link(&mounted_path).expect("symlink should resolve");
                assert_eq!(
                    target.as_os_str().as_bytes(),
                    fixture.git_show_path(rev, &entry.path)
                );
            }
            "blob" => {
                assert_eq!(
                    fs::read(&mounted_path).expect("file should be readable"),
                    fixture.git_show_path(rev, &entry.path)
                );
            }
            other => panic!("unexpected git entry kind in fixture: {other}"),
        }
    }
}

pub fn collect_mount_leaf_paths(root: &Path) -> Vec<Vec<u8>> {
    let mut paths = Vec::new();
    collect_mount_leaf_paths_recursive(root, root, &mut paths);
    paths.sort();
    paths
}

pub fn create_temp_dir(prefix: &str) -> PathBuf {
    let path = unique_temp_path(prefix);
    fs::create_dir_all(&path).expect("temporary directory creation should succeed");
    path
}

pub fn run_git_in<I, S>(root: &Path, args: I) -> Output
where
    I: IntoIterator<Item = S>,
    S: AsRef<OsStr>,
{
    let output = Command::new("git")
        .args(args)
        .current_dir(root)
        .output()
        .expect("git should be executable in tests");

    if output.status.success() {
        output
    } else {
        panic!(
            "git command failed with status {}: {}",
            output.status,
            String::from_utf8_lossy(&output.stderr)
        );
    }
}

pub fn make_executable(path: &Path) {
    let mut permissions = fs::metadata(path)
        .expect("script metadata should be readable")
        .permissions();
    permissions.set_mode(0o755);
    fs::set_permissions(path, permissions).expect("script permissions should be writable");
}

pub fn write_symlink(target: &str, path: &Path) {
    symlink(target, path).expect("symlink creation should succeed");
}

pub fn parse_ls_tree_entries(output: &[u8]) -> Vec<GitEntry> {
    output
        .split(|byte| *byte == 0)
        .filter(|record| !record.is_empty())
        .map(parse_ls_tree_entry)
        .collect()
}

fn parse_ls_tree_entry(record: &[u8]) -> GitEntry {
    let tab = record
        .iter()
        .position(|byte| *byte == b'\t')
        .expect("ls-tree records should contain a tab");
    let (header, path) = record.split_at(tab);
    let header = std::str::from_utf8(header).expect("ls-tree header should be UTF-8");
    let mut parts = header.split_whitespace();
    let mode = u32::from_str_radix(parts.next().expect("mode should exist"), 8)
        .expect("mode should be valid octal");
    let kind = parts.next().expect("kind should exist").to_owned();
    let _oid = parts.next().expect("oid should exist");

    GitEntry {
        mode,
        kind,
        path: path.get(1..).unwrap_or_default().to_vec(),
    }
}

fn run_timefs<I, S>(args: I)
where
    I: IntoIterator<Item = S>,
    S: AsRef<OsStr>,
{
    let output = Command::new(timefs_binary())
        .args(args)
        .output()
        .expect("timefs command should execute");

    if !output.status.success() {
        panic!(
            "timefs command failed with status {}: {}",
            output.status,
            String::from_utf8_lossy(&output.stderr)
        );
    }
}

fn wait_for_mount_cleared(mountpoint: &Path) {
    for _ in 0..120 {
        if let Ok(entries) = fs::read_dir(mountpoint) {
            if entries.count() == 0 {
                return;
            }
        }
        thread::sleep(Duration::from_millis(50));
    }

    panic!(
        "mountpoint did not clear after unmount: {}",
        mountpoint.display()
    );
}

fn child_stderr(child: &mut Child) -> String {
    let mut stderr = String::new();
    if let Some(mut pipe) = child.stderr.take() {
        let _ = pipe.read_to_string(&mut stderr);
    }
    stderr
}

fn collect_mount_leaf_paths_recursive(root: &Path, dir: &Path, out: &mut Vec<Vec<u8>>) {
    let mut entries: Vec<_> = fs::read_dir(dir)
        .expect("mounted directory should be readable")
        .filter_map(Result::ok)
        .collect();
    entries.sort_by(|left, right| left.file_name().cmp(&right.file_name()));

    for entry in entries {
        let path = entry.path();
        let file_type = entry.file_type().expect("entry type should be readable");
        if file_type.is_dir() {
            collect_mount_leaf_paths_recursive(root, &path, out);
        } else {
            let relative = path
                .strip_prefix(root)
                .expect("path should remain under root")
                .as_os_str()
                .as_bytes()
                .to_vec();
            out.push(relative);
        }
    }
}

fn unique_temp_path(prefix: &str) -> PathBuf {
    let nanos = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .expect("system time should be after the Unix epoch")
        .as_nanos();
    let mut path = std::env::temp_dir();
    path.push(OsString::from_vec(format!("{prefix}-{nanos}").into_bytes()));
    path
}

fn timefs_binary() -> OsString {
    OsString::from(env!("CARGO_BIN_EXE_timefs"))
}