proper file close operation based on feedback

Signed-off-by: Tom Huang <tom.huang@weave.works>
This commit is contained in:
Tom Huang 2022-01-11 15:50:25 -05:00
parent 8868d3938a
commit 5bb428349e
No known key found for this signature in database
GPG Key ID: 24C64FFFA6358BB7
2 changed files with 17 additions and 14 deletions

View File

@ -355,10 +355,13 @@ func (s *Storage) CopyFromPath(artifact *sourcev1.Artifact, path string) (err er
if err != nil { if err != nil {
return err return err
} }
if err = s.Copy(artifact, f); err != nil { defer func() {
return err if cerr := f.Close(); cerr != nil && err == nil {
} err = cerr
return f.Close() }
}()
err = s.Copy(artifact, f)
return err
} }
// CopyToPath copies the contents in the (sub)path of the given artifact to the given path. // CopyToPath copies the contents in the (sub)path of the given artifact to the given path.

View File

@ -303,21 +303,21 @@ func TestStorageCopyFromPath(t *testing.T) {
return return
} }
matchFile := func(t *testing.T, storage *Storage, artifact sourcev1.Artifact, file *File, wantErr bool) { matchFile := func(t *testing.T, storage *Storage, artifact sourcev1.Artifact, file *File, expectMismatch bool) {
c, err := os.ReadFile(storage.LocalPath(artifact)) c, err := os.ReadFile(storage.LocalPath(artifact))
if err != nil { if err != nil {
t.Fatalf("failed reading file: %v", err) t.Fatalf("failed reading file: %v", err)
} }
if (string(c) != string(file.Content)) != wantErr { if (string(c) != string(file.Content)) != expectMismatch {
t.Errorf("artifact content does not match, got: %q, want: %q", string(c), string(file.Content)) t.Errorf("artifact content does not match and not expecting mismatch, got: %q, want: %q", string(c), string(file.Content))
} }
} }
tests := []struct { tests := []struct {
name string name string
file *File file *File
want *File want *File
wantErr bool expectMismatch bool
}{ }{
{ {
name: "content match", name: "content match",
@ -338,9 +338,9 @@ func TestStorageCopyFromPath(t *testing.T) {
}, },
want: &File{ want: &File{
Name: "manifest.yaml", Name: "manifest.yaml",
Content: []byte(`bad contents`), Content: []byte(`mismatch contents`),
}, },
wantErr: true, expectMismatch: true,
}, },
} }
for _, tt := range tests { for _, tt := range tests {
@ -360,7 +360,7 @@ func TestStorageCopyFromPath(t *testing.T) {
if err := storage.CopyFromPath(&artifact, absPath); err != nil { if err := storage.CopyFromPath(&artifact, absPath); err != nil {
t.Errorf("CopyFromPath() error = %v", err) t.Errorf("CopyFromPath() error = %v", err)
} }
matchFile(t, storage, artifact, tt.want, tt.wantErr) matchFile(t, storage, artifact, tt.want, tt.expectMismatch)
}) })
} }
} }