Skip to content

Commit 107014b

Browse files
authored
Port a bug fix for GetPathRelativeTo over from Terragrunt (#76)
Original bug fix: gruntwork-io/terragrunt#100
1 parent b3539bc commit 107014b

File tree

2 files changed

+19
-8
lines changed

2 files changed

+19
-8
lines changed

files/paths.go

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
11
package files
22

33
import (
4+
"io/ioutil"
45
"path/filepath"
56
"regexp"
6-
"io/ioutil"
7-
"github.com/gruntwork-io/go-commons/errors"
7+
88
"github.com/mattn/go-zglob"
9+
10+
"github.com/gruntwork-io/go-commons/errors"
911
)
1012

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

6971
// Return the relative path you would have to take to get from basePath to path
7072
func GetPathRelativeTo(path string, basePath string) (string, error) {
73+
if path == "" {
74+
path = "."
75+
}
76+
if basePath == "" {
77+
basePath = "."
78+
}
79+
7180
inputFolderAbs, err := filepath.Abs(basePath)
7281
if err != nil {
7382
return "", errors.WithStackTrace(err)
@@ -83,6 +92,5 @@ func GetPathRelativeTo(path string, basePath string) (string, error) {
8392
return "", errors.WithStackTrace(err)
8493
}
8594

86-
return relPath, nil
95+
return filepath.ToSlash(relPath), nil
8796
}
88-

files/paths_test.go

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,23 @@
11
package files
22

33
import (
4+
"regexp"
45
"testing"
6+
57
"github.com/stretchr/testify/assert"
6-
"regexp"
78
)
89

910
func TestGetPathRelativeTo(t *testing.T) {
1011
t.Parallel()
1112

1213
testCases := []struct {
13-
path string
14+
path string
1415
basePath string
1516
expected string
1617
}{
1718
{"", "", "."},
19+
{"", "./child", ".."},
20+
{"./child", "", "child"},
1821
{"/root", "/root", "."},
1922
{"/root", "/root/child", ".."},
2023
{"/root", "/root/child/sub-child/sub-sub-child", "../../.."},
@@ -35,7 +38,7 @@ func TestCanonicalPath(t *testing.T) {
3538
t.Parallel()
3639

3740
testCases := []struct {
38-
path string
41+
path string
3942
basePath string
4043
expected string
4144
}{
@@ -97,4 +100,4 @@ func TestGrepDoesNotFindInvalidText(t *testing.T) {
97100
found, err := Grep(regex, "../fixtures/files/**/*")
98101
assert.Nil(t, err, "Unexpected error: %v", err)
99102
assert.False(t, found)
100-
}
103+
}

0 commit comments

Comments
 (0)