resource: Implement Resources.ByPrefix

Fixes #4266
This commit is contained in:
Bjørn Erik Pedersen 2018-01-12 18:06:35 +01:00
parent 60c9f3b1c3
commit 46db900dab
No known key found for this signature in database
GPG key ID: 330E6E2BD4859D8F
2 changed files with 30 additions and 10 deletions

View file

@ -72,22 +72,39 @@ func (r Resources) ByType(tp string) Resources {
func (r Resources) GetByPrefix(prefix string) Resource { func (r Resources) GetByPrefix(prefix string) Resource {
prefix = strings.ToLower(prefix) prefix = strings.ToLower(prefix)
for _, resource := range r { for _, resource := range r {
var name string if matchesPrefix(resource, prefix) {
f, ok := resource.(source.File)
if ok {
name = f.BaseFileName()
} else {
_, name = filepath.Split(resource.RelPermalink())
}
name = strings.ToLower(name)
if strings.HasPrefix(name, prefix) {
return resource return resource
} }
} }
return nil return nil
} }
// ByPrefix gets all resources matching the given base filename prefix, e.g
// "logo" will match logo.png.
func (r Resources) ByPrefix(prefix string) Resources {
var matches Resources
prefix = strings.ToLower(prefix)
for _, resource := range r {
if matchesPrefix(resource, prefix) {
matches = append(matches, resource)
}
}
return matches
}
func matchesPrefix(r Resource, prefix string) bool {
var name string
f, ok := r.(source.File)
if ok {
name = f.BaseFileName()
} else {
_, name = filepath.Split(r.RelPermalink())
}
name = strings.ToLower(name)
return strings.HasPrefix(name, prefix)
}
type Spec struct { type Spec struct {
*helpers.PathSpec *helpers.PathSpec
mimeTypes media.Types mimeTypes media.Types

View file

@ -126,4 +126,7 @@ func TestResourcesGetByPrefix(t *testing.T) {
assert.Equal("/foo1.css", resources.GetByPrefix("foo1").RelPermalink()) assert.Equal("/foo1.css", resources.GetByPrefix("foo1").RelPermalink())
assert.Nil(resources.GetByPrefix("asdfasdf")) assert.Nil(resources.GetByPrefix("asdfasdf"))
assert.Equal(2, len(resources.ByPrefix("logo")))
assert.Equal(1, len(resources.ByPrefix("logo2")))
} }