Skip to content

Commit

Permalink
Port a bug fix for GetPathRelativeTo over from Terragrunt (#76)
Browse files Browse the repository at this point in the history
Original bug fix: gruntwork-io/terragrunt#100
  • Loading branch information
infraredgirl authored Oct 24, 2022
1 parent b3539bc commit 107014b
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 8 deletions.
16 changes: 12 additions & 4 deletions files/paths.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
package files

import (
"io/ioutil"
"path/filepath"
"regexp"
"io/ioutil"
"github.com/gruntwork-io/go-commons/errors"

"github.com/mattn/go-zglob"

"github.com/gruntwork-io/go-commons/errors"
)

// Return the canonical version of the given path, relative to the given base path. That is, if the given path is a
Expand Down Expand Up @@ -68,6 +70,13 @@ func Grep(regex *regexp.Regexp, glob string) (bool, error) {

// Return the relative path you would have to take to get from basePath to path
func GetPathRelativeTo(path string, basePath string) (string, error) {
if path == "" {
path = "."
}
if basePath == "" {
basePath = "."
}

inputFolderAbs, err := filepath.Abs(basePath)
if err != nil {
return "", errors.WithStackTrace(err)
Expand All @@ -83,6 +92,5 @@ func GetPathRelativeTo(path string, basePath string) (string, error) {
return "", errors.WithStackTrace(err)
}

return relPath, nil
return filepath.ToSlash(relPath), nil
}

11 changes: 7 additions & 4 deletions files/paths_test.go
Original file line number Diff line number Diff line change
@@ -1,20 +1,23 @@
package files

import (
"regexp"
"testing"

"github.com/stretchr/testify/assert"
"regexp"
)

func TestGetPathRelativeTo(t *testing.T) {
t.Parallel()

testCases := []struct {
path string
path string
basePath string
expected string
}{
{"", "", "."},
{"", "./child", ".."},
{"./child", "", "child"},
{"/root", "/root", "."},
{"/root", "/root/child", ".."},
{"/root", "/root/child/sub-child/sub-sub-child", "../../.."},
Expand All @@ -35,7 +38,7 @@ func TestCanonicalPath(t *testing.T) {
t.Parallel()

testCases := []struct {
path string
path string
basePath string
expected string
}{
Expand Down Expand Up @@ -97,4 +100,4 @@ func TestGrepDoesNotFindInvalidText(t *testing.T) {
found, err := Grep(regex, "../fixtures/files/**/*")
assert.Nil(t, err, "Unexpected error: %v", err)
assert.False(t, found)
}
}

0 comments on commit 107014b

Please sign in to comment.