Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy a folder recursively in Rust?

Tags:

rust

From what I see in the documentation, there is no out-of-the-box solution.

like image 862
Bogdan Nechyporenko Avatar asked Nov 16 '14 15:11

Bogdan Nechyporenko


3 Answers

You can use the fs_extra crate that I have written. This crate expands on the standard library std::fs and std::io modules.

It can (among other things):

  • Copy files (optionally with information about the progress).
  • Copy directories recursively (optionally with information about the progress).
like image 64
webdesus Avatar answered Sep 30 '22 13:09

webdesus


use std::fs;
use std::path::{Path, PathBuf};

pub fn copy<U: AsRef<Path>, V: AsRef<Path>>(from: U, to: V) -> Result<(), std::io::Error> {
    let mut stack = Vec::new();
    stack.push(PathBuf::from(from.as_ref()));

    let output_root = PathBuf::from(to.as_ref());
    let input_root = PathBuf::from(from.as_ref()).components().count();

    while let Some(working_path) = stack.pop() {
        println!("process: {:?}", &working_path);

        // Generate a relative path
        let src: PathBuf = working_path.components().skip(input_root).collect();

        // Create a destination if missing
        let dest = if src.components().count() == 0 {
            output_root.clone()
        } else {
            output_root.join(&src)
        };
        if fs::metadata(&dest).is_err() {
            println!(" mkdir: {:?}", dest);
            fs::create_dir_all(&dest)?;
        }

        for entry in fs::read_dir(working_path)? {
            let entry = entry?;
            let path = entry.path();
            if path.is_dir() {
                stack.push(path);
            } else {
                match path.file_name() {
                    Some(filename) => {
                        let dest_path = dest.join(filename);
                        println!("  copy: {:?} -> {:?}", &path, &dest_path);
                        fs::copy(&path, &dest_path)?;
                    }
                    None => {
                        println!("failed: {:?}", path);
                    }
                }
            }
        }
    }

    Ok(())
}

Other answers don't actually show how to do it, they just say how you might do it; here is a concrete example.

As discussed in the other answers, the relevant APIs are fs::create_dir_all, fs::copy and fs::metadata.

There is no 'all in one' standard library API for this.

like image 23
Doug Avatar answered Sep 30 '22 13:09

Doug


Simplest code that I've found works:

use std::{io, fs};

fn copy_dir_all(src: impl AsRef<Path>, dst: impl AsRef<Path>) -> io::Result<()> {
    fs::create_dir_all(&dst)?;
    for entry in fs::read_dir(src)? {
        let entry = entry?;
        let ty = entry.file_type()?;
        if ty.is_dir() {
            copy_dir_all(entry.path(), dst.as_ref().join(entry.file_name()))?;
        } else {
            fs::copy(entry.path(), dst.as_ref().join(entry.file_name()))?;
        }
    }
    Ok(())
}
like image 6
Simon Buchan Avatar answered Sep 30 '22 12:09

Simon Buchan