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
use serde::{de::DeserializeOwned, Serialize};
use std::{
fs::{File, OpenOptions},
io::Write,
os::unix::prelude::OpenOptionsExt,
path::Path,
};
use crate::error::{CliError, CliTypedResult};
pub fn open_file(path: &Path) -> CliTypedResult<File> {
File::open(path)
.map_err(|e| CliError::UnableToReadFile(format!("{}", path.display()), e.to_string()))
}
pub fn read_from_file(path: &Path) -> CliTypedResult<Vec<u8>> {
std::fs::read(path)
.map_err(|e| CliError::UnableToReadFile(format!("{}", path.display()), e.to_string()))
}
pub fn write_to_file(path: &Path, name: &str, bytes: &[u8]) -> CliTypedResult<()> {
write_to_file_with_opts(path, name, bytes, &mut OpenOptions::new())
}
pub fn write_to_user_only_file(path: &Path, name: &str, bytes: &[u8]) -> CliTypedResult<()> {
let mut opts = OpenOptions::new();
#[cfg(unix)]
opts.mode(0o600);
write_to_file_with_opts(path, name, bytes, &mut opts)
}
pub fn write_to_file_with_opts(
path: &Path,
name: &str,
bytes: &[u8],
opts: &mut OpenOptions,
) -> CliTypedResult<()> {
let mut file = opts
.write(true)
.create(true)
.truncate(true)
.open(path)
.map_err(|e| CliError::IO(name.to_string(), e))?;
file.write_all(bytes)
.map_err(|e| CliError::IO(name.to_string(), e))
}
pub fn to_yaml<T: Serialize + ?Sized>(input: &T) -> CliTypedResult<String> {
Ok(serde_yaml::to_string(input)?)
}
pub fn from_yaml<T: DeserializeOwned>(input: &str) -> CliTypedResult<T> {
Ok(serde_yaml::from_str(input)?)
}