Skip to main content

arui_core/
utils.rs

1//! # 工具模块
2//! 提供一些通用的工具方法,包括:
3//! - 生成随机 id
4//! - 检查路径是否合法
5use crate::errors::IOError;
6use std::path::Path;
7use uuid::Uuid;
8
9/// 生成随机 id
10///
11/// # Examples
12///
13/// ```rust
14/// use arui_core::utils::generate_id;
15/// let id = generate_id();
16///
17/// assert_eq!(id.len(), 36);
18/// ```
19pub fn generate_id() -> String {
20    Uuid::new_v4().to_string()
21}
22
23/// 检查路径是否合法
24/// 接受一个路径参数,可以是绝对路径也可以是一个相对路径
25/// 若路径不存在则抛出错误 InvalidPath,存在则返回当前路径的绝对路径
26///
27/// # Examples
28///
29/// ```rust
30/// use arui_core::utils::check_path;
31///
32/// let valid = check_path('.');
33/// println!("{}", valid.unwrap());
34///
35/// let invalid = check_path("/not_exist");
36/// println!("{}", invalid.unwrap_err());
37/// ```
38pub fn check_path<S>(target: S) -> Result<String, IOError>
39where
40    S: Into<String>,
41{
42    let s = target.into();
43    let path = Path::new(&s);
44    if !path.exists() {
45        Err(IOError::InvalidPath(s))
46    } else {
47        Ok(path.canonicalize()?.to_string_lossy().to_string())
48    }
49}
50
51#[cfg(test)]
52mod tests {
53    use super::*;
54
55    #[test]
56    fn test_generate_id() {
57        let id = generate_id();
58        assert_eq!(id.len(), 36);
59    }
60
61    #[test]
62    fn test_check_path() {
63        let valid_path = check_path("./src".to_string());
64        assert!(valid_path.is_ok());
65        // 获取当前启动命令时的绝对路径
66        let current_path = std::env::current_dir()
67            .unwrap()
68            .to_string_lossy()
69            .to_string();
70        // current_path 拼接上 src 应该和 valid_path 相同
71        assert_eq!(current_path + "/src", valid_path.unwrap());
72        let invalid_path = check_path("/not_exist".to_string());
73        assert!(invalid_path.is_err());
74    }
75}