remove the temporary source file if we copied byte by byte.
Burcu Dogan
9 years ago
59 | 59 | } |
60 | 60 | |
61 | 61 | func copy(src, dest string) error { |
62 | // Try to rename generated source ... | |
62 | // Try to rename generated source. | |
63 | 63 | if err := os.Rename(src, dest); err == nil { |
64 | 64 | return nil |
65 | 65 | } |
66 | ||
67 | // ... if the rename failed (might do so due to temporary file residing on a | |
68 | // different device) try to copy byte by byte. | |
69 | ||
66 | // If the rename failed (might do so due to temporary file residing on a | |
67 | // different device), try to copy byte by byte. | |
70 | 68 | rc, err := os.Open(src) |
71 | 69 | if err != nil { |
72 | 70 | return err |
73 | 71 | } |
74 | defer rc.Close() | |
72 | defer func() { | |
73 | rc.Close() | |
74 | os.Remove(src) // ignore the error, source is in tmp. | |
75 | }() | |
75 | 76 | |
76 | 77 | if _, err = os.Stat(dest); !os.IsNotExist(err) { |
77 | 78 | return fmt.Errorf("file %q already exists", dest) |
85 | 86 | |
86 | 87 | if _, err = io.Copy(wc, rc); err != nil { |
87 | 88 | // Delete remains of failed copy attempt. |
88 | _ = os.Remove(dest) | |
89 | os.Remove(dest) | |
89 | 90 | } |
90 | 91 | return err |
91 | 92 | } |