Remove Chdir from util.FindFiles

Signed-off-by: Jonathon Anderson <janderson@ciq.com>
This commit is contained in:
Jonathon Anderson
2024-12-19 23:34:50 -07:00
parent e64396cfab
commit b0164c36b9
7 changed files with 68 additions and 41 deletions

View File

@@ -18,10 +18,6 @@ import (
"github.com/warewulf/warewulf/internal/pkg/wwlog"
)
func BoolP(p *bool) bool {
return p != nil && *p
}
func FirstError(errs ...error) (err error) {
for _, e := range errs {
if err == nil {
@@ -136,37 +132,40 @@ func ValidString(pattern string, expr string) bool {
return false
}
// ******************************************************************************
func FindFiles(path string) []string {
var ret []string
wwlog.Debug("Changing directory to FindFiles path: %s", path)
err := os.Chdir(path)
if err != nil {
wwlog.Warn("Could not chdir() to: %s", path)
return ret
}
wwlog.Debug("Finding files in path: %s", path)
err = filepath.Walk(".", func(location string, info os.FileInfo, err error) error {
err := filepath.Walk(path, func(location string, info os.FileInfo, err error) error {
if err != nil {
wwlog.Warn("Error walking path %s: %v", location, err)
return err
}
if location == "." {
// Get the relative path from the base directory
relPath, relErr := filepath.Rel(path, location)
if relErr != nil {
wwlog.Warn("Error computing relative path for %s: %v", location, relErr)
return relErr
}
if relPath == "." {
return nil
}
if IsDir(location) {
wwlog.Debug("FindFiles() found directory: %s", location)
ret = append(ret, location+"/")
if info.IsDir() {
wwlog.Debug("FindFiles() found directory: %s", relPath)
ret = append(ret, relPath+"/")
} else {
wwlog.Debug("FindFiles() found file: %s", location)
ret = append(ret, location)
wwlog.Debug("FindFiles() found file: %s", relPath)
ret = append(ret, relPath)
}
return nil
})
if err != nil {
wwlog.Warn("Error during file walk: %v", err)
return ret
}

View File

@@ -8,6 +8,7 @@ import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/warewulf/warewulf/internal/pkg/testenv"
"github.com/warewulf/warewulf/internal/pkg/wwlog"
)
@@ -19,6 +20,40 @@ func TryCreatePath(t *testing.T, elem ...string) {
}
}
func Test_FindFiles(t *testing.T) {
var tests = map[string]struct {
createFiles []string
findFiles []string
}{
"no files": {
createFiles: []string{},
findFiles: nil,
},
"single file": {
createFiles: []string{"testfile"},
findFiles: []string{"testfile"},
},
"nested file": {
createFiles: []string{"testdir/testfile"},
findFiles: []string{"testdir/", "testdir/testfile"},
},
}
for name, tt := range tests {
t.Run(name, func(t *testing.T) {
env := testenv.New(t)
defer env.RemoveAll(t)
env.MkdirAll(t, "/test")
for _, file_ := range tt.createFiles {
env.CreateFile(t, filepath.Join("/test", file_))
}
files := FindFiles(env.GetPath("/test"))
assert.Equal(t, tt.findFiles, files)
})
}
}
func Test_FindFilterFiles(t *testing.T) {
wwlog.SetLogLevel(wwlog.DEBUG)
dir, err := os.MkdirTemp(os.TempDir(), "warewulf-test")