rainbeam_shared/
fs.rs

1//! Fs access utilities
2//!
3//! This is essentially a wrapper around standard fs, so it's just to keep things similar.
4use std::path::Path;
5pub use std::{
6    fs::{
7        create_dir, read_dir, read_to_string, remove_dir_all, remove_file, write as std_write,
8        read as std_read, canonicalize, metadata, Metadata,
9    },
10    io::Result,
11};
12
13/// Get a path's metadata
14///
15/// # Arguments
16/// * `path`
17pub fn fstat<P>(path: P) -> Result<Metadata>
18where
19    P: AsRef<Path>,
20{
21    metadata(path)
22}
23
24/// Create a directory if it does not already exist
25///
26/// # Arguments
27/// * `path`
28pub fn mkdir<P>(path: P) -> Result<()>
29where
30    P: AsRef<Path>,
31{
32    if read_dir(&path).is_err() {
33        create_dir(path)?
34    }
35
36    Ok(())
37}
38
39/// `rm -r` for only directories
40///
41/// # Arguments
42/// * `path`
43pub fn rmdirr<P: AsRef<Path>>(path: P) -> Result<()>
44where
45    P: AsRef<Path>,
46{
47    if read_dir(&path).is_err() {
48        return Ok(()); // doesn't exist, return ok since there was nothing to remove
49    }
50
51    remove_dir_all(path)
52}
53
54/// `rm` for only files
55///
56/// # Arguments
57/// * `path`
58pub fn rm<P: AsRef<Path>>(path: P) -> Result<()>
59where
60    P: AsRef<Path>,
61{
62    remove_file(path)
63}
64
65/// Write to a file given its path and data
66///
67/// # Arguments
68/// * `path`
69/// * `data`
70pub fn write<P, D>(path: P, data: D) -> Result<()>
71where
72    P: AsRef<Path>,
73    D: AsRef<[u8]>,
74{
75    std_write(path, data)
76}
77
78/// `touch`
79///
80/// # Arguments
81/// * `path`
82pub fn touch<P>(path: P) -> Result<()>
83where
84    P: AsRef<Path>,
85{
86    std_write(path, "")
87}
88
89/// Append to a file given its path and data
90///
91/// # Arguments
92/// * `path`
93/// * `data`
94pub fn append<P, D>(path: P, data: D) -> Result<()>
95where
96    P: AsRef<Path>,
97    D: AsRef<[u8]>,
98{
99    let mut bytes = std_read(&path)?; // read current data as bytes
100    bytes = [&bytes, data.as_ref()].concat(); // append
101    std_write(path, bytes) // write
102}
103
104/// `cat`
105///
106/// # Arguments
107/// * `path`
108///
109/// # Returns
110/// * [`String`]
111pub fn read<P: AsRef<Path>>(path: P) -> Result<String>
112where
113    P: AsRef<Path>,
114{
115    read_to_string(path)
116}