resource: Implement Resources.ByPrefix
authorBjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com>
Fri, 12 Jan 2018 17:06:35 +0000 (18:06 +0100)
committerBjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com>
Fri, 12 Jan 2018 17:06:35 +0000 (18:06 +0100)
Fixes #4266

resource/resource.go
resource/resource_test.go

index 4a535889d69b3224d20ddfaa6322dcbe13fc2a24..bb84aed79fdff0f01eaa58b378ec839a21f48c9a 100644 (file)
@@ -72,22 +72,39 @@ func (r Resources) ByType(tp string) Resources {
 func (r Resources) GetByPrefix(prefix string) Resource {
        prefix = strings.ToLower(prefix)
        for _, resource := range r {
-               var name string
-               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) {
+               if matchesPrefix(resource, prefix) {
                        return resource
                }
        }
        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 {
        *helpers.PathSpec
        mimeTypes media.Types
index fbc66af8fd9545b35a9a66601d2ed3e86e50272c..73d98d62abb4657cd2ef80b6d380960acc9ae3ca 100644 (file)
@@ -126,4 +126,7 @@ func TestResourcesGetByPrefix(t *testing.T) {
        assert.Equal("/foo1.css", resources.GetByPrefix("foo1").RelPermalink())
        assert.Nil(resources.GetByPrefix("asdfasdf"))
 
+       assert.Equal(2, len(resources.ByPrefix("logo")))
+       assert.Equal(1, len(resources.ByPrefix("logo2")))
+
 }