/
decorator.go
34 lines (28 loc) · 1009 Bytes
/
decorator.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package output
import (
"fmt"
"go/format"
"strings"
)
// Decorator represents an interface to decorate the given content.
type Decorator interface {
Decorate(content string) (string, error)
}
// FormatDecorator applies a formatting decoration to the given content.
type FormatDecorator struct{}
// Decorate is the implementation of the Decorator interface.
func (FormatDecorator) Decorate(content string) (string, error) {
formatted, err := format.Source([]byte(content))
if err != nil {
return content, fmt.Errorf("could not format content: %w", err)
}
return string(formatted), nil
}
// ImportDecorator removes empty import statements from the given content.
type ImportDecorator struct{}
// Decorate is the implementation of the Decorator interface.
func (ImportDecorator) Decorate(content string) (string, error) {
// Fight the symptom instead of the cause - if we didn't import anything, remove it.
decorated := strings.ReplaceAll(content, "\nimport ()\n", "")
return decorated, nil
}