Created
February 15, 2017 13:01
-
-
Save arxdsilva/8fb7186cd3a85f6a1d8f7678309f7c59 to your computer and use it in GitHub Desktop.
Recursive glob in Go
This file contains hidden or 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
func RecursiveGlob(dirPath string, pattern string) ([]string, error) { | |
old, err := os.Getwd() | |
if err != nil { | |
return nil, err | |
} | |
defer os.Chdir(old) | |
err = os.Chdir(dirPath) | |
if err != nil { | |
return nil, err | |
} | |
paths, err := filepath.Glob(pattern) | |
if err != nil { | |
return nil, err | |
} | |
for i := range paths { | |
paths[i] = filepath.Join(dirPath, paths[i]) | |
} | |
dir, err := os.Open(dirPath) | |
if err != nil { | |
return nil, err | |
} | |
fis, err := dir.Readdir(0) | |
if err != nil { | |
return nil, err | |
} | |
for _, f := range fis { | |
if f.IsDir() { | |
glob, err := RecursiveGlob(filepath.Join(dirPath, f.Name()), pattern) | |
if err != nil { | |
return nil, err | |
} | |
paths = append(paths, glob...) | |
} | |
} | |
return paths, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment