diff --git a/cmd/packages.go b/cmd/packages.go index 626c535b9..fb8effd91 100644 --- a/cmd/packages.go +++ b/cmd/packages.go @@ -140,6 +140,7 @@ func setPackageFlags(flags *pflag.FlagSet) { ) } +// NOTE(alex): Write a helper for the binding operation, which can be used to perform the binding but also double check that the intended effect was had or else return an error. Another thought is to somehow provide zero-valued defaults for all values in our config struct (maybe with reflection?). There may be a mechanism that already exists in viper that protects against this that I'm not aware of. ref: https://github.com/anchore/syft/pull/805#discussion_r801931192 func bindPackagesConfigOptions(flags *pflag.FlagSet) error { // Formatting & Input options ////////////////////////////////////////////// diff --git a/internal/config/logging.go b/internal/config/logging.go index 26f59ef64..bb95425c3 100644 --- a/internal/config/logging.go +++ b/internal/config/logging.go @@ -15,4 +15,5 @@ type logging struct { func (cfg logging) loadDefaultValues(v *viper.Viper) { v.SetDefault("log.structured", false) + v.SetDefault("log.file", "") } diff --git a/test/cli/root_cmd_test.go b/test/cli/root_cmd_test.go index 5cdc33e64..4efa26d66 100644 --- a/test/cli/root_cmd_test.go +++ b/test/cli/root_cmd_test.go @@ -1,10 +1,13 @@ package cli import ( + "os" + "path/filepath" "strings" "testing" "github.com/sergi/go-diff/diffmatchpatch" + "github.com/stretchr/testify/assert" ) func TestRootCmdAliasesToPackagesSubcommand(t *testing.T) { @@ -114,3 +117,47 @@ func TestPersistentFlags(t *testing.T) { }) } } + +func TestLogFile(t *testing.T) { + request := "docker-archive:" + getFixtureImage(t, "image-pkg-coverage") + + envLogFile := filepath.Join(os.TempDir(), "a-pretty-log-file.log") + t.Logf("log file path: %s", envLogFile) + + tests := []struct { + name string + args []string + env map[string]string + assertions []traitAssertion + cleanup func() + }{ + { + name: "env-var-log-file-name", + args: []string{"-vv", request}, + env: map[string]string{"SYFT_LOG_FILE": envLogFile}, + assertions: []traitAssertion{ + func(tb testing.TB, stdout, stderr string, rc int) { + tb.Helper() + _, err := os.Stat(envLogFile) + assert.NoError(t, err) + }, + }, + cleanup: func() { assert.NoError(t, os.Remove(envLogFile)) }, + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + t.Cleanup(test.cleanup) + + cmd, stdout, stderr := runSyft(t, test.env, test.args...) + for _, traitFn := range test.assertions { + traitFn(t, stdout, stderr, cmd.ProcessState.ExitCode()) + } + if t.Failed() { + t.Log("STDOUT:\n", stdout) + t.Log("STDERR:\n", stderr) + t.Log("COMMAND:", strings.Join(cmd.Args, " ")) + } + }) + } +}