Skip to main content

lux_lib/fs/
sync.rs

1use std::{fs, path::Path};
2
3use super::FsError;
4
5/// Wrapped [`fs::read_to_string`].
6pub(crate) fn read_to_string(path: impl AsRef<Path>) -> Result<String, FsError> {
7    let path = path.as_ref();
8    fs::read_to_string(path).map_err(|source| FsError::ReadToString {
9        path: path.to_path_buf(),
10        source,
11    })
12}
13
14/// Wrapped [`fs::write`].
15pub(crate) fn write(path: impl AsRef<Path>, contents: impl AsRef<[u8]>) -> Result<(), FsError> {
16    let path = path.as_ref();
17    fs::write(path, contents).map_err(|source| FsError::Write {
18        path: path.to_path_buf(),
19        source,
20    })
21}
22
23/// Wrapped [`fs::copy`].
24pub(crate) fn copy(from: impl AsRef<Path>, to: impl AsRef<Path>) -> Result<u64, FsError> {
25    let from = from.as_ref();
26    let to = to.as_ref();
27    fs::copy(from, to).map_err(|source| FsError::Copy {
28        from: from.to_path_buf(),
29        to: to.to_path_buf(),
30        source,
31    })
32}
33
34/// Wrapped [`fs::create_dir_all`].
35pub(crate) fn create_dir_all(path: impl AsRef<Path>) -> Result<(), FsError> {
36    let path = path.as_ref();
37    fs::create_dir_all(path).map_err(|source| FsError::CreateDirAll {
38        path: path.to_path_buf(),
39        source,
40    })
41}
42
43/// Wrapped [`fs::remove_file`].
44pub(crate) fn remove_file(path: impl AsRef<Path>) -> Result<(), FsError> {
45    let path = path.as_ref();
46    fs::remove_file(path).map_err(|source| FsError::RemoveFile {
47        path: path.to_path_buf(),
48        source,
49    })
50}
51
52/// Wrapped [`fs::remove_dir_all`].
53pub(crate) fn remove_dir_all(path: impl AsRef<Path>) -> Result<(), FsError> {
54    let path = path.as_ref();
55    fs::remove_dir_all(path).map_err(|source| FsError::RemoveDirAll {
56        path: path.to_path_buf(),
57        source,
58    })
59}
60
61/// Wrapped [`fs::read_dir`].
62pub(crate) fn read_dir(path: impl AsRef<Path>) -> Result<fs::ReadDir, FsError> {
63    let path = path.as_ref();
64    fs::read_dir(path).map_err(|source| FsError::ReadDir {
65        path: path.to_path_buf(),
66        source,
67    })
68}
69
70/// Wrapped [`fs::File::open`].
71pub(crate) fn open(path: impl AsRef<Path>) -> Result<fs::File, FsError> {
72    let path = path.as_ref();
73    fs::File::open(path).map_err(|source| FsError::FileOpen {
74        path: path.to_path_buf(),
75        source,
76    })
77}
78
79/// Wrapped [`fs::File::create`].
80pub(crate) fn create(path: impl AsRef<Path>) -> Result<fs::File, FsError> {
81    let path = path.as_ref();
82    fs::File::create(path).map_err(|source| FsError::FileCreate {
83        path: path.to_path_buf(),
84        source,
85    })
86}