From 05818aa3b221a670d94c332f461ae3bb046a5de3 Mon Sep 17 00:00:00 2001 From: Aleksei Sviridkin Date: Thu, 12 Nov 2026 23:34:44 +0300 Subject: [PATCH] fix(cli): fail cozypkg and check-readiness on unwritable output For the commands this change touches (cozypkg list, the validation report of validate, push and tap, tap's summary, and check-readiness), a write error the process observes is a failure: the command exits non-zero and says whether the action it reports on already happened. Progress lines printed before the decisive step stay best-effort. A closed pipe ends the process with SIGPIPE, as for other Unix tools. `cozypkg list` and the validation report dropped write errors, and the list deferred its tabwriter flush, so a closed or full stdout still reported success with nothing printed. The list now writes to the command's writer and returns the flush error, and the report returns its write error. When validation refuses a push or a tap, or fails a validate run, the refusal stays the reported reason and the report's write error is joined to it. A push whose report cannot be written stops before flux runs and says "nothing was pushed"; a tap whose summary cannot be written fails with "tap applied, but writing its summary failed". check-readiness fails --help, --version and its readiness result the same way, in one-shot, --wait and --watch mode, with exit 1 as for a result that is not ready, which its help now lists among the exit statuses along with SIGPIPE for a closed pipe; the watch loop stops at the first frame it cannot write, and a timed-out wait still ends with its verdict. push writes its "Pushing" line before it runs flux and stops with "nothing was pushed" when that line cannot be written, with validation skipped or after the report. Assisted-by: LLM Signed-off-by: Aleksei Sviridkin --- cmd/check-readiness/main.go | 55 ++++-- cmd/check-readiness/main_test.go | 68 +++++++ cmd/cozypkg/cmd/list.go | 48 +++-- cmd/cozypkg/cmd/output_test.go | 185 ++++++++++++++++++ cmd/cozypkg/cmd/push.go | 12 +- cmd/cozypkg/cmd/tap.go | 34 ++-- cmd/cozypkg/cmd/validate.go | 17 +- test/check-readiness/main_test.go | 79 ++++++++ .../testdata/golden/help-long.stdout | 4 + .../testdata/golden/help-short.stdout | 4 + .../testdata/golden/unknown-arg.stderr | 4 + .../golden/watch-nonnumeric-interval.stderr | 4 + 12 files changed, 458 insertions(+), 56 deletions(-) create mode 100644 cmd/check-readiness/main_test.go create mode 100644 cmd/cozypkg/cmd/output_test.go diff --git a/cmd/check-readiness/main.go b/cmd/check-readiness/main.go index 50fb8aaf8..eb13f62e1 100644 --- a/cmd/check-readiness/main.go +++ b/cmd/check-readiness/main.go @@ -22,6 +22,7 @@ package main import ( "fmt" + "io" "os" "os/exec" "strconv" @@ -58,6 +59,10 @@ Options: --no-color Disable color output (auto-disabled on non-TTY) -h, --help Show this help +Exit status: 0 when everything is ready, 1 when something is not ready or a +write to stdout fails, 2 on invalid arguments. A closed pipe ends the process +with SIGPIPE, like other Unix tools. + ` // entry is a resource catalog item. @@ -181,10 +186,16 @@ func run(args []string) int { cfg.coreOnly = true i++ case "-h", "--help": - fmt.Fprint(os.Stdout, usageText) + if _, err := fmt.Fprint(os.Stdout, usageText); err != nil { + fmt.Fprintf(os.Stderr, "writing usage: %v\n", err) + return 1 + } return 0 case "--version": - fmt.Fprintln(os.Stdout, Version) + if _, err := fmt.Fprintln(os.Stdout, Version); err != nil { + fmt.Fprintf(os.Stderr, "writing version: %v\n", err) + return 1 + } return 0 default: fmt.Fprintf(os.Stderr, "Unknown argument: %s\n", a) @@ -213,14 +224,14 @@ func run(args []string) int { cfg.timeoutS = sec if cfg.waitMode { - return cfg.runWait() + return cfg.runWait(os.Stdout) } if cfg.watch { - cfg.runWatch() - return 0 + return cfg.runWatch(os.Stdout) + } + if writeOutput(os.Stdout, cfg.runOnce()) != nil { + return 1 } - out := cfg.runOnce() - fmt.Print(out) if cfg.foundIssues { return 1 } @@ -281,18 +292,31 @@ func parseTimeout(raw string) (int, bool) { return 0, false } -func (cfg *config) runWait() int { +// writeOutput prints a result. A result its reader never got fails the run, +// whatever the resources' state, since the exit code alone would vouch for it. +func writeOutput(w io.Writer, parts ...string) error { + for _, part := range parts { + if _, err := io.WriteString(w, part); err != nil { + fmt.Fprintf(os.Stderr, "writing output: %v\n", err) + return err + } + } + return nil +} + +func (cfg *config) runWait(w io.Writer) int { start := time.Now() for { output := cfg.runOnce() elapsed := int(time.Since(start).Seconds()) if strings.Contains(output, "All resources are ready.") { - fmt.Print(output) - fmt.Printf("%sReady after %ds.%s\n", cfg.green, elapsed, cfg.reset) + if writeOutput(w, output, fmt.Sprintf("%sReady after %ds.%s\n", cfg.green, elapsed, cfg.reset)) != nil { + return 1 + } return 0 } if elapsed >= cfg.timeoutS { - fmt.Print(output) + _ = writeOutput(w, output) fmt.Fprintf(os.Stderr, "%s%sTimeout after %ds — resources still not ready.%s\n", cfg.red, cfg.bold, cfg.timeoutS, cfg.reset) return 1 } @@ -300,13 +324,14 @@ func (cfg *config) runWait() int { } } -func (cfg *config) runWatch() { +func (cfg *config) runWatch(w io.Writer) int { for { output := cfg.runOnce() // Smooth clear is cosmetic and untested; just reprint. - fmt.Printf("%sLast updated: %s (refreshing every %ds, Ctrl+C to stop)%s\n", cfg.bold, time.Now().Format(time.UnixDate), cfg.interval, cfg.reset) - fmt.Println() - fmt.Print(output) + header := fmt.Sprintf("%sLast updated: %s (refreshing every %ds, Ctrl+C to stop)%s\n\n", cfg.bold, time.Now().Format(time.UnixDate), cfg.interval, cfg.reset) + if writeOutput(w, header, output) != nil { + return 1 + } time.Sleep(time.Duration(cfg.interval) * time.Second) } } diff --git a/cmd/check-readiness/main_test.go b/cmd/check-readiness/main_test.go new file mode 100644 index 000000000..9afddeedf --- /dev/null +++ b/cmd/check-readiness/main_test.go @@ -0,0 +1,68 @@ +/* +Copyright 2026 The Cozystack Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package main + +import ( + "io" + "os" + "strings" + "testing" +) + +func TestHelpAndVersionSucceedOnWritableStdout(t *testing.T) { + r, w, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = r.Close() }) + stdout := os.Stdout + os.Stdout = w + t.Cleanup(func() { os.Stdout = stdout }) + read := make(chan string, 1) + go func() { + b, _ := io.ReadAll(r) + read <- string(b) + }() + + for _, arg := range []string{"--help", "--version"} { + if code := run([]string{arg}); code != 0 { + t.Errorf("run(%s) = %d, want 0", arg, code) + } + } + _ = w.Close() + if out := <-read; !strings.Contains(out, "Usage:") || !strings.Contains(out, Version) { + t.Errorf("stdout = %q, want the usage text and the version", out) + } +} + +func TestHelpAndVersionFailOnUnwritableStdout(t *testing.T) { + r, w, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + _ = r.Close() + _ = w.Close() + stdout := os.Stdout + os.Stdout = w + t.Cleanup(func() { os.Stdout = stdout }) + + for _, arg := range []string{"--help", "--version"} { + if code := run([]string{arg}); code == 0 { + t.Errorf("run(%s) with an unwritable stdout = 0, want a failure", arg) + } + } +} diff --git a/cmd/cozypkg/cmd/list.go b/cmd/cozypkg/cmd/list.go index 6f7375026..4b08a602b 100644 --- a/cmd/cozypkg/cmd/list.go +++ b/cmd/cozypkg/cmd/list.go @@ -19,7 +19,7 @@ package cmd import ( "context" "fmt" - "os" + "io" "strings" "text/tabwriter" @@ -78,24 +78,25 @@ Use --components flag to show components on separate lines.`, } if listCmdFlags.installed { - return listPackages(ctx, k8sClient, listCmdFlags.components) + return listPackages(ctx, k8sClient, cmd.OutOrStdout(), listCmdFlags.components) } - return listPackageSources(ctx, k8sClient, listCmdFlags.components) + return listPackageSources(ctx, k8sClient, cmd.OutOrStdout(), listCmdFlags.components) }, } -func listPackageSources(ctx context.Context, k8sClient client.Client, showComponents bool) error { +func listPackageSources(ctx context.Context, k8sClient client.Client, out io.Writer, showComponents bool) error { var psList cozyv1alpha1.PackageSourceList if err := k8sClient.List(ctx, &psList); err != nil { return fmt.Errorf("failed to list PackageSources: %w", err) } // Use tabwriter for better column alignment - w := tabwriter.NewWriter(os.Stdout, 0, 0, 3, ' ', 0) - defer w.Flush() + w := tabwriter.NewWriter(out, 0, 0, 3, ' ', 0) // Print header - fmt.Fprintln(w, "NAME\tVARIANTS\tREADY\tSTATUS") + if _, err := fmt.Fprintln(w, "NAME\tVARIANTS\tREADY\tSTATUS"); err != nil { + return err + } // Print rows for _, ps := range psList.Items { @@ -123,24 +124,26 @@ func listPackageSources(ctx context.Context, k8sClient client.Client, showCompon } } - fmt.Fprintf(w, "%s\t%s\t%s\t%s\n", ps.Name, variantsStr, ready, status) + if _, err := fmt.Fprintf(w, "%s\t%s\t%s\t%s\n", ps.Name, variantsStr, ready, status); err != nil { + return err + } // Show components if requested if showComponents { for _, variant := range ps.Spec.Variants { for _, component := range variant.Components { - fmt.Fprintf(w, " %s\t%s\t\t\n", - fmt.Sprintf("%s.%s", ps.Name, component.Name), - variant.Name) + if _, err := fmt.Fprintf(w, " %s.%s\t%s\t\t\n", ps.Name, component.Name, variant.Name); err != nil { + return err + } } } } } - return nil + return w.Flush() } -func listPackages(ctx context.Context, k8sClient client.Client, showComponents bool) error { +func listPackages(ctx context.Context, k8sClient client.Client, out io.Writer, showComponents bool) error { var pkgList cozyv1alpha1.PackageList if err := k8sClient.List(ctx, &pkgList); err != nil { return fmt.Errorf("failed to list Packages: %w", err) @@ -160,11 +163,12 @@ func listPackages(ctx context.Context, k8sClient client.Client, showComponents b } // Use tabwriter for better column alignment - w := tabwriter.NewWriter(os.Stdout, 0, 0, 3, ' ', 0) - defer w.Flush() + w := tabwriter.NewWriter(out, 0, 0, 3, ' ', 0) // Print header - fmt.Fprintln(w, "NAME\tVARIANT\tREADY\tSTATUS") + if _, err := fmt.Fprintln(w, "NAME\tVARIANT\tREADY\tSTATUS"); err != nil { + return err + } // Print rows for _, pkg := range pkgList.Items { @@ -187,7 +191,9 @@ func listPackages(ctx context.Context, k8sClient client.Client, showComponents b } } - fmt.Fprintf(w, "%s\t%s\t%s\t%s\n", pkg.Name, variant, ready, status) + if _, err := fmt.Fprintf(w, "%s\t%s\t%s\t%s\n", pkg.Name, variant, ready, status); err != nil { + return err + } // Show components if requested if showComponents { @@ -197,9 +203,9 @@ func listPackages(ctx context.Context, k8sClient client.Client, showComponents b for _, v := range ps.Spec.Variants { if v.Name == variant { for _, component := range v.Components { - fmt.Fprintf(w, " %s\t%s\t\t\n", - fmt.Sprintf("%s.%s", pkg.Name, component.Name), - variant) + if _, err := fmt.Fprintf(w, " %s.%s\t%s\t\t\n", pkg.Name, component.Name, variant); err != nil { + return err + } } break } @@ -208,7 +214,7 @@ func listPackages(ctx context.Context, k8sClient client.Client, showComponents b } } - return nil + return w.Flush() } func init() { diff --git a/cmd/cozypkg/cmd/output_test.go b/cmd/cozypkg/cmd/output_test.go new file mode 100644 index 000000000..9eed21639 --- /dev/null +++ b/cmd/cozypkg/cmd/output_test.go @@ -0,0 +1,185 @@ +/* +Copyright 2026 The Cozystack Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package cmd + +import ( + "context" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "strings" + "testing" + + cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1" + "github.com/spf13/cobra" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + utilruntime "k8s.io/apimachinery/pkg/util/runtime" + "sigs.k8s.io/controller-runtime/pkg/client/fake" +) + +type failingWriter struct{} + +func (failingWriter) Write([]byte) (int, error) { return 0, errors.New("broken pipe") } + +func TestPrintReportReturnsWriteError(t *testing.T) { + r := &Report{Findings: []Finding{{Severity: SeverityError, Code: "X", Message: "m"}}} + if err := printReport(r, failingWriter{}); err == nil { + t.Fatal("printReport to an unwritable writer returned nil") + } +} + +// The table is buffered until the tabwriter flushes, so a failing reader shows +// up only as a Flush error, which list has to return. +func TestListReturnsWriteError(t *testing.T) { + s := runtime.NewScheme() + utilruntime.Must(cozyv1alpha1.AddToScheme(s)) + ps := &cozyv1alpha1.PackageSource{ObjectMeta: metav1.ObjectMeta{Name: "acme.app"}} + pkg := &cozyv1alpha1.Package{ObjectMeta: metav1.ObjectMeta{Name: "acme.app"}} + cl := fake.NewClientBuilder().WithScheme(s).WithObjects(ps, pkg).Build() + + for name, list := range map[string]func(io.Writer) error{ + "sources": func(w io.Writer) error { return listPackageSources(context.Background(), cl, w, true) }, + "packages": func(w io.Writer) error { return listPackages(context.Background(), cl, w, true) }, + } { + t.Run(name, func(t *testing.T) { + if err := list(failingWriter{}); err == nil { + t.Fatal("list to an unwritable writer returned nil") + } + var out strings.Builder + if err := list(&out); err != nil || !strings.Contains(out.String(), "acme.app") { + t.Fatalf("list = %v, output %q; want the row", err, out.String()) + } + }) + } +} + +// A command that cannot print its validation report still fails, and a +// refusal keeps validation as its reason with the write error joined to it. +func TestValidationCommandsReportUnwritableReport(t *testing.T) { + fakeFlux := t.TempDir() + if err := os.WriteFile(filepath.Join(fakeFlux, "flux"), []byte("#!/bin/sh\nexit 0\n"), 0o755); err != nil { + t.Fatal(err) + } + t.Setenv("PATH", fakeFlux+string(os.PathListSeparator)+os.Getenv("PATH")) + + emptyRepo := func(t *testing.T) string { + root := t.TempDir() + if err := os.Mkdir(filepath.Join(root, "packages"), 0o755); err != nil { + t.Fatal(err) + } + return root + } + run := func(c *cobra.Command, args ...string) error { + c.SetOut(failingWriter{}) + t.Cleanup(func() { c.SetOut(nil) }) + return c.RunE(c, args) + } + push := func(root string) error { + pushCmdFlags.path = root + t.Cleanup(func() { pushCmdFlags.path = "." }) + return run(pushCmd, "oci://registry.example/acme/apps:v1") + } + + for _, tc := range []struct { + name string + run func(t *testing.T) error + refusal string + }{ + {name: "validate, valid", run: func(t *testing.T) error { return run(validateCmd, validRepo(t)) }}, + {name: "validate, invalid", run: func(t *testing.T) error { return run(validateCmd, emptyRepo(t)) }, refusal: "validation failed"}, + {name: "push, valid", run: func(t *testing.T) error { return push(validRepo(t)) }, refusal: "nothing was pushed"}, + {name: "push, invalid", run: func(t *testing.T) error { return push(emptyRepo(t)) }, refusal: "refusing to push"}, + {name: "tap, invalid", run: func(t *testing.T) error { return run(tapCmd, "oci://registry.example/acme/apps:v1") }, refusal: "refusing to tap"}, + } { + t.Run(tc.name, func(t *testing.T) { + err := tc.run(t) + if err == nil || !strings.Contains(err.Error(), "broken pipe") { + t.Fatalf("err = %v, want the write error", err) + } + if tc.refusal != "" && !strings.Contains(err.Error(), tc.refusal) { + t.Errorf("err = %v, want the refusal %q kept", err, tc.refusal) + } + }) + } +} + +// A tap that applied is reported as applied even when its summary is lost, +// and the lost summary still fails the command. +func TestTapSummaryReportsUnwritableOutput(t *testing.T) { + err := writeTapSummary(failingWriter{}, "oci://registry.example/acme/apps:v1", "tap-acme", []string{"acme.app"}) + if err == nil || !strings.Contains(err.Error(), "tap applied") || !strings.Contains(err.Error(), "broken pipe") { + t.Fatalf("err = %v, want the write error with the tap reported as applied", err) + } + var out strings.Builder + if err := writeTapSummary(&out, "oci://registry.example/acme/apps:v1", "tap-acme", []string{"acme.app"}); err != nil || !strings.Contains(out.String(), "cozypkg add acme.app") { + t.Fatalf("writeTapSummary = %v, output %q", err, out.String()) + } +} + +// A clean report has no finding lines, so its summary is its only write and +// alone decides the result. +func TestPrintReportReturnsSummaryWriteError(t *testing.T) { + if err := printReport(&Report{}, failingWriter{}); err == nil { + t.Fatal("printReport of a clean report to an unwritable writer returned nil") + } +} + +// push runs flux only after its status line was written, with validation +// skipped and after a report that was written. +func TestPushStopsBeforeFluxWhenItsStatusIsLost(t *testing.T) { + fakeFlux := t.TempDir() + ran := filepath.Join(t.TempDir(), "flux-ran") + if err := os.WriteFile(filepath.Join(fakeFlux, "flux"), []byte("#!/bin/sh\ntouch "+ran+"\n"), 0o755); err != nil { + t.Fatal(err) + } + t.Setenv("PATH", fakeFlux+string(os.PathListSeparator)+os.Getenv("PATH")) + for _, skip := range []bool{true, false} { + t.Run(fmt.Sprintf("skip-validate=%v", skip), func(t *testing.T) { + pushCmdFlags.path, pushCmdFlags.skipValidate = validRepo(t), skip + pushCmdFlags.source, pushCmdFlags.revision = "https://example.com/acme.git", "v1" + t.Cleanup(func() { + pushCmdFlags.path, pushCmdFlags.skipValidate = ".", false + pushCmdFlags.source, pushCmdFlags.revision = "", "" + }) + pushCmd.SetOut(&failOn{want: "Pushing"}) + t.Cleanup(func() { pushCmd.SetOut(nil) }) + err := pushCmd.RunE(pushCmd, []string{"oci://registry.example/acme/apps:v1"}) + if err == nil || !strings.Contains(err.Error(), "nothing was pushed") { + t.Fatalf("push losing its status = %v, want nothing pushed", err) + } + if _, statErr := os.Stat(ran); statErr == nil { + t.Fatal("flux ran after the status line was lost") + } + }) + } +} + +// failOn fails every write that contains want, and takes every other one. +type failOn struct { + want string + buf strings.Builder +} + +func (w *failOn) Write(p []byte) (int, error) { + if strings.Contains(string(p), w.want) { + return 0, errors.New("broken pipe") + } + return w.buf.Write(p) +} diff --git a/cmd/cozypkg/cmd/push.go b/cmd/cozypkg/cmd/push.go index 3f8e65cac..f60004034 100644 --- a/cmd/cozypkg/cmd/push.go +++ b/cmd/cozypkg/cmd/push.go @@ -17,6 +17,7 @@ limitations under the License. package cmd import ( + "errors" "fmt" "os" "os/exec" @@ -106,10 +107,13 @@ published. Source URL and revision are derived from git when not given.`, if err != nil { return err } - printReport(rep, cmd.OutOrStdout()) + printErr := printReport(rep, cmd.OutOrStdout()) if rep.HasErrors() { errs, _, _ := rep.Counts() - return fmt.Errorf("refusing to push: validation failed with %d error(s) (use --skip-validate to override)", errs) + return errors.Join(fmt.Errorf("refusing to push: validation failed with %d error(s) (use --skip-validate to override)", errs), printErr) + } + if printErr != nil { + return fmt.Errorf("nothing was pushed: writing the validation report failed: %w", printErr) } } @@ -129,7 +133,9 @@ published. Source URL and revision are derived from git when not given.`, } fluxArgs := buildFluxPushArgs(ref, packagesDir, source, revision, pushCmdFlags.reproducible) - fmt.Fprintf(cmd.OutOrStdout(), "Pushing %s (source=%s revision=%s)\n", ref, source, revision) + if _, err := fmt.Fprintf(cmd.OutOrStdout(), "Pushing %s (source=%s revision=%s)\n", ref, source, revision); err != nil { + return fmt.Errorf("nothing was pushed: writing the push status failed: %w", err) + } flux := exec.Command("flux", fluxArgs...) flux.Stdout = cmd.OutOrStdout() flux.Stderr = cmd.ErrOrStderr() diff --git a/cmd/cozypkg/cmd/tap.go b/cmd/cozypkg/cmd/tap.go index e04edebd7..2d5f7bb9b 100644 --- a/cmd/cozypkg/cmd/tap.go +++ b/cmd/cozypkg/cmd/tap.go @@ -18,6 +18,7 @@ package cmd import ( "context" + "errors" "fmt" "io" "regexp" @@ -402,9 +403,8 @@ runs its charts in your management cluster: tap only sources you trust.`, return err } if rep.HasErrors() { - printReport(rep, cmd.OutOrStdout()) errs, _, _ := rep.Counts() - return fmt.Errorf("refusing to tap: artifact failed validation with %d error(s) (use --skip-validate to override)", errs) + return errors.Join(fmt.Errorf("refusing to tap: artifact failed validation with %d error(s) (use --skip-validate to override)", errs), printReport(rep, cmd.OutOrStdout())) } } @@ -487,19 +487,29 @@ runs its charts in your management cluster: tap only sources you trust.`, _, _ = fmt.Fprintf(cmd.ErrOrStderr(), "warning: could not reset materialization state on OCIRepository/%s: %v\n", srcName, err) } - fmt.Fprintf(cmd.OutOrStdout(), "Tapped %s\n OCIRepository/%s\n", fullRef, srcName) - for _, n := range names { - fmt.Fprintf(cmd.OutOrStdout(), " PackageSource/%s\n", n) - } - _, _ = fmt.Fprintf(cmd.OutOrStdout(), "Tapping installs nothing. Install an app with:\n") - for _, n := range names { - fmt.Fprintf(cmd.OutOrStdout(), " cozypkg add %s\n", n) - } - _, _ = fmt.Fprintf(cmd.OutOrStdout(), "A privileged install component is not installed until you confirm it with 'cozypkg add --allow-privileged'.\n") - return nil + return writeTapSummary(cmd.OutOrStdout(), fullRef, srcName, names) }, } +// writeTapSummary reports what a tap created. The tap is applied by then, so a +// summary that cannot be written fails the command while saying so. +func writeTapSummary(w io.Writer, fullRef, srcName string, names []string) error { + var b strings.Builder + fmt.Fprintf(&b, "Tapped %s\n OCIRepository/%s\n", fullRef, srcName) + for _, n := range names { + fmt.Fprintf(&b, " PackageSource/%s\n", n) + } + b.WriteString("Tapping installs nothing. Install an app with:\n") + for _, n := range names { + fmt.Fprintf(&b, " cozypkg add %s\n", n) + } + b.WriteString("A privileged install component is not installed until you confirm it with 'cozypkg add --allow-privileged'.\n") + if _, err := io.WriteString(w, b.String()); err != nil { + return fmt.Errorf("tap applied, but writing its summary failed: %w", err) + } + return nil +} + var untapCmd = &cobra.Command{ Use: "untap ", Short: "Remove a tapped repository", diff --git a/cmd/cozypkg/cmd/validate.go b/cmd/cozypkg/cmd/validate.go index 809f0f246..f781cfd8b 100644 --- a/cmd/cozypkg/cmd/validate.go +++ b/cmd/cozypkg/cmd/validate.go @@ -21,6 +21,7 @@ import ( "bytes" "context" "encoding/json" + "errors" "fmt" "io" "io/fs" @@ -535,16 +536,19 @@ func pullOCIArtifact(ref string) (string, func(), error) { return dir, cleanup, nil } -func printReport(r *Report, w io.Writer) { +func printReport(r *Report, w io.Writer) error { for _, f := range r.Findings { loc := f.Location if loc == "" { loc = "-" } - fmt.Fprintf(w, "[%s] %s (%s): %s\n", f.Severity, loc, f.Code, f.Message) + if _, err := fmt.Fprintf(w, "[%s] %s (%s): %s\n", f.Severity, loc, f.Code, f.Message); err != nil { + return err + } } errs, warns, infos := r.Counts() - fmt.Fprintf(w, "\nSummary: %d error(s), %d warning(s), %d info\n", errs, warns, infos) + _, err := fmt.Fprintf(w, "\nSummary: %d error(s), %d warning(s), %d info\n", errs, warns, infos) + return err } var validateCmdFlags struct { @@ -663,10 +667,13 @@ runs "helm lint" on every component chart.`, if err != nil { return err } - printReport(rep, cmd.OutOrStdout()) + printErr := printReport(rep, cmd.OutOrStdout()) if rep.HasErrors() { errs, _, _ := rep.Counts() - return fmt.Errorf("validation failed: %d error(s)", errs) + return errors.Join(fmt.Errorf("validation failed: %d error(s)", errs), printErr) + } + if printErr != nil { + return fmt.Errorf("writing the validation report failed: %w", printErr) } return nil }, diff --git a/test/check-readiness/main_test.go b/test/check-readiness/main_test.go index 622340c7f..01e6c1505 100644 --- a/test/check-readiness/main_test.go +++ b/test/check-readiness/main_test.go @@ -13,6 +13,7 @@ package checkreadiness_test import ( "bytes" + "context" "errors" "flag" "fmt" @@ -23,6 +24,7 @@ import ( "runtime" "strings" "testing" + "time" ) var update = flag.Bool("update", false, "regenerate golden files") @@ -335,3 +337,80 @@ func repoRoot(t *testing.T) string { } return root } + +// A result that never reaches stdout fails the run, whatever the cluster's +// state, and the watch loop stops instead of refreshing into the void. stdout +// is a read-only descriptor, so every write fails without a SIGPIPE. +func TestUnwritableStdoutFails(t *testing.T) { + root := repoRoot(t) + fakeBin := filepath.Join(root, "test", "check-readiness", "fakekubectl") + base := filepath.Join(root, "test", "check-readiness", "testdata", "fixtures", "_base") + for _, tc := range []struct { + name string + args []string + }{ + {name: "once", args: []string{"--no-color"}}, + {name: "wait", args: []string{"--wait", "--no-color"}}, + {name: "watch", args: []string{"-w", "1", "--no-color"}}, + } { + t.Run(tc.name, func(t *testing.T) { + stdout, err := os.Open(os.DevNull) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = stdout.Close() }) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + t.Cleanup(cancel) + argv := subjectArgv(tc.args) + cmd := exec.CommandContext(ctx, argv[0], argv[1:]...) + cmd.Env = testEnv(fakeBin, base, base, filepath.Join(t.TempDir(), "kubectl.log")) + var stderr bytes.Buffer + cmd.Stdout, cmd.Stderr = stdout, &stderr + runErr := cmd.Run() + if ctx.Err() != nil { + t.Fatalf("still running after its output failed\nstderr:\n%s", stderr.String()) + } + if code := exitCode(t, runErr); code != 1 { + t.Errorf("exit code = %d, want 1\nstderr:\n%s", code, stderr.String()) + } + if !strings.Contains(stderr.String(), "writing output") { + t.Errorf("stderr does not say the output was lost:\n%s", stderr.String()) + } + }) + } +} + +// A wait that times out ends with its verdict: the table comes first and the +// timeout line last, also when the table could not be written. +func TestWaitTimeoutVerdictComesLast(t *testing.T) { + root := repoRoot(t) + fakeBin := filepath.Join(root, "test", "check-readiness", "fakekubectl") + fixtures := filepath.Join(root, "test", "check-readiness", "testdata", "fixtures") + args := []string{"-w", "1", "--wait", "--timeout", "1s", "--no-color"} + for _, unwritable := range []bool{false, true} { + t.Run(fmt.Sprintf("unwritable=%v", unwritable), func(t *testing.T) { + cmd := scriptCommand(args) + cmd.Env = testEnv(fakeBin, filepath.Join(fixtures, "helmrelease-not-ready"), filepath.Join(fixtures, "_base"), filepath.Join(t.TempDir(), "kubectl.log")) + var combined bytes.Buffer + cmd.Stdout, cmd.Stderr = &combined, &combined + if unwritable { + stdout, err := os.Open(os.DevNull) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = stdout.Close() }) + cmd.Stdout = stdout + } + if code := exitCode(t, cmd.Run()); code != 1 { + t.Errorf("exit code = %d, want 1\n%s", code, combined.String()) + } + lines := strings.Split(strings.TrimRight(combined.String(), "\n"), "\n") + if last := lines[len(lines)-1]; !strings.HasPrefix(last, "Timeout after") { + t.Errorf("last line = %q, want the timeout verdict\n%s", last, combined.String()) + } + if unwritable && !strings.Contains(combined.String(), "writing output") { + t.Errorf("stderr does not say the table was lost:\n%s", combined.String()) + } + }) + } +} diff --git a/test/check-readiness/testdata/golden/help-long.stdout b/test/check-readiness/testdata/golden/help-long.stdout index f1f289e08..428f135aa 100644 --- a/test/check-readiness/testdata/golden/help-long.stdout +++ b/test/check-readiness/testdata/golden/help-long.stdout @@ -21,3 +21,7 @@ Options: --no-color Disable color output (auto-disabled on non-TTY) -h, --help Show this help +Exit status: 0 when everything is ready, 1 when something is not ready or a +write to stdout fails, 2 on invalid arguments. A closed pipe ends the process +with SIGPIPE, like other Unix tools. + diff --git a/test/check-readiness/testdata/golden/help-short.stdout b/test/check-readiness/testdata/golden/help-short.stdout index f1f289e08..428f135aa 100644 --- a/test/check-readiness/testdata/golden/help-short.stdout +++ b/test/check-readiness/testdata/golden/help-short.stdout @@ -21,3 +21,7 @@ Options: --no-color Disable color output (auto-disabled on non-TTY) -h, --help Show this help +Exit status: 0 when everything is ready, 1 when something is not ready or a +write to stdout fails, 2 on invalid arguments. A closed pipe ends the process +with SIGPIPE, like other Unix tools. + diff --git a/test/check-readiness/testdata/golden/unknown-arg.stderr b/test/check-readiness/testdata/golden/unknown-arg.stderr index d6ec7c0db..ca652d9ea 100644 --- a/test/check-readiness/testdata/golden/unknown-arg.stderr +++ b/test/check-readiness/testdata/golden/unknown-arg.stderr @@ -22,3 +22,7 @@ Options: --no-color Disable color output (auto-disabled on non-TTY) -h, --help Show this help +Exit status: 0 when everything is ready, 1 when something is not ready or a +write to stdout fails, 2 on invalid arguments. A closed pipe ends the process +with SIGPIPE, like other Unix tools. + diff --git a/test/check-readiness/testdata/golden/watch-nonnumeric-interval.stderr b/test/check-readiness/testdata/golden/watch-nonnumeric-interval.stderr index 3cb2c43bb..cc23fc457 100644 --- a/test/check-readiness/testdata/golden/watch-nonnumeric-interval.stderr +++ b/test/check-readiness/testdata/golden/watch-nonnumeric-interval.stderr @@ -22,3 +22,7 @@ Options: --no-color Disable color output (auto-disabled on non-TTY) -h, --help Show this help +Exit status: 0 when everything is ready, 1 when something is not ready or a +write to stdout fails, 2 on invalid arguments. A closed pipe ends the process +with SIGPIPE, like other Unix tools. +