akv/
utils.rs

1use std::{
2    env,
3    error::Error,
4    path::{Path, PathBuf},
5    time::{SystemTime, UNIX_EPOCH},
6};
7
8/// 获取当前 Unix 时间戳
9pub fn get_unix_timestamp() -> u64 {
10    SystemTime::now()
11        .duration_since(UNIX_EPOCH)
12        .expect("Time went backwards")
13        .as_secs()
14}
15
16/// 解析配置文件路径并转换为绝对路径
17pub fn resolve_config_path(path: &str) -> Result<PathBuf, Box<dyn Error>> {
18    let path = Path::new(path);
19
20    // 如果是绝对路径,直接返回
21    if path.is_absolute() {
22        return Ok(path.to_path_buf());
23    }
24
25    // 获取当前工作目录
26    let current_dir = env::current_dir()?;
27
28    // 拼接成绝对路径
29    let abs_path = current_dir.join(path);
30
31    // 规范化路径(处理 ../ 和 ./ 等)
32    let abs_path = normalize_path(&abs_path);
33
34    Ok(abs_path)
35}
36
37/// 规范化路径,处理 `.` 和 `..`
38pub fn normalize_path(path: &Path) -> PathBuf {
39    let mut components = path.components();
40    let mut normalized = PathBuf::new();
41
42    while let Some(component) = components.next() {
43        match component {
44            std::path::Component::ParentDir => {
45                if !normalized.pop() {
46                    // 如果无法继续回退(已经到根目录),保留这个 ..
47                    normalized.push("..");
48                }
49            }
50            std::path::Component::CurDir => {
51                // 忽略 .
52            }
53            _ => {
54                normalized.push(component.as_os_str());
55            }
56        }
57    }
58
59    normalized
60}