github.com/blend/go-sdk@v1.20220411.3/profanity/filter.go (about) 1 /* 2 3 Copyright (c) 2022 - 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 "fmt" 12 "strings" 13 ) 14 15 // Filter is the base rule helper. 16 type Filter struct { 17 // Include sets a glob filter for file inclusion by name. 18 Include []string `yaml:"include,omitempty"` 19 // ExcludeGlob sets a glob filter for file exclusion by name. 20 Exclude []string `yaml:"exclude,omitempty"` 21 } 22 23 // IsZero returns if the filter is set or not. 24 func (f Filter) IsZero() bool { 25 return len(f.Include) == 0 && len(f.Exclude) == 0 26 } 27 28 // Match returns the matching glob filter for a given value. 29 func (f Filter) Match(value string, filter func(string, string) bool) (includeMatch, excludeMatch string) { 30 if len(f.Include) > 0 { 31 for _, include := range f.Include { 32 if filter(value, include) { 33 includeMatch = include 34 break 35 } 36 } 37 } 38 if len(f.Include) == 0 || includeMatch != "" { 39 if len(f.Exclude) > 0 { 40 for _, exclude := range f.Exclude { 41 if filter(value, exclude) { 42 excludeMatch = exclude 43 break 44 } 45 } 46 } 47 } 48 return 49 } 50 51 // AllowMatch returns if the filter should allow a given match set. 52 func (f Filter) AllowMatch(includeMatch, excludeMatch string) bool { 53 if len(f.Include) > 0 && len(f.Exclude) > 0 { 54 return includeMatch != "" && excludeMatch == "" 55 } 56 if len(f.Include) > 0 { 57 return includeMatch != "" 58 } 59 if len(f.Exclude) > 0 { 60 return excludeMatch == "" 61 } 62 return true 63 } 64 65 // Allow returns if the filters include or exclude a given value. 66 func (f Filter) Allow(value string, filter func(string, string) bool) bool { 67 return f.AllowMatch(f.Match(value, filter)) 68 } 69 70 // Validate doesn't do anything right now for Filter. 71 func (f Filter) Validate() error { 72 return nil 73 } 74 75 // String implements fmt.Stringer. 76 func (f Filter) String() string { 77 if len(f.Include) > 0 && len(f.Exclude) > 0 { 78 return fmt.Sprintf("[include: %s, exclude: %s]", 79 strings.Join(f.Include, ", "), 80 strings.Join(f.Exclude, ", "), 81 ) 82 } else if len(f.Include) > 0 { 83 return fmt.Sprintf("[include: %s]", strings.Join(f.Include, ", ")) 84 } else if len(f.Exclude) > 0 { 85 return fmt.Sprintf("[exclude: %s]", strings.Join(f.Exclude, ", ")) 86 } 87 return "" 88 }