Skip to content

Commit

Permalink
feat(inplace): Write to a temporary file to ensure data integrity
Browse files Browse the repository at this point in the history
  • Loading branch information
gabe565 committed Oct 6, 2023
1 parent 76d99da commit 15659fd
Showing 1 changed file with 18 additions and 20 deletions.
38 changes: 18 additions & 20 deletions cmd/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"fmt"
"io"
"os"
"path/filepath"
"strings"

"github.com/clevyr/yampl/internal/config"
Expand Down Expand Up @@ -115,22 +116,9 @@ func openAndTemplate(cmd *cobra.Command, conf config.Config, p string) (err erro
}(conf.Log)
conf.Log = log.WithField("file", p)

var f *os.File
if conf.Inplace {
stat, err := os.Stat(p)
if err != nil {
return fmt.Errorf("%s: %w", p, err)
}

f, err = os.OpenFile(p, os.O_RDWR, stat.Mode())
if err != nil {
return fmt.Errorf("%s: %w", p, err)
}
} else {
f, err = os.Open(p)
if err != nil {
return fmt.Errorf("%s: %w", p, err)
}
f, err := os.Open(p)
if err != nil {
return fmt.Errorf("%s: %w", p, err)
}
defer func(f *os.File) {
_ = f.Close()
Expand All @@ -141,16 +129,26 @@ func openAndTemplate(cmd *cobra.Command, conf config.Config, p string) (err erro
return fmt.Errorf("%s: %w", p, err)
}

_ = f.Close()

if conf.Inplace {
if err := f.Truncate(int64(len(s))); err != nil {
temp, err := os.CreateTemp("", "yampl_*_"+filepath.Base(p))
if err != nil {
return fmt.Errorf("%s: %w", p, err)
}
defer func() {
_ = os.RemoveAll(temp.Name())
}()

if _, err := f.Seek(0, io.SeekStart); err != nil {
if _, err := temp.WriteString(s); err != nil {
return fmt.Errorf("%s: %w", p, err)
}

if _, err := f.WriteString(s); err != nil {
if err := temp.Close(); err != nil {
return fmt.Errorf("%s: %w", p, err)
}

if err := os.Rename(temp.Name(), p); err != nil {
return fmt.Errorf("%s: %w", p, err)
}
} else {
Expand All @@ -159,7 +157,7 @@ func openAndTemplate(cmd *cobra.Command, conf config.Config, p string) (err erro
}
}

return f.Close()
return nil
}

func templateReader(conf config.Config, r io.Reader) (string, error) {
Expand Down

0 comments on commit 15659fd

Please sign in to comment.