Skip to content

Commit

Permalink
chore(cmd,pkg): small improvements and initial test fixes.
Browse files Browse the repository at this point in the history
Signed-off-by: Federico Di Pierro <[email protected]>
  • Loading branch information
FedeDP committed Apr 11, 2024
1 parent 9723857 commit 22077d5
Show file tree
Hide file tree
Showing 7 changed files with 44 additions and 29 deletions.
10 changes: 7 additions & 3 deletions cmd/cli_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -315,9 +315,13 @@ var tests = []testCase{

func run(t *testing.T, test testCase) {
// Setup
c := NewRootCmd()
configOpts, err := NewConfigOptions()
assert.NilError(t, err)
rootOpts, err := NewRootOptions()
assert.NilError(t, err)
c := NewRootCmd(configOpts, rootOpts)
b := bytes.NewBufferString("")
c.SetOutput(b)
configOpts.SetOutput(b)
if len(test.args) == 0 || (test.args[0] != "__complete" && test.args[0] != "__completeNoDesc" && test.args[0] != "help" && test.args[0] != "completion") {
test.args = append(test.args, "--dryrun")
}
Expand All @@ -328,7 +332,7 @@ func run(t *testing.T, test testCase) {
}
}
// Test
err := c.Execute()
err = c.Execute()
if err != nil {
if test.expect.err == "" {
t.Fatalf("error executing CLI: %v", err)
Expand Down
33 changes: 19 additions & 14 deletions cmd/config_options.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,27 +37,32 @@ var aliasProcessors = []string{"docker", "k8s", "k8s-ic"}

// ConfigOptions represent the persistent configuration flags of driverkit.
type ConfigOptions struct {
ConfigFile string
Timeout int `validate:"number,min=30" default:"120" name:"timeout"`
ProxyURL string `validate:"omitempty,proxy" name:"proxy url"`
DryRun bool
configFile string
timeout int `validate:"number,min=30" default:"120" name:"timeout"`
proxyURL string `validate:"omitempty,proxy" name:"proxy url"`
dryRun bool

// Printer used by all commands to output messages.
Printer *output.Printer
// Writer is used to write the output of the printer.
Writer io.Writer
// writer is used to write the output of the printer.
writer io.Writer
logLevel *options.LogLevel
}

func (co *ConfigOptions) initPrinter() {
logLevel := co.logLevel.ToPtermLogLevel()
co.Printer = output.NewPrinter(logLevel, pterm.LogFormatterColorful, co.Writer)
co.Printer = output.NewPrinter(logLevel, pterm.LogFormatterColorful, co.writer)
}

func (co *ConfigOptions) SetOutput(writer io.Writer) {
co.writer = writer
co.initPrinter()
}

// NewConfigOptions creates an instance of ConfigOptions.
func NewConfigOptions() (*ConfigOptions, error) {
o := &ConfigOptions{
Writer: os.Stdout,
writer: os.Stdout,
logLevel: options.NewLogLevel(),
}
o.initPrinter()
Expand Down Expand Up @@ -85,11 +90,11 @@ func (co *ConfigOptions) validate() []error {

// AddFlags registers the common flags.
func (co *ConfigOptions) AddFlags(flags *pflag.FlagSet) {
flags.StringVarP(&co.ConfigFile, "config", "c", co.ConfigFile, "config file path (default $HOME/.driverkit.yaml if exists)")
flags.StringVarP(&co.configFile, "config", "c", co.configFile, "config file path (default $HOME/.driverkit.yaml if exists)")
flags.VarP(co.logLevel, "loglevel", "l", "Set level for logs "+co.logLevel.Allowed())
flags.IntVar(&co.Timeout, "timeout", co.Timeout, "timeout in seconds")
flags.StringVar(&co.ProxyURL, "proxy", co.ProxyURL, "the proxy to use to download data")
flags.BoolVar(&co.DryRun, "dryrun", co.DryRun, "do not actually perform the action")
flags.IntVar(&co.timeout, "timeout", co.timeout, "timeout in seconds")
flags.StringVar(&co.proxyURL, "proxy", co.proxyURL, "the proxy to use to download data")
flags.BoolVar(&co.dryRun, "dryrun", co.dryRun, "do not actually perform the action")
}

// Init reads in config file and ENV variables if set.
Expand All @@ -102,8 +107,8 @@ func (co *ConfigOptions) Init() bool {
}
configErr = true
}
if co.ConfigFile != "" {
viper.SetConfigFile(co.ConfigFile)
if co.configFile != "" {
viper.SetConfigFile(co.configFile)
} else {
// Find home directory.
home, err := homedir.Dir()
Expand Down
4 changes: 2 additions & 2 deletions cmd/docker.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ func NewDockerCmd(configOpts *ConfigOptions, rootOpts *RootOptions, rootFlags *p
RunE: func(c *cobra.Command, args []string) error {
configOpts.Printer.Logger.Info("starting build",
configOpts.Printer.Logger.Args("processor", c.Name()))
if !configOpts.DryRun {
if !configOpts.dryRun {
// Since we use a spinner, cache log data to a bytesbuffer;
// we will later print it once we stop the spinner.
var buf bytes.Buffer
Expand All @@ -44,7 +44,7 @@ func NewDockerCmd(configOpts *ConfigOptions, rootOpts *RootOptions, rootFlags *p
defer func() {
_ = configOpts.Printer.Spinner.Stop()
}()
return driverbuilder.NewDockerBuildProcessor(configOpts.Timeout, configOpts.ProxyURL).Start(b)
return driverbuilder.NewDockerBuildProcessor(configOpts.timeout, configOpts.proxyURL).Start(b)
}
return nil
},
Expand Down
6 changes: 3 additions & 3 deletions cmd/kubernetes.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ func NewKubernetesCmd(configOpts *ConfigOptions, rootOpts *RootOptions, rootFlag
kubernetesCmd.RunE = func(c *cobra.Command, args []string) error {
configOpts.Printer.Logger.Info("starting build",
configOpts.Printer.Logger.Args("processor", c.Name()))
if !configOpts.DryRun {
if !configOpts.dryRun {
// Since we use a spinner, cache log data to a bytesbuffer;
// we will later print it once we stop the spinner.
var buf bytes.Buffer
Expand Down Expand Up @@ -104,7 +104,7 @@ func kubernetesRun(kubefactory factory.Factory,
kubernetesOptions.RunAsUser,
kubernetesOptions.Namespace,
kubernetesOptions.ImagePullSecret,
configOpts.Timeout,
configOpts.ProxyURL)
configOpts.timeout,
configOpts.proxyURL)
return buildProcessor.Start(b)
}
6 changes: 3 additions & 3 deletions cmd/kubernetes_in_cluster.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ func NewKubernetesInClusterCmd(configOpts *ConfigOptions, rootOpts *RootOptions,
kubernetesInClusterCmd.RunE = func(c *cobra.Command, args []string) error {
configOpts.Printer.Logger.Info("starting build",
configOpts.Printer.Logger.Args("processor", c.Name()))
if !configOpts.DryRun {
if !configOpts.dryRun {
// Since we use a spinner, cache log data to a bytesbuffer;
// we will later print it once we stop the spinner.
var buf bytes.Buffer
Expand Down Expand Up @@ -85,7 +85,7 @@ func kubernetesInClusterRun(b *builder.Build, configOpts *ConfigOptions) error {
kubernetesOptions.RunAsUser,
kubernetesOptions.Namespace,
kubernetesOptions.ImagePullSecret,
configOpts.Timeout,
configOpts.ProxyURL)
configOpts.timeout,
configOpts.proxyURL)
return buildProcessor.Start(b)
}
4 changes: 2 additions & 2 deletions cmd/local.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ func NewLocalCmd(configOpts *ConfigOptions, rootOpts *RootOptions, rootFlags *pf
RunE: func(c *cobra.Command, args []string) error {
configOpts.Printer.Logger.Info("starting build",
configOpts.Printer.Logger.Args("processor", c.Name()))
if !configOpts.DryRun {
if !configOpts.dryRun {
// Since we use a spinner, cache log data to a bytesbuffer;
// we will later print it once we stop the spinner.
var buf bytes.Buffer
Expand All @@ -42,7 +42,7 @@ func NewLocalCmd(configOpts *ConfigOptions, rootOpts *RootOptions, rootFlags *pf
opts.downloadHeaders,
opts.srcDir,
opts.envMap,
configOpts.Timeout).Start(b)
configOpts.timeout).Start(b)
}
return nil
},
Expand Down
10 changes: 8 additions & 2 deletions pkg/driverbuilder/builder/image_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ limitations under the License.
package builder

import (
"github.com/falcosecurity/falcoctl/pkg/output"
"github.com/pterm/pterm"
"io"
"net/http"
"os"
Expand Down Expand Up @@ -236,6 +238,8 @@ images:
}

func TestFileImagesLister(t *testing.T) {
printer := output.NewPrinter(pterm.LogLevelInfo, pterm.LogFormatterColorful, os.Stdout)

// setup images file
f, err := os.CreateTemp(t.TempDir(), "imagetest")
if err != nil {
Expand Down Expand Up @@ -269,11 +273,13 @@ func TestFileImagesLister(t *testing.T) {
t.Fatal(err)
}

assert.DeepEqual(t, test.expected, lister.LoadImages())
assert.DeepEqual(t, test.expected, lister.LoadImages(printer))
}
}

func TestRepoImagesLister(t *testing.T) {
printer := output.NewPrinter(pterm.LogLevelInfo, pterm.LogFormatterColorful, os.Stdout)

mock, err := registry.NewMock(t)
assert.NilError(t, err)
defer mock.Close()
Expand All @@ -300,6 +306,6 @@ func TestRepoImagesLister(t *testing.T) {
mock.RegisterHandler("/v2/foo/test/tags/list", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(test.jsonData))
})
assert.DeepEqual(t, test.expected, lister.LoadImages())
assert.DeepEqual(t, test.expected, lister.LoadImages(printer))
}
}

0 comments on commit 22077d5

Please sign in to comment.