Skip to content

Commit

Permalink
feat: add file writing
Browse files Browse the repository at this point in the history
Signed-off-by: Matthew Rose <matthew.rose@maxkelsen.com>
  • Loading branch information
matty-rose committed Oct 25, 2021
1 parent cf61088 commit 68f12c0
Showing 1 changed file with 30 additions and 3 deletions.
33 changes: 30 additions & 3 deletions pkg/writer/writer.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ THE SOFTWARE.
package writer

import (
"fmt"
"io"
"os"

Expand All @@ -34,15 +35,41 @@ func (sw stdoutWriter) Write(content []byte) (int, error) {
return os.Stdout.Write(content)
}

type fileWriter struct {
file string
}

func (fw fileWriter) Write(content []byte) (n int, err error) {
f, err := os.OpenFile(fw.file, os.O_RDWR|os.O_CREATE, 0644)
if err != nil {
return 0, errors.Wrap(err, fmt.Sprintf("couldn't open file: %s", fw.file))
}

defer func() {
cerr := f.Close()
if err == nil {
err = cerr
}
}()

n, err = f.Write(content)
if err != nil {
return 0, errors.Wrap(err, fmt.Sprintf("couldn't write to file: %s", fw.file))
}

// Uses named return values
return
}

func Write(content string, outputFile string) error {
var w io.Writer

if outputFile != "" {
return errors.New("writing to file not implemented yet")
w = fileWriter{outputFile}
} else {
w = stdoutWriter{}
}

w = stdoutWriter{}

_, err := io.WriteString(w, content)

return err
Expand Down

0 comments on commit 68f12c0

Please sign in to comment.