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

     1  package io
     2  
     3  import "io/ioutil"
     4  
     5  // FileObj allows mocking the access to files
     6  type FileObj interface {
     7  	Load() ([]byte, error)
     8  	Path() string
     9  }
    10  
    11  // File represents a file that can be loaded from the file system
    12  type File struct {
    13  	FilePath string
    14  }
    15  
    16  func (f File) Path() string {
    17  	return f.FilePath
    18  }
    19  
    20  func (f File) Load() ([]byte, error) {
    21  	return ioutil.ReadFile(f.FilePath)
    22  }
    23  
    24  // FileGeneratorFunc returns a list of files that can be loaded and processed
    25  type FileGeneratorFunc func() ([]FileObj, error)
    26  
    27  func (a FileGeneratorFunc) Combine(b FileGeneratorFunc) FileGeneratorFunc {
    28  	return func() ([]FileObj, error) {
    29  		files, err := a()
    30  		if err != nil {
    31  			return nil, err
    32  		}
    33  		additionalFiles, err := b()
    34  		if err != nil {
    35  			return nil, err
    36  		}
    37  		files = append(files, additionalFiles...)
    38  		return files, err
    39  	}
    40  }
    41  
    42  func GoFilesInPathsGenerator(paths []string, skipVendor bool) FileGeneratorFunc {
    43  	checkFunc := isGoFile
    44  	if skipVendor {
    45  		checkFunc = checkChains(isGoFile, isOutsideVendorDir)
    46  	}
    47  
    48  	return FilesInPathsGenerator(paths, checkFunc)
    49  }
    50  
    51  func FilesInPathsGenerator(paths []string, fileCheckFun fileCheckFunction) FileGeneratorFunc {
    52  	return func() (foundFiles []FileObj, err error) {
    53  		for _, path := range paths {
    54  			files, err := FindFilesForPath(path, fileCheckFun)
    55  			if err != nil {
    56  				return nil, err
    57  			}
    58  			for _, filePath := range files {
    59  				foundFiles = append(foundFiles, File{filePath})
    60  			}
    61  		}
    62  		return foundFiles, nil
    63  	}
    64  }