Skip to content

Commit e7a2f53

Browse files
committed
fix: Cleanup temp file on failure
1 parent 63dfa97 commit e7a2f53

File tree

1 file changed

+6
-1
lines changed

1 file changed

+6
-1
lines changed

cli/configssh.go

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -311,7 +311,7 @@ func configSSH() *cobra.Command {
311311
// directory as path and renames the temp file to the file provided in
312312
// path. This ensure we avoid trashing the file we are writing due to
313313
// unforeseen circumstance like filesystem full, command killed, etc.
314-
func writeWithTempFileAndMove(path string, r io.Reader) error {
314+
func writeWithTempFileAndMove(path string, r io.Reader) (err error) {
315315
dir := filepath.Dir(path)
316316
name := filepath.Base(path)
317317

@@ -321,6 +321,11 @@ func writeWithTempFileAndMove(path string, r io.Reader) error {
321321
if err != nil {
322322
return xerrors.Errorf("create temp file failed: %w", err)
323323
}
324+
defer func() {
325+
if err != nil {
326+
_ = os.Remove(f.Name()) // Cleanup in case a step failed.
327+
}
328+
}()
324329

325330
_, err = io.Copy(f, r)
326331
if err != nil {

0 commit comments

Comments
 (0)