diff --git a/internal/view/log.go b/internal/view/log.go index ac5107fe..8d8238ac 100644 --- a/internal/view/log.go +++ b/internal/view/log.go @@ -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,18 +288,24 @@ func (l *Log) SaveCmd(evt *tcell.EventKey) *tcell.EventKey { return nil } +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 } now := time.Now().UnixNano() - fName := fmt.Sprintf("%s-%d.log", strings.Replace(name, "/", "-", -1), now) + fName := fmt.Sprintf("%s-%d.log", sanitizeFilename(name), now) path := filepath.Join(dir, fName) mod := os.O_CREATE | os.O_WRONLY diff --git a/internal/view/table_helper.go b/internal/view/table_helper.go index 64d86469..8e18c48e 100644 --- a/internal/view/table_helper.go +++ b/internal/view/table_helper.go @@ -18,12 +18,12 @@ import ( func computeFilename(cluster, ns, title, path string) (string, error) { now := time.Now().UnixNano() - dir := filepath.Join(config.K9sDumpDir, cluster) + dir := filepath.Join(config.K9sDumpDir, sanitizeFilename(cluster)) if err := ensureDir(dir); err != nil { return "", err } - name := title + "-" + strings.Replace(path, "/", "-", -1) + name := title + "-" + sanitizeFilename(path) if path == "" { name = title } diff --git a/internal/view/yaml.go b/internal/view/yaml.go index 90ff4258..6831490d 100644 --- a/internal/view/yaml.go +++ b/internal/view/yaml.go @@ -61,13 +61,13 @@ func enableRegion(str string) string { } func saveYAML(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 } now := time.Now().UnixNano() - fName := fmt.Sprintf("%s-%d.yml", strings.Replace(name, "/", "-", -1), now) + fName := fmt.Sprintf("%s-%d.yml", sanitizeFilename(name), now) path := filepath.Join(dir, fName) mod := os.O_CREATE | os.O_WRONLY