Skip to main content

cli_assert/
files.rs

1use std::path::{Path, PathBuf};
2
3pub struct TmpFile {
4  /// Temporary directory.
5  dir: tempfile::TempDir,
6  /// Full path to file in temporary directory.
7  path: PathBuf,
8}
9
10impl TmpFile {
11  /// Creates a new file with specified name.
12  pub fn new(file_name: impl AsRef<Path>) -> Self {
13    let dir = tempfile::TempDir::new().unwrap();
14    let path = dir.path().join(file_name);
15    std::fs::File::create_new(&path).unwrap();
16    Self { dir, path }
17  }
18
19  /// Writes data to file.
20  pub fn write(&self, data: impl AsRef<[u8]>) {
21    std::fs::write(&self.path, data.as_ref()).unwrap();
22  }
23
24  /// Asserts the expected file content.
25  pub fn assert(&self, expected: impl AsRef<[u8]>) {
26    let actual = std::fs::read(&self.path).unwrap();
27    let expected = expected.as_ref();
28    if actual != expected {
29      println!("expected content: {:?}", expected);
30      println!("  actual content: {:?}", actual);
31      panic!("unexpected content")
32    }
33  }
34
35  /// Returns the directory name.
36  pub fn dir(&self) -> &Path {
37    self.dir.path()
38  }
39
40  /// Returns the file path.
41  pub fn path(&self) -> &Path {
42    &self.path
43  }
44
45  /// Sets read-only permission on file.
46  pub fn set_readonly(&self, readonly: bool) {
47    let mut permissions = std::fs::metadata(self.path()).unwrap().permissions();
48    permissions.set_readonly(readonly);
49    std::fs::set_permissions(self.path(), permissions).unwrap();
50  }
51}