1
0
mirror of https://github.com/jesseduffield/lazygit.git synced 2025-01-24 05:36:19 +02:00

66 lines
1.3 KiB
Go
Raw Normal View History

package components
2022-12-26 11:12:56 +11:00
import (
"strings"
2022-12-26 17:15:33 +11:00
"github.com/samber/lo"
2022-12-26 11:12:56 +11:00
)
// for making assertions on string values
type Matcher[T any] struct {
rules []matcherRule[T]
2022-12-26 17:15:33 +11:00
// this is printed when there's an error so that it's clear what the context of the assertion is
prefix string
}
type matcherRule[T any] struct {
// e.g. "contains 'foo'"
name string
// returns a bool that says whether the test passed and if it returns false, it
// also returns a string of the error message
testFn func(T) (bool, string)
}
func (self *Matcher[T]) name() string {
2022-12-26 17:15:33 +11:00
if len(self.rules) == 0 {
return "anything"
}
return strings.Join(
lo.Map(self.rules, func(rule matcherRule[T], _ int) string { return rule.name }),
2022-12-26 17:15:33 +11:00
", ",
)
}
func (self *Matcher[T]) test(value T) (bool, string) {
2022-12-26 17:15:33 +11:00
for _, rule := range self.rules {
ok, message := rule.testFn(value)
if ok {
continue
}
2022-12-26 17:15:33 +11:00
if self.prefix != "" {
return false, self.prefix + " " + message
}
2022-12-26 17:15:33 +11:00
return false, message
}
2022-12-26 17:15:33 +11:00
return true, ""
}
2022-12-26 11:12:56 +11:00
func (self *Matcher[T]) appendRule(rule matcherRule[T]) *Matcher[T] {
2022-12-26 17:15:33 +11:00
self.rules = append(self.rules, rule)
return self
}
// adds context so that if the matcher test(s) fails, we understand what we were trying to test.
// E.g. prefix: "Unexpected content in view 'files'."
func (self *Matcher[T]) context(prefix string) *Matcher[T] {
2022-12-26 17:15:33 +11:00
self.prefix = prefix
return self
}