github.com/noqcks/syft@v0.0.0-20230920222752-a9e2c4e288e5/internal/file/glob_match.go (about)

     1  package file
     2  
     3  // GlobMatch evaluates the given glob pattern against the given "name" string, indicating if there is a match or not.
     4  // Source: https://research.swtch.com/glob.go
     5  func GlobMatch(pattern, name string) bool {
     6  	px := 0
     7  	nx := 0
     8  	nextPx := 0
     9  	nextNx := 0
    10  	for px < len(pattern) || nx < len(name) {
    11  		if px < len(pattern) {
    12  			c := pattern[px]
    13  			switch c {
    14  			default: // ordinary character
    15  				if nx < len(name) && name[nx] == c {
    16  					px++
    17  					nx++
    18  					continue
    19  				}
    20  			case '?': // single-character wildcard
    21  				if nx < len(name) {
    22  					px++
    23  					nx++
    24  					continue
    25  				}
    26  			case '*': // zero-or-more-character wildcard
    27  				// Try to match at nx.
    28  				// If that doesn't work out,
    29  				// restart at nx+1 next.
    30  				nextPx = px
    31  				nextNx = nx + 1
    32  				px++
    33  				continue
    34  			}
    35  		}
    36  		// Mismatch. Maybe restart.
    37  		if 0 < nextNx && nextNx <= len(name) {
    38  			px = nextPx
    39  			nx = nextNx
    40  			continue
    41  		}
    42  		return false
    43  	}
    44  	// Matched all of pattern to all of name. Success.
    45  	return true
    46  }