lib/
common.rs

1use fs_extra::{copy_items, dir};
2use std::env::current_dir;
3use std::fs::{create_dir_all, read_dir, read_to_string, remove_dir_all, write};
4use std::path::Path;
5
6pub fn read_file(path: &str) -> Result<String, Box<dyn std::error::Error>> {
7    let path = Path::new(path);
8    if path.exists() {
9        if path.is_file() {
10            Ok(read_to_string(path)?.parse()?)
11        } else {
12            Err(format!("{} is not a file", path.display()).into())
13        }
14    } else {
15        Err(format!("Could not find file {}", path.display()).into())
16    }
17}
18
19pub fn list_dir(path: &str) -> Result<Vec<String>, Box<dyn std::error::Error>> {
20    let path = Path::new(path);
21    if path.exists() {
22        if path.is_dir() {
23            let mut file_list: Vec<String> = Vec::new();
24            for file in read_dir(path)? {
25                file_list.push(file?.file_name().into_string().unwrap());
26            }
27
28            Ok(file_list)
29        } else {
30            Err(format!("{} is not a directory", path.display()).into())
31        }
32    } else {
33        Err(format!("Could not find directory {}", path.display()).into())
34    }
35}
36
37pub fn rm_dir(path: &str) -> std::io::Result<()> {
38    let path = Path::new(path);
39    if path.exists() && path.is_dir() {
40        remove_dir_all(path)?;
41    }
42    Ok(())
43}
44
45pub fn make_dirs(dirs: &[&str]) -> std::io::Result<()> {
46    for dir in dirs {
47        create_dir_all(dir)?;
48    }
49    Ok(())
50}
51
52pub fn pwd() -> std::io::Result<String> {
53    Ok(current_dir()?.display().to_string())
54}
55
56pub fn write_file(path: &str, text: &str) -> std::io::Result<()> {
57    let path = Path::new(path);
58    write(path, text)?;
59    Ok(())
60}
61
62pub fn copy_dir(from: &[&str], to: &str) -> Result<(), Box<dyn std::error::Error>> {
63    let options = dir::CopyOptions::new();
64    copy_items(from, to, &options)?;
65    Ok(())
66}