From ae6b7e6d28463389cc4d84696e897fbd679033f8 Mon Sep 17 00:00:00 2001 From: rsteube Date: Thu, 15 Aug 2024 12:54:03 +0200 Subject: [PATCH] context: abs - fix `~` --- context.go | 7 ++++++- context_test.go | 52 +++++++++++++++++++++++++++---------------------- 2 files changed, 35 insertions(+), 24 deletions(-) diff --git a/context.go b/context.go index b61b352ee..80c58ba5d 100644 --- a/context.go +++ b/context.go @@ -114,7 +114,12 @@ func expandHome(s string) (string, error) { return "", err } home = filepath.ToSlash(home) - s = strings.Replace(s, "~/", home+"/", 1) + switch s { + case "~": + s = home + default: + s = strings.Replace(s, "~/", home+"/", 1) + } } return s, nil } diff --git a/context_test.go b/context_test.go index 5fa710ce3..397b8e2fb 100644 --- a/context_test.go +++ b/context_test.go @@ -31,33 +31,39 @@ func parent(s string) string { } func TestContextAbs(t *testing.T) { - tests := append([]string{}, - "/", "file", "/file", - "", "file", wd("file"), - "", "../", parent(""), - "", "../file", parent("file"), - "", "~/file", home("file"), - "/", "~/file", home("file"), - "/", "file", "/file", - "/dir", "file", "/dir/file", - "/dir", "./.file", "/dir/.file", - "", "/dir/", "/dir/", - "/dir/", "", "/dir/", - "~/", "file", home("file"), - "", "/", "/", - "", ".hidden", wd(".hidden"), - "", "./", wd("")+"/", - "", "", wd("")+"/", - "", ".", wd("")+"/"+".", - ) + testCases := []struct { + Dir string + Path string + Expected string + }{ + {"/", "file", "/file"}, + {"", "file", wd("file")}, + {"", "../", parent("")}, + {"", "../file", parent("file")}, + {"", "~/file", home("file")}, + {"/", "~/file", home("file")}, + {"/", "file", "/file"}, + {"/dir", "file", "/dir/file"}, + {"/dir", "./.file", "/dir/.file"}, + {"", "/dir/", "/dir/"}, + {"/dir/", "", "/dir/"}, + {"~/", "file", home("file")}, + {"", "/", "/"}, + {"", ".hidden", wd(".hidden")}, + {"", "./", wd("") + "/"}, + {"", "", wd("") + "/"}, + {"", ".", wd("") + "/" + "."}, + {"", "~", home("")}, + {"", "~/file", home("file")}, + } - for index := 0; index < len(tests); index += 3 { - actual, err := Context{Dir: tests[index]}.Abs(tests[index+1]) + for _, tc := range testCases { + actual, err := Context{Dir: tc.Dir}.Abs(tc.Path) if err != nil { t.Error(err.Error()) } - if expected := tests[index+2]; expected != actual { - t.Errorf("context: '%v' arg: '%v' expected: '%v' was: '%v'", tests[index], tests[index+1], expected, actual) + if tc.Expected != actual { + t.Errorf("context: '%v' arg: '%v' expected: '%v' was: '%v'", tc.Dir, tc.Path, tc.Expected, actual) } } }