github.com/blend/go-sdk@v1.20220411.3/profanity/glob.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 "strings" 11 12 // GlobAnyMatch tests if a file matches a (potentially) csv of glob filters. 13 func GlobAnyMatch(filters []string, file string) bool { 14 for _, part := range filters { 15 if matches := Glob(file, strings.TrimSpace(part)); matches { 16 return true 17 } 18 } 19 return false 20 } 21 22 // Glob returns if a given pattern matches a given subject. 23 func Glob(subj, pattern string) bool { 24 // Empty pattern can only match empty subject 25 if pattern == "" { 26 return subj == pattern 27 } 28 29 // If the pattern _is_ a glob, it matches everything 30 if pattern == Star { 31 return true 32 } 33 34 parts := strings.Split(pattern, Star) 35 36 if len(parts) == 1 { 37 // No globs in pattern, so test for equality 38 return subj == pattern 39 } 40 41 leadingGlob := strings.HasPrefix(pattern, Star) 42 trailingGlob := strings.HasSuffix(pattern, Star) 43 end := len(parts) - 1 44 45 // Go over the leading parts and ensure they match. 46 for i := 0; i < end; i++ { 47 idx := strings.Index(subj, parts[i]) 48 49 switch i { 50 case 0: 51 // Check the first section. Requires special handling. 52 if !leadingGlob && idx != 0 { 53 return false 54 } 55 default: 56 // Check that the middle parts match. 57 if idx < 0 { 58 return false 59 } 60 } 61 62 // Trim evaluated text from subj as we loop over the pattern. 63 subj = subj[idx+len(parts[i]):] 64 } 65 66 // Reached the last section. Requires special handling. 67 return trailingGlob || strings.HasSuffix(subj, parts[end]) 68 }