2 // AGPL-3.0 License (see LICENSE)
10 use std::path::PathBuf;
12 use tokio::io::{self, AsyncWriteExt};
17 pub fn get_current_working_dir() -> PathBuf {
18 let res = env::current_dir();
21 Err(_) => PathBuf::new(),
25 pub fn get_output_dir() -> PathBuf {
26 let cwd = Helper::get_current_working_dir();
27 return cwd.join("output");
30 /// Replaces spaces with '-', only allows 'a-z', 'A-Z', '0-9' and '-' characters and finally
31 /// converts to lowercase.
35 /// * `str` - is the string to sanitize.
40 /// let str_to_sanitize = "This is a test, and so on.";
41 /// let str_sanitized = Helper::sanitize_string(str_to_sanitize);
42 /// assert_eq!(str_sanitized, "this-is-a-test-and-so-on");
44 pub fn sanitize_string(str: &str) -> String {
45 let re_whitespace = Regex::new(r"\s").unwrap();
46 let re_unsupported = Regex::new(r"[^0-9a-zA-Z-]").unwrap();
48 // replace all spaces with '-':
49 let after_whitespace = re_whitespace.replace_all(str, "-");
50 // only allow 'a-z' 'A-Z' '0-9' and '-' characters:
51 let after_unsupported = re_unsupported.replace_all(&after_whitespace, "");
53 // also convert to lower case:
54 return after_unsupported.to_string().to_lowercase();
57 pub fn create_dir_all<'a>(dir: &'a PathBuf) {
58 match fs::create_dir_all(dir) {
59 Ok(()) => info!("Created dir: '{}'", dir.display()),
61 "Failed to create dir: '{}'. Error msg: '{}'",
68 pub fn remove_dir_all<'a>(dir: &'a PathBuf) {
69 match fs::remove_dir_all(dir) {
70 Ok(()) => info!("Removed dir: '{}'", dir.display()),
72 "Failed to remove dir: '{}'. Error msg: '{}'",
79 pub fn exists_dir<'a>(dir: &'a PathBuf) -> bool {
80 return dir.as_path().exists();
83 #[async_recursion::async_recursion]
84 pub async fn copy_dir_all<S, D>(src: S, dst: D) -> Result<(), std::io::Error>
86 S: AsRef<Path> + Send + Sync,
87 D: AsRef<Path> + Send + Sync,
89 tokio::fs::create_dir_all(&dst).await?;
90 let mut entries = tokio::fs::read_dir(src).await?;
91 while let Some(entry) = entries.next_entry().await? {
92 let ty = entry.file_type().await?;
94 Self::copy_dir_all(entry.path(), dst.as_ref().join(entry.file_name())).await?;
96 tokio::fs::copy(entry.path(), dst.as_ref().join(entry.file_name())).await?;
102 pub async fn write_file<'a>(file_path: &'a PathBuf, data: &'a [u8]) -> io::Result<()> {
103 // create output file:
104 let mut file = File::create(file_path).await?;
106 // write data to file:
107 file.write_all(data).await?;
109 info!("Wrote '{}' successfully", file_path.display());
113 pub fn write_file_sync<'a>(file_path: &'a PathBuf, data: &'a [u8]) -> io::Result<()> {
114 // create output file:
115 let mut file = std::fs::File::create(file_path)?;
117 // write data to file:
118 file.write_all(data)?;
120 info!("Wrote '{}' successfully", file_path.display());