Skip to content

Commit

Permalink
Improve extracted archive file clean up (#714)
Browse files Browse the repository at this point in the history
* Improve extracted archive file clean up

Signed-off-by: egibs <20933572+egibs@users.noreply.github.com>

* Wrap tmpRoot removal in a defer instead

Signed-off-by: egibs <20933572+egibs@users.noreply.github.com>

* Only remove if tmpRoot is created successfully

Signed-off-by: egibs <20933572+egibs@users.noreply.github.com>

---------

Signed-off-by: egibs <20933572+egibs@users.noreply.github.com>
  • Loading branch information
egibs authored Dec 17, 2024
1 parent b5a589d commit e6d7f01
Showing 1 changed file with 10 additions and 5 deletions.
15 changes: 10 additions & 5 deletions pkg/action/scan.go
Original file line number Diff line number Diff line change
Expand Up @@ -497,6 +497,14 @@ func processArchive(ctx context.Context, c malcontent.Config, rfs []fs.FS, archi
if err != nil {
return nil, fmt.Errorf("extract to temp: %w", err)
}
// Ensure that tmpRoot is removed before returning if created successfully
if tmpRoot != "" {
defer func() {
if err := os.RemoveAll(tmpRoot); err != nil {
logger.Errorf("remove %s: %v", tmpRoot, err)
}
}()
}
// macOS will prefix temporary directories with `/private`
// update tmpRoot with this prefix to allow strings.TrimPrefix to work
if runtime.GOOS == "darwin" {
Expand All @@ -515,13 +523,10 @@ func processArchive(ctx context.Context, c malcontent.Config, rfs []fs.FS, archi
}
if fr != nil {
// Store a clean reprepsentation of the archive's scanned file to match single file scanning behavior
extractedFilePath = strings.TrimPrefix(extractedFilePath, tmpRoot)
frs.Store(extractedFilePath, fr)
clean := strings.TrimPrefix(extractedFilePath, tmpRoot)
frs.Store(clean, fr)
}
}
if err := os.RemoveAll(tmpRoot); err != nil {
logger.Errorf("remove %s: %v", tmpRoot, err)
}

return &frs, nil
}
Expand Down

0 comments on commit e6d7f01

Please sign in to comment.