Fix relative path derivation if root path can be cleaned (#64)

This commit is contained in:
Pieter Noordhuis 2022-09-16 15:13:49 +02:00 committed by GitHub
parent a7701cc8f3
commit ec6c58f1d1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 29 additions and 3 deletions

View File

@ -4,7 +4,7 @@ import (
"fmt"
"io/fs"
"os"
"path"
"path/filepath"
"strings"
"time"
@ -104,8 +104,11 @@ func readDir(dir, root string) (queue []File, err error) {
return
}
for _, v := range dirs {
absolute := path.Join(dir, v.Name())
relative := strings.TrimLeft(strings.Replace(absolute, root, "", 1), "/")
absolute := filepath.Join(dir, v.Name())
relative, err := filepath.Rel(root, absolute)
if err != nil {
return nil, err
}
queue = append(queue, File{v, absolute, relative})
}
return

View File

@ -3,9 +3,11 @@ package git
import (
"os"
"path/filepath"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestRecusiveListFile(t *testing.T) {
@ -55,3 +57,24 @@ func TestRecusiveListFile(t *testing.T) {
assert.Contains(t, fileNames, "databricks.yml")
assert.Contains(t, fileNames, "a/b/c/hello.txt")
}
func TestFileSetNonCleanRoot(t *testing.T) {
// Test what happens if the root directory can be simplified.
// Path simplification is done by most filepath functions.
root := "./../git"
require.NotEqual(t, root, filepath.Clean(root))
fs := NewFileSet(root)
files, err := fs.All()
require.NoError(t, err)
found := false
for _, f := range files {
if strings.Contains(f.Relative, "fileset_test") {
assert.Equal(t, "fileset_test.go", f.Relative)
assert.Equal(t, "../git/fileset_test.go", f.Absolute)
found = true
}
}
assert.True(t, found)
}