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
use crate::errors::OutputFileError;
use std::{
borrow::Cow,
fs::{self, File},
io::Write,
path::Path,
};
pub static OUTPUTS_DIRECTORY_NAME: &str = "outputs/";
pub static OUTPUT_FILE_EXTENSION: &str = ".out";
pub struct OutputFile {
pub package_name: String,
}
impl OutputFile {
pub fn new(package_name: &str) -> Self {
Self {
package_name: package_name.to_string(),
}
}
pub fn exists_at(&self, path: &Path) -> bool {
let path = self.setup_file_path(path);
path.exists()
}
pub fn read_from(&self, path: &Path) -> Result<String, OutputFileError> {
let path = self.setup_file_path(path);
let output = fs::read_to_string(&path).map_err(|_| OutputFileError::FileReadError(path.into_owned()))?;
Ok(output)
}
pub fn write(&self, path: &Path, bytes: &[u8]) -> Result<(), OutputFileError> {
let path = self.setup_file_path(path);
let mut file = File::create(&path)?;
Ok(file.write_all(bytes)?)
}
pub fn remove(&self, path: &Path) -> Result<bool, OutputFileError> {
let path = self.setup_file_path(path);
if !path.exists() {
return Ok(false);
}
fs::remove_file(&path).map_err(|_| OutputFileError::FileRemovalError(path.into_owned()))?;
Ok(true)
}
fn setup_file_path<'a>(&self, path: &'a Path) -> Cow<'a, Path> {
let mut path = Cow::from(path);
if path.is_dir() {
if !path.ends_with(OUTPUTS_DIRECTORY_NAME) {
path.to_mut().push(OUTPUTS_DIRECTORY_NAME);
}
path.to_mut()
.push(format!("{}{}", self.package_name, OUTPUT_FILE_EXTENSION));
}
path
}
}