diff --git a/stdlib/rglob.sh b/stdlib/rglob.sh new file mode 100644 index 00000000..2eab71bb --- /dev/null +++ b/stdlib/rglob.sh @@ -0,0 +1,29 @@ +fn dir_glob(dir, pattern, results) { + files <= find $dir -maxdepth 1 -mindepth 1 + files <= split($files, "\n") + + for f in $files { + _, status <= test -d $f + + if $status == "0" { + dir_pattern <= format("%s/%s", $f, $pattern) + current_results <= glob($dir_pattern) + + for r in $current_results { + results <= append($results, $r) + } + + results <= dir_glob($f, $pattern, $results) + } + } + + return $results +} + +fn rglob(pattern) { + working_dir <= pwd + result <= glob($working_dir+"/"+$pattern) + result <= dir_glob($working_dir, $pattern, $result) + + return $result +} diff --git a/stdlib/rglob_test.sh b/stdlib/rglob_test.sh new file mode 100755 index 00000000..235e9067 --- /dev/null +++ b/stdlib/rglob_test.sh @@ -0,0 +1,85 @@ +#!/usr/bin/env nash + +import rglob + +fn setup() { + temp_dir <= mktemp -d + + test_txt = $temp_dir+"/test.txt" + test_sh = $temp_dir+"/test.sh" + + touch $test_txt + touch $test_sh + + hello_dir = $temp_dir+"/hello" + world_dir = $temp_dir+"/world" + + mkdir $hello_dir + mkdir $world_dir + + honda_txt = $hello_dir+"/honda.txt" + honda_sh = $hello_dir+"/honda.sh" + civic_txt = $world_dir+"/civic.txt" + civic_sh = $world_dir+"/civic.sh" + + touch $honda_txt + touch $honda_sh + touch $civic_txt + touch $civic_sh + + return $temp_dir +} + +fn assert_success(expected, got) { + if len($got) != len($expected) { + print("expected length to be '%s' but got '%s'\n", len($expected), len($got)) + exit("1") + } + + found = "0" + + for x in $expected { + for y in $got { + if $x == $y { + found <= echo $found+" + 1" | bc + } + } + } + + if $found != len($expected) { + print("expected [%s] got [%s]\n", $expected, $got) + exit("1") + } +} + +fn test_rglob_txt(dir) { + expected_files = ( + $dir+"/test.txt" + $dir+"/hello/honda.txt" + $dir+"/world/civic.txt" + ) + + got_files <= rglob("*.txt") + + assert_success($expected_files, $got_files) +} + +fn test_rglob_sh(dir) { + expected_files = ( + $dir+"/test.sh" + $dir+"/hello/honda.sh" + $dir+"/world/civic.sh" + ) + + got_files <= rglob("*.sh") + + assert_success($expected_files, $got_files) +} + +old_dir <= pwd +temp_dir <= setup() + +chdir($temp_dir) +test_rglob_txt($temp_dir) +test_rglob_sh($temp_dir) +chdir($old_dir)