-
Notifications
You must be signed in to change notification settings - Fork 262
/
format_resolver.go
106 lines (89 loc) · 2.59 KB
/
format_resolver.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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package controldisplay
import (
"context"
"fmt"
"github.com/turbot/go-kit/files"
"github.com/turbot/steampipe/pkg/constants"
"github.com/turbot/steampipe/pkg/export"
"github.com/turbot/steampipe/pkg/filepaths"
)
type FormatResolver struct {
formatterByName map[string]Formatter
// array of unique formatters used for export
exportFormatters []Formatter
}
func NewFormatResolver(ctx context.Context) (*FormatResolver, error) {
templates, err := loadAvailableTemplates(ctx)
if err != nil {
return nil, err
}
formatters := []Formatter{
&NullFormatter{},
&TextFormatter{},
&SnapshotFormatter{},
}
res := &FormatResolver{
formatterByName: make(map[string]Formatter),
}
for _, f := range formatters {
if err := res.registerFormatter(f); err != nil {
return nil, err
}
}
for _, t := range templates {
f, err := NewTemplateFormatter(t)
if err != nil {
return nil, err
}
if err := res.registerFormatter(f); err != nil {
return nil, err
}
}
return res, nil
}
func (r *FormatResolver) GetFormatter(arg string) (Formatter, error) {
if formatter, found := r.formatterByName[arg]; found {
return formatter, nil
}
return nil, fmt.Errorf(" invalid output format: '%s'", arg)
}
func (r *FormatResolver) registerFormatter(f Formatter) error {
name := f.Name()
if _, ok := r.formatterByName[name]; ok {
return fmt.Errorf("failed to register output formatter - duplicate format name %s", name)
}
r.formatterByName[name] = f
// if the formatter has an alias, also register by alias
if alias := f.Alias(); alias != "" {
if _, ok := r.formatterByName[alias]; ok {
return fmt.Errorf("failed to register output formatter - duplicate format name %s", alias)
}
r.formatterByName[alias] = f
}
// add to exportFormatters list (exclude 'None')
if f.Name() != constants.OutputFormatNone {
r.exportFormatters = append(r.exportFormatters, f)
}
return nil
}
func (r *FormatResolver) controlExporters() []export.Exporter {
res := make([]export.Exporter, len(r.exportFormatters))
for i, formatter := range r.exportFormatters {
res[i] = NewControlExporter(formatter)
}
return res
}
func loadAvailableTemplates(ctx context.Context) ([]*OutputTemplate, error) {
templateDirectories, err := files.ListFilesWithContext(ctx, filepaths.EnsureTemplateDir(), &files.ListOptions{
Flags: files.DirectoriesFlat | files.NotEmpty,
Exclude: []string{"./.*"},
})
if err != nil {
return nil, err
}
templates := []*OutputTemplate{}
for _, templateDirectory := range templateDirectories {
templates = append(templates, NewOutputTemplate(templateDirectory))
}
return templates, nil
}