Skip to content

Commit

Permalink
fix: resolve param expansion <no value> errors
Browse files Browse the repository at this point in the history
  • Loading branch information
Neil Hemming committed Jul 21, 2021
1 parent 95ffccd commit 191a931
Show file tree
Hide file tree
Showing 8 changed files with 210 additions and 41 deletions.
50 changes: 34 additions & 16 deletions internal/cmd/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package cmd

import (
"context"
"errors"
"fmt"
"os"

Expand Down Expand Up @@ -38,25 +39,16 @@ type (
// Run executes the command line interface to the app. The passed ctx is used to cancel long running tasks.
// appName is the name of the application and forms the suffix of the dot config file.
func Run(ctx context.Context) int {
return runWithArgs(ctx, os.Args)
}

func runWithArgs(ctx context.Context, args []string) int {
// Setup cli clogging handler
loggee.SetLogger(apexlog.NewCli(2))

info := buildinfo.GetBuildInfo(ctx)
cli := newCli(ctx)

cli := &cli{
appName: info.RunName,
rootCmd: &cobra.Command{
Use: info.RunName,
Short: "\U0001F680 Rocket powered task runner",
Long: "Rocket powered task runner to assist delivering ci build missions",
Args: cobra.NoArgs,
SilenceErrors: true,
Version: info.String(),
},
ctx: ctx,
}

cli.rootCmd.SetVersionTemplate(`{{printf "%s:%s\n" .Name .Version}}`)
cli.rootCmd.SetArgs(args)

initCmd := &cobra.Command{
Use: "init",
Expand All @@ -75,7 +67,7 @@ func Run(ctx context.Context) int {
Args: cobra.ArbitraryArgs,
SilenceErrors: true,
SilenceUsage: true,
RunE: cli.runFireCmd,
RunE: cli.runLaunchCmd,
}

cli.rootCmd.PersistentFlags().StringVar(&cli.configFile, flagConfig, "",
Expand All @@ -102,6 +94,27 @@ func Run(ctx context.Context) int {
return ExitCodeSuccess
}

func newCli(ctx context.Context) *cli {
info := buildinfo.GetBuildInfo(ctx)

cli := &cli{
appName: info.RunName,
rootCmd: &cobra.Command{
Use: info.RunName,
Short: "\U0001F680 Rocket powered task runner",
Long: "Rocket powered task runner to assist delivering ci build missions",
Args: cobra.NoArgs,
SilenceErrors: true,
Version: info.String(),
},
ctx: ctx,
}

cli.rootCmd.SetVersionTemplate(`{{printf "%s:%s\n" .Name .Version}}`)

return cli
}

// initConfig is called during the cobra start up process to init the config settings.
func (cli *cli) initConfig() {
// Switch dir if necessary
Expand All @@ -112,6 +125,11 @@ func (cli *cli) initConfig() {
}
}

if cli.appName == "" {
cli.initError = errors.New("No app name")
return
}

// Establish logging
isCustomConfig := false
viper.SetConfigType("yaml")
Expand Down
82 changes: 82 additions & 0 deletions internal/cmd/cli_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
package cmd

import (
"context"
"strings"
"testing"

"github.com/nehemming/cirocket/pkg/buildinfo"
)

func TestNewCli(t *testing.T) {
ctx := context.Background()

cli := newCli(ctx)

if cli.rootCmd == nil {
t.Error("no root cmd")
}

if cli.ctx != ctx {
t.Error("wrong context")
}
}

func TestNewCliRootCmd(t *testing.T) {
ctx := buildinfo.NewInfo("1.0", "", "", "", "").NewContext(context.Background())

cli := newCli(ctx)

rootCmd := cli.rootCmd

if rootCmd.Args == nil {
t.Error("Args")
}
if rootCmd.SilenceErrors == false {
t.Error("SilenceErrors")
}

if rootCmd.Version == "" {
t.Error("Version")
}
}

func TestInitConfigBlankAppNameErrors(t *testing.T) {
cli := newCli(context.Background())

if cli.initError != nil {
t.Error("pre init error")
}

cli.appName = ""

cli.initConfig()
if cli.initError == nil {
t.Error("expected error")
}
}

func TestInitConfig(t *testing.T) {
cli := newCli(context.Background())

if cli.initError != nil {
t.Error("pre init error")
}

cli.appName = "notknown"

cli.initConfig()
if cli.initError == nil || !strings.HasPrefix(cli.initError.Error(), "Config File \".notknown.yml\"") {
t.Error("unexpected", cli.initError)
}
}

func TestRun(t *testing.T) {
ctx := buildinfo.NewInfo("1.0", "", "", "", "").NewContext(context.Background())

exitCode := runWithArgs(ctx, []string{"--version"})

if exitCode != ExitCodeSuccess {
t.Error("unexpected exit code", exitCode)
}
}
2 changes: 1 addition & 1 deletion internal/cmd/launch.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ func parseParams(valueParams []string) ([]rocket.Param, error) {
return params, nil
}

func (cli *cli) runFireCmd(cmd *cobra.Command, args []string) error {
func (cli *cli) runLaunchCmd(cmd *cobra.Command, args []string) error {
// Check that the init process found a config file
if cli.initError != nil {
return cli.initError
Expand Down
3 changes: 3 additions & 0 deletions internal/cmd/launch_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,3 +51,6 @@ func TestParseParamsMultiple(t *testing.T) {
t.Error("unexpected value", r[1].Name, r[0].Value)
}
}

func TestGetCliParams(t *testing.T) {
}
1 change: 1 addition & 0 deletions pkg/rocket/builtin/template.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ func loadTemplate(ctx context.Context, capComm *rocket.CapComm, name string, tem
}

return template.New(name).
Option("missingkey=zero").
Funcs(capComm.FuncMap()).
Delims(templateCfg.Delims.Left, templateCfg.Delims.Right).Parse(string(b))
}
Expand Down
24 changes: 24 additions & 0 deletions pkg/rocket/builtin/template_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,27 @@ func TestTemplateHelloWorld(t *testing.T) {
t.Error("failure", err)
}
}

func TestTemplateMissingArgIsBalk(t *testing.T) {
loggee.SetLogger(stdlog.New())

capComm := rocket.NewCapComm("testdata/test.yml", stdlog.New())

ctx := context.Background()

templateCfg := &Template{
Template: rocket.InputSpec{
Path: "{{.notfound}}testdata/hello.yml",
},
}

if err := capComm.AttachInputSpec(ctx, templateResourceID, templateCfg.Template); err != nil {
t.Error("unexpected", err)
return
}

_, err := loadTemplate(ctx, capComm, "test", templateCfg)
if err != nil {
t.Error("unexpected", err)
}
}
22 changes: 12 additions & 10 deletions pkg/rocket/capcomm.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,11 @@ func getUserName() string {
return "unknown"
}

// NewCapComm returns a cap comm object that is suitable for using for testing.
func NewCapComm(testConfigFile string, log loggee.Logger) *CapComm {
return newCapCommFromEnvironment(testConfigFile, log).Copy(false)
}

// newCapCommFromEnvironment creates a new capCom from the environment.
func newCapCommFromEnvironment(configFile string, log loggee.Logger) *CapComm {
paramKvg := NewKeyValueGetter(nil)
Expand Down Expand Up @@ -556,8 +561,8 @@ func (capComm *CapComm) AttachRedirect(ctx context.Context, redirect Redirection
func (capComm *CapComm) MergeParams(ctx context.Context, params []Param) error {
capComm.mustNotBeSealed()

// Params need to be expanded prior to merging
expanded := make(map[string]string)
// safe type conversion as KeyValueGetter used all cases except root thats sealed sp not possible to be here
kvg := capComm.params.(*KeyValueGetter)

for index, p := range params {
if p.Name == "" {
Expand All @@ -568,13 +573,7 @@ func (capComm *CapComm) MergeParams(ctx context.Context, params []Param) error {
if err != nil {
return errors.Wrapf(err, "parameter %s", p.Name)
}
expanded[p.Name] = v
}

// safe type conversion as KeyValueGetter used all cases except root thats sealed sp not possible to be here
kvg := capComm.params.(*KeyValueGetter)
for k, v := range expanded {
kvg.kv[k] = v
kvg.kv[p.Name] = v
}

return nil
Expand Down Expand Up @@ -627,8 +626,11 @@ func (capComm *CapComm) ExpandString(ctx context.Context, name, value string) (s
return "", errors.Wrap(err, "executing template")
}

// fix <no value> on nil see https://github.com/golang/go/issues/24963
clean := strings.Replace(buf.String(), "<no value>", "", -1)

// Finally expand any environment variables in the $VAR format
return capComm.expandShellEnv(buf.String()), nil
return capComm.expandShellEnv(clean), nil
}

// FuncMap returns the function mapping used by CapComm.
Expand Down
Loading

0 comments on commit 191a931

Please sign in to comment.