Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

non-readonly block op buffers in mem #9

Merged
merged 1 commit into from
Feb 25, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 8 additions & 22 deletions lib/blocks/blockreader.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package blocks

import (
"bufio"
"bytes"
"fmt"
"io"
"io/ioutil"
Expand Down Expand Up @@ -68,7 +69,7 @@ func IsFinishLine(line string) bool {
}

func (br *Reader) DoTheThing(filename string) error {
var tmpfile *os.File
var buf *bytes.Buffer

if filename != "" {
br.FileName = filename
Expand All @@ -80,14 +81,10 @@ func (br *Reader) DoTheThing(filename string) error {
defer fs.Close()
br.Reader = fs

// for now write to a temporary file, TODO is there a better way?
// for now write to buffer
if !br.ReadOnly {
tmpfile, err = ioutil.TempFile("", "terrafmt")
if err != nil {
return fmt.Errorf("unable to create tmpfile: %v", err)
}
common.Log.Debugf("opening tmp file %s", tmpfile.Name())
br.Writer = tmpfile
buf = bytes.NewBuffer([]byte{})
br.Writer = buf
} else {
br.Writer = ioutil.Discard
}
Expand Down Expand Up @@ -175,27 +172,16 @@ func (br *Reader) DoTheThing(filename string) error {
}
}

//todo add better error checking and cleanup
if tmpfile != nil {
common.Log.Debugf("tmp file %s exists", tmpfile.Name())
tmpfile.Close()

common.Log.Debugf("reopening tmp file %s", tmpfile.Name())
source, err := os.Open(tmpfile.Name())
if err != nil {
return err
}
defer source.Close()

common.Log.Debugf("creating destination @ %s", tmpfile.Name())
// If not read-only, need to write back to file.
if !br.ReadOnly {
destination, err := os.Create(filename)
if err != nil {
return err
}
defer destination.Close()

common.Log.Debugf("copying..")
_, err = io.Copy(destination, source)
_, err = io.Copy(destination, buf)
return err
}

Expand Down