diff --git a/files/paths.go b/files/paths.go index 9ebe407..dbd3bf4 100644 --- a/files/paths.go +++ b/files/paths.go @@ -68,7 +68,8 @@ func Grep(regex *regexp.Regexp, glob string) (bool, error) { return false, nil } -// Return the relative path you would have to take to get from basePath to path +// GetPathRelativeTo returns the relative path you would have to take to get from basePath to path. If either path +// or basePath are symbolic links, they will be evaluated before the relative path between them is calculated. func GetPathRelativeTo(path string, basePath string) (string, error) { if path == "" { path = "." @@ -77,12 +78,22 @@ func GetPathRelativeTo(path string, basePath string) (string, error) { basePath = "." } - inputFolderAbs, err := filepath.Abs(basePath) + basePathEvaluated, err := filepath.EvalSymlinks(basePath) if err != nil { return "", errors.WithStackTrace(err) } - fileAbs, err := filepath.Abs(path) + inputFolderAbs, err := filepath.Abs(basePathEvaluated) + if err != nil { + return "", errors.WithStackTrace(err) + } + + pathEvaluated, err := filepath.EvalSymlinks(path) + if err != nil { + return "", errors.WithStackTrace(err) + } + + fileAbs, err := filepath.Abs(pathEvaluated) if err != nil { return "", errors.WithStackTrace(err) } diff --git a/files/paths_test.go b/files/paths_test.go index 16e384b..fdae385 100644 --- a/files/paths_test.go +++ b/files/paths_test.go @@ -1,6 +1,7 @@ package files import ( + "path/filepath" "regexp" "testing" @@ -27,8 +28,12 @@ func TestGetPathRelativeTo(t *testing.T) { {"/root", "/other-root/sub-child/sub-sub-child", "../../../root"}, } + fixtureRoot := "../fixtures/files" + for _, testCase := range testCases { - actual, err := GetPathRelativeTo(testCase.path, testCase.basePath) + path := filepath.Join(fixtureRoot, testCase.path) + basePath := filepath.Join(fixtureRoot, testCase.basePath) + actual, err := GetPathRelativeTo(path, basePath) assert.Nil(t, err, "Unexpected error for path %s and basePath %s: %v", testCase.path, testCase.basePath, err) assert.Equal(t, testCase.expected, actual, "For path %s and basePath %s", testCase.path, testCase.basePath) } diff --git a/fixtures/files/child/.gitkeep b/fixtures/files/child/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/fixtures/files/other-root/sub-child/sub-sub-child/.gitkeep b/fixtures/files/other-root/sub-child/sub-sub-child/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/fixtures/files/root/child/sub-child/sub-sub-child/.gitkeep b/fixtures/files/root/child/sub-child/sub-sub-child/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/fixtures/files/root/other-child/sub-child/.gitkeep b/fixtures/files/root/other-child/sub-child/.gitkeep new file mode 100644 index 0000000..e69de29