Skip to content

Instantly share code, notes, and snippets.

@lukewilson2002
Last active September 15, 2020 16:59
Show Gist options
  • Save lukewilson2002/17b631fc6222b9c8b0393ed59b6cfaad to your computer and use it in GitHub Desktop.
Save lukewilson2002/17b631fc6222b9c8b0393ed59b6cfaad to your computer and use it in GitHub Desktop.
Copying files from a directory recursively with Zig...
/// Copy a source directory's files and its subdirectories' files to a destination. Will only copy directories and files.
fn copyRecursiveDir(src_dir: fs.Dir, dest_dir: fs.Dir, src_path: []const u8, dest_path: []const u8) anyerror!void {
var iter = src_dir.iterate();
while (true) {
const entry = try iter.next();
if (entry == null) {
break;
} else {
switch (entry.?.kind) {
.File => try src_dir.copyFile(entry.?.name, dest_dir, entry.?.name, fs.CopyFileOptions{}),
.Directory => {
// Create destination directory
dest_dir.makeDir(entry.?.name) catch |e| {
switch (e) {
std.os.MakeDirError.PathAlreadyExists => {},
else => return e,
}
};
// Open destination directory
var dest_entry_dir = try dest_dir.openDir(entry.?.name, fs.Dir.OpenDirOptions{ .access_sub_paths = true, .iterate = true, .no_follow = true });
defer dest_entry_dir.close();
// Open directory we're copying files from
var src_entry_dir = try src_dir.openDir(entry.?.name, fs.Dir.OpenDirOptions{ .access_sub_paths = true, .iterate = true, .no_follow = true });
defer src_entry_dir.close();
// Begin the recursive descent!
try copyRecursiveDir(src_entry_dir, dest_entry_dir, entry.?.name, entry.?.name);
},
else => {}, // ¯\_(ツ)_/¯ Don't want any of that stuff, anyway
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment