grin_util/
file.rs

1// Copyright 2021 The Grin Developers
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14use std::fs;
15use std::io::{self, BufRead};
16use std::path::{Path, PathBuf};
17use walkdir::WalkDir;
18
19/// Delete a directory or file
20pub 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
30/// Copy directory, create destination if needed
31pub 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
46/// List directory
47pub 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
71/// Retrieve first line from file
72pub 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}