1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
use crate::file::FileInfo;
use crate::recover::RecoverType;
use crate::{is_exist, is_same_root, fix_path, replace, FileAttr, RecoverResult};
use std::collections::VecDeque;
use std::ffi::OsStr;
use std::fmt::{Debug, Display, Formatter};
use std::fs::{create_dir_all, read_dir, remove_dir_all, rename};
use std::io::{Error, ErrorKind, Result};
use std::path::{Path, PathBuf};

#[derive(Clone)]
pub struct DirectoryInfo {
    pub(crate) path: PathBuf,
}
impl Debug for DirectoryInfo {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DirectoryInfo")
            .field("path", &self.as_path().display().to_string())
            .finish()
    }
}
impl Display for DirectoryInfo {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.path.display().to_string())
    }
}

impl DirectoryInfo {
    pub fn open<P: AsRef<Path>>(path: P) -> Result<DirectoryInfo> {
        let path = fix_path(path)?;
        if path.is_dir() {
            Ok(DirectoryInfo { path })
        } else {
            Err(Error::new(
                ErrorKind::NotFound,
                format!(
                    "The path '{}' is not a directory or does not exist",
                    path.display()
                ),
            ))
        }
    }
    pub unsafe fn open_uncheck(path: impl AsRef<Path>) -> DirectoryInfo {
        DirectoryInfo {
            path: path.as_ref().to_path_buf()
        }
    }
    pub fn create<P: AsRef<Path>>(path: P) -> Result<DirectoryInfo> {
        let path = fix_path(path)?;
        create_dir_all(path.as_path())?;
        Ok(DirectoryInfo { path })
    }
    fn _open(path: PathBuf) -> DirectoryInfo {
        DirectoryInfo { path }
    }

    pub fn children(&self) -> Result<Vec<PathBuf>> {
        get_children(self.as_path(), |path| path.is_dir() || path.is_file())
    }

    pub fn children_filter_by<F>(&self, f: F) -> Result<Vec<PathBuf>>
    where
        F: Fn(&Path) -> bool,
    {
        get_children(self.as_path(), |path| {
            (path.is_dir() || path.is_file()) && f(path)
        })
    }
    pub fn files(&self) -> Result<Vec<FileInfo>> {
        get_children(self.as_path(), |path| path.is_file()).and_then(|paths| {
            Ok(paths
                .into_iter()
                .map(|path| FileInfo::_open(path))
                .collect())
        })
    }
    pub fn files_filter_by<F>(&self, f: F) -> Result<Vec<FileInfo>>
    where
        F: Fn(&FileInfo) -> bool,
    {
        get_children(self.as_path(), |path| path.is_file()).and_then(|paths| {
            Ok(paths
                .into_iter()
                .map(|path| FileInfo::_open(path))
                .filter(f)
                .collect())
        })
    }
    pub fn directories(&self) -> Result<Vec<DirectoryInfo>> {
        get_children(self.as_path(), |path| path.is_dir()).and_then(|paths| {
            Ok(paths
                .into_iter()
                .map(|path| DirectoryInfo::_open(path))
                .collect())
        })
    }
    pub fn directories_filter_by<F>(&self, f: F) -> Result<Vec<DirectoryInfo>>
    where
        F: Fn(&DirectoryInfo) -> bool,
    {
        get_children(self.as_path(), |path| path.is_dir()).and_then(|paths| {
            Ok(paths
                .into_iter()
                .map(|path| DirectoryInfo::_open(path))
                .filter(f)
                .collect())
        })
    }
}

#[inline]
fn get_children<F>(path: &Path, f: F) -> Result<Vec<PathBuf>>
where
    F: Fn(&Path) -> bool,
{
    let children = read_dir(path)?
        .into_iter()
        .filter_map(|dir| match dir {
            Ok(dir) => {
                let path = dir.path();
                if f(&path) {
                    Some(path)
                } else {
                    None
                }
            }
            _ => None,
        })
        .collect();
    Ok(children)
}

impl FileAttr for DirectoryInfo {
    fn as_path(&self) -> &Path {
        self.path.as_path()
    }

    fn size(&self) -> u64 {
        let mut queue = VecDeque::new();
        queue.push_back(self.clone());
        let mut size = 0;
        while let Some(dir) = queue.pop_front() {
            for directory in dir.directories().unwrap_or_default() {
                queue.push_back(directory);
            }
            for file in dir.files().unwrap_or_default() {
                size += file.size();
            }
        }
        size
    }

    fn rename<T: AsRef<OsStr>>(&mut self, name: T) -> Result<()> {
        let mut path = self.path.clone();
        path.set_file_name(name);
        rename(self.as_path(), path.as_path())?;
        self.path = path;
        Ok(())
    }
    /// Check whether all files and directories under the two file directories are equal
    ///
    /// If both directories are `empty`, the return is always `true`
    fn eq(&self, other: &Self) -> bool {
        fn _eq(dir: DirectoryInfo, other: DirectoryInfo) -> Result<bool> {
            let mut queue = VecDeque::new();
            queue.push_back((dir, other));
            while let Some((dir, other)) = queue.pop_front() {
                let mut dir_vec = dir.directories()?;
                let mut other_vec = other.directories()?;
                if dir_vec.len() != other_vec.len() {
                    return Ok(false);
                }
                while let Some(dir) = dir_vec.pop() {
                    let Some(other) = other_vec.pop() else {
                        return Ok(false)
                    };
                    if dir.file_name() != other.file_name() {
                        return Ok(false);
                    }
                    queue.push_back((dir, other));
                }
                let mut f_vec = dir.files()?;
                let mut other_vec = other.files()?;
                if f_vec.len() != other_vec.len() {
                    return Ok(false);
                }
                while let Some(f) = f_vec.pop() {
                    let Some(other) = other_vec.pop() else {
                        return Ok(false)
                    };
                    if f.file_name() != other.file_name() || !f.eq(&other) {
                        return Ok(false);
                    }
                }
            }
            Ok(true)
        }
        _eq(self.clone(), other.clone()).unwrap_or_default()
    }

    fn copy_new<P: AsRef<Path>>(&self, path: P) -> RecoverResult {
        let path = fix_path(path)?;
        if is_exist(path.as_path()) {
            return Err((RecoverType::CopyDirectory(self), path).into());
        }
        _copy_dir(self.clone(), path)?;
        Ok(())
    }

    fn move_new<P: AsRef<Path>>(&mut self, path: P) -> RecoverResult {
        let path = fix_path(path)?;
        if is_exist(path.as_path()) {
            return Err((RecoverType::MoveDirectory(self), path).into());
        }
        if is_same_root(self.as_path(), path.as_path()) {
            rename(self.as_path(), path.as_path())?;
        } else {
            _move_dir(self.clone(), path.clone())?;
            _delete_dir(self)?;
        }
        self.path = path;
        Ok(())
    }
}

pub(crate) fn _delete_dir(dir: &mut DirectoryInfo) -> Result<()> {
    if dir.read_only()? {
        dir.set_readonly(false)?
    }
    remove_dir_all(dir.as_path())
}
pub(crate) fn _move_dir(dir: DirectoryInfo, to: PathBuf) -> Result<()> {
    let mut queue = VecDeque::new();
    let path = dir.path.clone();
    queue.push_back(dir);
    while let Some(dir) = queue.pop_front() {
        for directory in dir.directories()? {
            queue.push_front(directory)
        }
        let dir_path = replace(dir.as_path(), path.as_path(), to.as_path());
        if !dir_path.is_dir() {
            create_dir_all(dir_path.as_path())?;
        }
        for mut file in dir.files()? {
            file.move_to(dir_path.as_path())
                .or_else(|e| e.try_recover())?;
        }
    }
    Ok(())
}
pub(crate) fn _copy_dir(dir: DirectoryInfo, to: PathBuf) -> Result<()> {
    let mut queue = VecDeque::new();
    let path = dir.path.clone();
    queue.push_back(dir);
    while let Some(dir) = queue.pop_front() {
        for directory in dir.directories()? {
            queue.push_front(directory)
        }
        let dir_path = replace(dir.as_path(), path.as_path(), to.as_path());
        if !dir_path.is_dir() {
            create_dir_all(dir_path.as_path())?;
        }
        for file in dir.files()? {
            file.copy_to(dir_path.as_path())
                .or_else(|e| e.try_recover())?;
        }
    }
    Ok(())
}