Skip to content

Commit

Permalink
Improve error handling in temporary file operations for fonts and images
Browse files Browse the repository at this point in the history
  • Loading branch information
chrisreddington committed Nov 22, 2024
1 parent aab6589 commit ac554ae
Showing 1 changed file with 17 additions and 10 deletions.
27 changes: 17 additions & 10 deletions stl/geometry/assets.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package geometry

import (
"embed"
"fmt"
"os"

"github.com/github/gh-skyline/errors"
Expand All @@ -25,14 +26,17 @@ func writeTempFont(fontName string) (string, func(), error) {
}

if _, err := tmpFile.Write(fontBytes); err != nil {
tmpFile.Close()
os.Remove(tmpFile.Name())
return "", nil, errors.New(errors.IOError, "failed to write font to temp file", err)
closeErr := tmpFile.Close()
removeErr := os.Remove(tmpFile.Name())
return "", nil, errors.New(errors.IOError, "failed to write font to temp file", fmt.Errorf("%w; close error: %v; remove error: %v", err, closeErr, removeErr))
}
if err := tmpFile.Close(); err != nil {
removeErr := os.Remove(tmpFile.Name())
return "", nil, errors.New(errors.IOError, "failed to close temp font file", fmt.Errorf("%w; remove error: %v", err, removeErr))
}
tmpFile.Close()

cleanup := func() {
os.Remove(tmpFile.Name())
_ = os.Remove(tmpFile.Name()) // Ignore cleanup errors in defer
}

return tmpFile.Name(), cleanup, nil
Expand All @@ -52,14 +56,17 @@ func getEmbeddedImage() (string, func(), error) {
}

if _, err := tmpFile.Write(imgBytes); err != nil {
tmpFile.Close()
os.Remove(tmpFile.Name())
return "", nil, errors.New(errors.IOError, "failed to write image to temp file", err)
closeErr := tmpFile.Close()
removeErr := os.Remove(tmpFile.Name())
return "", nil, errors.New(errors.IOError, "failed to write image to temp file", fmt.Errorf("%w; close error: %v; remove error: %v", err, closeErr, removeErr))
}
if err := tmpFile.Close(); err != nil {
removeErr := os.Remove(tmpFile.Name())
return "", nil, errors.New(errors.IOError, "failed to close temp image file", fmt.Errorf("%w; remove error: %v", err, removeErr))
}
tmpFile.Close()

cleanup := func() {
os.Remove(tmpFile.Name())
_ = os.Remove(tmpFile.Name()) // Ignore cleanup errors in defer
}

return tmpFile.Name(), cleanup, nil
Expand Down

0 comments on commit ac554ae

Please sign in to comment.