Skip to content

Commit

Permalink
fix: possible memory leak caused by defer
Browse files Browse the repository at this point in the history
  • Loading branch information
tnevrlka committed Feb 26, 2024
1 parent 22e96cb commit 84f95b1
Showing 1 changed file with 21 additions and 12 deletions.
33 changes: 21 additions & 12 deletions pkg/testspecs/ginkgosspec.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"
"io"
"os"
"path"
"path/filepath"
"reflect"
"strings"
Expand Down Expand Up @@ -186,21 +187,29 @@ func mergeTemplates(paths ...string) (*os.File, error) {
}
defer tempFile.Close()

for _, path := range paths {
tmplFile, err := os.Open(cwd + "/" + path)
if err != nil {
return nil, err
}
defer tmplFile.Close()
for _, templatePath := range paths {
// Avoid possible memory leak caused by defer by wrapping in a function
appendToTempPath := func() error {
tmplFile, err := os.Open(path.Clean(cwd + "/" + templatePath))
if err != nil {
return err
}
defer tmplFile.Close()

_, err = io.Copy(tempFile, tmplFile)
if err != nil {
return nil, err
}
_, err = io.Copy(tempFile, tmplFile)
if err != nil {
return err
}

_, err = tempFile.Write([]byte{'\n', '\n'})
_, err = tempFile.Write([]byte{'\n', '\n'})
if err != nil {
return err
}
return nil
}
err = appendToTempPath()
if err != nil {
return nil, err
return nil, fmt.Errorf("error during appending to temp templatePath: %+v", err)
}
}
return tempFile, nil
Expand Down

0 comments on commit 84f95b1

Please sign in to comment.