github.com/jlmeeker/kismatic@v1.10.1-0.20180612190640-57f9005a1f1a/pkg/inspector/check/file_content.go (about)

     1  package check
     2  
     3  import (
     4  	"fmt"
     5  	"io/ioutil"
     6  	"os"
     7  	"regexp"
     8  )
     9  
    10  // FileContentCheck runs a search against the contents of the specified file.
    11  // The SearchString is a regular expression that is in accordance with the
    12  // RE2 syntax defined by the Go regexp package.
    13  type FileContentCheck struct {
    14  	File         string
    15  	SearchString string
    16  }
    17  
    18  // Check returns true if file contents match the regular expression. Otherwise,
    19  // returns false. If an error occurrs, returns false and the error.
    20  func (c FileContentCheck) Check() (bool, error) {
    21  	if _, err := os.Stat(c.File); os.IsNotExist(err) {
    22  		return false, fmt.Errorf("Attempted to validate file %q, but it doesn't exist.", c.File)
    23  	}
    24  	r, err := regexp.Compile(c.SearchString)
    25  	if err != nil {
    26  		return false, fmt.Errorf("Invalid search string provided %q: %v", c.SearchString, err)
    27  	}
    28  	b, err := ioutil.ReadFile(c.File)
    29  	if err != nil {
    30  		return false, fmt.Errorf("Error reading file %q: %v", c.File, err)
    31  	}
    32  	return r.Match(b), nil
    33  }