common-utils 0.1.2

common utils library
Documentation
use std::path::{self, Path, PathBuf};

use crate::strings::is_repeat;

/// ### 路径拼接
///
/// 安全路径拼接,会主动忽略跳父目录,从而避免特殊参数注入以夸路径修改特定文件
#[allow(dead_code)]
pub fn safe_join_path(path1: String, path2: String) -> PathBuf {
    Path::new(safe_path(path1).as_str()).join(safe_path(path2))
}

#[test]
fn test_path_join() {
    assert_eq!(
        PathBuf::from("a/b/c"),
        safe_join_path(String::from("a"), String::from("../b/..../c"))
    );
}

/// 计算安全路径
///
/// 可以防止路径访问上级目录,即 ../
#[allow(dead_code)]
pub fn safe_path(raw_path: String) -> String {
    let mut result: String = String::from("");
    for segment in raw_path.split(path::MAIN_SEPARATOR) {
        if segment == ""
            || (is_repeat(segment.to_string())
                && segment.chars().collect::<Box<[char]>>()[0] == '.')
        {
            continue;
        }
        result.push_str(segment);
        result.push_str(&String::from(path::MAIN_SEPARATOR));
    }
    result.pop();
    result
}

#[test]
fn test_safe_path() {
    assert_eq!(String::from("a/b/c"), safe_path(String::from("a/../b/c")));
}