resources: Create a common ResourceFinder interface

And make both .Resources and resources implement it.

This gets us 2 new methods/functions, so you can now also do:

* .Resources.Get
* resources.ByType

Note that GetRemote is not covered by this interface, as that is only available as a global template function.

Fixes #8653
This commit is contained in:
Bjørn Erik Pedersen
2021-10-20 10:11:48 +02:00
parent 20162518c4
commit e58a540895
7 changed files with 148 additions and 36 deletions

View File

@@ -65,26 +65,27 @@ func (c *Client) Get(filename string) (resource.Resource, error) {
// Match gets the resources matching the given pattern from the assets filesystem.
func (c *Client) Match(pattern string) (resource.Resources, error) {
return c.match(pattern, false)
return c.match("__match", pattern, nil, false)
}
func (c *Client) ByType(tp string) resource.Resources {
res, err := c.match(path.Join("_byType", tp), "**", func(r resource.Resource) bool { return r.ResourceType() == tp }, false)
if err != nil {
panic(err)
}
return res
}
// GetMatch gets first resource matching the given pattern from the assets filesystem.
func (c *Client) GetMatch(pattern string) (resource.Resource, error) {
res, err := c.match(pattern, true)
res, err := c.match("__get-match", pattern, nil, true)
if err != nil || len(res) == 0 {
return nil, err
}
return res[0], err
}
func (c *Client) match(pattern string, firstOnly bool) (resource.Resources, error) {
var name string
if firstOnly {
name = "__get-match"
} else {
name = "__match"
}
func (c *Client) match(name, pattern string, matchFunc func(r resource.Resource) bool, firstOnly bool) (resource.Resources, error) {
pattern = glob.NormalizePath(pattern)
partitions := glob.FilterGlobParts(strings.Split(pattern, "/"))
if len(partitions) == 0 {
@@ -110,6 +111,10 @@ func (c *Client) match(pattern string, firstOnly bool) (resource.Resources, erro
return true, err
}
if matchFunc != nil && !matchFunc(r) {
return false, nil
}
res = append(res, r)
return firstOnly, nil