Skip to content

Commit

Permalink
save: Create temporary file only in case the target file already exists
Browse files Browse the repository at this point in the history
  • Loading branch information
JoeKar committed Apr 29, 2024
1 parent 35016cc commit 7d663d8
Showing 1 changed file with 25 additions and 16 deletions.
41 changes: 25 additions & 16 deletions internal/buffer/save.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,16 @@ func overwriteFile(name string, enc encoding.Encoding, fn func(io.Writer) error,
var writeCloser io.WriteCloser
var screenb bool
var cmd *exec.Cmd
tmpName := name + ".tmp"
potentialName := name
rename := false

if _, statErr := os.Stat(potentialName); os.IsNotExist(statErr) {
potentialName = name + ".tmp"
rename = true
}

if withSudo {
cmd = exec.Command(config.GlobalSettings["sucmd"].(string), "dd", "bs=4k", "of="+tmpName)
cmd = exec.Command(config.GlobalSettings["sucmd"].(string), "dd", "bs=4k", "of="+potentialName)

if writeCloser, err = cmd.StdinPipe(); err != nil {
return
Expand All @@ -55,7 +61,7 @@ func overwriteFile(name string, enc encoding.Encoding, fn func(io.Writer) error,
screen.TempStart(screenb)
return err
}
} else if writeCloser, err = os.OpenFile(tmpName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666); err != nil {
} else if writeCloser, err = os.OpenFile(potentialName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666); err != nil {
return
}

Expand Down Expand Up @@ -85,28 +91,31 @@ func overwriteFile(name string, enc encoding.Encoding, fn func(io.Writer) error,
return err
}

cmd = exec.Command(config.GlobalSettings["sucmd"].(string), "mv", tmpName, name)
if rename {
cmd = exec.Command(config.GlobalSettings["sucmd"].(string), "mv", potentialName, name)

c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
go func() {
<-c
cmd.Process.Kill()
}()
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
go func() {
<-c
cmd.Process.Kill()
}()

if e := cmd.Start(); e != nil && err == nil {
screen.TempStart(screenb)
return err
if e := cmd.Start(); e != nil && err == nil {
screen.TempStart(screenb)
return err
}

err = cmd.Wait()
}

err = cmd.Wait()
screen.TempStart(screenb)
if err != nil {
return err
}
} else {
} else if rename {
if err == nil {
err = os.Rename(tmpName, name)
err = os.Rename(potentialName, name)
}
}

Expand Down

0 comments on commit 7d663d8

Please sign in to comment.