flashpoint_archive/util/
mod.rs

1use std::{fs, path::Path};
2use fs_extra::{copy_items, dir::CopyOptions};
3use serde::{Deserialize, Serialize};
4
5#[cfg_attr(feature = "napi", napi(object))]
6#[derive(Debug, Clone, Deserialize, Serialize)]
7pub struct ContentTreeNode {
8    pub name: String,
9    pub expanded: bool,
10    pub size: i64,
11    pub node_type: String,
12    pub children: Vec<ContentTreeNode>,
13    pub count: i64
14}
15
16pub fn gen_content_tree(root: &str) -> Result<ContentTreeNode, Box<dyn std::error::Error + Send + Sync>> {
17    let children = load_branch(std::path::Path::new(root))?;
18    let children_total: i64 = children.iter().map(|n| n.count).sum();
19    let count = (children.len() as i64) + children_total;
20    let node = ContentTreeNode {
21        name: String::from("content"),
22        expanded: true,
23        node_type: String::from("directory"),
24        size: 0,
25        children,
26        count,
27    };
28    Ok(node)
29}
30
31fn load_branch(root: &std::path::Path) -> Result<Vec<ContentTreeNode>, Box<dyn std::error::Error + Send + Sync>> {
32    let mut nodes: Vec<ContentTreeNode> = Vec::new();
33    let dir = std::fs::read_dir(root)?;
34    for entry in dir {
35        let entry = entry?;
36        let path = entry.path();
37        if path.is_dir() {
38            let children = load_branch(path.as_path())?;
39            let children_total: i64 = children.iter().map(|n| n.count).sum();
40            let count = (children.len() as i64) + children_total;
41            let node = ContentTreeNode {
42                name: String::from(path.file_name().unwrap().to_str().unwrap()),
43                expanded: true,
44                node_type: String::from("directory"),
45                children,
46                size: 0,
47                count: count as i64
48            };
49            nodes.push(node);
50        } else {
51            let node = ContentTreeNode {
52                name: String::from(path.file_name().unwrap().to_str().unwrap()),
53                expanded: true,
54                node_type: String::from("file"),
55                children: Vec::new(),
56                size: path.metadata()?.len() as i64, 
57                count: 0
58            };
59            nodes.push(node);
60        }
61    }
62    Ok(nodes)
63}
64
65pub fn copy_folder(src: &str, dest: &str) -> Result<u64, Box<dyn std::error::Error>> {
66    let root_path = Path::new(src);
67    let dest_path = Path::new(dest);
68    fs::create_dir_all(dest_path).unwrap();
69
70    let options = CopyOptions::new(); //Initialize default values for CopyOptions
71
72    // copy dir1 and file1.txt to target/dir1 and target/file1.txt
73    let mut from_paths = Vec::new();
74    from_paths.push(root_path);
75    let copied_items = copy_items(&from_paths, dest_path, &options)?;
76    Ok(copied_items)
77}