github.com/daixiang0/gci@v0.13.4/pkg/io/search.go (about)

     1  package io
     2  
     3  import (
     4  	"io/fs"
     5  	"os"
     6  	"path/filepath"
     7  )
     8  
     9  type fileCheckFunction func(path string, file os.FileInfo) bool
    10  
    11  func FindFilesForPath(path string, fileCheckFun fileCheckFunction) ([]string, error) {
    12  	switch entry, err := os.Stat(path); {
    13  	case err != nil:
    14  		return nil, err
    15  	case entry.IsDir():
    16  		return findFilesForDirectory(path, fileCheckFun)
    17  	case fileCheckFun(path, entry):
    18  		return []string{filepath.Clean(path)}, nil
    19  	default:
    20  		return []string{}, nil
    21  	}
    22  }
    23  
    24  func findFilesForDirectory(dirPath string, fileCheckFun fileCheckFunction) ([]string, error) {
    25  	var filePaths []string
    26  	err := filepath.WalkDir(dirPath, func(path string, entry fs.DirEntry, err error) error {
    27  		if err != nil {
    28  			return err
    29  		}
    30  		file, err := entry.Info()
    31  		if err != nil {
    32  			return err
    33  		}
    34  		if !entry.IsDir() && fileCheckFun(path, file) {
    35  			filePaths = append(filePaths, filepath.Clean(path))
    36  		}
    37  		return nil
    38  	})
    39  	if err != nil {
    40  		return nil, err
    41  	}
    42  	return filePaths, nil
    43  }
    44  
    45  func isGoFile(_ string, file os.FileInfo) bool {
    46  	return !file.IsDir() && filepath.Ext(file.Name()) == ".go"
    47  }
    48  
    49  func isOutsideVendorDir(path string, _ os.FileInfo) bool {
    50  	for {
    51  		base := filepath.Base(path)
    52  		if base == "vendor" {
    53  			return false
    54  		}
    55  
    56  		prevPath := path
    57  		path = filepath.Dir(path)
    58  
    59  		if prevPath == path {
    60  			break
    61  		}
    62  	}
    63  
    64  	return true
    65  }
    66  
    67  func checkChains(funcs ...fileCheckFunction) fileCheckFunction {
    68  	return func(path string, file os.FileInfo) bool {
    69  		for _, checkFunc := range funcs {
    70  			if !checkFunc(path, file) {
    71  				return false
    72  			}
    73  		}
    74  
    75  		return true
    76  	}
    77  }