From 7ede0dee72fde84ad88a42b40962a2f7692ab9c9 Mon Sep 17 00:00:00 2001 From: Timmy Welch Date: Thu, 31 Oct 2024 21:12:53 -0500 Subject: [PATCH] Fix file closing --- cmd/comic-hasher/main.go | 11 ++++++++--- cv/cv.go | 7 +++++-- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/cmd/comic-hasher/main.go b/cmd/comic-hasher/main.go index 21dff6d..511cca3 100644 --- a/cmd/comic-hasher/main.go +++ b/cmd/comic-hasher/main.go @@ -538,10 +538,10 @@ func (s *Server) reader(workerID int, done func(i int)) { panic(err) } i, format, err := image.Decode(bufio.NewReader(file)) + file.Close() if err != nil { continue // skip this image } - file.Close() im := ch.Im{ Im: i, @@ -759,16 +759,21 @@ func downloadProcessor(opts Opts, imagePaths chan cv.Download, server Server) { continue } - file, err := os.Open(path.Dest) + file, err := os.OpenFile(path.Dest, os.O_RDWR|os.O_CREATE, 0666) if err != nil { panic(err) } i, format, err := image.Decode(bufio.NewReader(file)) if err != nil { + file.Close() continue // skip this image } if opts.truncateHashedImages { - file.Truncate(0) + file.Seek(0, io.SeekStart) + err = file.Truncate(0) + if err != nil { + log.Printf("Failed to truncate %#v: %v", path.Dest, err) + } } file.Close() diff --git a/cv/cv.go b/cv/cv.go index 5f2cf46..2e56d80 100644 --- a/cv/cv.go +++ b/cv/cv.go @@ -272,6 +272,7 @@ func (c *CVDownloader) updateIssues() { } resp, err, cancelDownloadCTX := Get(c.Context, URI.String()) if err != nil { + _ = resp.Body.Close() cancelDownloadCTX() if retry(URI.String(), err) { continue @@ -281,11 +282,13 @@ func (c *CVDownloader) updateIssues() { if resp.StatusCode != 200 { cancelDownloadCTX() if retry(URI.String(), nil) { + _ = resp.Body.Close() continue } log.Println("Failed to download this page, we'll wait for an hour to see if it clears up") select { case <-c.Context.Done(): // allows us to return immediately even during a timeout + _ = resp.Body.Close() return case <-time.After(1 * time.Hour): } @@ -296,6 +299,8 @@ func (c *CVDownloader) updateIssues() { } body := io.TeeReader(resp.Body, file) err = json.NewDecoder(bufio.NewReader(body)).Decode(issue) + _ = resp.Body.Close() + _ = file.Close() if err != nil || issue.Offset != offset { os.Remove(filepath.Join(c.JSONPath, "cv-"+strconv.Itoa(offset)+".json")) cancelDownloadCTX() @@ -304,8 +309,6 @@ func (c *CVDownloader) updateIssues() { } return } - _ = resp.Body.Close() - _ = file.Close() cancelDownloadCTX() if issue.NumberOfTotalResults > c.totalResults { c.totalResults = issue.NumberOfTotalResults