1
0
mirror of https://github.com/jesseduffield/lazygit.git synced 2025-02-09 13:47:11 +02:00

add FindNamedMatches function in utils

This commit is contained in:
Jesse Duffield 2021-12-26 15:56:05 +11:00
parent 38743ec99f
commit 7bc8b96aba
2 changed files with 61 additions and 0 deletions

17
pkg/utils/regexp.go Normal file
View File

@ -0,0 +1,17 @@
package utils
import "regexp"
func FindNamedMatches(regex *regexp.Regexp, str string) map[string]string {
match := regex.FindStringSubmatch(str)
if len(match) == 0 {
return nil
}
results := map[string]string{}
for i, value := range match[1:] {
results[regex.SubexpNames()[i+1]] = value
}
return results
}

44
pkg/utils/regexp_test.go Normal file
View File

@ -0,0 +1,44 @@
package utils
import (
"reflect"
"regexp"
"testing"
)
func TestFindNamedMatches(t *testing.T) {
scenarios := []struct {
regex *regexp.Regexp
input string
expected map[string]string
}{
{
regexp.MustCompile(`^(?P<name>\w+)`),
"hello world",
map[string]string{
"name": "hello",
},
},
{
regexp.MustCompile(`^https?://.*/(?P<owner>.*)/(?P<repo>.*?)(\.git)?$`),
"https://my_username@bitbucket.org/johndoe/social_network.git",
map[string]string{
"owner": "johndoe",
"repo": "social_network",
"": ".git", // unnamed capture group
},
},
{
regexp.MustCompile(`(?P<owner>hello) world`),
"yo world",
nil,
},
}
for _, scenario := range scenarios {
actual := FindNamedMatches(scenario.regex, scenario.input)
if !reflect.DeepEqual(actual, scenario.expected) {
t.Errorf("FindNamedMatches(%s, %s) == %s, expected %s", scenario.regex, scenario.input, actual, scenario.expected)
}
}
}