Skip to content

Commit 322330f

Browse files
committed
Fail upgrade tool on download and write errors
1 parent 0cfec60 commit 322330f

1 file changed

Lines changed: 24 additions & 16 deletions

File tree

upgrade/upgrade.go

Lines changed: 24 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,9 @@ func download(prefix string) (url string, content []byte, err error) {
2626
return "", nil, err
2727
}
2828
defer resp.Body.Close()
29+
if resp.StatusCode != http.StatusOK {
30+
return "", nil, fmt.Errorf("downloading download.html: %s", resp.Status)
31+
}
2932

3033
b, err := ioutil.ReadAll(resp.Body)
3134
if err != nil {
@@ -60,10 +63,13 @@ func download(prefix string) (url string, content []byte, err error) {
6063
if err != nil {
6164
return "", nil, err
6265
}
66+
defer resp.Body.Close()
67+
if resp.StatusCode != http.StatusOK {
68+
return "", nil, fmt.Errorf("downloading %s: %s", url, resp.Status)
69+
}
6370

6471
// Ready Body Content
6572
content, err = ioutil.ReadAll(resp.Body)
66-
defer resp.Body.Close()
6773
if err != nil {
6874
return "", nil, err
6975
}
@@ -72,17 +78,6 @@ func download(prefix string) (url string, content []byte, err error) {
7278
}
7379

7480
func mergeFile(src string, dst string) error {
75-
defer func() error {
76-
fmt.Printf("Removing: %s\n", src)
77-
err := os.Remove(src)
78-
79-
if err != nil {
80-
return err
81-
}
82-
83-
return nil
84-
}()
85-
8681
// Open destination
8782
fdst, err := os.OpenFile(dst, os.O_APPEND|os.O_WRONLY, 0666)
8883
if err != nil {
@@ -106,7 +101,9 @@ func mergeFile(src string, dst string) error {
106101
return err
107102
}
108103

109-
return nil
104+
// Only remove the source once it has been merged successfully.
105+
fmt.Printf("Removing: %s\n", src)
106+
return os.Remove(src)
110107
}
111108

112109
func main() {
@@ -170,6 +167,7 @@ func main() {
170167
log.Fatal(err)
171168
}
172169
scanner := bufio.NewScanner(zr)
170+
var werr error
173171
for scanner.Scan() {
174172
text := scanner.Text()
175173
if text == `#include "sqlite3.h"` {
@@ -179,11 +177,19 @@ func main() {
179177
#endif
180178
`
181179
}
182-
_, err = fmt.Fprintln(f, text)
183-
if err != nil {
180+
_, werr = fmt.Fprintln(f, text)
181+
if werr != nil {
184182
break
185183
}
186184
}
185+
// A write failure must not be masked by scanner.Err(), which
186+
// reports nil in that case; either way a truncated output file
187+
// must never be reported as successfully extracted.
188+
if werr != nil {
189+
zr.Close()
190+
f.Close()
191+
log.Fatal(werr)
192+
}
187193
err = scanner.Err()
188194
if err != nil {
189195
zr.Close()
@@ -197,7 +203,9 @@ func main() {
197203
log.Fatal(err)
198204
}
199205
zr.Close()
200-
f.Close()
206+
if err := f.Close(); err != nil {
207+
log.Fatal(err)
208+
}
201209
fmt.Printf("Extracted: %v\n", filepath.Base(f.Name()))
202210
}
203211

0 commit comments

Comments
 (0)