Debian Codegraph @

helpers/regex_maker.go

raw
1 package helpers
2
3 import (
4 "bytes"
5 "fmt"
6 "regexp"
7 "strings"
8 )
9
10 var (
11 baseDefaultPattern = "[^/]*"
12 DefaultPatternRegex = regexp.MustCompile("^([^/]*)$")
13 DefaultPatternRegexString = DefaultPatternRegex.String()
14 )
15
16 // GetRegexForPath returns a compiled regular expression for the given path template.
17 //
18 // This function takes a path template string `tpl` and generates a regular expression
19 // that matches the structure of the template. The template can include placeholders
20 // enclosed in braces `{}` with optional custom patterns.
21 //
22 // Placeholders in the template can be defined as:
23 // - `{name}`: Matches any sequence of characters except '/'
24 // - `{name:pattern}`: Matches the specified custom pattern
25 //
26 // The function ensures that the template is well-formed, with balanced and properly
27 // nested braces. If the template is invalid, an error is returned.
28 //
29 // Parameters:
30 // - tpl: The path template string to convert into a regular expression.
31 //
32 // Returns:
33 // - *regexp.Regexp: A compiled regular expression that matches the template.
34 // - error: An error if the template is invalid or the regular expression cannot be compiled.
35 //
36 // Example:
37 //
38 // regex, err := GetRegexForPath("/orders/{id:[0-9]+}/items/{itemId}")
39 // // regex: ^/orders/([0-9]+)/items/([^/]+)$
40 // // err: nil
41 func GetRegexForPath(tpl string) (*regexp.Regexp, error) {
42 // Check if it is well-formed.
43 idxs, errBraces := BraceIndices(tpl)
44 if errBraces != nil {
45 return nil, errBraces
46 }
47
48 // Backup the original.
49 template := tpl
50
51 pattern := bytes.NewBufferString("^")
52 var end int
53
54 for i := 0; i < len(idxs); i += 2 {
55
56 // Set all values we are interested in.
57 raw := tpl[end:idxs[i]]
58 end = idxs[i+1]
59 parts := strings.SplitN(tpl[idxs[i]+1:end-1], ":", 2)
60 name := parts[0]
61 patt := baseDefaultPattern
62 if len(parts) == 2 {
63 patt = parts[1]
64 }
65
66 // Name or pattern can't be empty.
67 if name == "" || patt == "" {
68 return nil, fmt.Errorf("missing name or pattern in %q", tpl[idxs[i]:end])
69 }
70
71 // Build the regexp pattern.
72 _, err := fmt.Fprintf(pattern, "%s(%s)", regexp.QuoteMeta(raw), patt)
73 if err != nil {
74 return nil, err
75 }
76
77 }
78
79 // Add the remaining.
80 raw := tpl[end:]
81 pattern.WriteString(regexp.QuoteMeta(raw))
82
83 pattern.WriteByte('$')
84
85 patternString := pattern.String()
86
87 if patternString == DefaultPatternRegexString {
88 return DefaultPatternRegex, nil
89 }
90
91 // Compile full regexp.
92 reg, errCompile := regexp.Compile(patternString)
93 if errCompile != nil {
94 return nil, errCompile
95 }
96
97 // Check for capturing groups which used to work in older versions
98 if reg.NumSubexp() != len(idxs)/2 {
99 return nil, fmt.Errorf("route %s contains capture groups in its regexp. Only non-capturing groups are accepted: e.g. (?:pattern) instead of (pattern)", template)
100 }
101
102 // Done!
103 return reg, nil
104 }
105
106 // BraceIndices returns the indices of the opening and closing braces in a string.
107 //
108 // It scans the input string `s` and identifies the positions of matching pairs
109 // of braces ('{' and '}'). The function ensures that the braces are balanced
110 // and properly nested.
111 //
112 // If the braces are unbalanced or improperly nested, an error is returned.
113 //
114 // Parameters:
115 // - s: The input string to scan for braces.
116 //
117 // Returns:
118 // - []int: A slice of integers where each pair of indices represents the
119 // start and end positions of a matching pair of braces.
120 // - error: An error if the braces are unbalanced or improperly nested.
121 //
122 // Example:
123 //
124 // indices, err := BraceIndices("/orders/{id}/items/{itemId}")
125 // // indices: [8, 12, 19, 26]
126 // // err: nil
127 func BraceIndices(s string) ([]int, error) {
128 var level, idx int
129 var idxs []int
130 for i := 0; i < len(s); i++ {
131 switch s[i] {
132 case '{':
133 if level++; level == 1 {
134 idx = i
135 }
136 case '}':
137 if level--; level == 0 {
138 idxs = append(idxs, idx, i+1)
139 } else if level < 0 {
140 return nil, fmt.Errorf("unbalanced braces in %q", s)
141 }
142 }
143 }
144 if level != 0 {
145 return nil, fmt.Errorf("unbalanced braces in %q", s)
146 }
147 return idxs, nil
148 }