2 * Copyright (C) 2017 "IoT.bzh"
3 * Author Sebastien Douheret <sebastien@iot.bzh>
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
18 * xds-cli: command line tool used to control / interface X(cross) Development System.
31 "github.com/Sirupsen/logrus"
32 common "github.com/iotbzh/xds-common/golib"
33 "github.com/joho/godotenv"
34 socketio_client "github.com/sebd71/go-socket.io-client"
35 "github.com/urfave/cli"
38 var appAuthors = []cli.Author{
39 cli.Author{Name: "Sebastien Douheret", Email: "sebastien@iot.bzh"},
42 // AppName name of this application
43 var AppName = "xds-cli"
45 // AppNativeName native command name that this application can overload
46 var AppNativeName = "cli"
48 // AppVersion Version of this application
50 var AppVersion = "?.?.?"
52 // AppSubVersion is the git tag id added to version string
53 // Should be set by compilation -ldflags "-X main.AppSubVersion=xxx"
55 var AppSubVersion = "unknown-dev"
57 // Application details
59 appCopyright = "Copyright (C) 2017 IoT.bzh - Apache-2.0"
60 defaultLogLevel = "error"
63 // Log Global variable that hold logger
64 var Log = logrus.New()
66 // EnvConfFileMap Global variable that hold environment vars loaded from config file
67 var EnvConfFileMap map[string]string
69 // HTTPCli Global variable that hold HTTP Client
70 var HTTPCli *common.HTTPClient
72 // IOsk Global variable that hold SocketIo client
73 var IOsk *socketio_client.Client
75 // exitError exists this program with the specified error
76 func exitError(code int, f string, a ...interface{}) {
77 err := fmt.Sprintf(f, a...)
78 fmt.Fprintf(os.Stderr, err+"\n")
84 var earlyDebug []string
86 // Allow to set app name from cli (useful for debugging)
88 AppName = os.Getenv("XDS_APPNAME")
91 panic("Invalid setup, AppName not define !")
93 if AppNativeName == "" {
94 AppNativeName = AppName[4:]
96 appUsage := fmt.Sprintf("command line tool for X(cross) Development System.")
97 appDescription := fmt.Sprintf("%s utility for X(cross) Development System\n", AppName)
99 Setting of global options is driven either by environment variables or by command
100 line options or using a config file knowning that the following priority order is used:
101 1. use option value (for example --url option),
102 2. else use variable 'XDS_xxx' (for example 'XDS_SERVER_URL' variable) when a
103 config file is specified with '--config|-c' option,
104 3. else use 'XDS_xxx' (for example 'XDS_SERVER_URL') environment variable.
107 # Get help of 'projects' sub-command
108 ` + AppName + ` projects --help
111 ` + AppName + ` sdks ls
114 ` + AppName + ` prj add --label="myProject" --type=cs --path=$HOME/xds-workspace/myProject
117 // Create a new App instance
121 app.Version = AppVersion + " (" + AppSubVersion + ")"
122 app.Authors = appAuthors
123 app.Copyright = appCopyright
124 app.Metadata = make(map[string]interface{})
125 app.Metadata["version"] = AppVersion
126 app.Metadata["git-tag"] = AppSubVersion
127 app.Metadata["logger"] = Log
129 // Create env vars help
130 dynDesc := "\nENVIRONMENT VARIABLES:"
131 for _, f := range app.Flags {
132 var env, usage string
135 fs := f.(cli.StringFlag)
139 fb := f.(cli.BoolFlag)
143 exitError(1, "Un-implemented option type")
146 dynDesc += fmt.Sprintf("\n %s \t\t %s", env, usage)
149 app.Description = appDescription + dynDesc
151 // Declare global flags
152 app.Flags = []cli.Flag{
155 EnvVar: "XDS_CONFIG",
156 Usage: "env config file to source on startup",
160 EnvVar: "XDS_LOGLEVEL",
161 Usage: "logging level (supported levels: panic, fatal, error, warn, info, debug)",
162 Value: defaultLogLevel,
166 EnvVar: "XDS_SERVER_URL",
167 Value: "localhost:8000",
168 Usage: "remote XDS server url",
171 Name: "timestamp, ts",
172 EnvVar: "XDS_TIMESTAMP",
173 Usage: "prefix output with timestamp",
178 app.Commands = []cli.Command{}
180 initCmdProjects(&app.Commands)
181 initCmdSdks(&app.Commands)
182 initCmdExec(&app.Commands)
183 initCmdMisc(&app.Commands)
185 sort.Sort(cli.FlagsByName(app.Flags))
186 sort.Sort(cli.CommandsByName(app.Commands))
188 // Early and manual processing of --config option in order to set XDS_xxx
189 // variables before parsing of option by app cli
190 confFile := os.Getenv("XDS_CONFIG")
191 for idx, a := range os.Args[1:] {
192 if a == "-c" || a == "--config" || a == "-config" {
193 confFile = os.Args[idx+2]
198 // Load config file if requested
200 earlyDebug = append(earlyDebug, fmt.Sprintf("confFile detected: %v", confFile))
201 if !common.Exists(confFile) {
202 exitError(1, "Error env config file not found")
204 // Load config file variables that will overwrite env variables
205 err := godotenv.Overload(confFile)
207 exitError(1, "Error loading env config file "+confFile)
210 // Keep confFile settings in a map
211 EnvConfFileMap, err = godotenv.Read(confFile)
213 exitError(1, "Error reading env config file "+confFile)
215 earlyDebug = append(earlyDebug, fmt.Sprintf("EnvConfFileMap: %v", EnvConfFileMap))
218 app.Before = func(ctx *cli.Context) error {
221 // Don't init anything when no argument or help option is set
225 for _, a := range ctx.Args() {
227 case "-h", "--h", "-help", "--help":
232 loglevel := ctx.String("log")
233 // Set logger level and formatter
234 if Log.Level, err = logrus.ParseLevel(loglevel); err != nil {
235 msg := fmt.Sprintf("Invalid log level : \"%v\"\n", loglevel)
236 return cli.NewExitError(msg, 1)
238 Log.Formatter = &logrus.TextFormatter{}
240 Log.Infof("%s version: %s", AppName, app.Version)
241 for _, str := range earlyDebug {
244 Log.Debugf("\nEnvironment: %v\n", os.Environ())
246 if err = XdsConnInit(ctx); err != nil {
247 // Directly call HandleExitCoder to avoid to print help (ShowAppHelp)
248 // Note that this function wil never return and program will exit
249 cli.HandleExitCoder(err)
255 // Close HTTP client and WS connection on exit
263 // XdsConnInit Initialized HTTP and WebSocket connection to XDS agent
264 func XdsConnInit(ctx *cli.Context) error {
267 // Define HTTP and WS url
268 baseURL := ctx.String("url")
270 // Allow to only set port number
271 if match, _ := regexp.MatchString("^([0-9]+)$", baseURL); match {
272 baseURL = "http://localhost:" + ctx.String("url")
275 // Add http prefix if missing
276 if !strings.HasPrefix(baseURL, "http://") {
277 baseURL = "http://" + baseURL
280 // Create HTTP client
281 Log.Debugln("Connect HTTP client on ", baseURL)
282 conf := common.HTTPClientConfig{
283 URLPrefix: "/api/v1",
284 HeaderClientKeyName: "Xds-Agent-Sid",
287 LogPrefix: "XDSAGENT: ",
288 LogLevel: common.HTTPLogLevelWarning,
291 HTTPCli, err = common.HTTPNewClient(baseURL, conf)
293 errmsg := err.Error()
294 if m, err := regexp.MatchString("Get http.?://", errmsg); m && err == nil {
295 i := strings.LastIndex(errmsg, ":")
296 errmsg = "Cannot connection to " + baseURL + errmsg[i:]
298 return cli.NewExitError(errmsg, 1)
300 HTTPCli.SetLogLevel(ctx.String("loglevel"))
301 Log.Infoln("HTTP session ID : ", HTTPCli.GetClientID())
303 // Create io Websocket client
304 Log.Debugln("Connecting IO.socket client on ", baseURL)
306 opts := &socketio_client.Options{
307 Transport: "websocket",
308 Header: make(map[string][]string),
310 opts.Header["XDS-AGENT-SID"] = []string{HTTPCli.GetClientID()}
312 IOsk, err = socketio_client.NewClient(baseURL, opts)
314 return cli.NewExitError("IO.socket connection error: "+err.Error(), 1)
317 IOsk.On("error", func(err error) {
318 fmt.Println("ERROR Websocket: ", err.Error())
321 ctx.App.Metadata["httpCli"] = HTTPCli
322 ctx.App.Metadata["ioskCli"] = IOsk
327 // XdsConnClose Terminate connection to XDS agent
328 func XdsConnClose() {
329 Log.Debugf("Closing HTTP client session...")
331 if httpCli, ok := app.Metadata["httpCli"]; ok {
332 c := httpCli.(*common.HTTPClient)
336 Log.Debugf("Closing WebSocket connection...")
338 if ioskCli, ok := app.Metadata["ioskCli"]; ok {
339 c := ioskCli.(*socketio_client.Client)
344 // NewTableWriter Create a writer that inserts padding around tab-delimited
345 func NewTableWriter() *tabwriter.Writer {
346 writer := new(tabwriter.Writer)
347 writer.Init(os.Stdout, 0, 8, 0, '\t', 0)