Skip to content

Commit

Permalink
fix(indexer): add validation to slug
Browse files Browse the repository at this point in the history
  • Loading branch information
waynezhang committed Jan 2, 2024
1 parent 11879ec commit 0f1170e
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
9 changes: 9 additions & 0 deletions internal/indexer/indexer.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"html/template"
"os"
"path/filepath"
"regexp"
"sort"

"github.com/waynezhang/foto/internal/config"
Expand Down Expand Up @@ -35,6 +36,9 @@ func Build(metadata []config.SectionMetadata, option config.ExtractOption) ([]Se

for _, val := range metadata {
slug := val.Slug
if !validSlug(slug) {
return nil, fmt.Errorf("Slug \"%s\" is invalid. Only letters([a-zA-Z]), numbers([09-]), underscore(_) and hyphen(-) can be used.", slug)
}
if slugs[slug] {
return nil, fmt.Errorf("Slug \"%s\" already exists. Slug needs to be unique.", slug)
}
Expand Down Expand Up @@ -113,3 +117,8 @@ func buildImageSet(path string, option config.ExtractOption) (*ImageSet, error)
},
}, nil
}

func validSlug(slug string) bool {
matched, _ := regexp.MatchString("^[a-zA-Z0-9-_]+$", slug)
return matched
}
8 changes: 8 additions & 0 deletions internal/indexer/indexer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,14 @@ var (
}
)

func TestValidSlug(t *testing.T) {
assert.True(t, validSlug("abcde-efg_9999"))
assert.False(t, validSlug("abcde efg_9999"))
assert.False(t, validSlug("abcde-efgかたかな"))
assert.False(t, validSlug("abcde.efg_999"))
assert.False(t, validSlug(""))
}

func TestBuild(t *testing.T) {
var meta1 config.SectionMetadata
var meta2 config.SectionMetadata
Expand Down

0 comments on commit 0f1170e

Please sign in to comment.