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:
parent
38743ec99f
commit
7bc8b96aba
17
pkg/utils/regexp.go
Normal file
17
pkg/utils/regexp.go
Normal 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
44
pkg/utils/regexp_test.go
Normal 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)
|
||||
}
|
||||
}
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user