ListFilesWithDepth returns an array of full path of files found in a directory, traversing up to maxDepth levels. maxDepth=0 means only files directly in dir, maxDepth=1 means dir and one level of subdirectories, etc. maxDepth=-1 means unlimited depth (all files recursively).
(dir string, maxDepth int)
| 280 | // maxDepth=0 means only files directly in dir, maxDepth=1 means dir and one level of subdirectories, etc. |
| 281 | // maxDepth=-1 means unlimited depth (all files recursively). |
| 282 | func ListFilesWithDepth(dir string, maxDepth int) ([]string, error) { |
| 283 | var files []string |
| 284 | err := filepath.WalkDir(dir, func(path string, d os.DirEntry, err error) error { |
| 285 | if err != nil { |
| 286 | return err |
| 287 | } |
| 288 | if d.IsDir() { |
| 289 | if maxDepth == -1 { |
| 290 | return nil |
| 291 | } |
| 292 | // Calculate depth and skip directories beyond maxDepth |
| 293 | relPath, _ := filepath.Rel(dir, path) |
| 294 | var depth int |
| 295 | if relPath == "." { |
| 296 | depth = 0 |
| 297 | } else { |
| 298 | depth = strings.Count(relPath, string(filepath.Separator)) + 1 |
| 299 | } |
| 300 | if depth > maxDepth { |
| 301 | return filepath.SkipDir |
| 302 | } |
| 303 | return nil |
| 304 | } |
| 305 | files = append(files, path) |
| 306 | return nil |
| 307 | }) |
| 308 | return files, err |
| 309 | } |
| 310 | |
| 311 | // RandomFilenameBase generates a temporary filename for use in testing or whatever. |
| 312 | // From https://stackoverflow.com/a/28005931/215713 |