From bd18f50c8a7f1ba3c0fd8e98b0475e6416d197ce Mon Sep 17 00:00:00 2001 From: lorenzo pirro Date: Wed, 6 Nov 2019 21:05:35 +0100 Subject: [PATCH] os: cp_r fn to copy files recursively --- vlib/os/os.v | 35 ++++++++++++++++++++++++++++++++++- vlib/os/os_test.v | 18 ++++++++++++++++++ 2 files changed, 52 insertions(+), 1 deletion(-) diff --git a/vlib/os/os.v b/vlib/os/os.v index 93f13d2adc..6e017dbe10 100644 --- a/vlib/os/os.v +++ b/vlib/os/os.v @@ -151,7 +151,40 @@ pub fn cp(old, new string) ?bool { } } -fn vfopen(path, mode string) voidptr { //*C.FILE { +pub fn cp_r(source_path, dest_path string, overwrite bool) ?bool{ + if !os.file_exists(source_path) { + return error('Source path doesn\'t exist') + } + //single file copy + if !os.is_dir(source_path) { + adjasted_path := if os.is_dir(dest_path) { + filepath.join(dest_path, os.basedir(source_path)) } else { dest_path } + if os.file_exists(adjasted_path) { + if overwrite { os.rm(adjasted_path) } + else { return error('Destination file path already exist') } + } + os.cp(source_path, adjasted_path) or { return error(err) } + return true + } + if !os.is_dir(dest_path) { + return error('Destination path is not a valid directory') + } + files := os.ls(source_path) or { return error(err) } + for file in files { + sp := filepath.join(source_path, file) + dp := filepath.join(dest_path, file) + if os.is_dir(sp) { + os.mkdir(dp) + } + cp_r(sp, dp, overwrite) or { + os.rmdir(dp) + panic(err) + } + } + return true +} + +fn vfopen(path, mode string) *C.FILE { $if windows { return C._wfopen(path.to_wide(), mode.to_wide()) } $else { diff --git a/vlib/os/os_test.v b/vlib/os/os_test.v index 9fa5a11c31..5c8f5c4e99 100644 --- a/vlib/os/os_test.v +++ b/vlib/os/os_test.v @@ -130,6 +130,24 @@ fn test_cp() { } } +fn test_cp_r() { + //fileX -> dir/fileX + os.write_file('ex1.txt', 'wow!') + os.mkdir('ex') + os.cp_r('ex1.txt', 'ex', false) or { panic(err) } + old := os.read_file('ex1.txt') or { panic(err) } + new := os.read_file('ex/ex1.txt') or { panic(err) } + assert old == new + os.mkdir('ex/ex2') + os.write_file('ex2.txt', 'great!') + os.cp_r('ex2.txt', 'ex/ex2', false) or { panic(err) } + old2 := os.read_file('ex2.txt') or { panic(err) } + new2 := os.read_file('ex/ex2/ex2.txt') or { panic(err) } + assert old2 == new2 + //recurring on dir -> local dir + os.cp_r('ex', './', true) or { panic(err) } +} + //fn test_fork() { // pid := os.fork() // if pid == 0 {