github.com/blend/go-sdk@v1.20240719.1/profanity/regex_filter.go (about)

     1  /*
     2  
     3  Copyright (c) 2024 - Present. Blend Labs, Inc. All rights reserved
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file.
     5  
     6  */
     7  
     8  package profanity
     9  
    10  import (
    11  	"regexp"
    12  )
    13  
    14  // RegexFilter represents rules around matching (or excluding) based on
    15  // regular expressions.
    16  type RegexFilter struct {
    17  	Filter `yaml:",inline"`
    18  
    19  	compiledExpressions map[string]*regexp.Regexp
    20  }
    21  
    22  // Match returns the matching glob filter for a given value.
    23  func (rf *RegexFilter) Match(value string) (includeMatch, excludeMatch string) {
    24  	return rf.Filter.Match(value, rf.MustMatch)
    25  }
    26  
    27  // Allow returns if the filters include or exclude a given filename.
    28  func (rf *RegexFilter) Allow(value string) (result bool) {
    29  	return rf.Filter.Allow(value, rf.MustMatch)
    30  }
    31  
    32  // MustMatch regexp but panics
    33  func (rf *RegexFilter) MustMatch(value, expr string) bool {
    34  	if rf.compiledExpressions == nil {
    35  		rf.compiledExpressions = make(map[string]*regexp.Regexp)
    36  	}
    37  	if expr, ok := rf.compiledExpressions[expr]; ok {
    38  		return expr.MatchString(value)
    39  	}
    40  	compiled, err := regexp.Compile(expr)
    41  	if err != nil {
    42  		panic(err)
    43  	}
    44  	rf.compiledExpressions[expr] = compiled
    45  	return compiled.MatchString(value)
    46  }