Skip to content

Commit 46db900

Browse files
committed
resource: Implement Resources.ByPrefix
Fixes #4266
1 parent 60c9f3b commit 46db900

File tree

2 files changed

+30
-10
lines changed

2 files changed

+30
-10
lines changed

‎resource/resource.go‎

Lines changed: 27 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -72,22 +72,39 @@ func (r Resources) ByType(tp string) Resources {
7272
func (r Resources) GetByPrefix(prefix string) Resource {
7373
prefix = strings.ToLower(prefix)
7474
for _, resource := range r {
75-
var name string
76-
f, ok := resource.(source.File)
77-
if ok {
78-
name = f.BaseFileName()
79-
} else {
80-
_, name = filepath.Split(resource.RelPermalink())
81-
}
82-
name = strings.ToLower(name)
83-
84-
if strings.HasPrefix(name, prefix) {
75+
if matchesPrefix(resource, prefix) {
8576
return resource
8677
}
8778
}
8879
return nil
8980
}
9081

82+
// ByPrefix gets all resources matching the given base filename prefix, e.g
83+
// "logo" will match logo.png.
84+
func (r Resources) ByPrefix(prefix string) Resources {
85+
var matches Resources
86+
prefix = strings.ToLower(prefix)
87+
for _, resource := range r {
88+
if matchesPrefix(resource, prefix) {
89+
matches = append(matches, resource)
90+
}
91+
}
92+
return matches
93+
}
94+
95+
func matchesPrefix(r Resource, prefix string) bool {
96+
var name string
97+
f, ok := r.(source.File)
98+
if ok {
99+
name = f.BaseFileName()
100+
} else {
101+
_, name = filepath.Split(r.RelPermalink())
102+
}
103+
name = strings.ToLower(name)
104+
105+
return strings.HasPrefix(name, prefix)
106+
}
107+
91108
type Spec struct {
92109
*helpers.PathSpec
93110
mimeTypes media.Types

‎resource/resource_test.go‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,4 +126,7 @@ func TestResourcesGetByPrefix(t *testing.T) {
126126
assert.Equal("/foo1.css", resources.GetByPrefix("foo1").RelPermalink())
127127
assert.Nil(resources.GetByPrefix("asdfasdf"))
128128

129+
assert.Equal(2, len(resources.ByPrefix("logo")))
130+
assert.Equal(1, len(resources.ByPrefix("logo2")))
131+
129132
}

0 commit comments

Comments
 (0)