From 2feacb6a3a41b19c720d59533eada56a46a46e69 Mon Sep 17 00:00:00 2001 From: Wittano Date: Mon, 12 Feb 2024 21:02:43 +0100 Subject: [PATCH] fix(path): added replacing tidal char by home directory path --- path/path.go | 18 ++++++++++++++++++ path/path_test.go | 11 +++++++++++ 2 files changed, 29 insertions(+) diff --git a/path/path.go b/path/path.go index d481b70..70be961 100644 --- a/path/path.go +++ b/path/path.go @@ -1,8 +1,10 @@ package path import ( + "github.com/mitchellh/go-homedir" "os" "path/filepath" + "regexp" "strings" ) @@ -37,6 +39,8 @@ func PathsFromPattern(src string) ([]string, error) { } func ReplaceEnvVariablesInPath(src string) string { + src = replaceTildeInPath(src) + sep := string(filepath.Separator) parts := strings.Split(src, sep) @@ -49,6 +53,20 @@ func ReplaceEnvVariablesInPath(src string) string { return strings.Join(parts, sep) } +func replaceTildeInPath(src string) string { + regex := regexp.MustCompile("^~*") + if regex.MatchString(src) { + home, err := homedir.Dir() + if err != nil { + home = os.Getenv("HOME") + } + + return strings.ReplaceAll(src, "~", home) + } + + return src +} + func PathsFromPatternRecursive(path string) ([]string, error) { path = ReplaceEnvVariablesInPath(path) diff --git a/path/path_test.go b/path/path_test.go index 96c25e1..5f072ba 100644 --- a/path/path_test.go +++ b/path/path_test.go @@ -1,6 +1,7 @@ package path import ( + "fmt" "github.com/wittano/filebot/internal/test" "os" "path/filepath" @@ -32,6 +33,16 @@ func TestPathsFromRegexWithEnvVariable(t *testing.T) { } } +func TestReplaceTildaInPath(t *testing.T) { + testPath := "~/test" + exp := fmt.Sprintf("%s/test", os.Getenv("HOME")) + + res := replaceTildeInPath(testPath) + if res != exp { + t.Fatalf("Failed replace tilde char by absolute HOME directory path. Result: %s", res) + } +} + func TestPathsFromRegexButRegexStartFromStar(t *testing.T) { p := test.CreateTempFile(t) exp := strings.Replace(p, "test", "*est", 1)