-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
303 lines (262 loc) · 6.73 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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
// This code based on contributions from https://github.com/i2-open/i2goSignals with permission
package main
import (
"errors"
"fmt"
"io"
"slices"
"log"
"os"
"strings"
"github.com/alecthomas/kong"
"github.com/chzyer/readline"
"github.com/google/shlex"
"github.com/hexa-org/policy-mapper/sdk"
)
type ParserData struct {
parser *kong.Kong
cli *CLI
}
type Globals struct {
Config string `help:"Location of client config files" env:"HEXA_HOME" type:"path"`
Data ConfigData `kong:"-"`
ConfigFile string `kong:"-"`
Output string `short:"o" help:"To redirect output to a file" type:"path" `
AppendOutput bool `short:"a" default:"false" help:"When true, output to file (--output) will be appended"`
}
type CLI struct {
Globals
Add AddCmd `cmd:"" help:"Add a new integration"`
Delete DeleteCmd `cmd:"" help:"Delete an integration or policy application point from local configuration"`
Get GetCmd `cmd:"" help:"Retrieve or update information and display"`
Map MapCmd `cmd:"" help:"Convert syntactical policies to and from IDQL"`
Reconcile ReconcileCmd `cmd:"" help:"Reconcile compares a source set of policies another source (file or alias) of policies to determine differences."`
Set SetCmd `cmd:"" help:"Set or update policies (e.g. set policies -file=idql.json)"`
Show ShowCmd `cmd:"" help:"Show locally stored information about integrations and applications"`
Exit ExitCmd `cmd:"" help:"Exit Hexa CLI"`
Help HelpCmd `cmd:"" help:"Show help on a command"`
}
type OutputWriter struct {
output *os.File
isReady bool
err error
}
/*
GetOutputWriter returns an output writer if one was requested or nil. If one was requested and the output
cannot be opened an error is returned.
*/
func (cli *CLI) GetOutputWriter() *OutputWriter {
if cli.Output == "" {
return &OutputWriter{
isReady: false,
}
}
if cli.AppendOutput {
file, err := os.OpenFile(cli.Output, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
fmt.Println(err.Error())
return &OutputWriter{
isReady: false,
err: err,
}
}
return &OutputWriter{
output: file,
isReady: true,
}
}
file, err := os.OpenFile(cli.Output, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644)
if err != nil {
fmt.Println(err.Error())
return &OutputWriter{
isReady: false,
err: err,
}
}
return &OutputWriter{
output: file,
isReady: true,
}
}
func (o *OutputWriter) GetOutput() io.Writer {
if o.isReady {
return o.output
}
return nil
}
func (o *OutputWriter) WriteString(msg string, andClose bool) {
if msg != "" && o.isReady {
_, _ = o.output.WriteString(msg)
_ = o.output.Sync()
}
if andClose {
o.Close()
}
}
func (o *OutputWriter) WriteBytes(msgBytes []byte, andClose bool) {
if len(msgBytes) != 0 && o.isReady {
_, _ = o.output.Write(msgBytes)
_ = o.output.Sync()
}
if andClose {
o.Close()
}
}
func (o *OutputWriter) Close() {
if o.isReady {
_ = o.output.Sync()
o.isReady = false
_ = o.output.Close()
}
}
func initParser(cli *CLI) (*ParserData, error) {
if cli == nil {
cli = &CLI{}
}
cli.Data = ConfigData{
Integrations: map[string]*sdk.Integration{},
}
parser, err := kong.New(cli,
kong.Name("hexa"),
kong.Description("Hexa CLI Version: 0.6.6"),
kong.ConfigureHelp(kong.HelpOptions{
Compact: true,
Summary: true,
Tree: true,
NoAppSummary: false,
}),
kong.UsageOnError(),
kong.Writers(os.Stdout, os.Stdout),
kong.NoDefaultHelp(),
kong.Bind(&cli.Globals),
kong.Exit(func(int) {}),
)
td := ParserData{
parser: parser,
cli: cli,
}
return &td, err
}
var keywords = []string{"add", "aws", "cognito", "apigw", "avp", "gcp", "azure", "integration", "int", "paps", "app", "applications", "policies", "map", "to", "from", "reconcile", "set", "show", "exit", "help", "--file="}
// lowercaseKeywords helps make console appear case insensitive
func lowercaseKeywords(args []string) []string {
for i, v := range args {
argLower := strings.ToLower(v)
if slices.Contains(keywords, argLower) {
args[i] = argLower
}
mi := strings.Index(args[i], "--file=")
if mi == 0 {
args[i] = strings.ReplaceAll(args[i], "\\ ", " ")
}
}
return args
}
// breakIntoArgs separates the command by spaces while preserving escaped space
func breakIntoArgs(command string) []string {
res, _ := shlex.Split(command)
/*
lr := ' '
res := strings.FieldsFunc(command, func(r rune) bool {
if r == ' ' && lr == '\\' {
lr = r
return false
}
lr = r
return r == ' '
})
*/
return res
}
func main() {
console, err := readline.NewEx(&readline.Config{
Prompt: "hexa> ",
// HistoryFile: os.TempDir() + "/goSignals-history",
DisableAutoSaveHistory: true,
})
if err != nil {
panic(err)
}
defer func(console *readline.Instance) {
_ = console.Close()
}(console)
td, err := initParser(&CLI{})
// ctx.FatalIfErrorf(err)
if err != nil {
fmt.Println(err.Error())
panic(err)
}
oneCommand := false
initialArgs := os.Args
if len(initialArgs) > 1 {
initialArgs = initialArgs[1:]
firstArg := initialArgs[0]
if firstArg[0:1] != "-" {
oneCommand = true
} else {
for i, arg := range initialArgs {
prefix := arg[0:8]
if strings.EqualFold("--config", prefix) {
filepath := arg[strings.Index(arg, "=")+1:]
td.cli.Globals.Config = filepath
initialArgs = append(initialArgs[0:i], initialArgs[i+1:]...)
}
}
}
}
// fmt.Println("Loading existing configuration...")
if td == nil {
panic(errors.New("CLI parser failed to initialize"))
}
err = td.cli.Data.checkConfigPath(&td.cli.Globals)
if err != nil {
fmt.Println("Error reading config directory: " + err.Error())
panic(-1)
}
_ = td.cli.Data.Load(&td.cli.Globals)
for true {
var args []string
if oneCommand {
args = initialArgs
fullCommand := initialArgs[0]
for i, arg := range initialArgs {
if i > 0 {
fullCommand = fullCommand + " " + arg
}
}
initialArgs = []string{}
_ = console.SaveHistory(fullCommand)
} else {
line, err := console.Readline()
if err != nil {
panic(err)
}
//line = line[0 : len(line)-1]
_ = console.SaveHistory(line)
args = breakIntoArgs(line)
}
// fmt.Println("Args:", args)
args = lowercaseKeywords(args)
var ctx *kong.Context
ctx, err = td.parser.Parse(args)
// ctx.Bind(&cli.Globals)
// ctx.Bind(args)
if err != nil {
// Put out the help text response
td.parser.Errorf("%s", err.Error())
if err, ok := err.(*kong.ParseError); ok {
log.Println(err.Error())
_ = err.Context.PrintUsage(false)
}
continue
}
err = ctx.Run(&td.cli.Globals)
if err != nil {
td.parser.Errorf("%s", err)
continue
}
if oneCommand {
return
}
}
}