github.com/billybanfield/evergreen@v0.0.0-20170525200750-eeee692790f7/util/file.go (about)

     1  package util
     2  
     3  import (
     4  	"io"
     5  	"io/ioutil"
     6  	"os"
     7  	"path/filepath"
     8  
     9  	ignore "github.com/sabhiram/go-git-ignore"
    10  )
    11  
    12  // FileExists returns true if 'path' exists.
    13  func FileExists(elem ...string) (bool, error) {
    14  	path := filepath.Join(elem...)
    15  	_, err := os.Stat(path)
    16  	if err == nil {
    17  		return true, nil
    18  	}
    19  	if os.IsNotExist(err) {
    20  		return false, nil
    21  	}
    22  	return false, err
    23  }
    24  
    25  // WriteToTempFile writes the given string to a temporary file and returns the
    26  // path to the file.
    27  func WriteToTempFile(data string) (string, error) {
    28  	dir := filepath.Join(os.TempDir(), "evergreen")
    29  	if err := os.MkdirAll(dir, 0755); err != nil {
    30  		return "", err
    31  	}
    32  
    33  	file, err := ioutil.TempFile(dir, "temp_file_")
    34  	if err != nil {
    35  		return "", err
    36  	}
    37  	defer file.Close()
    38  	if _, err = io.WriteString(file, data); err != nil {
    39  		return "", err
    40  	}
    41  	return file.Name(), nil
    42  }
    43  
    44  // fileListBuilder contains the information for building a list of files in the given directory.
    45  // It adds the files to include in the fileNames array and uses the ignorer to determine if a given
    46  // file matches and should be added.
    47  type fileListBuilder struct {
    48  	fileNames []string
    49  	ignorer   *ignore.GitIgnore
    50  }
    51  
    52  func (fb *fileListBuilder) walkFunc(path string, info os.FileInfo, err error) error {
    53  	if !info.IsDir() && fb.ignorer.MatchesPath(path) {
    54  		fb.fileNames = append(fb.fileNames, path)
    55  	}
    56  	return nil
    57  }
    58  
    59  // BuildFileList returns a list of files that match the given list of expressions
    60  // rooted at the given startPath. The expressions correspond to gitignore ignore
    61  // expressions: anything that would be matched - and therefore ignored by git - is included
    62  // in the returned list of file paths. BuildFileList does not follow symlinks as
    63  // it uses filpath.Walk, which does not follow symlinks.
    64  func BuildFileList(startPath string, expressions ...string) ([]string, error) {
    65  	ignorer, err := ignore.CompileIgnoreLines(expressions...)
    66  	if err != nil {
    67  		return nil, err
    68  	}
    69  	fb := &fileListBuilder{
    70  		fileNames: []string{},
    71  		ignorer:   ignorer,
    72  	}
    73  	err = filepath.Walk(startPath, fb.walkFunc)
    74  	if err != nil {
    75  		return nil, err
    76  	}
    77  	return fb.fileNames, nil
    78  }