/
command.go
282 lines (258 loc) · 7.16 KB
/
command.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
package command
import (
"bytes"
"coscale/api"
"errors"
"flag"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"text/template"
"time"
"unicode"
"unicode/utf8"
)
const (
DEFAULT_FLAG_VALUE string = `!>dUmmy<!`
)
const (
// Status codes for os.Exit.
EXIT_SUCCESS int = 0
EXIT_SUCCESS_ERROR int = 1
EXIT_AUTHENTICATION_ERROR int = 2
EXIT_FLAG_ERROR int = 3
)
type Command struct {
Name string
UsageLine string
Long string
SubCommands []*Command
Capi *api.Api //api connector
Flag flag.FlagSet
Run func(cmd *Command, args []string)
}
func NewCommand(name, usage string, subCommands []*Command) *Command {
return &Command{
Name: name,
UsageLine: usage,
SubCommands: subCommands,
Run: func(cmd *Command, args []string) {
subCmd := cmd.GetSubCommand(args)
if subCmd != nil {
subCmd.Run(subCmd, args[1:])
}
},
}
}
func (c *Command) Runnable() bool {
return len(c.SubCommands) == 0
}
func (c *Command) GetSubCommand(args []string) *Command {
if len(args) < 1 {
c.PrintUsage()
}
for _, cmd := range c.SubCommands {
if cmd.Name == args[0] {
return cmd
}
}
c.PrintUsage()
return nil
}
func (c *Command) GetAllSubCommands() []*Command {
commands := make([]*Command, 0, 0)
if c.Runnable() {
commands = append(commands, c)
} else {
for _, subCmd := range c.SubCommands {
commands = append(commands, subCmd.GetAllSubCommands()...)
}
}
return commands
}
// tmpl executes the given template text on data, writing the result to w.
func tmpl(w io.Writer, text string, data interface{}) {
t := template.New("top")
t.Funcs(template.FuncMap{"trim": strings.TrimSpace, "capitalize": capitalize})
template.Must(t.Parse(text))
if err := t.Execute(w, data); err != nil {
panic(err)
}
}
//make the first letter form a string uppercase
func capitalize(s string) string {
if s == "" {
return s
}
r, n := utf8.DecodeRuneInString(s)
return string(unicode.ToTitle(r)) + s[n:]
}
func (c *Command) PrintUsage() {
tmpl(os.Stderr, usageTemplate, c)
os.Exit(2)
}
// GetApi returns a Api object
func (c *Command) GetApi(baseUrl, accessToken, appId string, rawOutput bool) *api.Api {
if accessToken == "" || appId == "" {
configPath, err := GetConfigPath()
if err != nil {
os.Exit(EXIT_FLAG_ERROR)
}
config, err := api.ReadApiConfiguration(configPath)
if err != nil {
c.PrintUsage()
}
baseUrl = config.BaseUrl
accessToken = config.AccessToken
appId = config.AppId
}
return api.NewApi(baseUrl, accessToken, appId, rawOutput)
}
func (c *Command) ParseArgs(args []string) {
if len(args) > 0 && args[0] == "help" {
c.PrintUsage()
}
//add the flags for the api configuration
var baseUrl, accessToken, appId string
var rawOutput bool
c.Flag.StringVar(&baseUrl, "api-url", "https://api.coscale.com", "Base url for the api")
c.Flag.StringVar(&appId, "app-id", "", "The application id")
c.Flag.StringVar(&accessToken, "access-token", "", "A valid access token for the given application")
c.Flag.BoolVar(&rawOutput, "rawOutput", false, "The returned json objects are returned formatted by default")
c.Flag.Parse(args)
unknownArgs := c.Flag.Args()
if len(unknownArgs) > 0 && unknownArgs[0] != "help" {
fmt.Fprintf(os.Stderr, "Unknown field %s\n", unknownArgs[0])
os.Exit(EXIT_FLAG_ERROR)
}
c.Capi = c.GetApi(baseUrl, accessToken, appId, rawOutput)
}
func (c *Command) PrintResult(result string, err error) {
if err == nil {
fmt.Fprintln(os.Stdout, result)
os.Exit(EXIT_SUCCESS)
} else if api.IsAuthenticationError(err) {
fmt.Fprintln(os.Stderr, `{"msg":"Authentication failed!"}`)
os.Exit(EXIT_AUTHENTICATION_ERROR)
} else {
fmt.Fprintln(os.Stderr, GetErrorJson(err))
os.Exit(EXIT_SUCCESS_ERROR)
}
}
// GetErrorJson return only the json string from a error message from api
func GetErrorJson(err error) string {
index := strings.Index(err.Error(), `{`)
if index > -1 {
return err.Error()[strings.Index(err.Error(), `{`):]
}
return fmt.Sprintf(`{"msg":"%s"}`, err.Error())
}
var usageTemplate = `coscale-cli a tool for CoScale Api.
Usage:
{{.UsageLine}}
{{if .Runnable}}
{{.Name | printf "Action \"%s\" usage:"}}
{{.Long | trim}}{{else}}
{{.Name | printf "Actions for command \"%s\":"}}
{{range .SubCommands}}
{{.Name | printf "%s"}}
{{.UsageLine | printf "%-11s"}}{{end}}
{{end}}
The json objects are returned formatted by default, but can be returned on 1 line by using:
--rawOutput
By default the CoScale api credentials (authentication) will be taken from api.conf
located in the same directory as the coscale-cli binary. If the file does not exist,
the credentials can also be provided on the command line using:
--api-url
Base url for the api (optional, default = "https://api.coscale.com/").
--app-id
The application id.
--access-token
A valid access token for the given application.
Use "coscale-cli [object] <help>" for more information about a command.
`
// GetConfigPath is used to return the absolut path of the api configuration file
func GetConfigPath() (c string, e error) {
command := os.Args[0]
var configFile, backwardsConfigFile, dir, cmdName, carriageReturn string
var err error
if runtime.GOOS == "windows" {
configFile = "api.conf"
backwardsConfigFile = "api.conf"
cmdName = "where"
carriageReturn = "\r\n"
} else {
configFile = filepath.Join("etc", "api.conf")
backwardsConfigFile = "api.conf" // once we had api.conf in the same folder as cli executable
cmdName = "which"
carriageReturn = "\n"
}
// we calculate folder where the command is
// 1. check if command is in PATH
// if we check a command that doesn't exist on linux we get error
response, err := GetCommandOutput(cmdName, 2*time.Second, command)
if err == nil {
command = string(bytes.Split(response, []byte(carriageReturn))[0])
}
err = nil
// 2. check if it is a symlink
file, err := os.Lstat(command)
if err != nil {
return "", err
}
if file.Mode()&os.ModeSymlink == os.ModeSymlink {
// This is a symlink
command, err = filepath.EvalSymlinks(command)
if err != nil {
return "", err
}
}
// check if config file is in dir
dir, err = filepath.Abs(filepath.Dir(command))
if err != nil {
os.Exit(EXIT_FLAG_ERROR)
}
configPath := filepath.Join(dir, configFile)
_, err = os.Stat(configPath)
if err == nil {
return configPath, nil
}
// try the backwards compatible approach
configPath = filepath.Join(dir, backwardsConfigFile)
_, err = os.Stat(configPath)
if err == nil {
return configPath, nil
}
return "", err
}
// GetCommandOutput returns stdout of command as a string
func GetCommandOutput(command string, timeout time.Duration, arg ...string) ([]byte, error) {
var err error
var stdOut bytes.Buffer
var stdErr bytes.Buffer
var c = make(chan []byte)
cmd := exec.Command(command, arg...)
cmd.Stdout = &stdOut
cmd.Stderr = &stdErr
if err = cmd.Start(); err != nil {
return nil, fmt.Errorf("%s %s", err.Error(), stdErr.String())
}
go func() {
err = cmd.Wait()
c <- stdOut.Bytes()
}()
time.AfterFunc(timeout, func() {
cmd.Process.Kill()
err = errors.New("Maxruntime exceeded")
c <- nil
})
response := <-c
if err != nil {
fmt.Errorf("%s %s", err.Error(), stdErr.String())
}
return response, nil
}