github.com/blend/go-sdk@v1.20220411.3/stringutil/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 stringutil 9 10 import "strings" 11 12 const ( 13 // GlobStar is the "match anything" constant. 14 GlobStar = "*" 15 ) 16 17 // GlobAny tests if a file matches a (potentially) csv of glob filters. 18 func GlobAny(subj string, patterns ...string) bool { 19 for _, pattern := range patterns { 20 if matches := Glob(subj, pattern); matches { 21 return true 22 } 23 } 24 return false 25 } 26 27 // Glob returns if a subject matches a given pattern. 28 func Glob(subj, pattern string) bool { 29 if pattern == "" { 30 return subj == pattern 31 } 32 33 if pattern == GlobStar { 34 return true 35 } 36 37 parts := strings.Split(pattern, GlobStar) 38 39 if len(parts) == 1 { 40 return subj == pattern 41 } 42 43 leadingGlob := strings.HasPrefix(pattern, GlobStar) 44 trailingGlob := strings.HasSuffix(pattern, GlobStar) 45 end := len(parts) - 1 46 47 for i := 0; i < end; i++ { 48 idx := strings.Index(subj, parts[i]) 49 50 switch i { 51 case 0: 52 if !leadingGlob && idx != 0 { 53 return false 54 } 55 default: 56 if idx < 0 { 57 return false 58 } 59 } 60 61 subj = subj[idx+len(parts[i]):] 62 } 63 64 return trailingGlob || strings.HasSuffix(subj, parts[end]) 65 }