diff --git a/pkg/action/scan.go b/pkg/action/scan.go index bba6e52b0..a328a3d73 100644 --- a/pkg/action/scan.go +++ b/pkg/action/scan.go @@ -497,6 +497,12 @@ 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 + 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" { @@ -511,10 +517,6 @@ func processArchive(ctx context.Context, c malcontent.Config, rfs []fs.FS, archi for _, extractedFilePath := range extractedPaths { fr, err := processFile(ctx, c, rfs, extractedFilePath, archivePath, tmpRoot, logger) if err != nil { - // Ensure we clean up the extracted file path after any error - if err := os.RemoveAll(extractedFilePath); err != nil { - logger.Errorf("remove %s: %v", tmpRoot, err) - } return nil, err } if fr != nil { @@ -522,10 +524,6 @@ func processArchive(ctx context.Context, c malcontent.Config, rfs []fs.FS, archi clean := strings.TrimPrefix(extractedFilePath, tmpRoot) frs.Store(clean, fr) } - // Clean up the extracted file path after processing - if err := os.RemoveAll(extractedFilePath); err != nil { - logger.Errorf("remove %s: %v", tmpRoot, err) - } } // Remove the temporary parent path after all files are processed to clean up any remaining files if err := os.RemoveAll(tmpRoot); err != nil {