Last active
September 15, 2020 16:59
-
-
Save lukewilson2002/17b631fc6222b9c8b0393ed59b6cfaad to your computer and use it in GitHub Desktop.
Copying files from a directory recursively with Zig...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// 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