From d89eb8eddf0b42f5445554e9ba685fe8ef125bf7 Mon Sep 17 00:00:00 2001 From: dlorenc Date: Sun, 2 Jan 2022 13:40:50 -0600 Subject: [PATCH] Fix output-file flag. (#1264) The writer was getting closed prematurely in the PreRun command. We need to save this as a temp variable at the command level and close the writer in PostRun. Signed-off-by: Dan Lorenc --- cmd/cosign/cli/commands.go | 19 +++++++++++++------ test/e2e_test_secrets.sh | 5 +++++ 2 files changed, 18 insertions(+), 6 deletions(-) diff --git a/cmd/cosign/cli/commands.go b/cmd/cosign/cli/commands.go index 90ebc8ff1bb..68d334dfa85 100644 --- a/cmd/cosign/cli/commands.go +++ b/cmd/cosign/cli/commands.go @@ -30,21 +30,22 @@ var ( ) func New() *cobra.Command { + var ( + out, stdout *os.File + ) + cmd := &cobra.Command{ Use: "cosign", DisableAutoGenTag: true, SilenceUsage: true, // Don't show usage on errors PersistentPreRunE: func(cmd *cobra.Command, args []string) error { if ro.OutputFile != "" { - out, err := os.Create(ro.OutputFile) + var err error + out, err = os.Create(ro.OutputFile) if err != nil { return errors.Wrapf(err, "Error creating output file %s", ro.OutputFile) } - stdout := os.Stdout - defer func() { - os.Stdout = stdout - _ = out.Close() - }() + stdout = os.Stdout os.Stdout = out // TODO: don't do this. cmd.SetOut(out) } @@ -54,6 +55,12 @@ func New() *cobra.Command { } return nil }, + PersistentPostRun: func(cmd *cobra.Command, args []string) { + if out != nil { + _ = out.Close() + } + os.Stdout = stdout + }, } ro.AddFlags(cmd) diff --git a/test/e2e_test_secrets.sh b/test/e2e_test_secrets.sh index ccc9451db1d..70531656500 100755 --- a/test/e2e_test_secrets.sh +++ b/test/e2e_test_secrets.sh @@ -51,6 +51,11 @@ crane cp gcr.io/distroless/base $multiarch_img # `initialize` ./cosign initialize +## Generate (also test output redirection +./cosign generate $img > payload1 +./cosign generate --output-file=payload2 $img +diff payload1 payload2 + ## sign/verify ./cosign sign --key ${signing_key} $img ./cosign verify --key ${verification_key} $img