Skip to content

Commit

Permalink
Sanitaze file names - draft
Browse files Browse the repository at this point in the history
  • Loading branch information
przemekd committed Aug 18, 2023
1 parent 3e8a628 commit d418785
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 0 deletions.
37 changes: 37 additions & 0 deletions util/sanitaze.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package util

import (
"regexp"
)

var illegalRe = regexp.MustCompile(`[\/\?<>\\:\*\|"]`)
var controlRe = regexp.MustCompile(`[\x00-\x1f\x80-\x9f]`)
var reservedRe = regexp.MustCompile(`^\.+$`)
var windowsReservedRe = regexp.MustCompile(`(?i)^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$`)
var windowsTrailingRe = regexp.MustCompile(`[\. ]+$`)
var whitespaceRe = regexp.MustCompile(`\s`)

type FileName string

func (n *FileName) sanitize(r *regexp.Regexp, replacement string) *FileName {
var result FileName = FileName(r.ReplaceAllString(string(*n), replacement))
return &result
}

func SanitazeFileName(fileName string, replacement string) string {
var n FileName = FileName(fileName)
sanitazed := n.
sanitize(illegalRe, replacement).
sanitize(controlRe, replacement).
sanitize(reservedRe, replacement).
sanitize(windowsReservedRe, replacement).
sanitize(windowsTrailingRe, replacement)

return string(*sanitazed)
}

func SanitazeFileNameAndReplaceWhitespaces(fileName string, replacement string) string {
sanitazed := SanitazeFileName(fileName, replacement)
sanitazed = whitespaceRe.ReplaceAllString(sanitazed, replacement)
return sanitazed
}
24 changes: 24 additions & 0 deletions util/sanitaze_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package util

import "testing"

type sanitazeFileNameTest struct {
filename, expected string
}

var tests = []sanitazeFileNameTest{
{"How does rsync work?.epub", "test"},
{"CON", "fdfd"},
{"...epub", ""},
{"/.epub", ""},
{"_--.epub", ""},
{"_--.epub", ""},
}

func TestSanitazeFileName(t *testing.T) {
for _, test := range tests {
if output := SanitazeFileName(test.filename, ""); output != test.expected {
t.Errorf("Output %q not equal to expected %q", output, test.expected)
}
}
}

0 comments on commit d418785

Please sign in to comment.