Commit 73497c76 authored by Robert Griesemer's avatar Robert Griesemer

cmd/gofmt: don't leave tmp file if -w failed

Follow-up on https://golang.org/cl/33018.

For #8984.

Change-Id: I6655a5537a60d4ea3ee13029a56a75b150f8c8f8
Reviewed-on: https://go-review.googlesource.com/33020Reviewed-by: 's avatarBrad Fitzpatrick <bradfitz@golang.org>
parent b188b4cc
......@@ -243,15 +243,17 @@ func diff(b1, b2 []byte) (data []byte, err error) {
// implemented.
func writeFile(filename string, data []byte, perm os.FileMode) error {
// open temp file
f, err := ioutil.TempFile(filepath.Dir(filename), "tmp")
f, err := ioutil.TempFile(filepath.Dir(filename), "gofmt-")
if err != nil {
return err
}
tmpname := f.Name()
err = f.Chmod(perm)
if err != nil {
f.Close()
os.Remove(tmpname)
return err
}
tmpname := f.Name()
// write data to temp file
n, err := f.Write(data)
......@@ -261,9 +263,12 @@ func writeFile(filename string, data []byte, perm os.FileMode) error {
if err1 := f.Close(); err == nil {
err = err1
}
if err == nil {
err = os.Rename(tmpname, filename)
}
if err != nil {
return err
os.Remove(tmpname)
}
return os.Rename(tmpname, filename)
return err
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment