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

View File

@ -3,9 +3,11 @@ package git
import ( import (
"os" "os"
"path/filepath" "path/filepath"
"strings"
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestRecusiveListFile(t *testing.T) { func TestRecusiveListFile(t *testing.T) {
@ -55,3 +57,24 @@ func TestRecusiveListFile(t *testing.T) {
assert.Contains(t, fileNames, "databricks.yml") assert.Contains(t, fileNames, "databricks.yml")
assert.Contains(t, fileNames, "a/b/c/hello.txt") 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)
}