github.com/saucelabs/saucectl@v0.175.1/internal/cypress/grep/grep.go (about)

     1  // Package grep implements functions to parse and filter spec files by cypress-grep expressions.
     2  //
     3  // See https://www.npmjs.com/package/@cypress/grep for details on the specific syntax
     4  // of cypress-grep expressions.
     5  package grep
     6  
     7  import (
     8  	"io/fs"
     9  
    10  	"github.com/saucelabs/saucectl/internal/cypress/code"
    11  )
    12  
    13  // MatchFiles finds the files whose contents match the grep expression in the title parameter
    14  // and the grep tag expression in the tag parameter.
    15  func MatchFiles(sys fs.FS, files []string, title string, tag string) (matched []string, unmatched []string) {
    16  	for _, f := range files {
    17  		b, err := fs.ReadFile(sys, f)
    18  
    19  		if err != nil {
    20  			continue
    21  		}
    22  
    23  		testcases := code.Parse(string(b))
    24  		grepExp := ParseGrepTitleExp(title)
    25  		grepTagsExp := ParseGrepTagsExp(tag)
    26  
    27  		include := false
    28  		for _, tc := range testcases {
    29  			include = include || match(grepExp, grepTagsExp, tc.Title, tc.Tags)
    30  			if include {
    31  				// As long as one testcase matched, we know the spec will need to be executed
    32  				matched = append(matched, f)
    33  				break
    34  			}
    35  		}
    36  		if !include {
    37  			unmatched = append(unmatched, f)
    38  		}
    39  	}
    40  
    41  	return matched, unmatched
    42  }
    43  
    44  func match(titleExp Expression, tagsExp Expression, title string, tags string) bool {
    45  	// Allow empty title to match. This mimics the behaviour of cypress-grep.
    46  	titleMatch := title == "" || titleExp.Eval(title)
    47  	tagMatch := tagsExp.Eval(tags)
    48  
    49  	return titleMatch && tagMatch
    50  }