Skip to content

Commit

Permalink
Extend show command with --sh and --json formatting options (#165)
Browse files Browse the repository at this point in the history
  • Loading branch information
5nord committed Feb 17, 2021
1 parent f12036b commit 8a8eebd
Show file tree
Hide file tree
Showing 4 changed files with 217 additions and 20 deletions.
4 changes: 4 additions & 0 deletions cmd/ntt/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,8 @@ var (
}

Verbose = false
ShSetup = false
JSON = false

version = "dev"
commit = "none"
Expand All @@ -79,6 +81,8 @@ var (
func init() {
session.SharedDir = "/tmp/k3"
rootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output")
rootCmd.PersistentFlags().BoolVarP(&ShSetup, "sh", "", false, "output test suite data for shell consumption")
rootCmd.PersistentFlags().BoolVarP(&JSON, "json", "", false, "output in JSON format")
rootCmd.PersistentFlags().StringVarP(&cpuprofile, "cpuprofile", "", "", "write cpu profile to `file`")
rootCmd.AddCommand(showCmd)
rootCmd.AddCommand(dump.Command)
Expand Down
87 changes: 87 additions & 0 deletions cmd/ntt/report.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
package main

import (
"strconv"

"github.com/nokia/ntt/internal/ntt"
)

type Report struct {
Args []string `json:"args"`
Err error `json:"error"`
Name string `json:"name"`
Timeout float64 `json:"timeout"`
ParametersFile string `json:"parameters_file"`
TestHook string `json:"test_hook"`
SourceDir string `json:"source_dir"`
DataDir string `json:"datadir"`
SessionID int `json:"session_id"`
Environ []string `json:"env"`
Sources []string `json:"sources"`
Imports []string `json:"imports"`
Files []string `json:"files"`
AuxFiles []string `json:"aux_files"`

suite *ntt.Suite
}

func NewReport(args []string) *Report {
r := Report{Args: args}
r.suite, r.Err = ntt.NewFromArgs(args...)

if r.Err == nil {
r.Name, r.Err = r.suite.Name()
}

if r.Err == nil {
r.Timeout, r.Err = r.suite.Timeout()
}

if r.Err == nil {
r.ParametersFile, r.Err = path(r.suite.ParametersFile())
}

if r.Err == nil {
r.TestHook, r.Err = path(r.suite.TestHook())
}

if r.Err == nil {
r.DataDir, r.Err = r.suite.Getenv("NTT_DATADIR")
}

if r.Err == nil {
if env, err := r.suite.Getenv("NTT_SESSION_ID"); err != nil {
r.SessionID, r.Err = strconv.Atoi(env)
}
}

if r.Err == nil {
r.Environ, r.Err = r.suite.Environ()
}

if r.Err == nil {
paths, err := r.suite.Sources()
r.Sources, r.Err = ntt.PathSlice(paths...), err
}

if r.Err == nil {
paths, err := r.suite.Imports()
r.Imports, r.Err = ntt.PathSlice(paths...), err
}

if r.Err == nil {
r.Files, r.Err = r.suite.Files()
}

if root := r.suite.Root(); root != nil {
r.SourceDir = root.Path()
}

r.AuxFiles = ntt.FindAuxiliaryTTCN3Files()

return &r
}

func path(f *ntt.File, err error) (string, error) {
return f.Path(), err
}
144 changes: 125 additions & 19 deletions cmd/ntt/show.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
package main

import (
"encoding/json"
"fmt"
"os"
"sort"
"strings"
"text/template"

"github.com/nokia/ntt/internal/ntt"
"github.com/spf13/cobra"
Expand Down Expand Up @@ -41,7 +43,6 @@ var (
}
return strings.Join(ntt.PathSlice(imps...), "\n")
},

"timeout": func(suite *ntt.Suite) string {
t, err := suite.Timeout()
if err != nil {
Expand Down Expand Up @@ -105,7 +106,11 @@ var (
fatal(err)
}
sort.Strings(env)
return strings.Join(env, "\n")
res := make([]string, 0, len(env))
for _, e := range env {
res = append(res, fmt.Sprintf(`'%s'`, e))
}
return strings.Join(res, "\n")
},
}
)
Expand All @@ -120,25 +125,106 @@ func show(cmd *cobra.Command, args []string) error {
os.Exit(1)
}

if len(keys) == 0 {
for _, key := range []string{
"name",
"sources",
"imports",
"timeout",
"parameters_file",
"test_hook",
"source_dir",
"datadir",
"session_id",
} {
if s := stringers[key](suite); s != "" {
fmt.Printf("K3_%s=\"%s\"\n", strings.ToUpper(key), strings.Replace(s, "\n", " ", -1))
}
}
report := NewReport(sources)

return nil
switch {
case JSON:
return printJSON(report, keys)
case ShSetup:
return printShellScript(report, keys)
case len(keys) != 0:
return printUserKeys(suite, keys)
default:
return printDefaultKeys(suite)
}
}

func printJSON(report *Report, keys []string) error {
if len(keys) != 0 {
return fmt.Errorf("command line option --json does not accept additional command line arguments")
}

b, err := json.MarshalIndent(report, "", " ")
fmt.Println(string(b))
return err
}

func printShellScript(report *Report, keys []string) error {
const shellTemplate = `# This is a generated output of ntt show. Args: {{ .Args }}
# k3-cached-file searches for file $1 in $K3_CACHE and $NTT_CACHE and returns its first
# occurrence.
function k3-cached-file()
{
local IFS=:
read -r -a dirs <<<"$K3_CACHE:$NTT_CACHE"
for dir in "${dirs[@]}"; do
local cached_file="$dir/$1"
if [ -e "$cached_file" ]; then
echo "$cached_file"
return
fi
done
echo "$1"
}
# k3-hook calls the K3 test hook (if defined) with action passed by $1.
function k3-hook()
{
if [ -n "$K3_TEST_HOOK" ]; then
K3_SOURCES="${K3_SOURCES[*]}" \
K3_IMPORTS="${K3_IMPORTS[*]}" \
K3_TTCN3_FILES="${K3_TTCN3_FILES[*]}" \
"$K3_TEST_HOOK" "$@" 1>&2
fi
}
{{ if .Name -}} export K3_NAME='{{ .Name }}' {{- end }}
{{ if gt .Timeout 0.0 -}} export K3_TIMEOUT='{{ .Timeout }}' {{- end }}
{{ if .ParametersFile -}} export K3_PARAMETERS_FILE='{{ .ParametersFile }}' {{- end }}
{{ if .TestHook -}} export K3_TEST_HOOK='{{ .TestHook }}' {{- end }}
{{ if .SourceDir -}} export K3_SOURCE_DIR='{{ .SourceDir }}' {{- end }}
{{ if .DataDir -}} export K3_DATADIR='{{ .DataDir }}' {{- end }}
{{ if .SessionID -}} export K3_SESSION_ID='{{ .SessionID }}' {{- end }}
{{ range .Environ }}export '{{.}}'
{{end}}
K3_SOURCES=(
{{ range .Sources }} {{.}}
{{end}})
K3_IMPORTS=(
{{ range .Imports }} {{.}}
{{end}})
K3_TTCN3_FILES=(
{{ range .Files }} {{.}}
{{end}}
# Auxiliary files from K3
{{ range .AuxFiles }} {{.}}
{{end}})
{{ if .Err }}
# ERROR
# Output might not be complete, because some errors have occurred during
# execution. We return "false", to give you the chance to detect this
# situation
false
{{ end }}
`
if len(keys) != 0 {
return fmt.Errorf("command line option --sh does not accept additional command line arguments")
}

t := template.Must(template.New("k3-sh-setup").Parse(shellTemplate))
if err := t.Execute(os.Stdout, report); err != nil {
panic(err.Error())
}

return report.Err
}

func printUserKeys(suite *ntt.Suite, keys []string) error {

for _, key := range keys {
if fun, found := stringers[key]; found {
Expand All @@ -158,6 +244,26 @@ func show(cmd *cobra.Command, args []string) error {
return nil
}

func printDefaultKeys(suite *ntt.Suite) error {
for _, key := range []string{
"name",
"sources",
"imports",
"timeout",
"parameters_file",
"test_hook",
"source_dir",
"datadir",
"session_id",
} {
if s := stringers[key](suite); s != "" {
fmt.Printf("K3_%s=\"%s\"\n", strings.ToUpper(key), strings.Replace(s, "\n", " ", -1))
}
}

return nil
}

// splitArgs splits an argument list at pos. Pos is usually the position of '--'
// (see cobra.Command.ArgsLenAtDash).
//
Expand Down
2 changes: 1 addition & 1 deletion internal/ntt/env.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ func (suite *Suite) Environ() ([]string, error) {
if err != nil {
return nil, err
}
ret = append(ret, fmt.Sprintf("%s=\"%s\"", k, v))
ret = append(ret, fmt.Sprintf("%s=%s", k, v))
}
return ret, nil
}
Expand Down

0 comments on commit 8a8eebd

Please sign in to comment.