Skip to content

Commit

Permalink
Make GetPathRelativeTo() resolve symbolic links (#78)
Browse files Browse the repository at this point in the history
  • Loading branch information
infraredgirl authored Oct 25, 2022
1 parent 31c33b7 commit 027003c
Show file tree
Hide file tree
Showing 6 changed files with 20 additions and 4 deletions.
17 changes: 14 additions & 3 deletions files/paths.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 = "."
Expand All @@ -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)
}
Expand Down
7 changes: 6 additions & 1 deletion files/paths_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package files

import (
"path/filepath"
"regexp"
"testing"

Expand All @@ -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)
}
Expand Down
Empty file added fixtures/files/child/.gitkeep
Empty file.
Empty file.
Empty file.
Empty file.

0 comments on commit 027003c

Please sign in to comment.