1use crate::utils::log::rap_error_and_exit;
2
3use std::fs::{self, File};
4use std::io::Write;
5use std::path::Path;
6
7use rustc_demangle::try_demangle;
8
9pub fn rap_create_dir<P: AsRef<Path>>(path: P, msg: impl AsRef<str>) {
10 if fs::read_dir(&path).is_err() {
11 fs::create_dir(path)
12 .unwrap_or_else(|e| rap_error_and_exit(format!("{}: {}", msg.as_ref(), e)));
13 }
14}
15
16pub fn rap_remove_dir<P: AsRef<Path>>(path: P, msg: impl AsRef<str>) {
17 if fs::read_dir(&path).is_ok() {
18 fs::remove_dir_all(path)
19 .unwrap_or_else(|e| rap_error_and_exit(format!("{}: {}", msg.as_ref(), e)));
20 }
21}
22
23pub fn rap_can_read_dir<P: AsRef<Path>>(path: P, msg: impl AsRef<str>) -> bool {
24 match fs::read_dir(path) {
25 Ok(_) => true,
26 Err(e) => rap_error_and_exit(format!("{}: {}", msg.as_ref(), e)),
27 }
28}
29
30pub fn rap_copy_file<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q, msg: impl AsRef<str>) {
31 fs::copy(from, to).unwrap_or_else(|e| rap_error_and_exit(format!("{}: {}", msg.as_ref(), e)));
32}
33
34pub fn rap_create_file<P: AsRef<Path>>(path: P, msg: impl AsRef<str>) -> fs::File {
35 match fs::File::create(path) {
36 Ok(file) => file,
37 Err(e) => rap_error_and_exit(format!("{}: {}", msg.as_ref(), e)),
38 }
39}
40
41pub fn rap_read<P: AsRef<Path>>(path: P, msg: impl AsRef<str>) -> fs::File {
42 match fs::File::open(path) {
43 Ok(file) => file,
44 Err(e) => rap_error_and_exit(format!("{}: {}", msg.as_ref(), e)),
45 }
46}
47
48pub fn rap_write(mut file: File, buf: &[u8], msg: impl AsRef<str>) -> usize {
49 file.write(buf)
50 .unwrap_or_else(|e| rap_error_and_exit(format!("{}: {}", msg.as_ref(), e)))
51}
52
53pub fn rap_demangle(name: &str) -> String {
54 match try_demangle(name) {
55 Ok(d) => format!("{:#}", d),
56 Err(_) => name.to_string(),
57 }
58}