Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions entity/command.go
Original file line number Diff line number Diff line change
Expand Up @@ -391,20 +391,20 @@ func addNamedCommand[T any, R any](
})
if err != nil {
if result != nil {
err = errors.Join(err, RenderResult(result))
err = errors.Join(err, RenderResult(ctx, result))
}
return renderCommandError(name, err)
return renderCommandError(ctx, name, err)
}

return RenderResult(result)
return RenderResult(ctx, result)
}

return cmd
}

func renderCommandError(name string, err error) error {
func renderCommandError(ctx context.Context, name string, err error) error {
if rich, ok := renderableError(err); ok {
if renderErr := RenderResult(rich); renderErr != nil {
if renderErr := RenderResult(ctx, rich); renderErr != nil {
return renderErr
}
} else {
Expand Down
2 changes: 1 addition & 1 deletion entity/delete_flags_spec_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ var _ = Describe("entity delete with flags", func() {
BeforeEach(func() {
rendered = nil
originalRender := RenderResult
RenderResult = func(value any) error {
RenderResult = func(_ context.Context, value any) error {
rendered = append(rendered, value)
return nil
}
Expand Down
2 changes: 1 addition & 1 deletion entity/entity_action_error_spec_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ var _ = Describe("entity action errors", func() {

var rendered any
originalRender := RenderResult
RenderResult = func(value any) error {
RenderResult = func(_ context.Context, value any) error {
rendered = value
return nil
}
Expand Down
10 changes: 5 additions & 5 deletions entity/entity_cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -315,7 +315,7 @@ func generateListCommand(parent *cobra.Command, entity EntityInfo, op EntityOper
if err != nil {
return err
}
return RenderResult(result)
return RenderResult(c.Context(), result)
},
}

Expand Down Expand Up @@ -403,10 +403,10 @@ func generateIDCommand(parent *cobra.Command, spec idCommand) {
}
result, err := runEntityOp(c, op, flagMap, args)
if err != nil {
return renderCommandError(verb, err)
return renderCommandError(c.Context(), verb, err)
}
if result != nil {
return RenderResult(result)
return RenderResult(c.Context(), result)
}
return nil
},
Expand Down Expand Up @@ -515,7 +515,7 @@ func generateBodyCommand(parent *cobra.Command, verb, short string, op EntityOpe
return err
}
if result != nil {
return RenderResult(result)
return RenderResult(c.Context(), result)
}
return nil
},
Expand Down Expand Up @@ -585,7 +585,7 @@ func generateBulkActionCommand(parent *cobra.Command, ba BulkActionInfo) {
return err
}
if result != nil {
return RenderResult(result)
return RenderResult(c.Context(), result)
}
return nil
},
Expand Down
2 changes: 1 addition & 1 deletion entity/primary_action.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ func generatePrimaryAction(entityCmd *cobra.Command, action ActionInfo) {
return err
}
if result != nil {
return RenderResult(result)
return RenderResult(c.Context(), result)
}
return nil
}
Expand Down
7 changes: 5 additions & 2 deletions entity/render.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package entity

import "fmt"
import (
"context"
"fmt"
)

// ParseArgs parses HTTPie-style positional arguments (key=value, key:=json, …)
// into a body map for create/update commands. Root clicky wires it in init() to
Expand All @@ -19,7 +22,7 @@ var ParseArgs = func(args []string) (map[string]any, error) {
// It is a package-level hook rather than a direct dependency so the entity
// package stays free of the root clicky package (which owns the global flag
// state) — preserving the one-way entity → clicky-subpackages dependency.
var RenderResult = func(o any) error { return nil }
var RenderResult = func(ctx context.Context, o any) error { return nil }

// PreflightOutput validates CLI output options before a generated operation runs.
var PreflightOutput = func() error { return nil }
6 changes: 4 additions & 2 deletions entity_aliases.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,13 @@ import (

func init() {
entity.PreflightOutput = Flags.ParseFormatSpec
entity.RenderResult = func(o any) error {
entity.RenderResult = func(ctx context.Context, o any) error {
if err := Flags.ParseFormatSpec(); err != nil {
return err
}
return PrintAndWriteSinks(o, Flags.FormatOptions)
options := Flags.FormatOptions
options.Context = ctx
return PrintAndWriteSinks(o, options)
}
entity.ParseArgs = ParseArgumentsAsMap
}
Expand Down
7 changes: 4 additions & 3 deletions format.go
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,8 @@ func MustPrint(o any, opts ...FormatOptions) {

// Terminate the output. Without this the shell prompt lands on the last
// rendered line, and line-oriented consumers of a redirect drop it.
if result != "" && !strings.HasSuffix(result, "\n") {
options := formatters.MergeOptions(append([]FormatOptions{defaultOpts}, opts...)...)
if result != "" && !strings.HasSuffix(result, "\n") && !formatters.IsBinaryFormat(options.ResolveFormat()) {
result += "\n"
}
fmt.Print(result)
Expand All @@ -171,7 +172,7 @@ func MustPrintStderr(o any, opts ...FormatOptions) {
if err != nil {
panic(err)
}
if result != "" && !strings.HasSuffix(result, "\n") {
if result != "" && !strings.HasSuffix(result, "\n") && !formatters.IsBinaryFormat(options.ResolveFormat()) {
result += "\n"
}
fmt.Fprint(os.Stderr, result)
Expand Down Expand Up @@ -235,7 +236,7 @@ func printFormat(o any, opts FormatOptions) error {
if err != nil {
return err
}
if output != "" && !strings.HasSuffix(output, "\n") && opts.Format != "excel" && opts.Format != "pdf" {
if output != "" && !strings.HasSuffix(output, "\n") && !formatters.IsBinaryFormat(opts.ResolveFormat()) {
output += "\n"
}
_, err = fmt.Fprint(os.Stdout, output)
Expand Down
37 changes: 37 additions & 0 deletions format_sinks_ginkgo_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package clicky

import (
"context"
"errors"
"io"
"os"
Expand All @@ -9,6 +10,7 @@ import (
"github.com/flanksource/clicky/formatters"
"github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/spf13/cobra"
)

type sinkViews struct{}
Expand Down Expand Up @@ -46,6 +48,41 @@ func (sinkViews) FormatView(opts FormatOptions) (any, error) {
}

var _ = ginkgo.Describe("format sinks", func() {
ginkgo.It("passes a generated command context to its formatter", func() {
type contextKey struct{}
var received context.Context
formatters.RegisterFormatter("context-report", func(_ any, opts formatters.FormatOptions) (string, error) {
received = opts.Context
return "", nil
})
defer formatters.UnregisterFormatter("context-report")
previous := Flags.FormatOptions
defer func() { Flags.FormatOptions = previous }()
Flags.FormatOptions = FormatOptions{Format: "context-report"}
parent := &cobra.Command{Use: "root"}
command := AddNamedCommandWithContext("report", parent, struct{}{}, func(context.Context, struct{}) (string, error) { return "report", nil })
ctx, cancel := context.WithCancel(context.WithValue(context.Background(), contextKey{}, "command"))
cancel()
command.SetContext(ctx)
Expect(command.RunE(command, nil)).To(Succeed())
Expect(received.Value(contextKey{})).To(Equal("command"))
Expect(received.Err()).To(MatchError(context.Canceled))
})
ginkgo.It("writes a registered binary formatter to stdout without changing its bytes", func() {
formatters.RegisterFormatter("binary-report", func(any, formatters.FormatOptions) (string, error) {
return "%PDF-binary", nil
}, formatters.WithContentType("application/pdf"))
defer formatters.UnregisterFormatter("binary-report")
output, err := os.CreateTemp(ginkgo.GinkgoT().TempDir(), "stdout")
Expect(err).NotTo(HaveOccurred())
original := os.Stdout
os.Stdout = output
defer func() { os.Stdout = original; _ = output.Close() }()
Expect(printFormat("report", FormatOptions{Format: "binary-report"})).To(Succeed())
contents, err := os.ReadFile(output.Name())
Expect(err).NotTo(HaveOccurred())
Expect(string(contents)).To(Equal("%PDF-binary"))
})
ginkgo.It("uses an independent view for every format", func() {
dir := ginkgo.GinkgoT().TempDir()
jsonPath := filepath.Join(dir, "rows.json")
Expand Down
7 changes: 7 additions & 0 deletions formatters/format_spec_ginkgo_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,13 @@ import (
)

var _ = Describe("format specification preflight", func() {
It("accepts registered custom formats for stdout and file sinks", func() {
RegisterFormatter("report-format", func(any, FormatOptions) (string, error) { return "report", nil })
defer UnregisterFormatter("report-format")
opts := FormatOptions{Format: "report-format,report-format=report.html"}
Expect(opts.ParseFormatSpec()).To(Succeed())
Expect(opts.Sinks).To(Equal([]FormatSink{{Format: "report-format"}, {Format: "report-format", File: "report.html"}}))
})
It("leaves no partial sinks after a bad entry", func() {
opts := FormatOptions{Format: "json=rows.json,unknown"}
Expect(opts.ParseFormatSpec()).To(MatchError(ContainSubstring("unknown format")))
Expand Down
13 changes: 10 additions & 3 deletions formatters/manager_context.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ import (
// forwarded to registered format callbacks.
func (f *FormatManager) FormatWithContext(ctx any, options FormatOptions, data ...any) (string, error) {
defer rpchttp.Track(callerContext(ctx), "format")()
if ctx != nil || options.Context == nil {
options.Context = callerContext(ctx)
}
options.NoColor = options.NoColor || f.noColor
before := collapseFormatInput(data...)
before = f.applyBeforeFormatCallbacks(ctx, options, before)
Expand All @@ -23,7 +26,7 @@ func (f *FormatManager) FormatWithContext(ctx any, options FormatOptions, data .
return "", err
}
output = f.applyAfterFormatCallbacks(ctx, options, before, output)
if options.NoColor && !isBinaryFormat(options.ResolveFormat()) {
if options.NoColor && !IsBinaryFormat(options.ResolveFormat()) {
output = ansi.Strip(output)
}
return output, nil
Expand All @@ -32,6 +35,9 @@ func (f *FormatManager) FormatWithContext(ctx any, options FormatOptions, data .
// FormatWithSchemaContext handles schema-aware formatting while forwarding ctx
// to registered format callbacks.
func (f *FormatManager) FormatWithSchemaContext(ctx any, prettyData *api.PrettyData, options FormatOptions) (string, error) {
if ctx != nil || options.Context == nil {
options.Context = callerContext(ctx)
}
options.NoColor = options.NoColor || f.noColor
before := any(prettyData)
before = f.applyBeforeFormatCallbacks(ctx, options, before)
Expand Down Expand Up @@ -86,13 +92,14 @@ func (f *FormatManager) FormatWithSchemaContext(ctx any, prettyData *api.PrettyD
return "", err
}
output = f.applyAfterFormatCallbacks(ctx, options, before, output)
if options.NoColor && !isBinaryFormat(format) {
if options.NoColor && !IsBinaryFormat(format) {
output = ansi.Strip(output)
}
return output, nil
}

func isBinaryFormat(format string) bool {
// IsBinaryFormat reports whether a built-in or registered format emits binary data.
func IsBinaryFormat(format string) bool {
switch canonicalFormat(strings.ToLower(format)) {
case "pdf", "html-pdf", "excel":
return true
Expand Down
15 changes: 15 additions & 0 deletions formatters/manager_options_test.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,27 @@
package formatters

import (
"context"
"github.com/flanksource/clicky/api"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"net/http/httptest"
)

var _ = Describe("Non-terminal format manager", func() {
It("passes the request context to custom formatters", func() {
type key struct{}
ctx, cancel := context.WithCancel(context.WithValue(context.Background(), key{}, "request"))
request := httptest.NewRequest("GET", "/", nil).WithContext(ctx)
RegisterFormatter("context-test", func(_ any, opts FormatOptions) (string, error) {
Expect(opts.Context.Value(key{})).To(Equal("request"))
cancel()
return "", opts.Context.Err()
})
DeferCleanup(UnregisterFormatter, "context-test")
_, err := NewFormatManager().FormatWithContext(request, FormatOptions{Format: "context-test"}, "example")
Expect(err).To(MatchError(context.Canceled))
})
DescribeTable("preserves binary bytes with NoColor on both formatting paths",
func(format string) {
const binary = "binary\x00\xff\x1b[31mpayload\x1b[0m"
Expand Down
9 changes: 8 additions & 1 deletion formatters/options.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package formatters

import (
"context"
"flag"
"fmt"
"os"
Expand Down Expand Up @@ -65,6 +66,7 @@ type FormatSink struct {

// FormatOptions contains options for formatting operations
type FormatOptions struct {
Context context.Context `json:"-" yaml:"-"`
Format string `json:"format,omitempty"`
NoColor bool `json:"no_color,omitempty"`
Output string `json:"output,omitempty"`
Expand Down Expand Up @@ -168,7 +170,9 @@ func (o *FormatOptions) ParseFormatSpec() error {
return fmt.Errorf("invalid --format entry %q: empty format name", part)
}
if !knownFormats[name] {
return fmt.Errorf("invalid --format entry %q: unknown format %q", part, name)
if _, registered := GetCustomFormatter(name); !registered {
return fmt.Errorf("invalid --format entry %q: unknown format %q", part, name)
}
}
if hasFile && file == "" {
return fmt.Errorf("invalid --format entry %q: empty file path after '='", part)
Expand Down Expand Up @@ -226,6 +230,9 @@ func (o FormatOptions) SkipTree() bool {
func MergeOptions(opts ...FormatOptions) FormatOptions {
merged := FormatOptions{}
for _, opt := range opts {
if opt.Context != nil {
merged.Context = opt.Context
}
if opt.Format != "" {
merged.Format = opt.Format
}
Expand Down
Loading
Loading