1 // xds-cli: command line tool used to control / interface X(cross) Development System.
12 "github.com/Sirupsen/logrus"
13 common "github.com/iotbzh/xds-common/golib"
14 "github.com/joho/godotenv"
15 socketio_client "github.com/sebd71/go-socket.io-client"
16 "github.com/urfave/cli"
19 var appAuthors = []cli.Author{
20 cli.Author{Name: "Sebastien Douheret", Email: "sebastien@iot.bzh"},
23 // AppName name of this application
24 var AppName = "xds-cli"
26 // AppNativeName native command name that this application can overload
27 var AppNativeName = "cli"
29 // AppVersion Version of this application
31 var AppVersion = "?.?.?"
33 // AppSubVersion is the git tag id added to version string
34 // Should be set by compilation -ldflags "-X main.AppSubVersion=xxx"
36 var AppSubVersion = "unknown-dev"
38 // Application details
40 appCopyright = "Apache-2.0"
41 defaultLogLevel = "error"
44 // Log Global variable that hold logger
45 var Log = logrus.New()
47 // EnvConfFileMap Global variable that hold environment vars loaded from config file
48 var EnvConfFileMap map[string]string
50 // HTTPCli Global variable that hold HTTP Client
51 var HTTPCli *common.HTTPClient
53 // IOsk Global variable that hold SocketIo client
54 var IOsk *socketio_client.Client
56 // exitError exists this program with the specified error
57 func exitError(code int, f string, a ...interface{}) {
58 err := fmt.Sprintf(f, a...)
59 fmt.Fprintf(os.Stderr, err+"\n")
65 EnvConfFileMap := make(map[string]string)
67 // Allow to set app name from cli (useful for debugging)
69 AppName = os.Getenv("XDS_APPNAME")
72 panic("Invalid setup, AppName not define !")
74 if AppNativeName == "" {
75 AppNativeName = AppName[4:]
77 appUsage := fmt.Sprintf("command line tool for X(cross) Development System.")
78 appDescription := fmt.Sprintf("%s utility for X(cross) Development System\n", AppName)
80 Setting of global options is driven either by environment variables or by command
81 line options or using a config file knowning that the following priority order is used:
82 1. use option value (for example --url option),
83 2. else use variable 'XDS_xxx' (for example 'XDS_SERVER_URL' variable) when a
84 config file is specified with '--config|-c' option,
85 3. else use 'XDS_xxx' (for example 'XDS_SERVER_URL') environment variable.
88 # Get help of 'projects' sub-command
89 ` + AppName + ` projects --help
92 ` + AppName + ` sdks ls
95 ` + AppName + ` prj add --label="myProject" --type=cs --path=$HOME/xds-workspace/myProject
98 // Create a new App instance
102 app.Version = AppVersion + " (" + AppSubVersion + ")"
103 app.Authors = appAuthors
104 app.Copyright = appCopyright
105 app.Metadata = make(map[string]interface{})
106 app.Metadata["version"] = AppVersion
107 app.Metadata["git-tag"] = AppSubVersion
108 app.Metadata["logger"] = Log
110 // Create env vars help
111 dynDesc := "\nENVIRONMENT VARIABLES:"
112 for _, f := range app.Flags {
113 var env, usage string
116 fs := f.(cli.StringFlag)
120 fb := f.(cli.BoolFlag)
124 exitError(1, "Un-implemented option type")
127 dynDesc += fmt.Sprintf("\n %s \t\t %s", env, usage)
130 app.Description = appDescription + dynDesc
132 // Declare global flags
133 app.Flags = []cli.Flag{
136 EnvVar: "XDS_CONFIG",
137 Usage: "env config file to source on startup",
141 EnvVar: "XDS_LOGLEVEL",
142 Usage: "logging level (supported levels: panic, fatal, error, warn, info, debug)",
143 Value: defaultLogLevel,
147 EnvVar: "XDS_SERVER_URL",
148 Value: "localhost:8000",
149 Usage: "remote XDS server url",
152 Name: "timestamp, ts",
153 EnvVar: "XDS_TIMESTAMP",
154 Usage: "prefix output with timestamp",
159 app.Commands = []cli.Command{}
161 initCmdProjects(&app.Commands)
162 initCmdSdks(&app.Commands)
163 initCmdExec(&app.Commands)
164 initCmdMisc(&app.Commands)
166 sort.Sort(cli.FlagsByName(app.Flags))
167 sort.Sort(cli.CommandsByName(app.Commands))
169 app.Before = func(ctx *cli.Context) error {
172 // Don't init anything when user wants help
173 for _, a := range ctx.Args() {
175 case "-h", "--h", "-help", "--help":
180 // Load config file if requested
181 confFile := ctx.String("config")
183 if !common.Exists(confFile) {
184 exitError(1, "Error env config file not found")
186 // Load config file variables that will overwrite env variables
187 err := godotenv.Overload(confFile)
189 exitError(1, "Error loading env config file "+confFile)
191 // Keep confFile settings in a map
192 EnvConfFileMap, err = godotenv.Read(confFile)
194 exitError(1, "Error reading env config file "+confFile)
198 loglevel := ctx.String("log")
199 // Set logger level and formatter
200 if Log.Level, err = logrus.ParseLevel(loglevel); err != nil {
201 msg := fmt.Sprintf("Invalid log level : \"%v\"\n", loglevel)
202 return cli.NewExitError(msg, 1)
204 Log.Formatter = &logrus.TextFormatter{}
206 Log.Infof("%s version: %s", AppName, app.Version)
207 Log.Debugf("Environment: %v", os.Environ())
209 if err = XdsConnInit(ctx); err != nil {
210 // Directly call HandleExitCoder to avoid to print help (ShowAppHelp)
211 // Note that this function wil never return and program will exit
212 cli.HandleExitCoder(err)
218 // Close HTTP client and WS connection on exit
226 // XdsConnInit Initialized HTTP and WebSocket connection to XDS agent
227 func XdsConnInit(ctx *cli.Context) error {
230 // Define HTTP and WS url
231 baseURL := ctx.String("url")
232 if !strings.HasPrefix(ctx.String("url"), "http://") {
233 baseURL = "http://" + ctx.String("url")
236 // Create HTTP client
237 Log.Debugln("Connect HTTP client on ", baseURL)
238 conf := common.HTTPClientConfig{
239 URLPrefix: "/api/v1",
240 HeaderClientKeyName: "Xds-Agent-Sid",
243 LogPrefix: "XDSAGENT: ",
244 LogLevel: common.HTTPLogLevelWarning,
247 HTTPCli, err = common.HTTPNewClient(baseURL, conf)
249 errmsg := err.Error()
250 if m, err := regexp.MatchString("Get http.?://", errmsg); m && err == nil {
251 i := strings.LastIndex(errmsg, ":")
252 errmsg = "Cannot connection to " + baseURL + errmsg[i:]
254 return cli.NewExitError(errmsg, 1)
256 HTTPCli.SetLogLevel(ctx.String("loglevel"))
258 // Create io Websocket client
259 Log.Debugln("Connecting IO.socket client on ", baseURL)
261 opts := &socketio_client.Options{
262 Transport: "websocket",
263 Header: make(map[string][]string),
265 opts.Header["XDS-AGENT-SID"] = []string{HTTPCli.GetClientID()}
267 IOsk, err = socketio_client.NewClient(baseURL, opts)
269 return cli.NewExitError("IO.socket connection error: "+err.Error(), 1)
272 IOsk.On("error", func(err error) {
273 fmt.Println("ERROR Websocket: ", err.Error())
276 ctx.App.Metadata["httpCli"] = HTTPCli
277 ctx.App.Metadata["ioskCli"] = IOsk
282 // XdsConnClose Terminate connection to XDS agent
283 func XdsConnClose() {
284 Log.Debugf("Closing HTTP client session...")
286 if httpCli, ok := app.Metadata["httpCli"]; ok {
287 c := httpCli.(*common.HTTPClient)
291 Log.Debugf("Closing WebSocket connection...")
293 if ioskCli, ok := app.Metadata["ioskCli"]; ok {
294 c := ioskCli.(*socketio_client.Client)
299 // NewTableWriter Create a writer that inserts padding around tab-delimited
300 func NewTableWriter() *tabwriter.Writer {
301 writer := new(tabwriter.Writer)
302 writer.Init(os.Stdout, 0, 8, 0, '\t', 0)