Passed
Pull Request — master (#17)
by Frank
02:58
created

pkg/output/writer.go   A

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 25
dl 0
loc 53
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A output.NewFileWriter 0 2 1
A output.FileWriter.Write 0 9 2
A output.decorate 0 13 3
1
package output
2
3
import (
4
	"io/ioutil"
5
)
6
7
const (
8
	// FileWriterExtension is the extension to write files of.
9
	FileWriterExtension = ".go"
10
)
11
12
// Writer represents an interface to write the produced struct content.
13
type Writer interface {
14
	Write(tableName string, content string) error
15
}
16
17
// FileWriter is a writer that writes to a file given by the path and the table name.
18
type FileWriter struct {
19
	path string
20
}
21
22
// NewFileWriter constructs a new FileWriter.
23
func NewFileWriter(path string) *FileWriter {
24
	return &FileWriter{path: path}
25
}
26
27
// Write is the implementation of the Writer interface. The FilerWriter writes
28
// decorated content to the file specified by the given path and table name.
29
func (w FileWriter) Write(tableName string, content string) error {
30
	fileName := w.path + tableName + FileWriterExtension
31
32
	decorated, err := decorate(content)
33
	if err != nil {
34
		return err
35
	}
36
37
	return ioutil.WriteFile(fileName, []byte(decorated), 0666)
38
}
39
40
// decorate applies some decorations like formatting and empty import removal.
41
func decorate(content string) (decorated string, err error) {
42
	decorators := []Decorator{
43
		FormatDecorator{},
44
		ImportDecorator{},
45
	}
46
	for _, decorator := range decorators {
47
		content, err = decorator.Decorate(content)
48
		if err != nil {
49
			return content, err
50
		}
51
	}
52
53
	return content, nil
54
}
55