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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
// Copyright 2016-2019 Cargo-Bundle developers <https://github.com/burtonageo/cargo-bundle>
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT

use std::{
  fs::{create_dir, create_dir_all, read_dir, remove_dir_all},
  path::{Path, PathBuf},
};

/// Directory options.
#[derive(Default, Clone)]
pub struct DirOpts {
  pub depth: u64,
}

/// File options.
pub struct FileOpts {
  pub overwrite: bool,
  pub skip: bool,
  pub buffer_size: usize,
}

/// Copy options.
#[derive(Clone)]
pub struct Options {
  pub overwrite: bool,
  pub skip: bool,
  pub buffer_size: usize,
  pub copy_files: bool,
  pub content_only: bool,
  pub depth: u64,
}

/// Directory information descriptor
pub struct DirInfo {
  pub size: u64,
  pub files: Vec<String>,
  pub directories: Vec<String>,
}

impl Default for Options {
  fn default() -> Options {
    Options {
      overwrite: false,
      skip: false,
      buffer_size: 64000,
      copy_files: false,
      content_only: false,
      depth: 0,
    }
  }
}

impl Default for FileOpts {
  fn default() -> FileOpts {
    FileOpts {
      overwrite: false,
      skip: false,
      buffer_size: 64000,
    }
  }
}

/// Creates the given directory path,
/// erasing it first if specified.
pub fn create<P>(path: P, erase: bool) -> crate::Result<()>
where
  P: AsRef<Path>,
{
  if erase && path.as_ref().exists() {
    remove(&path)?;
  }
  Ok(create_dir(&path)?)
}

/// Creates all of the directories of the specified path,
/// erasing it first if specified.
pub fn create_all<P>(path: P, erase: bool) -> crate::Result<()>
where
  P: AsRef<Path>,
{
  if erase && path.as_ref().exists() {
    remove(&path)?;
  }
  Ok(create_dir_all(&path)?)
}

/// Removes the directory if it exists.
pub fn remove<P: AsRef<Path>>(path: P) -> crate::Result<()> {
  if path.as_ref().exists() {
    Ok(remove_dir_all(path)?)
  } else {
    Ok(())
  }
}

/// Copy file with the given options.
pub fn copy_file<P, Q>(from: P, to: Q, options: &FileOpts) -> crate::Result<u64>
where
  P: AsRef<Path>,
  Q: AsRef<Path>,
{
  let from = from.as_ref();
  if !from.exists() {
    if let Some(msg) = from.to_str() {
      let msg = format!("Path \"{}\" does not exist or you don't have access", msg);
      return Err(crate::Error::PathUtilError(msg));
    }
    return Err(crate::Error::PathUtilError(
      "Path does not exist or you don't have access!".to_owned(),
    ));
  }

  if !from.is_file() {
    if let Some(msg) = from.to_str() {
      let msg = format!("Path \"{}\" is not a file!", msg);
      return Err(crate::Error::PathUtilError(msg));
    }
    return Err(crate::Error::PathUtilError(
      "Path is not a file!".to_owned(),
    ));
  }
  if !options.overwrite && to.as_ref().exists() {
    if options.skip {
      return Ok(0);
    }

    if let Some(msg) = to.as_ref().to_str() {
      let msg = format!("Path \"{}\" is exist", msg);
      return Err(crate::Error::PathUtilError(msg));
    }
  }

  Ok(std::fs::copy(from, to)?)
}

/// Copies the directory with the given options.
#[allow(dead_code)]
pub fn copy<P, Q>(from: P, to: Q, options: &Options) -> crate::Result<u64>
where
  P: AsRef<Path>,
  Q: AsRef<Path>,
{
  let from = from.as_ref();
  if !from.exists() {
    if let Some(msg) = from.to_str() {
      let msg = format!("Path \"{}\" does not exist or you don't have access!", msg);
      return Err(crate::Error::PathUtilError(msg));
    }
    return Err(crate::Error::PathUtilError(
      "Path does not exist or you don't have access".to_owned(),
    ));
  }
  if !from.is_dir() {
    if let Some(msg) = from.to_str() {
      let msg = format!("Path \"{}\" is not a directory!", msg);
      return Err(crate::Error::PathUtilError(msg));
    }
    return Err(crate::Error::PathUtilError(
      "Path is not a directory".to_owned(),
    ));
  }

  let dir_name = if let Some(val) = from.components().last() {
    val.as_os_str()
  } else {
    return Err(crate::Error::PathUtilError(
      "Invalid Folder form".to_owned(),
    ));
  };
  let mut to: PathBuf = to.as_ref().to_path_buf();
  if !options.content_only && (!options.copy_files || to.exists()) {
    to.push(dir_name);
  }

  let mut read_options = DirOpts::default();
  if options.depth > 0 {
    read_options.depth = options.depth;
  }

  let dir_content = get_dir_info(from, &read_options)?;
  for directory in dir_content.directories {
    let tmp_to = Path::new(&directory).strip_prefix(from)?;
    let dir = to.join(tmp_to);
    if !dir.exists() {
      if options.copy_files {
        create_all(dir, false)?;
      } else {
        create(dir, false)?;
      }
    }
  }
  let mut result: u64 = 0;
  for file in dir_content.files {
    let to = to.to_path_buf();
    let tp = Path::new(&file).strip_prefix(from)?;
    let path = to.join(tp);

    let file_options = FileOpts {
      overwrite: options.overwrite,
      skip: options.skip,
      buffer_size: options.buffer_size,
    };
    let mut result_copy: crate::Result<u64>;
    let mut work = true;

    while work {
      #[allow(clippy::needless_borrow)]
      {
        result_copy = copy_file(&file, &path, &file_options);
      }
      match result_copy {
        Ok(val) => {
          result += val;
          work = false;
        }
        Err(err) => {
          let err_msg = err.to_string();
          return Err(crate::Error::PathUtilError(err_msg));
        }
      }
    }
  }
  Ok(result)
}

/// Gets the DirInfo from the directory path with the given options.
pub fn get_dir_info<P>(path: P, options: &DirOpts) -> crate::Result<DirInfo>
where
  P: AsRef<Path>,
{
  let depth = if options.depth == 0 {
    0
  } else {
    options.depth + 1
  };

  _get_dir_info(path, depth)
}

/// Gets the DirInfo from the directory with the given depth.
fn _get_dir_info<P>(path: P, mut depth: u64) -> crate::Result<DirInfo>
where
  P: AsRef<Path>,
{
  let mut directories = Vec::new();
  let mut files = Vec::new();
  let mut size = 0;
  let item = path.as_ref().to_str();
  if item.is_none() {
    return Err(crate::Error::PathUtilError("Invalid Path".to_owned()));
  }
  let item = item.expect("Item had no data").to_string();

  if path.as_ref().is_dir() {
    directories.push(item);
    if depth == 0 || depth > 1 {
      if depth > 1 {
        depth -= 1;
      }
      for entry in read_dir(&path)? {
        let _path = entry?.path();

        match _get_dir_info(_path, depth) {
          Ok(items) => {
            let mut _files = items.files;
            let mut _directories = items.directories;
            size += items.size;
            files.append(&mut _files);
            directories.append(&mut _directories);
          }
          Err(err) => return Err(err),
        }
      }
    }
  } else {
    size = path.as_ref().metadata()?.len();
    files.push(item);
  }
  Ok(DirInfo {
    size,
    files,
    directories,
  })
}