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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
use log::*;
// use rayon::prelude::*;
use std::fs::copy;
use std::io::{Error, ErrorKind};
use std::path::{Path, PathBuf};
use std::time::SystemTime;
use walkdir::WalkDir;
// use jwalk::WalkDir as ParWalk;

#[cfg(test)]
mod tests;

#[derive(Debug, Clone)]
/// Recursively copy a directory from a to b.
/// ```
/// use dircpy::*;
///
/// // Most basic example:
/// copy_dir("src", "dest");
///
/// // Simple builder example:
///CopyBuilder::new("src", "dest")
///.run()
///.unwrap();
///
/// // Copy recursively, only including certain files:
///CopyBuilder::new("src", "dest")
///.overwrite_if_newer(true)
///.overwrite_if_size_differs(true)
///.with_include_filter(".txt")
///.with_include_filter(".csv")
///.run()
///.unwrap();
/// ```

pub struct CopyBuilder {
    /// The source directory
    pub source: PathBuf,
    /// the destination directory
    pub destination: PathBuf,
    overwrite_all: bool,
    overwrite_if_newer: bool,
    overwrite_if_size_differs: bool,
    exclude_filters: Vec<String>,
    include_filters: Vec<String>,
}

/// Determine if the modification date of file_a is newer than that of file_b
fn is_file_newer(file_a: &Path, file_b: &Path) -> bool {
    match (file_a.metadata(), file_b.metadata()) {
        (Ok(meta_a), Ok(meta_b)) => {
            meta_a.modified().unwrap_or_else(|_| SystemTime::now())
                > meta_b.modified().unwrap_or(SystemTime::UNIX_EPOCH)
        }
        _ => false,
    }
}

/// Determine if file_a and file_b's size differs.
fn is_filesize_different(file_a: &Path, file_b: &Path) -> bool {
    match (file_a.metadata(), file_b.metadata()) {
        (Ok(meta_a), Ok(meta_b)) => meta_a.len() != meta_b.len(),
        _ => false,
    }
}

fn copy_file(source: &Path, options: CopyBuilder) -> Result<(), std::io::Error> {
    let abs_source = options.source.canonicalize()?;
    let abs_dest = options.destination.canonicalize()?;

    let rel_dest = source
        .strip_prefix(&abs_source)
        .map_err(|e| Error::new(ErrorKind::Other, format!("Could not strip prefix: {:?}", e)))?;
    let dest_entry = abs_dest.join(rel_dest);

    if source.is_file() {
        // the source exists

        // Early out if target is present and overwrite is off
        if !options.overwrite_all
            && dest_entry.is_file()
            && !options.overwrite_if_newer
            && !options.overwrite_if_size_differs
        {
            return Ok(());
        }

        for f in &options.exclude_filters {
            if source.to_string_lossy().contains(f) {
                return Ok(());
            }
        }

        for f in &options.include_filters {
            if !source.to_string_lossy().contains(f) {
                return Ok(());
            }
        }

        // File is not present: copy it
        if !dest_entry.is_file() {
            debug!(
                "Dest not present: CP {} DST {}",
                source.display(),
                dest_entry.display()
            );
            copy(source, dest_entry)?;
            return Ok(());
        }

        // File newer?
        if options.overwrite_if_newer {
            if is_file_newer(source, &dest_entry) {
                debug!(
                    "Source newer: CP {} DST {}",
                    source.display(),
                    dest_entry.display()
                );
                copy(source, &dest_entry)?;
            }
            return Ok(());
        }

        // Different size?
        if options.overwrite_if_size_differs {
            if is_filesize_different(source, &dest_entry) {
                debug!(
                    "Source differs: CP {} DST {}",
                    source.display(),
                    dest_entry.display()
                );
                copy(source, &dest_entry)?;
            }
            return Ok(());
        }

        // The regular copy operation
        debug!("CP {} DST {}", source.display(), dest_entry.display());
        copy(source, dest_entry)?;
    } else if source.is_dir() && !dest_entry.is_dir() {
        debug!("MKDIR {}", source.display());
        std::fs::create_dir_all(dest_entry)?;
    }

    Ok(())
}

impl CopyBuilder {
    /// Construct a new CopyBuilder with `source` and `dest`.
    pub fn new<P: AsRef<Path>, Q: AsRef<Path>>(source: P, dest: Q) -> CopyBuilder {
        CopyBuilder {
            source: source.as_ref().to_path_buf(),
            destination: dest.as_ref().to_path_buf(),
            overwrite_all: false,
            overwrite_if_newer: false,
            overwrite_if_size_differs: false,
            exclude_filters: vec![],
            include_filters: vec![],
        }
    }

    /// Overwrite target files (off by default)
    pub fn overwrite(self, overwrite: bool) -> CopyBuilder {
        CopyBuilder {
            overwrite_all: overwrite,
            ..self
        }
    }

    /// Overwrite if the source is newer (off by default)
    pub fn overwrite_if_newer(self, overwrite_only_newer: bool) -> CopyBuilder {
        CopyBuilder {
            overwrite_if_newer: overwrite_only_newer,
            ..self
        }
    }

    /// Overwrite if size between source and dest differs (off by default)
    pub fn overwrite_if_size_differs(self, overwrite_if_size_differs: bool) -> CopyBuilder {
        CopyBuilder {
            overwrite_if_size_differs,
            ..self
        }
    }

    /// Do not copy files that contain this string
    pub fn with_exclude_filter(self, f: &str) -> CopyBuilder {
        let mut filters = self.exclude_filters.clone();
        filters.push(f.to_owned());
        CopyBuilder {
            exclude_filters: filters,
            ..self
        }
    }

    /// Only copy files that contain this string.
    pub fn with_include_filter(self, f: &str) -> CopyBuilder {
        let mut filters = self.exclude_filters.clone();
        filters.push(f.to_owned());
        CopyBuilder {
            include_filters: filters,
            ..self
        }
    }
    /// Execute the copy operation
    pub fn run(&self) -> Result<(), std::io::Error> {
        if !self.destination.is_dir() {
            debug!("MKDIR {:?}", &self.destination);
            std::fs::create_dir_all(&self.destination)?;
        }
        let abs_source = self.source.canonicalize()?;
        let abs_dest = self.destination.canonicalize()?;
        debug!(
            "Building copy operation: SRC {} DST {}",
            abs_source.display(),
            abs_dest.display()
        );

        for entry in WalkDir::new(&abs_source).into_iter().filter_map(|e| e.ok()) {
            let rel_dest = entry.path().strip_prefix(&abs_source).map_err(|e| {
                Error::new(ErrorKind::Other, format!("Could not strip prefix: {:?}", e))
            })?;
            let dest_entry = abs_dest.join(rel_dest);

            if entry.path().is_file() {
                // the source exists

                // Early out if target is present and overwrite is off
                if !self.overwrite_all
                    && dest_entry.is_file()
                    && !self.overwrite_if_newer
                    && !self.overwrite_if_size_differs
                {
                    continue;
                }

                for f in &self.exclude_filters {
                    if entry.path().to_string_lossy().contains(f) {
                        continue;
                    }
                }

                for f in &self.include_filters {
                    if !entry.path().to_string_lossy().contains(f) {
                        continue;
                    }
                }

                // File is not present: copy it
                if !dest_entry.is_file() {
                    debug!(
                        "Dest not present: CP {} DST {}",
                        entry.path().display(),
                        dest_entry.display()
                    );
                    copy(entry.path(), dest_entry)?;
                    continue;
                }

                // File newer?
                if self.overwrite_if_newer {
                    if is_file_newer(entry.path(), &dest_entry) {
                        debug!(
                            "Source newer: CP {} DST {}",
                            entry.path().display(),
                            dest_entry.display()
                        );
                        copy(entry.path(), &dest_entry)?;
                    }
                    continue;
                }

                // Different size?
                if self.overwrite_if_size_differs {
                    if is_filesize_different(entry.path(), &dest_entry) {
                        debug!(
                            "Source differs: CP {} DST {}",
                            entry.path().display(),
                            dest_entry.display()
                        );
                        copy(entry.path(), &dest_entry)?;
                    }
                    continue;
                }

                // The regular copy operation
                debug!("CP {} DST {}", entry.path().display(), dest_entry.display());
                copy(entry.path(), dest_entry)?;
            } else if entry.path().is_dir() && !dest_entry.is_dir() {
                debug!("MKDIR {}", entry.path().display());
                std::fs::create_dir_all(dest_entry)?;
            }
        }

        Ok(())
    }

    /// Execute the copy operation
    pub fn run_par(&self) -> Result<(), std::io::Error> {
        if !self.destination.is_dir() {
            debug!("MKDIR {:?}", &self.destination);
            std::fs::create_dir_all(&self.destination)?;
        }
        let abs_source = self.source.canonicalize()?;
        let abs_dest = self.destination.canonicalize()?;
        debug!(
            "Building copy operation: SRC {} DST {}",
            abs_source.display(),
            abs_dest.display()
        );
        for entry in WalkDir::new(&abs_source).into_iter().filter_map(|e| e.ok()) {
            copy_file(&entry.path(), self.clone());
        }

        // WalkDir::new(&abs_source)
        //     .into_iter()
        //     .filter_map(|e| e.ok())
        //     .map(|p| p.path().to_path_buf())
        //     .collect::<Vec<PathBuf>>()
        //     .par_iter()
        //     .for_each(|p| {
        //         copy_file(&p, self.clone());
        //     })
        //     ;

        // for entry in ParWalk::new(&abs_source) {
        //     // println!("{}", entry?.path().display());
        //     copy_file(&entry?.path(), self.clone());

        //   }


        Ok(())
    }
}

/// Copy a directory from `source` to `dest`, creating `dest`, with all options.
pub fn copy_dir_advanced<P: AsRef<Path>, Q: AsRef<Path>>(
    source: P,
    dest: Q,
    overwrite_all: bool,
    overwrite_if_newer: bool,
    overwrite_if_size_differs: bool,
    exclude_filters: Vec<String>,
    include_filters: Vec<String>,
) -> Result<(), std::io::Error> {
    CopyBuilder {
        source: source.as_ref().to_path_buf(),
        destination: dest.as_ref().to_path_buf(),
        overwrite_all,
        overwrite_if_newer,
        overwrite_if_size_differs,
        exclude_filters,
        include_filters,
    }
    .run()
}

/// Copy a directory from `source` to `dest`, creating `dest`, with minimal options.
pub fn copy_dir<P: AsRef<Path>, Q: AsRef<Path>>(source: P, dest: Q) -> Result<(), std::io::Error> {
    CopyBuilder {
        source: source.as_ref().to_path_buf(),
        destination: dest.as_ref().to_path_buf(),
        overwrite_all: false,
        overwrite_if_newer: false,
        overwrite_if_size_differs: false,
        exclude_filters: vec![],
        include_filters: vec![],
    }
    .run()
}