Skip to content

Commit

Permalink
[go-jira#44] Close tmpfile before rename to work around "The process …
Browse files Browse the repository at this point in the history
…cannot access the file because it is being used by another process" error on windows.
  • Loading branch information
coryb committed Jun 30, 2016
1 parent 34ca09c commit 6016bda
Showing 1 changed file with 16 additions and 4 deletions.
20 changes: 16 additions & 4 deletions cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -261,13 +261,25 @@ func (c *Cli) editTemplate(template string, tmpFilePrefix string, templateData m
log.Errorf("Failed to make temp file in %s: %s", tmpdir, err)
return err
}
defer fh.Close()

tmpFileName := fmt.Sprintf("%s.yml", fh.Name())
if err := os.Rename(fh.Name(), tmpFileName); err != nil {
log.Errorf("Failed to rename %s to %s: %s", fh.Name(), fmt.Sprintf("%s.yml", fh.Name()), err)
oldFileName := fh.Name()
tmpFileName := fmt.Sprintf("%s.yml", oldFileName)

// close tmpfile so we can rename on windows
fh.Close()

if err := os.Rename(oldFileName, tmpFileName); err != nil {
log.Errorf("Failed to rename %s to %s: %s", oldFileName, tmpFileName, err)
return err
}

fh, err = os.OpenFile(tmpFileName, os.O_RDWR|os.O_EXCL, 0600)
if err != nil {
log.Errorf("Failed to reopen temp file file in %s: %s", tmpFileName, err)
return err
}

defer fh.Close()
defer func() {
os.Remove(tmpFileName)
}()
Expand Down

0 comments on commit 6016bda

Please sign in to comment.