github.com/jfrog/jfrog-client-go@v1.40.2/utils/antutils.go (about) 1 package utils 2 3 import ( 4 "fmt" 5 "os" 6 "regexp" 7 "strings" 8 9 "github.com/jfrog/gofrog/stringutils" 10 "github.com/jfrog/jfrog-client-go/utils/io" 11 ) 12 13 var ( 14 // Replace ** with a special string. 15 doubleStartSpecialString = "__JFROG_DOUBLE_STAR__" 16 17 // Match **/ ('__JFROG_DOUBLE_STAR__\/...') 18 prefixDoubleStarRegex = regexp.MustCompile(fmt.Sprintf("%s%s", doubleStartSpecialString, getFileSeparatorForDoubleStart())) 19 20 // match /** ('\/__JFROG_DOUBLE_STAR__...') 21 postfixDoubleStarRegex = regexp.MustCompile(fmt.Sprintf("%s%s", getFileSeparatorForDoubleStart(), doubleStartSpecialString)) 22 23 // match ** ('...__JFROG_DOUBLE_STAR__...') 24 middleDoubleStarNoSeparateRegex = regexp.MustCompile(doubleStartSpecialString) 25 ) 26 27 func getFileSeparatorForDoubleStart() string { 28 if io.IsWindows() { 29 return `\\\\` 30 } 31 return `\/` 32 } 33 34 func AntToRegex(antPattern string) string { 35 antPattern = stringutils.EscapeSpecialChars(antPattern) 36 antPattern = antQuestionMarkToRegex(antPattern) 37 return "^" + antStarsToRegex(antPattern) + "$" 38 } 39 40 func getFileSeparatorForAntToRegex() string { 41 if io.IsWindows() { 42 return `\\` 43 } 44 return `/` 45 } 46 47 func antStarsToRegex(antPattern string) string { 48 separator := getFileSeparatorForAntToRegex() 49 antPattern = addMissingShorthand(antPattern) 50 51 // Replace ** with a special string, so it doesn't get mixed up with single * 52 antPattern = strings.ReplaceAll(antPattern, "**", doubleStartSpecialString) 53 54 // ant `*` => regexp `([^/]*)` : `*` matches zero or more characters except from `/`. 55 antPattern = strings.ReplaceAll(antPattern, `*`, "([^"+separator+"]*)") 56 57 // ant `**/` => regexp `(.*/)*` : Matches zero or more 'directories' at the beginning of the path. 58 antPattern = prefixDoubleStarRegex.ReplaceAllString(antPattern, "(.*"+separator+")*") 59 60 // ant `/**` => regexp `(/.*)*` : Matches zero or more 'directories' at the end of the path. 61 antPattern = postfixDoubleStarRegex.ReplaceAllString(antPattern, "("+separator+".*)*") 62 63 // ant `**` => regexp `(.*)*` : Matches zero or more 'directories'. 64 return middleDoubleStarNoSeparateRegex.ReplaceAllString(antPattern, "(.*)") 65 } 66 67 func antQuestionMarkToRegex(antPattern string) string { 68 return strings.ReplaceAll(antPattern, "?", ".") 69 } 70 71 func addMissingShorthand(antPattern string) string { 72 // There is one "shorthand": if a pattern ends with / or \, then ** is appended. For example, mypackage/test/ is interpreted as if it were mypackage/test/**. 73 if strings.HasSuffix(antPattern, string(os.PathSeparator)) { 74 return antPattern + "**" 75 } 76 return antPattern 77 }