From 98c016b41d7126c6ed9bfdf1e72263aaf5e0ad56 Mon Sep 17 00:00:00 2001 From: Larpon Date: Thu, 24 Oct 2019 14:17:09 +0200 Subject: [PATCH] os: walk() function --- vlib/os/os.v | 19 +++++++++++++++++++ vlib/os/os_test.v | 21 +++++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/vlib/os/os.v b/vlib/os/os.v index d0200a3708..54ef5d5fcc 100644 --- a/vlib/os/os.v +++ b/vlib/os/os.v @@ -828,6 +828,25 @@ pub fn walk_ext(path, ext string) []string { return res } +// walk recursively traverse the given directory path. +// When a file is encountred it will call the callback function with current file as argument. +pub fn walk(path string, fnc fn(path string)) { + if !os.is_dir(path) { + return + } + mut files := os.ls(path) or { panic(err) } + for file in files { + p := path + os.path_separator + file + if os.is_dir(p) { + walk(p, fnc) + } + else if os.file_exists(p) { + fnc(p) + } + } + return +} + pub fn signal(signum int, handler voidptr) { C.signal(signum, handler) } diff --git a/vlib/os/os_test.v b/vlib/os/os_test.v index a0d64c35d1..b551c60e83 100644 --- a/vlib/os/os_test.v +++ b/vlib/os/os_test.v @@ -92,6 +92,27 @@ fn test_dir() { } } +fn walk_callback(file string) { + if file == '.' || file == '..' { + return + } + assert file == 'test_walk'+os.path_separator+'test1' +} + +fn test_walk() { + folder := 'test_walk' + os.mkdir(folder) + + file1 := folder+os.path_separator+'test1' + + os.write_file(file1,'test-1') + + os.walk(folder, walk_callback) + + os.rm(file1) + os.rmdir(folder) +} + //fn test_fork() { // pid := os.fork() // if pid == 0 {