-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathmain.go
203 lines (177 loc) · 5.99 KB
/
main.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"github.com/hashicorp/go-multierror"
"github.com/mitchellh/cli"
"github.com/spf13/viper"
)
func main() {
c := &cli.CLI{
Name: "builder",
Version: "",
Args: os.Args[1:],
HelpWriter: os.Stdout,
}
ui := &cli.ColoredUi{
ErrorColor: cli.UiColorRed,
WarnColor: cli.UiColorYellow,
Ui: &cli.BasicUi{
Writer: os.Stdout,
Reader: os.Stdin,
ErrorWriter: os.Stderr,
},
}
c.Commands = map[string]cli.CommandFactory{
"build": func() (cli.Command, error) {
return &BuildCommand{
Ui: ui,
}, nil
},
}
exitStatus, err := c.Run()
if err != nil {
ui.Error("Error: " + err.Error())
}
os.Exit(exitStatus)
}
type BuildCommand struct {
Ui cli.Ui
}
func (c *BuildCommand) Help() string {
helpText := `Usage: syntax build
` + c.Synopsis()
return strings.TrimSpace(helpText)
}
func (c *BuildCommand) Synopsis() string {
return "Builds syntax files"
}
func (c *BuildCommand) Run(args []string) int {
// This currently uses the cwd to find all the files used here
// This can be improved in the future to accept User input or use some kind of
// convention for where things are located
wd, err := os.Getwd()
if err != nil {
return 1
}
// The _main.yml file is where all rules in the Patterns and the Repository are defined
// Each product file provides specific overrides for rules defined in _main.yml
// Here we build a main Viper instance to store the config we will merge in product specific maps to
mainFile := filepath.Join(wd, "../src/_main.yml")
c.Ui.Info(fmt.Sprintf("Pulling in main template: %s", mainFile))
mainViper := viper.New()
mainViper.SetConfigFile(mainFile)
if err := mainViper.ReadInConfig(); err == nil {
c.Ui.Info(fmt.Sprintf("Merging config file: %v", mainViper.ConfigFileUsed()))
} else {
c.Ui.Error(fmt.Sprintf("Error reading %v: %v", mainViper.ConfigFileUsed(), err))
return 1
}
var result *multierror.Error
// For each product defined, read the yml and merge into the main Viper instance
products := []string{"hcl", "terraform"}
for _, product := range products {
c.Ui.Info(fmt.Sprintf("Evaluating %s", product))
productFile := filepath.Join(wd, fmt.Sprintf("../src/%s.yml", product))
c.Ui.Info(fmt.Sprintf("Processing: %s", productFile))
// Create a product Viper instance that reads each product yml for rules
productV := viper.New()
productV.SetConfigFile(productFile)
if err := productV.ReadInConfig(); err == nil {
c.Ui.Info(fmt.Sprintf("Merging config file: %v", productV.ConfigFileUsed()))
} else {
c.Ui.Error(fmt.Sprintf("Error reading %v: %v", productV.ConfigFileUsed(), err.Error()))
result = multierror.Append(result, err)
continue
}
// merge the product Viper map into the main Viper instance
// This overrides anything already loaded so each product can replace existing
// rules and/or provide new ones
if err := mainViper.MergeConfigMap(productV.AllSettings()); err != nil {
c.Ui.Error(fmt.Sprintf("Unable to merge values from %v: %v", productV.ConfigFileUsed(), err.Error()))
result = multierror.Append(result, err)
continue
}
// Export the merged map to a struct so we can write to file
c.Ui.Info(fmt.Sprintf("Building %s", product))
var config TextMateGrammar
err := mainViper.Unmarshal(&config)
if err != nil {
c.Ui.Error(fmt.Sprintf("Unable to merge values from %s: %s", productV.ConfigFileUsed(), err.Error()))
result = multierror.Append(result, err)
continue
}
// Write the struct to JSON. We can modify this to include writing to other formats in the future
productGrammarFile := filepath.Join(wd, fmt.Sprintf("../syntaxes/%s.tmGrammar.json", product))
c.Ui.Info(fmt.Sprintf("Writing %s", productGrammarFile))
err = writeJSON(config, productGrammarFile)
if err != nil {
c.Ui.Error(fmt.Sprintf("Error writing grammar file: %v", err))
result = multierror.Append(result, err)
}
}
if result.ErrorOrNil() != nil {
return 1
} else {
return 0
}
}
func writeJSON(data TextMateGrammar, file string) error {
// We don't use json.MarshalIndent here because that escapes special characters automatically
// without allowing you to change the behavior. So, we make our own encoder and disable
// encoding and indent on our own.
buffer := &bytes.Buffer{}
encoder := json.NewEncoder(buffer)
encoder.SetEscapeHTML(false)
err := encoder.Encode(data)
if err != nil {
return err
}
var out bytes.Buffer
err = json.Indent(&out, buffer.Bytes(), "", " ")
if err != nil {
return err
}
err = ioutil.WriteFile(file, out.Bytes(), 0644)
if err != nil {
return err
}
return nil
}
// As defined in https://macromates.com/manual/en/language_grammars
type TextMateGrammar struct {
ScopeName string `json:"scopeName"`
Name string `json:"name"`
UUID string `json:"uuid"`
FileTypes []string `json:"fileTypes"`
Patterns []Rule `json:"patterns"`
Repository map[string]Rule `json:"repository"`
}
type Rule struct {
Include string `json:"include,omitempty"`
Name string `json:"name,omitempty"`
Match string `json:"match,omitempty"`
Begin string `json:"begin,omitempty"`
End string `json:"end,omitempty"`
ContentName string `json:"contentName,omitempty"`
Comment string `json:"comment,omitempty"`
Captures map[string]Capture `json:"captures,omitempty"`
BeginCaptures map[string]Capture `json:"beginCaptures,omitempty"`
EndCaptures map[string]Capture `json:"endCaptures,omitempty"`
Patterns []Rule `json:"patterns,omitempty"`
}
type Capture struct {
Name string `json:"name,omitempty"`
Patterns []CapturePattern `json:"patterns,omitempty"`
}
type CapturePattern struct {
Match string `json:"match,omitempty"`
Comment string `json:"comment,omitempty"`
Name string `json:"name,omitempty"`
Include string `json:"include,omitempty"`
}