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 var earlyDebug []string
67 EnvConfFileMap := make(map[string]string)
69 // Allow to set app name from cli (useful for debugging)
71 AppName = os.Getenv("XDS_APPNAME")
74 panic("Invalid setup, AppName not define !")
76 if AppNativeName == "" {
77 AppNativeName = AppName[4:]
79 appUsage := fmt.Sprintf("command line tool for X(cross) Development System.")
80 appDescription := fmt.Sprintf("%s utility for X(cross) Development System\n", AppName)
82 Setting of global options is driven either by environment variables or by command
83 line options or using a config file knowning that the following priority order is used:
84 1. use option value (for example --url option),
85 2. else use variable 'XDS_xxx' (for example 'XDS_SERVER_URL' variable) when a
86 config file is specified with '--config|-c' option,
87 3. else use 'XDS_xxx' (for example 'XDS_SERVER_URL') environment variable.
90 # Get help of 'projects' sub-command
91 ` + AppName + ` projects --help
94 ` + AppName + ` sdks ls
97 ` + AppName + ` prj add --label="myProject" --type=cs --path=$HOME/xds-workspace/myProject
100 // Create a new App instance
104 app.Version = AppVersion + " (" + AppSubVersion + ")"
105 app.Authors = appAuthors
106 app.Copyright = appCopyright
107 app.Metadata = make(map[string]interface{})
108 app.Metadata["version"] = AppVersion
109 app.Metadata["git-tag"] = AppSubVersion
110 app.Metadata["logger"] = Log
112 // Create env vars help
113 dynDesc := "\nENVIRONMENT VARIABLES:"
114 for _, f := range app.Flags {
115 var env, usage string
118 fs := f.(cli.StringFlag)
122 fb := f.(cli.BoolFlag)
126 exitError(1, "Un-implemented option type")
129 dynDesc += fmt.Sprintf("\n %s \t\t %s", env, usage)
132 app.Description = appDescription + dynDesc
134 // Declare global flags
135 app.Flags = []cli.Flag{
138 EnvVar: "XDS_CONFIG",
139 Usage: "env config file to source on startup",
143 EnvVar: "XDS_LOGLEVEL",
144 Usage: "logging level (supported levels: panic, fatal, error, warn, info, debug)",
145 Value: defaultLogLevel,
149 EnvVar: "XDS_SERVER_URL",
150 Value: "localhost:8000",
151 Usage: "remote XDS server url",
154 Name: "timestamp, ts",
155 EnvVar: "XDS_TIMESTAMP",
156 Usage: "prefix output with timestamp",
161 app.Commands = []cli.Command{}
163 initCmdProjects(&app.Commands)
164 initCmdSdks(&app.Commands)
165 initCmdExec(&app.Commands)
166 initCmdMisc(&app.Commands)
168 sort.Sort(cli.FlagsByName(app.Flags))
169 sort.Sort(cli.CommandsByName(app.Commands))
171 // Early and manual processing of --config option in order to set XDS_xxx
172 // variables before parsing of option by app cli
173 confFile := os.Getenv("XDS_CONFIG")
174 for idx, a := range os.Args[1:] {
175 if a == "-c" || a == "--config" || a == "-config" {
176 confFile = os.Args[idx+2]
181 // Load config file if requested
183 earlyDebug = append(earlyDebug, fmt.Sprintf("confFile detected: %v", confFile))
184 if !common.Exists(confFile) {
185 exitError(1, "Error env config file not found")
187 // Load config file variables that will overwrite env variables
188 err := godotenv.Overload(confFile)
190 exitError(1, "Error loading env config file "+confFile)
193 // Keep confFile settings in a map
194 EnvConfFileMap, err = godotenv.Read(confFile)
196 exitError(1, "Error reading env config file "+confFile)
198 earlyDebug = append(earlyDebug, fmt.Sprintf("EnvConfFileMap: %v", EnvConfFileMap))
201 app.Before = func(ctx *cli.Context) error {
204 // Don't init anything when no argument or help option is set
208 for _, a := range ctx.Args() {
210 case "-h", "--h", "-help", "--help":
215 loglevel := ctx.String("log")
216 // Set logger level and formatter
217 if Log.Level, err = logrus.ParseLevel(loglevel); err != nil {
218 msg := fmt.Sprintf("Invalid log level : \"%v\"\n", loglevel)
219 return cli.NewExitError(msg, 1)
221 Log.Formatter = &logrus.TextFormatter{}
223 Log.Infof("%s version: %s", AppName, app.Version)
224 for _, str := range earlyDebug {
227 Log.Debugf("\nEnvironment: %v\n", os.Environ())
229 if err = XdsConnInit(ctx); err != nil {
230 // Directly call HandleExitCoder to avoid to print help (ShowAppHelp)
231 // Note that this function wil never return and program will exit
232 cli.HandleExitCoder(err)
238 // Close HTTP client and WS connection on exit
246 // XdsConnInit Initialized HTTP and WebSocket connection to XDS agent
247 func XdsConnInit(ctx *cli.Context) error {
250 // Define HTTP and WS url
251 baseURL := ctx.String("url")
252 if !strings.HasPrefix(ctx.String("url"), "http://") {
253 baseURL = "http://" + ctx.String("url")
256 // Create HTTP client
257 Log.Debugln("Connect HTTP client on ", baseURL)
258 conf := common.HTTPClientConfig{
259 URLPrefix: "/api/v1",
260 HeaderClientKeyName: "Xds-Agent-Sid",
263 LogPrefix: "XDSAGENT: ",
264 LogLevel: common.HTTPLogLevelWarning,
267 HTTPCli, err = common.HTTPNewClient(baseURL, conf)
269 errmsg := err.Error()
270 if m, err := regexp.MatchString("Get http.?://", errmsg); m && err == nil {
271 i := strings.LastIndex(errmsg, ":")
272 errmsg = "Cannot connection to " + baseURL + errmsg[i:]
274 return cli.NewExitError(errmsg, 1)
276 HTTPCli.SetLogLevel(ctx.String("loglevel"))
277 Log.Infoln("HTTP session ID : ", HTTPCli.GetClientID())
279 // Create io Websocket client
280 Log.Debugln("Connecting IO.socket client on ", baseURL)
282 opts := &socketio_client.Options{
283 Transport: "websocket",
284 Header: make(map[string][]string),
286 opts.Header["XDS-AGENT-SID"] = []string{HTTPCli.GetClientID()}
288 IOsk, err = socketio_client.NewClient(baseURL, opts)
290 return cli.NewExitError("IO.socket connection error: "+err.Error(), 1)
293 IOsk.On("error", func(err error) {
294 fmt.Println("ERROR Websocket: ", err.Error())
297 ctx.App.Metadata["httpCli"] = HTTPCli
298 ctx.App.Metadata["ioskCli"] = IOsk
303 // XdsConnClose Terminate connection to XDS agent
304 func XdsConnClose() {
305 Log.Debugf("Closing HTTP client session...")
307 if httpCli, ok := app.Metadata["httpCli"]; ok {
308 c := httpCli.(*common.HTTPClient)
312 Log.Debugf("Closing WebSocket connection...")
314 if ioskCli, ok := app.Metadata["ioskCli"]; ok {
315 c := ioskCli.(*socketio_client.Client)
320 // NewTableWriter Create a writer that inserts padding around tab-delimited
321 func NewTableWriter() *tabwriter.Writer {
322 writer := new(tabwriter.Writer)
323 writer.Init(os.Stdout, 0, 8, 0, '\t', 0)