]> luflow.net public git repositories - flow-web.git/blob - src/site/helper.rs
Initial commit.
[flow-web.git] / src / site / helper.rs
1 // luflow.net web site
2 // AGPL-3.0 License (see LICENSE)
3
4 use log::info;
5 use regex::Regex;
6 use std::env;
7 use std::fs;
8 use std::io::Write;
9 use std::path::Path;
10 use std::path::PathBuf;
11 use tokio::fs::File;
12 use tokio::io::{self, AsyncWriteExt};
13
14 pub struct Helper {}
15
16 impl Helper {
17 pub fn get_current_working_dir() -> PathBuf {
18 let res = env::current_dir();
19 match res {
20 Ok(path) => path,
21 Err(_) => PathBuf::new(),
22 }
23 }
24
25 pub fn get_output_dir() -> PathBuf {
26 let cwd = Helper::get_current_working_dir();
27 return cwd.join("output");
28 }
29
30 /// Replaces spaces with '-', only allows 'a-z', 'A-Z', '0-9' and '-' characters and finally
31 /// converts to lowercase.
32 ///
33 /// # Arguments
34 ///
35 /// * `str` - is the string to sanitize.
36 ///
37 /// # Examples
38 ///
39 /// ```
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");
43 /// ```
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();
47
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, "");
52
53 // also convert to lower case:
54 return after_unsupported.to_string().to_lowercase();
55 }
56
57 pub fn create_dir_all<'a>(dir: &'a PathBuf) {
58 match fs::create_dir_all(dir) {
59 Ok(()) => info!("Created dir: '{}'", dir.display()),
60 Err(err) => panic!(
61 "Failed to create dir: '{}'. Error msg: '{}'",
62 dir.display(),
63 err
64 ),
65 };
66 }
67
68 pub fn remove_dir_all<'a>(dir: &'a PathBuf) {
69 match fs::remove_dir_all(dir) {
70 Ok(()) => info!("Removed dir: '{}'", dir.display()),
71 Err(err) => panic!(
72 "Failed to remove dir: '{}'. Error msg: '{}'",
73 dir.display(),
74 err
75 ),
76 };
77 }
78
79 pub fn exists_dir<'a>(dir: &'a PathBuf) -> bool {
80 return dir.as_path().exists();
81 }
82
83 #[async_recursion::async_recursion]
84 pub async fn copy_dir_all<S, D>(src: S, dst: D) -> Result<(), std::io::Error>
85 where
86 S: AsRef<Path> + Send + Sync,
87 D: AsRef<Path> + Send + Sync,
88 {
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?;
93 if ty.is_dir() {
94 Self::copy_dir_all(entry.path(), dst.as_ref().join(entry.file_name())).await?;
95 } else {
96 tokio::fs::copy(entry.path(), dst.as_ref().join(entry.file_name())).await?;
97 }
98 }
99 Ok(())
100 }
101
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?;
105
106 // write data to file:
107 file.write_all(data).await?;
108
109 info!("Wrote '{}' successfully", file_path.display());
110 Ok(())
111 }
112
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)?;
116
117 // write data to file:
118 file.write_all(data)?;
119
120 info!("Wrote '{}' successfully", file_path.display());
121 Ok(())
122 }
123 }