Skip to content

Commit e892273

Browse files
authored
chore: defer file closes (#1180)
## What? Replaced manual `Close()` calls on every error path in the binary copy block of `runUpdateCLI` with `defer`, and report close errors on `out` via the named return value. ## Why? The previous manual `Close()` calls on every return path were fragile and silently discarded flush errors on `out`. Closes #1056
1 parent 6780894 commit e892273

1 file changed

Lines changed: 12 additions & 8 deletions

File tree

main.go

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3371,7 +3371,7 @@ func isFlagSet(fs *flag.FlagSet, name string) bool {
33713371
return found
33723372
}
33733373

3374-
func runUpdateCLI() error {
3374+
func runUpdateCLI() (err error) {
33753375
const api = "https://api.github.com/repos/floatpane/matcha/releases/latest"
33763376
resp, err := httpClient.Get(api)
33773377
if err != nil {
@@ -3638,18 +3638,22 @@ func runUpdateCLI() error {
36383638
if err != nil {
36393639
return fmt.Errorf("could not open new binary: %w", err)
36403640
}
3641+
defer in.Close()
36413642
out, err := os.OpenFile(tmpNew, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0755)
36423643
if err != nil {
3643-
in.Close()
36443644
return fmt.Errorf("could not create temp binary in target dir: %w", err)
36453645
}
3646-
if _, err := io.Copy(out, in); err != nil {
3647-
in.Close()
3648-
out.Close()
3646+
3647+
defer func() {
3648+
cerr := out.Close()
3649+
if err == nil && cerr != nil {
3650+
err = fmt.Errorf("could not flush new binary to disk: %w", cerr)
3651+
}
3652+
}()
3653+
3654+
if _, err = io.Copy(out, in); err != nil {
36493655
return fmt.Errorf("could not write new binary to disk: %w", err)
36503656
}
3651-
in.Close()
3652-
out.Close()
36533657

36543658
// On Windows, a running executable cannot be overwritten directly.
36553659
// Move the old binary out of the way first, then rename the new one in.
@@ -3661,7 +3665,7 @@ func runUpdateCLI() error {
36613665
}
36623666
}
36633667

3664-
if err := os.Rename(tmpNew, execPath); err != nil {
3668+
if err = os.Rename(tmpNew, execPath); err != nil {
36653669
return fmt.Errorf("could not replace executable: %w", err)
36663670
}
36673671

0 commit comments

Comments
 (0)