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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
use std::path::{Path, PathBuf};
use error::*;
use std::fs::{create_dir, create_dir_all, remove_dir_all, read_dir};

///	Options and flags which can be used to configure how a file will be  copied  or moved.
pub struct CopyOptions {
    /// Sets the option true for overwrite existing files.
    pub overwrite: bool,
    /// Sets the option true for skipe existing files.
    pub skip_exist: bool,
    /// Sets buffer size for copy/move work only with receipt information about process work.
    pub buffer_size: usize,
}

impl CopyOptions {
    /// Initialize struct CopyOptions with default value.
    ///
    /// ```rust,ignore
    /// overwrite: false
    ///
    /// skip_exist: false
    ///
    /// buffer_size: 64000 //64kb
    /// ```
    pub fn new() -> CopyOptions {
        CopyOptions {
            overwrite: false,
            skip_exist: false,
            buffer_size: 64000, //64kb
        }
    }
}

/// A structure which imclude information about directory
pub struct DirContent {
    /// Directory size.
    pub dir_size: u64,
    /// List all files directory and sub directories.
    pub files: Vec<String>,
    /// List all folders and sub folders directory.
    pub directories: Vec<String>,
}

/// A structure which include information about the current status of the copy or move directory.
pub struct TransitProcess {
    /// Copied bytes on this time for folder
    pub copied_bytes: u64,
    /// All the bytes which should to copy or move (dir size).
    pub total_bytes: u64,
    /// Copied bytes on this time for file.
    pub file_bytes_copied: u64,
    /// Size current copied file.
    pub file_total_bytes: u64,
    /// Name current copied file.
    pub file_name: String,
}

impl Clone for TransitProcess {
    fn clone(&self) -> TransitProcess {
        TransitProcess {
            copied_bytes: self.copied_bytes,
            total_bytes: self.total_bytes,
            file_bytes_copied: self.file_bytes_copied,
            file_total_bytes: self.file_total_bytes,
            file_name: self.file_name.clone(),
        }
    }
}

/// Creates a new, empty directory at the provided path.
///
/// This function takes to arguments:
///
/// * `path` - Path to new directory.
///
/// * `erase` - If set true and folder exist, then folder will be erased.
///
/// #Errors
///
/// This function will return an error in the following situations,
/// but is not limited to just these cases:
///
/// * User lacks permissions to create directory at `path`.
///
/// * `path` already exists if `erase` set false.
///
/// #Examples
///
/// ```rust,ignore
/// extern crate fs_extra;
/// use fs_extra::dir::create;
///
/// create("dir", false); // create directory
/// ```
pub fn create<P>(path: P, erase: bool) -> Result<()>
    where P: AsRef<Path>
{
    if erase && path.as_ref().exists() {
        remove(&path)?;
    }
    Ok(create_dir(&path)?)
}

/// Recursively create a directory and all of its parent components if they are missing.
///
/// This function takes to arguments:
///
/// * `path` - Path to new directory.
///
/// * `erase` - If set true and folder exist, then folder will be erased.
///
///#Errors
///
/// This function will return an error in the following situations,
/// but is not limited to just these cases:
///
/// * User lacks permissions to create directory at `path`.
///
/// * `path` already exists if `erase` set false.
///
/// #Examples
///
/// ```rust,ignore
/// extern crate fs_extra;
/// use fs_extra::dir::create_all;
///
/// create_all("/some/dir", false); // create directory some and dir
pub fn create_all<P>(path: P, erase: bool) -> Result<()>
    where P: AsRef<Path>
{
    if erase && path.as_ref().exists() {
        remove(&path)?;
    }
    Ok(create_dir_all(&path)?)
}

/// Copies the directory contents from one place to another using recursive method.
/// This function will also copy the permission bits of the original files to
/// destionation files (not for directories).
///
/// # Errors
///
/// This function will return an error in the following situations, but is not limited to just
/// these cases:
///
/// * This `from` path is not a directory.
/// * This `from` directory does not exist.
/// * Invalid folder name for `from` or `to`.
/// * The current process does not have the permission rights to access `from` or write `to`.
///
/// # Example
/// ```rust,ignore
///
///     extern crate fs_extra;
///     use fs_extra::dir::copy;
///
///     let options = CopyOptions::new(); //Initialize default values for CopyOptions
///
///     // copy source/dir1 to target/dir1
///     copy("source/dir1", "target/dir1", &options)?;
///
/// ```
pub fn copy<P, Q>(from: P, to: Q, options: &CopyOptions) -> 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", msg);
            err!(&msg, ErrorKind::NotFound);
        }
        err!("Path does not exist", ErrorKind::NotFound);
    }

    let mut to: PathBuf = to.as_ref().to_path_buf();
    if !from.is_dir() {
        if let Some(msg) = from.to_str() {
            let msg = format!("Path \"{}\" is not a directory!", msg);
            err!(&msg, ErrorKind::InvalidFolder);
        }
        err!("Path is not a directory!", ErrorKind::InvalidFolder);
    }

    if let Some(dir_name) = from.components().last() {
        to.push(dir_name.as_os_str());
    } else {
        err!("Invalid folder from", ErrorKind::InvalidFolder);
    }

    if !to.exists() {
        create(&to, false)?;
    }

    let mut result: u64 = 0;
    for entry in read_dir(from)? {
        let entry = entry?;
        let path = entry.path();
        if path.is_dir() {
            result += copy(path, to.clone(), &options)?;
        } else {
            let mut to = to.to_path_buf();
            match path.file_name() {
                None => err!("No file name"),
                Some(file_name) => {
                    to.push(file_name);

                    let mut file_options = super::file::CopyOptions::new();
                    file_options.overwrite = options.overwrite;
                    file_options.skip_exist = options.skip_exist;
                    result += super::file::copy(&path, to.as_path().clone(), &file_options)?;

                }
            }
        }
    }

    Ok(result)
}


/// Return DirContent which containt information about directory:
///
/// * Size directory.
/// * List all files source directory(files subdirectories  included too).
/// * List all directory and subdirectories source path.
///
/// # Errors
///
/// This function will return an error in the following situations, but is not limited to just
/// these cases:
///
/// * This `path` directory does not exist.
/// * Invalid `path`.
/// * The current process does not have the permission rights to access `path`.
///
/// # Examples
/// ```rust,ignore
///    extern crate fs_extra;
///    use fs_extra::dir::get_dir_content;
///
///    let dir_content = get_dir_content("dir")?;
///    for directory in dir_content.directories {
///        println!("{}", directory); // print directory path
///    }
/// ```
///
pub fn get_dir_content<P>(path: P) -> Result<DirContent>
    where P: AsRef<Path>
{
    let mut directories = Vec::new();
    let mut files = Vec::new();
    let mut dir_size = 0;
    let item = path.as_ref().to_str();
    if !item.is_some() {
        err!("Invalid path", ErrorKind::InvalidPath);
    }
    let item = item.unwrap().to_string();

    if path.as_ref().is_dir() {
        directories.push(item);
        for entry in read_dir(&path)? {
            let _path = entry?.path();

            match get_dir_content(_path) {
                Ok(items) => {
                    let mut _files = items.files;
                    let mut _dirrectories = items.directories;
                    dir_size += items.dir_size;
                    files.append(&mut _files);
                    directories.append(&mut _dirrectories);
                }
                Err(err) => return Err(err),
            }
        }

    } else {
        dir_size = path.as_ref().metadata()?.len();
        files.push(item);
    }
    Ok(DirContent {
        dir_size: dir_size,
        files: files,
        directories: directories,
    })
}

/// Returns the size of the file or directory
///
/// # Errors
///
/// This function will return an error in the following situations, but is not limited to just
/// these cases:
///
/// * This `path` directory does not exist.
/// * Invalid `path`.
/// * The current process does not have the permission rights to access `path`.
///
/// # Examples
/// ```rust,ignore
///    extern crate fs_extra;
///    use fs_extra::dir::get_size;
///
///    let folder_size = get_size("dir")?;
///    println!("{}", folder_size); // print directory sile in bytes
/// ```
pub fn get_size<P>(path: P) -> Result<u64>
    where P: AsRef<Path>
{
    let mut result = 0;

    if path.as_ref().is_dir() {
        for entry in read_dir(&path)? {
            let _path = entry?.path();

            match get_dir_content(_path) {
                Ok(items) => {
                    result += items.dir_size;
                }
                Err(err) => return Err(err),
            }
        }

    } else {
        result = path.as_ref().metadata()?.len();
    }
    Ok(result)
}

/// Copies the directory contents from one place to another using recursive method,
/// with recept information about process. This function will also copy the
/// permission bits of the original files to destionation files (not for directories).
///
/// # Errors
///
/// This function will return an error in the following situations, but is not limited to just
/// these cases:
///
/// * This `from` path is not a directory.
/// * This `from` directory does not exist.
/// * Invalid folder name for `from` or `to`.
/// * The current process does not have the permission rights to access `from` or write `to`.
///
/// # Example
/// ```rust,ignore
///     extern crate fs_extra;
///     use fs_extra::dir::copy;
///
///     let options = CopyOptions::new(); //Initialize default values for CopyOptions
///     let handle = |process_info: TransitProcess|  println!("{}", process_info.total_bytes);
///
///     // copy source/dir1 to target/dir1
///     copy_with_progress("source/dir1", "target/dir1", &options, handle)?;
///
/// ```
pub fn copy_with_progress<P, Q, F>(from: P,
                                   to: Q,
                                   options: &CopyOptions,
                                   mut progress_handler: F)
                                   -> Result<u64>
    where P: AsRef<Path>,
          Q: AsRef<Path>,
          F: FnMut(TransitProcess) -> ()
{

    let from = from.as_ref();

    if !from.exists() {
        if let Some(msg) = from.to_str() {
            let msg = format!("Path \"{}\" does not exist", msg);
            err!(&msg, ErrorKind::NotFound);
        }
        err!("Path does not exist", ErrorKind::NotFound);
    }

    let mut to: PathBuf = to.as_ref().to_path_buf();
    if !from.is_dir() {
        if let Some(msg) = from.to_str() {
            let msg = format!("Path \"{}\" is not a directory!", msg);
            err!(&msg, ErrorKind::InvalidFolder);
        }
        err!("Path is not a directory!", ErrorKind::InvalidFolder);
    }

    if let Some(dir_name) = from.components().last() {
        to.push(dir_name.as_os_str());
    } else {
        err!("Invalid folder from", ErrorKind::InvalidFolder);
    }

    let dir_content = get_dir_content(from)?;
    for directory in dir_content.directories {
        let tmp_to = Path::new(&directory).strip_prefix(from)?;
        let dir = to.join(&tmp_to);
        if !dir.exists() {
            create(dir, false)?;
        }

    }

    let mut result: u64 = 0;
    let mut info_process = TransitProcess {
        copied_bytes: 0,
        total_bytes: dir_content.dir_size,
        file_bytes_copied: 0,
        file_total_bytes: 0,
        file_name: String::new(),
    };

    for file in dir_content.files {
        let mut to = to.to_path_buf();
        let tp = Path::new(&file).strip_prefix(from)?;
        let path = to.join(&tp);

        let file_name = path.file_name();
        if !file_name.is_some() {
            err!("No file name");
        }
        let file_name = file_name.unwrap();
        to.push(file_name);

        let file_options = super::file::CopyOptions {
            overwrite: options.overwrite,
            skip_exist: options.skip_exist,
            buffer_size: options.buffer_size,
        };

        if let Some(file_name) = file_name.to_str() {
            info_process.file_name = file_name.to_string();
        } else {
            err!("Invalid file name", ErrorKind::InvalidFileName);
        }

        info_process.file_bytes_copied = 0;
        info_process.file_total_bytes = Path::new(&file).metadata()?.len();

        let copied_bytes = result;
        let _progress_hadler = |info: super::file::TransitProcess| {
            info_process.copied_bytes = copied_bytes + info.copied_bytes;
            info_process.file_bytes_copied = info.copied_bytes;
            progress_handler(info_process.clone());

        };

        result += super::file::copy_with_progress(&file, &path, &file_options, _progress_hadler)?;

    }

    Ok(result)
}


/// Moves the directory contents from one place to another.
/// This function will also copy the permission bits of the original files to
/// destionation files (not for directories).
///
/// # Errors
///
/// This function will return an error in the following situations, but is not limited to just
/// these cases:
///
/// * This `from` path is not a directory.
/// * This `from` directory does not exist.
/// * Invalid folder name for `from` or `to`.
/// * The current process does not have the permission rights to access `from` or write `to`.
///
/// # Example
/// ```rust,ignore
///
///     extern crate fs_extra;
///     use fs_extra::dir::move_dir;
///
///     let options = CopyOptions::new(); //Initialize default values for CopyOptions
///
///     // move source/dir1 to target/dir1
///     move_dir("source/dir1", "target/dir1", &options)?;
///
/// ```
pub fn move_dir<P, Q>(from: P, to: Q, options: &CopyOptions) -> 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", msg);
            err!(&msg, ErrorKind::NotFound);
        }
        err!("Path does not exist", ErrorKind::NotFound);
    }

    let mut is_remove = true;
    if options.skip_exist && to.as_ref().exists() && !options.overwrite {
        is_remove = false;
    }

    let mut to: PathBuf = to.as_ref().to_path_buf();
    if !from.is_dir() {
        if let Some(msg) = from.to_str() {
            let msg = format!("Path \"{}\" is not a directory!", msg);
            err!(&msg, ErrorKind::InvalidFolder);
        }
        err!("Path is not a directory!", ErrorKind::InvalidFolder);
    }

    if let Some(dir_name) = from.components().last() {
        to.push(dir_name.as_os_str());
    } else {
        err!("Invalid folder from", ErrorKind::InvalidFolder);
    }

    if !to.exists() {
        create(&to, false)?;
    }

    let mut result: u64 = 0;
    for entry in read_dir(from)? {
        let entry = entry?;
        let path = entry.path();
        if path.is_dir() {
            result += move_dir(path, to.clone(), &options)?;
        } else {
            let mut to = to.to_path_buf();
            match path.file_name() {
                None => err!("No file name"),
                Some(file_name) => {
                    to.push(file_name);

                    let mut file_options = super::file::CopyOptions::new();
                    file_options.overwrite = options.overwrite;
                    file_options.skip_exist = options.skip_exist;
                    result += super::file::move_file(&path, to.as_path().clone(), &file_options)?;

                }
            }
        }
    }

    if is_remove {
        remove(from)?;
    }

    Ok(result)

}

/// Moves the directory contents from one place to another with recept information about process.
/// This function will also copy the permission bits of the original files to
/// destionation files (not for directories).
///
/// # Errors
///
/// This function will return an error in the following situations, but is not limited to just
/// these cases:
///
/// * This `from` path is not a directory.
/// * This `from` directory does not exist.
/// * Invalid folder name for `from` or `to`.
/// * The current process does not have the permission rights to access `from` or write `to`.
///
/// # Example
/// ```rust,ignore
///
///     extern crate fs_extra;
///     use fs_extra::dir::move_dir_with_progress;
///
///     let options = CopyOptions::new(); //Initialize default values for CopyOptions
///     let handle = |process_info: TransitProcess|  println!("{}", process_info.total_bytes);
///
///     // move source/dir1 to target/dir1
///     move_dir_with_progress("source/dir1", "target/dir1", &options, handle)?;
///
/// ```
pub fn move_dir_with_progress<P, Q, F>(from: P,
                                       to: Q,
                                       options: &CopyOptions,
                                       mut progress_handler: F)
                                       -> Result<u64>
    where P: AsRef<Path>,
          Q: AsRef<Path>,
          F: FnMut(TransitProcess) -> ()
{
    let mut is_remove = true;
    if options.skip_exist && to.as_ref().exists() && !options.overwrite {
        is_remove = false;
    }
    let from = from.as_ref();

    if !from.exists() {
        if let Some(msg) = from.to_str() {
            let msg = format!("Path \"{}\" does not exist", msg);
            err!(&msg, ErrorKind::NotFound);
        }
        err!("Path does not exist", ErrorKind::NotFound);
    }

    let mut to: PathBuf = to.as_ref().to_path_buf();
    if !from.is_dir() {
        if let Some(msg) = from.to_str() {
            let msg = format!("Path \"{}\" is not a directory!", msg);
            err!(&msg, ErrorKind::InvalidFolder);
        }
        err!("Path is not a directory!", ErrorKind::InvalidFolder);
    }

    if let Some(dir_name) = from.components().last() {
        to.push(dir_name.as_os_str());
    } else {
        err!("Invalid folder from", ErrorKind::InvalidFolder);
    }

    let dir_content = get_dir_content(from)?;
    for directory in dir_content.directories {
        let tmp_to = Path::new(&directory).strip_prefix(from)?;
        let dir = to.join(&tmp_to);
        if !dir.exists() {
            create(dir, false)?;
        }

    }

    let mut result: u64 = 0;
    let mut info_process = TransitProcess {
        copied_bytes: 0,
        total_bytes: dir_content.dir_size,
        file_bytes_copied: 0,
        file_total_bytes: 0,
        file_name: String::new(),
    };

    for file in dir_content.files {
        let mut to = to.to_path_buf();
        let tp = Path::new(&file).strip_prefix(from)?;
        let path = to.join(&tp);

        let file_name = path.file_name();
        if !file_name.is_some() {
            err!("No file name");
        }
        let file_name = file_name.unwrap();
        to.push(file_name);

        let file_options = super::file::CopyOptions {
            overwrite: options.overwrite,
            skip_exist: options.skip_exist,
            buffer_size: options.buffer_size,
        };

        if let Some(file_name) = file_name.to_str() {
            info_process.file_name = file_name.to_string();
        } else {
            err!("Invalid file name", ErrorKind::InvalidFileName);
        }

        info_process.file_bytes_copied = 0;
        info_process.file_total_bytes = Path::new(&file).metadata()?.len();

        let copied_bytes = result;
        let hadler = |info: super::file::TransitProcess| {
            info_process.copied_bytes = copied_bytes + info.copied_bytes;
            info_process.file_bytes_copied = info.copied_bytes;
            progress_handler(info_process.clone());

        };

        result += super::file::move_file_with_progress(&file, &path, &file_options, hadler)?;

    }
    if is_remove {
        remove(from)?;
    }

    Ok(result)
}


/// Removes directory.
///
/// # Example
/// ```rust,ignore
///
///     extern crate fs_extra;
///     use fs_extra::dir::remove;
///
///     remove("source/dir1"); // remove dir1
/// ```
pub fn remove<P: AsRef<Path>>(path: P) -> Result<()> {
    if path.as_ref().exists() {
        Ok(remove_dir_all(path)?)
    } else {
        Ok(())
    }
}