mirror of
https://github.com/stashapp/stash.git
synced 2025-12-17 04:14:39 +03:00
Fix json filename generation (#2887)
This commit is contained in:
@@ -5,6 +5,7 @@ import (
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
@@ -116,3 +117,25 @@ func Touch(path string) error {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var (
|
||||
replaceCharsRE = regexp.MustCompile(`[&=\\/:*"?_ ]`)
|
||||
removeCharsRE = regexp.MustCompile(`[^[:alnum:]-.]`)
|
||||
multiHyphenRE = regexp.MustCompile(`\-+`)
|
||||
)
|
||||
|
||||
// SanitiseBasename returns a file basename removing any characters that are illegal or problematic to use in the filesystem.
|
||||
func SanitiseBasename(v string) string {
|
||||
v = strings.TrimSpace(v)
|
||||
|
||||
// replace illegal filename characters with -
|
||||
v = replaceCharsRE.ReplaceAllString(v, "-")
|
||||
|
||||
// remove other characters
|
||||
v = removeCharsRE.ReplaceAllString(v, "")
|
||||
|
||||
// remove multiple hyphens
|
||||
v = multiHyphenRE.ReplaceAllString(v, "-")
|
||||
|
||||
return strings.TrimSpace(v)
|
||||
}
|
||||
|
||||
26
pkg/fsutil/file_test.go
Normal file
26
pkg/fsutil/file_test.go
Normal file
@@ -0,0 +1,26 @@
|
||||
package fsutil
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestSanitiseBasename(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
v string
|
||||
want string
|
||||
}{
|
||||
{"basic", "basic", "basic"},
|
||||
{"spaces", `spaced name`, "spaced-name"},
|
||||
{"leading/trailing spaces", ` spaced name `, "spaced-name"},
|
||||
{"hyphen name", `hyphened-name`, "hyphened-name"},
|
||||
{"multi-hyphen", `hyphened--name`, "hyphened-name"},
|
||||
{"replaced characters", `a&b=c\d/:e*"f?_ g`, "a-b-c-d-e-f-g"},
|
||||
{"removed characters", `foo!!bar@@and, more`, "foobarand-more"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := SanitiseBasename(tt.v); got != tt.want {
|
||||
t.Errorf("SanitiseBasename() = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user