1use std::fs;
15use std::io::{self, BufRead};
16use std::path::{Path, PathBuf};
17use walkdir::WalkDir;
18
19pub fn delete(path_buf: PathBuf) -> io::Result<()> {
21 if path_buf.is_dir() {
22 fs::remove_dir_all(path_buf)
23 } else if path_buf.is_file() {
24 fs::remove_file(path_buf)
25 } else {
26 Ok(())
27 }
28}
29
30pub fn copy_dir_to(src: &Path, dst: &Path) -> io::Result<u64> {
32 let mut counter = 0u64;
33 if !dst.is_dir() {
34 fs::create_dir(dst)?
35 }
36
37 for entry_result in src.read_dir()? {
38 let entry = entry_result?;
39 let file_type = entry.file_type()?;
40 let count = copy_to(&entry.path(), file_type, &dst.join(entry.file_name()))?;
41 counter += count;
42 }
43 Ok(counter)
44}
45
46pub fn list_files(path: &Path) -> Vec<PathBuf> {
48 WalkDir::new(path)
49 .sort_by(|a, b| a.path().cmp(b.path()))
50 .min_depth(1)
51 .into_iter()
52 .filter_map(|x| x.ok())
53 .filter(|x| x.file_type().is_file())
54 .filter_map(|x| x.path().strip_prefix(path).map(|x| x.to_path_buf()).ok())
55 .collect()
56}
57
58fn copy_to(src: &Path, src_type: fs::FileType, dst: &Path) -> io::Result<u64> {
59 if src_type.is_file() {
60 fs::copy(src, dst)
61 } else if src_type.is_dir() {
62 copy_dir_to(src, dst)
63 } else {
64 Err(io::Error::new(
65 io::ErrorKind::Other,
66 format!("Could not copy: {}", src.display()),
67 ))
68 }
69}
70
71pub fn get_first_line(file_path: Option<String>) -> Option<String> {
73 file_path.and_then(|path| match fs::File::open(path) {
74 Ok(file) => {
75 let buf_reader = io::BufReader::new(file);
76 let mut lines_iter = buf_reader.lines().map(|l| l.unwrap());
77 lines_iter.next()
78 }
79 Err(_) => None,
80 })
81}