Skip to content

Commit

Permalink
Wrap file closer jfrog/closer
Browse files Browse the repository at this point in the history
Wrap file closer
  • Loading branch information
sverdlov93 authored Mar 3, 2024
2 parents 041a424 + 4077a01 commit 5aef0ea
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 3 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/analysis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout Source
uses: actions/checkout@v3
uses: actions/checkout@v4

- name: Install Go
uses: actions/setup-go@v3
Expand All @@ -29,7 +29,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout Source
uses: actions/checkout@v3
uses: actions/checkout@v4

- name: Install Go
uses: actions/setup-go@v3
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ jobs:
uses: actions/checkout@v4

- name: Go Cache
uses: actions/cache@v3
uses: actions/cache@v4
with:
path: ~/go/pkg/mod
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
Expand Down
8 changes: 8 additions & 0 deletions io/fileutils.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
cr "crypto/rand"
"errors"
"fmt"
"io"
"math/rand"
"os"
"path/filepath"
Expand Down Expand Up @@ -236,3 +237,10 @@ func GetFileInfo(path string, followSymlink bool) (fileInfo os.FileInfo, err err
// We should not do CheckError here, because the error is checked by the calling functions.
return fileInfo, 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))
}
}
29 changes: 29 additions & 0 deletions io/fileutils_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package io

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

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

Close(f, &err)
assert.NoError(t, err)

// Try closing the same file again and expect error
Close(f, &err)
assert.Error(t, err)

// Check that both errors are aggregated
err = errors.New("original error")
Close(f, &err)
assert.Len(t, strings.Split(err.Error(), "\n"), 2)
}

0 comments on commit 5aef0ea

Please sign in to comment.