github.com/imannamdari/v2ray-core/v5@v5.0.5/main/commands/helpers/fs.go (about)

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