rainbeam_shared/
fs.rs

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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
//! Fs access utilities
//!
//! This is essentially a wrapper around standard fs, so it's just to keep things similar.
use std::path::Path;
pub use std::{
    fs::{
        create_dir, read_dir, read_to_string, remove_dir_all, remove_file, write as std_write,
        read as std_read, canonicalize, metadata, Metadata,
    },
    io::Result,
};

/// Get a path's metadata
///
/// # Arguments
/// * `path`
pub fn fstat<P>(path: P) -> Result<Metadata>
where
    P: AsRef<Path>,
{
    metadata(path)
}

/// Create a directory if it does not already exist
///
/// # Arguments
/// * `path`
pub fn mkdir<P>(path: P) -> Result<()>
where
    P: AsRef<Path>,
{
    if let Err(_) = read_dir(&path) {
        create_dir(path)?
    }

    Ok(())
}

/// `rm -r` for only directories
///
/// # Arguments
/// * `path`
pub fn rmdirr<P: AsRef<Path>>(path: P) -> Result<()>
where
    P: AsRef<Path>,
{
    if let Err(_) = read_dir(&path) {
        return Ok(()); // doesn't exist, return ok since there was nothing to remove
    }

    remove_dir_all(path)
}

/// `rm` for only files
///
/// # Arguments
/// * `path`
pub fn rm<P: AsRef<Path>>(path: P) -> Result<()>
where
    P: AsRef<Path>,
{
    remove_file(path)
}

/// Write to a file given its path and data
///
/// # Arguments
/// * `path`
/// * `data`
pub fn write<P, D>(path: P, data: D) -> Result<()>
where
    P: AsRef<Path>,
    D: AsRef<[u8]>,
{
    std_write(path, data)
}

/// `touch`
///
/// # Arguments
/// * `path`
pub fn touch<P>(path: P) -> Result<()>
where
    P: AsRef<Path>,
{
    std_write(path, "")
}

/// Append to a file given its path and data
///
/// # Arguments
/// * `path`
/// * `data`
pub fn append<P, D>(path: P, data: D) -> Result<()>
where
    P: AsRef<Path>,
    D: AsRef<[u8]>,
{
    let mut bytes = std_read(&path)?; // read current data as bytes
    bytes = [&bytes, data.as_ref()].concat(); // append
    std_write(path, bytes) // write
}

/// `cat`
///
/// # Arguments
/// * `path`
///
/// # Returns
/// * [`String`]
pub fn read<P: AsRef<Path>>(path: P) -> Result<String>
where
    P: AsRef<Path>,
{
    read_to_string(path)
}