Total Lines | 56 |
Duplicated Lines | 0 % |
Changes | 0 |
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 | decorators []Decorator |
||
21 | } |
||
22 | |||
23 | // NewFileWriter constructs a new FileWriter. |
||
24 | func NewFileWriter(path string) *FileWriter { |
||
25 | return &FileWriter{ |
||
26 | path: path, |
||
27 | decorators: []Decorator{ |
||
28 | FormatDecorator{}, |
||
29 | ImportDecorator{}, |
||
30 | }, |
||
31 | } |
||
32 | } |
||
33 | |||
34 | // Write is the implementation of the Writer interface. The FilerWriter writes |
||
35 | // decorated content to the file specified by the given path and table name. |
||
36 | func (w FileWriter) Write(tableName string, content string) error { |
||
37 | fileName := w.path + tableName + FileWriterExtension |
||
38 | |||
39 | decorated, err := w.decorate(content) |
||
40 | if err != nil { |
||
41 | return err |
||
42 | } |
||
43 | |||
44 | return ioutil.WriteFile(fileName, []byte(decorated), 0666) |
||
45 | } |
||
46 | |||
47 | // decorate applies some decorations like formatting and empty import removal. |
||
48 | func (w FileWriter) decorate(content string) (decorated string, err error) { |
||
49 | for _, decorator := range w.decorators { |
||
50 | content, err = decorator.Decorate(content) |
||
51 | if err != nil { |
||
52 | return content, err |
||
53 | } |
||
54 | } |
||
55 | |||
56 | return content, nil |
||
57 | } |
||
58 |