os: support dotfiles := os.walk_ext('.', '', hidden: true) (#24617)

This commit is contained in:
Denise 2025-06-01 16:10:04 +02:00 committed by GitHub
parent aaf3d3315d
commit ea25988dac
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 18 additions and 5 deletions

View File

@ -726,27 +726,33 @@ fn normalize_path_in_builder(mut sb strings.Builder) {
}
}
@[params]
pub struct WalkParams {
pub:
hidden bool
}
// walk_ext returns a recursive list of all files in `path` ending with `ext`.
// For listing only one level deep, see: `os.ls`
pub fn walk_ext(path string, ext string) []string {
pub fn walk_ext(path string, ext string, opts WalkParams) []string {
mut res := []string{}
impl_walk_ext(path, ext, mut res)
impl_walk_ext(path, ext, mut res, opts)
return res
}
fn impl_walk_ext(path string, ext string, mut out []string) {
fn impl_walk_ext(path string, ext string, mut out []string, opts WalkParams) {
if !is_dir(path) {
return
}
mut files := ls(path) or { return }
separator := if path.ends_with(path_separator) { '' } else { path_separator }
for file in files {
if file.starts_with('.') {
if !opts.hidden && file.starts_with('.') {
continue
}
p := path + separator + file
if is_dir(p) && !is_link(p) {
impl_walk_ext(p, ext, mut out)
impl_walk_ext(p, ext, mut out, opts)
} else if file.ends_with(ext) {
out << p
}

View File

@ -225,6 +225,7 @@ fn create_tree() ! {
os.mkdir_all('myfolder/a1/a2/a3', mode: 0o700)!
f3 := os.real_path('myfolder/f1/f2/f3')
assert os.is_dir(f3)
create_file('myfolder/f1/f2/f3/.hfile1')!
create_file('myfolder/f1/f2/f3/a.txt')!
create_file('myfolder/f1/f2/f3/b.txt')!
create_file('myfolder/f1/f2/f3/c.txt')!
@ -235,6 +236,7 @@ fn create_tree() ! {
create_file('myfolder/a1/a2/a3/y.txt')!
create_file('myfolder/a1/a2/a3/z.txt')!
create_file('myfolder/a1/1.txt')!
create_file('myfolder/a1/.hfile2')!
create_file('myfolder/xyz.ini')!
}
@ -274,6 +276,11 @@ fn test_walk_ext() {
]
mut mds := normalise_paths(os.walk_ext('myfolder', '.md'))
assert mds == ['myfolder/another.md', 'myfolder/f1/f2/f3/d.md']
all_with_hidden := os.walk_ext('.', '', hidden: true)
assert all_with_hidden.len > all.len
hidden := normalise_paths(all_with_hidden.filter(it !in all))
assert hidden == ['./myfolder/a1/.hfile2', './myfolder/f1/f2/f3/.hfile1']
}
fn test_walk_with_context() {