github.com/v2fly/v2ray-core/v5@v5.16.2-0.20240507031116-8191faa6e095/main/commands/helpers/fs.go (about) 1 package helpers 2 3 import ( 4 "fmt" 5 "os" 6 "path/filepath" 7 "strings" 8 ) 9 10 // ReadDir finds files according to extensions in the dir 11 func ReadDir(dir string, extensions []string) ([]string, error) { 12 confs, err := os.ReadDir(dir) 13 if err != nil { 14 return nil, err 15 } 16 files := make([]string, 0) 17 for _, f := range confs { 18 ext := filepath.Ext(f.Name()) 19 for _, e := range extensions { 20 if strings.EqualFold(ext, e) { 21 files = append(files, filepath.Join(dir, f.Name())) 22 break 23 } 24 } 25 } 26 return files, nil 27 } 28 29 // ReadDirRecursively finds files according to extensions in the dir recursively 30 func ReadDirRecursively(dir string, extensions []string) ([]string, error) { 31 files := make([]string, 0) 32 err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { 33 ext := filepath.Ext(path) 34 for _, e := range extensions { 35 if strings.EqualFold(ext, e) { 36 files = append(files, path) 37 break 38 } 39 } 40 return nil 41 }) 42 if err != nil { 43 return nil, err 44 } 45 return files, nil 46 } 47 48 // ResolveFolderToFiles expands folder path (if any and it exists) to file paths. 49 // Any other paths, like file, even URL, it returns them as is. 50 func ResolveFolderToFiles(paths []string, extensions []string, recursively bool) ([]string, error) { 51 dirReader := ReadDir 52 if recursively { 53 dirReader = ReadDirRecursively 54 } 55 files := make([]string, 0) 56 for _, p := range paths { 57 i, err := os.Stat(p) 58 if err == nil && i.IsDir() { 59 fs, err := dirReader(p, extensions) 60 if err != nil { 61 return nil, fmt.Errorf("failed to read dir %s: %s", p, err) 62 } 63 files = append(files, fs...) 64 continue 65 } 66 files = append(files, p) 67 } 68 return files, nil 69 }