Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
139 changes: 139 additions & 0 deletions helpers/regex_maker.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
package helpers

import (
"bytes"
"fmt"
"regexp"
"strings"
)

// GetRegexForPath returns a compiled regular expression for the given path template.
//
// This function takes a path template string `tpl` and generates a regular expression
// that matches the structure of the template. The template can include placeholders
// enclosed in braces `{}` with optional custom patterns.
//
// Placeholders in the template can be defined as:
// - `{name}`: Matches any sequence of characters except '/'
// - `{name:pattern}`: Matches the specified custom pattern
//
// The function ensures that the template is well-formed, with balanced and properly
// nested braces. If the template is invalid, an error is returned.
//
// Parameters:
// - tpl: The path template string to convert into a regular expression.
//
// Returns:
// - *regexp.Regexp: A compiled regular expression that matches the template.
// - error: An error if the template is invalid or the regular expression cannot be compiled.
//
// Example:
//
// regex, err := GetRegexForPath("/orders/{id:[0-9]+}/items/{itemId}")
// // regex: ^/orders/([0-9]+)/items/([^/]+)$
// // err: nil
func GetRegexForPath(tpl string) (*regexp.Regexp, error) {
Comment thread
Rishabh-Daga marked this conversation as resolved.
// Check if it is well-formed.
idxs, errBraces := BraceIndices(tpl)
if errBraces != nil {
return nil, errBraces
}

// Backup the original.
template := tpl

// Now let's parse it.
defaultPattern := "[^/]*"

pattern := bytes.NewBufferString("^")
var end int

for i := 0; i < len(idxs); i += 2 {

// Set all values we are interested in.
raw := tpl[end:idxs[i]]
end = idxs[i+1]
parts := strings.SplitN(tpl[idxs[i]+1:end-1], ":", 2)
name := parts[0]
patt := defaultPattern
if len(parts) == 2 {
patt = parts[1]
}

// Name or pattern can't be empty.
if name == "" || patt == "" {
return nil, fmt.Errorf("missing name or pattern in %q", tpl[idxs[i]:end])
}

// Build the regexp pattern.
_, err := fmt.Fprintf(pattern, "%s(%s)", regexp.QuoteMeta(raw), patt)
if err != nil {
return nil, err
}

Check warning on line 72 in helpers/regex_maker.go

View check run for this annotation

Codecov / codecov/patch

helpers/regex_maker.go#L71-L72

Added lines #L71 - L72 were not covered by tests

}

// Add the remaining.
raw := tpl[end:]
pattern.WriteString(regexp.QuoteMeta(raw))

pattern.WriteByte('$')

// Compile full regexp.
reg, errCompile := regexp.Compile(pattern.String())
if errCompile != nil {
return nil, errCompile
}

Check warning on line 86 in helpers/regex_maker.go

View check run for this annotation

Codecov / codecov/patch

helpers/regex_maker.go#L85-L86

Added lines #L85 - L86 were not covered by tests

// Check for capturing groups which used to work in older versions
if reg.NumSubexp() != len(idxs)/2 {
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)
}

Check warning on line 91 in helpers/regex_maker.go

View check run for this annotation

Codecov / codecov/patch

helpers/regex_maker.go#L90-L91

Added lines #L90 - L91 were not covered by tests

// Done!
return reg, nil
}

// BraceIndices returns the indices of the opening and closing braces in a string.
//
// It scans the input string `s` and identifies the positions of matching pairs
// of braces ('{' and '}'). The function ensures that the braces are balanced
// and properly nested.
//
// If the braces are unbalanced or improperly nested, an error is returned.
//
// Parameters:
// - s: The input string to scan for braces.
//
// Returns:
// - []int: A slice of integers where each pair of indices represents the
// start and end positions of a matching pair of braces.
// - error: An error if the braces are unbalanced or improperly nested.
//
// Example:
//
// indices, err := BraceIndices("/orders/{id}/items/{itemId}")
// // indices: [8, 12, 19, 26]
// // err: nil
func BraceIndices(s string) ([]int, error) {
Comment thread
Rishabh-Daga marked this conversation as resolved.
var level, idx int
var idxs []int
for i := 0; i < len(s); i++ {
switch s[i] {
case '{':
if level++; level == 1 {
idx = i
}
case '}':
if level--; level == 0 {
idxs = append(idxs, idx, i+1)
} else if level < 0 {
return nil, fmt.Errorf("unbalanced braces in %q", s)
}
}
}
if level != 0 {
return nil, fmt.Errorf("unbalanced braces in %q", s)
}
return idxs, nil
}
141 changes: 141 additions & 0 deletions helpers/regex_maker_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
package helpers

import (
"testing"
)

func TestGetRegexForPath(t *testing.T) {
tests := []struct {
name string
tpl string
wantErr bool
wantExpr string
}{
{
name: "well-formed template with default pattern",
tpl: "/orders/{id}",
wantErr: false,
wantExpr: "^/orders/([^/]*)$",
},
{
name: "well-formed template with custom pattern",
tpl: "/orders/{id:[0-9]+}",
wantErr: false,
wantExpr: "^/orders/([0-9]+)$",
},
{
name: "missing name in template",
tpl: "/orders/{:pattern}",
wantErr: true,
},
{
name: "missing pattern in template",
tpl: "/orders/{name:}",
wantErr: true,
},
{
name: "unbalanced braces in template",
tpl: "/orders/{id",
wantErr: true,
},
{
name: "unbalanced braces in template",
tpl: "/orders/id}",
wantErr: true,
},
{
name: "template with multiple variables",
tpl: "/orders/{id:[0-9]+}/items/{itemId}",
wantErr: false,
wantExpr: "^/orders/([0-9]+)/items/([^/]*)$",
},
{
name: "OData formatted URL with single quotes",
tpl: "/entities('{id}')",
wantErr: false,
wantExpr: "^/entities\\('([^/]*)'\\)$",
},
{
name: "OData formatted URL with custom pattern",
tpl: "/entities('{id:[0-9]+}')",
wantErr: false,
wantExpr: "^/entities\\('([0-9]+)'\\)$",
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := GetRegexForPath(tt.tpl)
if (err != nil) != tt.wantErr {
t.Errorf("GetRegexForPath() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !tt.wantErr && got.String() != tt.wantExpr {
t.Errorf("GetRegexForPath() = %v, want %v", got.String(), tt.wantExpr)
}
})
}
}

func TestBraceIndices(t *testing.T) {
tests := []struct {
name string
s string
want []int
wantErr bool
}{
{
name: "well-formed braces",
s: "/orders/{id}/items/{itemId}",
want: []int{8, 12, 19, 27},
wantErr: false,
},
{
name: "unbalanced braces",
s: "/orders/{id/items/{itemId}",
wantErr: true,
},
{
name: "unbalanced braces",
s: "/orders/{id}/items/{itemId",
wantErr: true,
},
{
name: "no braces",
s: "/orders/id/items/itemId",
want: []int{},
wantErr: false,
},
{
name: "OData formatted URL with single quotes",
s: "/entities('{id}')",
want: []int{11, 15},
wantErr: false,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := BraceIndices(tt.s)
if (err != nil) != tt.wantErr {
t.Errorf("BraceIndices() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !tt.wantErr && !equal(got, tt.want) {
t.Errorf("BraceIndices() = %v, want %v", got, tt.want)
}
})
}
}

func equal(a, b []int) bool {
if len(a) != len(b) {
return false
}
for i := range a {
if a[i] != b[i] {
return false
}
}
return true
}
34 changes: 25 additions & 9 deletions parameters/path_parameters.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import (
"fmt"
"net/http"
"regexp"
"strconv"
"strings"

Expand Down Expand Up @@ -54,14 +55,34 @@
if pathSegments[x] == "" { // skip empty segments
continue
}
i := strings.IndexRune(pathSegments[x], '{')
if i > -1 {

r, err := helpers.GetRegexForPath(pathSegments[x])
if err != nil {
continue

Check warning on line 61 in parameters/path_parameters.go

View check run for this annotation

Codecov / codecov/patch

parameters/path_parameters.go#L61

Added line #L61 was not covered by tests
}

re := regexp.MustCompile(r.String())
matches := re.FindStringSubmatch(submittedSegments[x])
matches = matches[1:]

// Check if it is well-formed.
idxs, errBraces := helpers.BraceIndices(pathSegments[x])
if errBraces != nil {
continue

Check warning on line 71 in parameters/path_parameters.go

View check run for this annotation

Codecov / codecov/patch

parameters/path_parameters.go#L71

Added line #L71 was not covered by tests
}

idx := 0

for _, match := range matches {

isMatrix := false
isLabel := false
// isExplode := false
isSimple := true
paramTemplate := pathSegments[x][i+1 : len(pathSegments[x])-1]
paramTemplate := pathSegments[x][idxs[idx]+1 : idxs[idx+1]-1]
idx += 2 // move to the next brace pair
paramName := paramTemplate

// check for an asterisk on the end of the parameter (explode)
if strings.HasSuffix(paramTemplate, helpers.Asterisk) {
// isExplode = true
Expand All @@ -83,12 +104,7 @@
continue
}

paramValue := ""

// extract the parameter value from the path.
if x < len(submittedSegments) {
paramValue = submittedSegments[x]
}
paramValue := match

if paramValue == "" {
// Mandatory path parameter cannot be empty
Expand Down
Loading
Loading