Skip to content

Commit

Permalink
style: Simplify error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
gabe565 committed Oct 6, 2023
1 parent 8ffb868 commit a921f2a
Showing 1 changed file with 11 additions and 11 deletions.
22 changes: 11 additions & 11 deletions cmd/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ func run(cmd *cobra.Command, args []string) error {

for i, p := range args {
if err := openAndTemplate(cmd, conf, p); err != nil {
return err
return fmt.Errorf("%s: %w", p, err)
}

if !conf.Inplace && i != len(args)-1 {
Expand All @@ -118,63 +118,63 @@ func openAndTemplate(cmd *cobra.Command, conf config.Config, p string) (err erro

f, err := os.Open(p)
if err != nil {
return fmt.Errorf("%s: %w", p, err)
return err
}
defer func(f *os.File) {
_ = f.Close()
}(f)

s, err := templateReader(conf, f)
if err != nil {
return fmt.Errorf("%s: %w", p, err)
return err
}

stat, err := f.Stat()
if err != nil {
return fmt.Errorf("%s: %w", p, err)
return err
}

_ = f.Close()

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

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

if err := temp.Chmod(stat.Mode()); err != nil {
return fmt.Errorf("%s: %w", p, err)
return err
}

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

if err := os.Rename(temp.Name(), p); err != nil {
log.Debug("failed to rename file, attempting to copy contents")

in, err := os.Open(temp.Name())
if err != nil {
return fmt.Errorf("%s: %w", p, err)
return err
}
defer func() {
_ = in.Close()
}()

out, err := os.OpenFile(p, os.O_WRONLY|os.O_TRUNC, stat.Mode())
if err != nil {
return fmt.Errorf("%s: %w", p, err)
return err
}

if _, err := io.Copy(out, in); err != nil {
return fmt.Errorf("%s: %w", p, err)
return err
}

if err := out.Close(); err != nil {
Expand Down

0 comments on commit a921f2a

Please sign in to comment.