cfo/
lib.rs

1use std::fs;
2use std::fs::{File, OpenOptions};
3use std::io;
4use std::io::prelude::*;
5#[cfg(target_family = "unix")]
6use std::os::unix;
7#[cfg(target_family = "windows")]
8use std::os::windows;
9use std::path::Path;
10
11/// A simple implementation of `% cat path`
12pub fn read_file(path: &Path) -> io::Result<String> {
13    let mut f = File::open(path)?;
14    let mut s = String::new();
15    match f.read_to_string(&mut s) {
16        Ok(_) => Ok(s),
17        Err(e) => Err(e),
18    }
19}
20
21/// A simple implementation of `% echo s > path`
22pub fn write_file(s: &str, path: &Path) -> io::Result<()> {
23    let mut f = File::create(path)?;
24    f.write_all(s.as_bytes())
25}
26
27/// A simple implementation of `% touch path` (ignores existing files)
28pub fn touch_file(path: &Path) -> io::Result<()> {
29    match OpenOptions::new().create(true).write(true).open(path) {
30        Ok(_) => Ok(()),
31        Err(e) => Err(e),
32    }
33}
34
35/// Recursively create a directory, returns `io::Result<()>`
36/// like `mkdir -p a/c/d`
37pub fn create_dir(path: &Path) -> io::Result<()>{
38    match fs::create_dir_all(path) {
39        Ok(_) => Ok(()),
40        Err(e) => Err(e),
41    }
42}
43
44/// Remove a file, returns `io::Result<()>`
45pub fn remove_file(path: &Path) -> io::Result<()> {
46    match fs::remove_file(path) {
47        Ok(_) => Ok(()),
48        Err(e) => Err(e),
49    }
50}
51
52/// Remove an empty directory, returns `io::Result<()>`
53/// Or pass not_empty [bool] as true to remove non empty ones
54pub fn remove_dir (path: &Path, not_empty: bool) -> io::Result<()> {
55    if not_empty {
56        match fs::remove_dir_all(path) {
57            Ok(_) => Ok(()),
58            Err(e) => Err(e),
59        }
60    } else {
61        match fs::remove_dir(path) {
62            Ok(_) => Ok(()),
63            Err(e) => Err(e),
64        }
65    }
66}
67
68/// Create a symbolic link, returns `io::Result<()>`
69pub fn create_link (src_path: &Path, dst_path: &Path) -> io::Result<()> {
70    #[cfg(target_family = "unix")] {
71        match unix::fs::symlink(src_path, dst_path) {
72            Ok(_) => Ok(()),
73            Err(e) => Err(e),
74        }
75    }
76    #[cfg(target_family = "windows")] {
77        match windows::fs::symlink_file(src_path, dst_path) {
78            Ok(_) => Ok(()),
79            Err(e) => Err(e),
80        }
81    }
82}
83