Skip to content

Commit

Permalink
Fix io.Close() nil error parameter
Browse files Browse the repository at this point in the history
  • Loading branch information
omerzi committed Mar 4, 2024
1 parent 4077a01 commit 10db98f
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 6 deletions.
12 changes: 10 additions & 2 deletions io/fileutils.go
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,15 @@ func GetFileInfo(path string, followSymlink bool) (fileInfo os.FileInfo, err err

// Close the reader/writer and append the error to the given error.
func Close(closer io.Closer, err *error) {
if closeErr := closer.Close(); closeErr != nil {
*err = errors.Join(*err, fmt.Errorf("failed to close %T: %w", closer, closeErr))
var closeErr error
if closeErr = closer.Close(); closeErr == nil {
return
}
closeErr = fmt.Errorf("failed to close %T: %w", closer, closeErr)
if err == nil {
err = &closeErr

Check failure on line 249 in io/fileutils.go

View workflow job for this annotation

GitHub Actions / Static-Check

ineffectual assignment to err (ineffassign)

Check failure on line 249 in io/fileutils.go

View workflow job for this annotation

GitHub Actions / Static-Check

ineffectual assignment to err (ineffassign)
return
}
*err = errors.Join(*err, closeErr)
return

Check failure on line 253 in io/fileutils.go

View workflow job for this annotation

GitHub Actions / Static-Check

S1023: redundant `return` statement (gosimple)

Check failure on line 253 in io/fileutils.go

View workflow job for this annotation

GitHub Actions / Static-Check

S1023: redundant `return` statement (gosimple)
}
16 changes: 12 additions & 4 deletions io/fileutils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,17 @@ package io

import (
"errors"
"github.com/stretchr/testify/assert"
"os"
"path"
"path/filepath"
"strings"
"testing"

"github.com/stretchr/testify/assert"
)

func TestClose(t *testing.T) {
var err error
t.TempDir()
f, err := os.Create(path.Join(t.TempDir(), "test"))
f, err := os.Create(filepath.Join(t.TempDir(), "test"))
assert.NoError(t, err)

Close(f, &err)
Expand All @@ -26,4 +26,12 @@ func TestClose(t *testing.T) {
err = errors.New("original error")
Close(f, &err)
assert.Len(t, strings.Split(err.Error(), "\n"), 2)

nilErr := new(error)
Close(f, nilErr)
assert.NotNil(t, nilErr)
}

func getNilErr() error {

Check failure on line 35 in io/fileutils_test.go

View workflow job for this annotation

GitHub Actions / Static-Check

func `getNilErr` is unused (unused)

Check failure on line 35 in io/fileutils_test.go

View workflow job for this annotation

GitHub Actions / Static-Check

func `getNilErr` is unused (unused)
return nil
}

0 comments on commit 10db98f

Please sign in to comment.