Skip to content

Commit

Permalink
feat: ⚡ Improve regex pattern
Browse files Browse the repository at this point in the history
Closes #270
  • Loading branch information
RamiAwar committed Feb 10, 2024
1 parent 6d0fa33 commit dbc472b
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 3 deletions.
9 changes: 6 additions & 3 deletions dialog/params.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,14 @@ var (
//FinalCommand is the command after assigning to variables
FinalCommand string

patternRegex = `<([\S]+?)>`
// This matches most encountered patterns
// Skips match if there is a whitespace at the end ex. <param='my >
// Ignores <, > characters since they're used to match the pattern
patternRegex = `<([^<>]*[^\s])>`
)

func insertParams(command string, params map[string]string) string {
r, _ := regexp.Compile(patternRegex)
r := regexp.MustCompile(patternRegex)

matches := r.FindAllStringSubmatch(command, -1)
if len(matches) == 0 {
Expand All @@ -38,7 +41,7 @@ func insertParams(command string, params map[string]string) string {
// SearchForParams returns variables from a command
func SearchForParams(lines []string) [][2]string {
if len(lines) == 1 {
r, _ := regexp.Compile(patternRegex)
r := regexp.MustCompile(patternRegex)

params := r.FindAllStringSubmatch(lines[0], -1)
if len(params) == 0 {
Expand Down
26 changes: 26 additions & 0 deletions dialog/params_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,20 @@ func TestSearchForParams_WithNewline(t *testing.T) {
}
}

func TestSearchForParams_ValueWithSpaces(t *testing.T) {
command := "example_function --flag=<param=Lots of Bananas>"

want := [][2]string{
{"param", "Lots of Bananas"},
}

got := SearchForParams([]string{command})

if diff := deep.Equal(want, got); diff != nil {
t.Fatal(diff)
}
}

func TestSearchForParams_InvalidParamFormat(t *testing.T) {
command := "<a=1 <b> hello"
want := [][2]string{
Expand All @@ -85,6 +99,18 @@ func TestSearchForParams_InvalidParamFormat(t *testing.T) {
}
}

func TestSearchForParams_InvalidParamFormatWithoutSpaces(t *testing.T) {
command := "<a=1<b>hello"
want := [][2]string{
{"b", ""},
}
got := SearchForParams([]string{command})

if diff := deep.Equal(want, got); diff != nil {
t.Fatal(diff)
}
}

func TestSearchForParams_ConfusingBrackets(t *testing.T) {
command := "cat <<EOF > <file=path/to/file>\nEOF"
want := [][2]string{
Expand Down

0 comments on commit dbc472b

Please sign in to comment.