mf_utils/
lib.rs

1use regex::Regex;
2use fs_extra;
3use std::fs;
4use std::path::{Path, PathBuf};
5
6pub fn is_md_file_name(file_name: &str) -> bool {
7    let reg = Regex::new(r"\.md$").unwrap();
8
9    reg.is_match(file_name)
10}
11
12pub fn move_files(source_paths: &Vec<PathBuf>, dest_path: &Path) {
13    let options = fs_extra::dir::CopyOptions::new();
14  
15    if !dest_path.exists() {
16        fs::create_dir(dest_path).expect("Cannot create destination directory");
17    }
18  
19    let dest = dest_path.to_str().unwrap().to_string();
20    let mut sources: Vec<String> = Vec::new();
21  
22    for path in source_paths {
23        sources.push(path.to_str().unwrap().to_string());
24    }
25  
26    fs_extra::move_items(&sources, &dest, &options)
27        .expect(&format!("Failed to move files to {}", dest));
28  }
29
30
31pub fn get_relative_path(path: &Path, base_path: &Path) -> PathBuf {
32    let mut relative_path = PathBuf::new();
33
34    for component in path.components() {
35        if component == std::path::Component::Normal("..".as_ref()) {
36            relative_path.pop();
37        } else if component != std::path::Component::Normal(".".as_ref()) {
38            relative_path.push(component);
39        }
40    }
41
42    relative_path.strip_prefix(base_path).unwrap().to_path_buf()
43}
44
45#[cfg(test)]
46mod tests {
47    #[test]
48    fn test_md_file_name() {
49        assert!(super::is_md_file_name("test.md"));
50        assert!(!super::is_md_file_name("test.txt"));
51        assert!(!super::is_md_file_name("test.mdx"));
52    }
53
54    #[test]
55    fn test_get_relative_path() {
56        let path = std::path::Path::new("/a/b/c/d");
57        let base_path = std::path::Path::new("/a/b");
58
59        let relative_path = super::get_relative_path(path, base_path);
60
61        assert_eq!(relative_path.to_str().unwrap(), "c/d");
62    }
63}