Skip to content
This repository has been archived by the owner on May 12, 2021. It is now read-only.

Commit

Permalink
kata-env: Add ability to output as JSON
Browse files Browse the repository at this point in the history
Having a direct JSON output for kata-env will help record
results in our CIs in some instances. Add that ability with
a kata-env command line extension.

Fixes: #474

Signed-off-by: Graham Whaley <graham.whaley@intel.com>
  • Loading branch information
Graham Whaley committed Jul 6, 2018
1 parent b2bec33 commit cbd108a
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 17 deletions.
40 changes: 23 additions & 17 deletions cli/kata-env.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
package main

import (
"encoding/json"
"errors"
"os"
"strings"
Expand Down Expand Up @@ -328,28 +329,17 @@ func getEnvInfo(configFile string, config oci.RuntimeConfig) (env EnvInfo, err e
return env, nil
}

func showSettings(env EnvInfo, file *os.File) error {
encoder := toml.NewEncoder(file)

err := encoder.Encode(env)
if err != nil {
return err
}

return nil
}

func handleSettings(file *os.File, metadata map[string]interface{}) error {
func handleSettings(file *os.File, c *cli.Context) error {
if file == nil {
return errors.New("Invalid output file specified")
}

configFile, ok := metadata["configFile"].(string)
configFile, ok := c.App.Metadata["configFile"].(string)
if !ok {
return errors.New("cannot determine config file")
}

runtimeConfig, ok := metadata["runtimeConfig"].(oci.RuntimeConfig)
runtimeConfig, ok := c.App.Metadata["runtimeConfig"].(oci.RuntimeConfig)
if !ok {
return errors.New("cannot determine runtime config")
}
Expand All @@ -359,13 +349,29 @@ func handleSettings(file *os.File, metadata map[string]interface{}) error {
return err
}

return showSettings(env, file)
if c.Bool("json") {
encoder := json.NewEncoder(file)
// Make it more human readable
encoder.SetIndent("", " ")
return encoder.Encode(env)
}

// Default to toml output
encoder := toml.NewEncoder(file)

return encoder.Encode(env)
}

var kataEnvCLICommand = cli.Command{
Name: envCmd,
Usage: "display settings",
Usage: "display settings. Default to TOML",
Flags: []cli.Flag{
cli.BoolFlag{
Name: "json",
Usage: "Format output as JSON",
},
},
Action: func(context *cli.Context) error {
return handleSettings(defaultOutputFile, context.App.Metadata)
return handleSettings(defaultOutputFile, context)
},
}
7 changes: 7 additions & 0 deletions cli/kata-env_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -906,6 +906,13 @@ func TestEnvCLIFunction(t *testing.T) {

err = fn(ctx)
assert.NoError(t, err)

set := flag.NewFlagSet("", 0)
set.Bool("json", true, "")
ctx := cli.NewContext(app, set, nil)

err = fn(ctx)
assert.NoError(t, err)
}

func TestEnvCLIFunctionFail(t *testing.T) {
Expand Down

0 comments on commit cbd108a

Please sign in to comment.