From 556c9e78405cd92c23eefb084069c72f488cfcf2 Mon Sep 17 00:00:00 2001 From: Ivan Milchev Date: Thu, 12 Dec 2024 11:45:02 +0200 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20fix=20find=20files=20for=20tar?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Ivan Milchev --- providers/os/connection/tar/fs.go | 20 +++++++++++++++++++- providers/os/fs/fs.go | 3 +++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/providers/os/connection/tar/fs.go b/providers/os/connection/tar/fs.go index 323f3ae920..5eb4acae96 100644 --- a/providers/os/connection/tar/fs.go +++ b/providers/os/connection/tar/fs.go @@ -16,9 +16,12 @@ import ( "github.com/rs/zerolog/log" "github.com/spf13/afero" + "go.mondoo.com/cnquery/v11/providers/os/connection/shared" "go.mondoo.com/cnquery/v11/providers/os/fsutil" ) +var _ shared.FileSearch = (*FS)(nil) + func NewFs(source string) *FS { return &FS{ Source: source, @@ -192,7 +195,7 @@ func (fs *FS) tar(path string, header *tar.Header) (io.ReadCloser, error) { // searches for files and returns the file info // regex can be nil -func (fs *FS) Find(from string, r *regexp.Regexp, typ string) ([]string, error) { +func (fs *FS) Find(from string, r *regexp.Regexp, typ string, perm *uint32, depth *int) ([]string, error) { list := []string{} for k := range fs.FileMap { p := strings.HasPrefix(k, from) @@ -200,6 +203,9 @@ func (fs *FS) Find(from string, r *regexp.Regexp, typ string) ([]string, error) if r != nil { m = r.MatchString(k) } + if !depthMatch(from, k, depth) { + continue + } log.Trace().Str("path", k).Str("from", from).Str("prefix", from).Bool("prefix", p).Bool("m", m).Msg("check if matches") if p && m { entry := fs.FileMap[k] @@ -212,3 +218,15 @@ func (fs *FS) Find(from string, r *regexp.Regexp, typ string) ([]string, error) } return list, nil } + +func depthMatch(from, filepath string, depth *int) bool { + if depth == nil { + return true + } + + trimmed := strings.TrimPrefix(filepath, from) + // WalkDir always uses slash for separating, ignoring the OS separator. This is why we need to replace it. + normalized := strings.ReplaceAll(trimmed, string(os.PathSeparator), "/") + fileDepth := strings.Count(normalized, "/") + return fileDepth <= *depth +} diff --git a/providers/os/fs/fs.go b/providers/os/fs/fs.go index e9dd5891f2..41cd45a566 100644 --- a/providers/os/fs/fs.go +++ b/providers/os/fs/fs.go @@ -11,8 +11,11 @@ import ( "time" "github.com/spf13/afero" + "go.mondoo.com/cnquery/v11/providers/os/connection/shared" ) +var _ shared.FileSearch = (*MountedFs)(nil) + var notSupported = errors.New("not supported") type MountedFs struct {