manifest: handle "close()" errors in sbomWriter()
This commit adds error handling for the `f.Close()` errors when
we write the SBOM. Errors on close for RW fds are rare but we
should handle them so we return the result of `f.Close()` now
when returning in sbomWriter(). We still keep the `defer f.Close()`
to ensure we do not leak file descriptors when e.g. `io.Copy()`
fails. In the "happy" case f is closed without an error and
then the defer f.Close() runs and will error with "ErrClosed"
but we can ignore that.
An alternative implementaiton might be:
```golang
func sbomWriter(outputDir, filename string, content io.Reader) (err error) {
...
f, err := os.Create(p)
if err != nil {
return err
}
defer func() { err = errors.Join(err, f.Close()) }()
...
return nil
}
```
no super strong opinion here.
Thanks to Flo for finding this issues!
This commit is contained in:
parent
1a2f4be378
commit
c829e60649
1 changed files with 3 additions and 1 deletions
|
|
@ -41,11 +41,13 @@ func sbomWriter(outputDir, filename string, content io.Reader) error {
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
// ensure we do not leak FDs if the function returns prematurely
|
||||||
defer f.Close()
|
defer f.Close()
|
||||||
|
|
||||||
if _, err := io.Copy(f, content); err != nil {
|
if _, err := io.Copy(f, content); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
return nil
|
return f.Close()
|
||||||
}
|
}
|
||||||
|
|
||||||
// used in tests
|
// used in tests
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue