Sanitize log filename before saving

Remove invalid path characters
mine
groselt 2020-05-30 17:04:36 +01:00
parent 48317abc2a
commit 0fc2bb13a7
2 changed files with 29 additions and 1 deletions

View File

@ -7,6 +7,7 @@ import (
"io"
"os"
"path/filepath"
"regexp"
"strings"
"time"
@ -29,6 +30,9 @@ const (
flushTimeout = 50 * time.Millisecond
)
// InvalidCharsRX contains invalid filename characters.
var invalidPathCharsRX = regexp.MustCompile(`[:/\\]+`)
// Log represents a generic log viewer.
type Log struct {
*tview.Flex
@ -284,12 +288,19 @@ func (l *Log) SaveCmd(evt *tcell.EventKey) *tcell.EventKey {
return nil
}
// SanitizeFilename removes characters not allowed by OS
func SanitizeFilename(name string) string {
processedString := invalidPathCharsRX.ReplaceAllString(name, "-")
return processedString
}
func ensureDir(dir string) error {
return os.MkdirAll(dir, 0744)
}
func saveData(cluster, name, data string) (string, error) {
dir := filepath.Join(config.K9sDumpDir, cluster)
dir := filepath.Join(config.K9sDumpDir, SanitizeFilename(cluster))
if err := ensureDir(dir); err != nil {
return "", err
}

View File

@ -43,6 +43,23 @@ func TestLogViewSave(t *testing.T) {
assert.Equal(t, len(c2), len(c1)+1)
}
func TestSanitizedFilename(t *testing.T) {
uu := []struct {
name string
expected string
}{
{"alpha", "alpha"},
{"123", "123"},
{"with/slash", "with-slash"},
{"with:colon", "with-colon"},
{":many:invalid\\characters\\", "-many-invalid-characters-"},
}
for _, u := range uu {
assert.Equal(t, u.expected, view.SanitizeFilename(u.name))
}
}
// ----------------------------------------------------------------------------
// Helpers...