home ~ socials ~ projects ~ rss

Copy A Directory Recursively In Rust Without std::fs::copy

May 2024

See the notes below

```cargo
[dependencies]
walkdir = "2.5.0"
```

use std::fs;
use std::path::PathBuf;
use walkdir::WalkDir;

fn main() {
  let source = PathBuf::from("target_source");
  let dest = PathBuf::from("target_dest");
  match copy_dir(&source, &dest) {
    Ok(_) => { println!("copied the directory"); }
    Err(e) =>  { println!("{:?}", e); }
  }
}

pub fn copy_dir(source_dir: &PathBuf, dest_dir: &PathBuf) -> Result<(), std::io::Error> {
  for entry in WalkDir::new(source_dir) {
    let source_path = entry?.into_path();
    let dest_path = dest_dir.join(source_path.strip_prefix(source_dir).unwrap());
    if source_path.is_dir() {
      fs::create_dir_all(dest_path)?;
    }
    else {
      let data = std::fs::read(source_path)?;
      std::fs::write(dest_path, &data)?;
    }
  }
  Ok(())
}
Output:
error: unknown start of token: `
 --> _active_nvim_run:1:1
  |
1 | ```cargo
  | ^^^
  |
  = note: character appears 2 more times
help: Unicode character '`' (Grave Accent) looks like ''' (Single Quote), but it is not
  |
1 - ```cargo
1 + '''cargo
  |

error: unknown start of token: `
 --> _active_nvim_run:4:1
  |
4 | ```
  | ^^^
  |
  = note: character appears 2 more times
help: Unicode character '`' (Grave Accent) looks like ''' (Single Quote), but it is not
  |
4 - ```
4 + '''
  |

error: expected one of `!` or `::`, found `[`
 --> _active_nvim_run:2:1
  |
1 | ```cargo
  |         - expected one of `!` or `::`
2 | [dependencies]
  | ^ unexpected token

error: could not compile `_active_nvim_run` (bin "_active_nvim_run") due to 3 previous errors

Notes

  • There's an issue with notify and std::fs::copy where copying a file triggers an event. That means you can't watch and copy files the way you'd expect because they keep triggeing themselves
  • This is very naive (e.g. it doesn't deal with links or have substantial error handling)
end of line
Share link:
https://www.alanwsmith.com/en/2g/gy/cq/3m/?copy-a-directory-recursively-in-rust-without-std-fs-copy