Skip to content
Open
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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,6 @@ Reading works against any Flagsmith instance. Changing flags — `flag update`,

## Conventions

- `--json` (or `FLAGSMITH_JSON_OUTPUT`) for machine-readable output; `--jq <expr>` to filter it.
- `--json` (or `FLAGSMITH_JSON_OUTPUT`) for machine-readable output; `--jq <expr>` to filter it. Add `--jq-pretty` to indent filtered JSON when reading or saving it.
- Static credentials: `FLAGSMITH_API_KEY` (Admin API), `FLAGSMITH_ENVIRONMENT_KEY` (SDK). When self-hosting Flagsmith, append the host and port, doubling `-` and writing `.` and `:` as `_`: `https://flagsmith-staging.com:8000` reads `FLAGSMITH_API_KEY_flagsmith__staging_com_8000`.
- Self-hosted: `--api-url` or `FLAGSMITH_API_URL`.
8 changes: 4 additions & 4 deletions internal/cmd/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ func runAPI(cmd *cobra.Command, args []string) error {
if apiIncludeFlag {
writeStatusLine(out, resp)
}
return writeBody(out, respBody, jqFlag)
return writeBody(out, respBody, outputOpts())
}

// apiTarget resolves the base URL and the auth applier for the chosen surface.
Expand Down Expand Up @@ -266,16 +266,16 @@ func writeStatusLine(w io.Writer, resp *http.Response) {

// writeBody writes the response verbatim, or filters it through jq. Raw
// passthrough preserves the API's own formatting; --jq requires JSON.
func writeBody(w io.Writer, body []byte, jqExpr string) error {
if jqExpr == "" {
func writeBody(w io.Writer, body []byte, opts output.Options) error {
if opts.JQ == "" {
_, err := w.Write(body)
return err
}
var v any
if err := json.Unmarshal(body, &v); err != nil {
return fmt.Errorf("response is not JSON, cannot apply --jq: %w", err)
}
return output.Render(w, v, output.Options{JQ: jqExpr}, nil)
return output.Render(w, v, opts, nil)
}

func init() {
Expand Down
17 changes: 17 additions & 0 deletions internal/cmd/cmd_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8173,6 +8173,23 @@ func TestAPI(t *testing.T) {
}
})

t.Run("--jq-pretty indents filtered API output", func(t *testing.T) {
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
// Given
flagUpdateEnv(t)

// When
out, err := run("", "api", "api/v1/organisations/", "--jq", "{names: [.results[].name]}", "--jq-pretty")

// Then
if err != nil {
t.Fatalf("api: %v", err)
}
want := "{\n \"names\": [\n \"Acme\"\n ]\n}\n"
if out != want {
t.Errorf("out = %q, want %q", out, want)
}
})

t.Run("a field implies POST with a typed JSON body", func(t *testing.T) {
flagUpdateEnv(t)
e := echoJSON(t, "", "-F", "n=3", "-f", "s=3")
Expand Down
4 changes: 3 additions & 1 deletion internal/cmd/environment.go
Original file line number Diff line number Diff line change
Expand Up @@ -258,7 +258,9 @@ var environmentDocumentCmd = &cobra.Command{
return err
}
// A document is always JSON; --jq composes.
return output.Render(cmd.OutOrStdout(), parsed, output.Options{JSON: true, JQ: jqFlag}, nil)
opts := outputOpts()
opts.JSON = true
return output.Render(cmd.OutOrStdout(), parsed, opts, nil)
},
}

Expand Down
5 changes: 4 additions & 1 deletion internal/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ var (
noInputFlag bool
jsonFlag bool
jqFlag string
jqPrettyFlag bool
)

// jsonOutput reports whether machine-readable output was requested.
Expand All @@ -103,7 +104,7 @@ func jsonOutput() bool {

// outputOpts is the render format for the current invocation.
func outputOpts() output.Options {
return output.Options{JSON: jsonOutput(), JQ: jqFlag}
return output.Options{JSON: jsonOutput(), JQ: jqFlag, JQPretty: jqPrettyFlag}
}

// usageError is a missing/invalid input a prompt would have collected
Expand Down Expand Up @@ -264,6 +265,8 @@ func init() {
"output JSON instead of human-readable text (env: FLAGSMITH_JSON_OUTPUT)")
flags.StringVar(&jqFlag, "jq", "",
"filter JSON output through a jq expression (implies --json)")
flags.BoolVar(&jqPrettyFlag, "jq-pretty", false,
"indent JSON results from --jq")

rootCmd.SetUsageTemplate(singleLineUsage(rootCmd.UsageTemplate()))

Expand Down
23 changes: 14 additions & 9 deletions internal/output/output.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,9 @@ import (

// Options selects the output format for a single command invocation.
type Options struct {
JSON bool // emit JSON instead of a human view
JQ string // filter JSON through this jq expression (implies JSON)
JSON bool // emit JSON instead of a human view
JQ string // filter JSON through this jq expression (implies JSON)
JQPretty bool // indent structured jq results
}

func (o Options) jsonMode() bool { return o.JSON || o.JQ != "" }
Expand Down Expand Up @@ -66,7 +67,7 @@ func Render(w io.Writer, data any, opts Options, human func(io.Writer) error) er
return human(w)
}
if opts.JQ != "" {
return renderJQ(w, data, opts.JQ)
return renderJQ(w, data, opts.JQ, opts.JQPretty)
}
encoded, err := json.MarshalIndent(data, "", " ")
if err != nil {
Expand All @@ -77,8 +78,8 @@ func Render(w io.Writer, data any, opts Options, human func(io.Writer) error) er
}

// renderJQ runs a jq expression over data and prints each result: raw for
// strings, compact JSON otherwise (matching `gh --jq`).
func renderJQ(w io.Writer, data any, expr string) error {
// strings, JSON otherwise. JSON is compact by default (matching `gh --jq`).
func renderJQ(w io.Writer, data any, expr string, pretty bool) error {
query, err := gojq.Parse(expr)
if err != nil {
return fmt.Errorf("invalid jq expression: %w", err)
Expand All @@ -93,6 +94,10 @@ func renderJQ(w io.Writer, data any, expr string) error {
return err
}
iter := query.Run(input)
encoder := json.NewEncoder(w)
if pretty {
encoder.SetIndent("", " ")
}
for {
v, ok := iter.Next()
if !ok {
Expand All @@ -102,14 +107,14 @@ func renderJQ(w io.Writer, data any, expr string) error {
return err
}
if s, ok := v.(string); ok {
fmt.Fprintln(w, s)
if _, err := fmt.Fprintln(w, s); err != nil {
return err
}
continue
}
encoded, err := json.Marshal(v)
if err != nil {
if err := encoder.Encode(v); err != nil {
return err
}
fmt.Fprintln(w, string(encoded))
}
return nil
}
Expand Down
19 changes: 19 additions & 0 deletions internal/output/output_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,25 @@ func TestRenderJQImpliesJSONAndFilters(t *testing.T) {
}
})

t.Run("pretty output indents objects and keeps strings raw", func(t *testing.T) {
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
// Given
var b bytes.Buffer

// When
err := Render(&b, sample{7, "beta"}, Options{
JQ: "{n: [.id]}, .name", JQPretty: true,
}, nil)

// Then
if err != nil {
t.Fatal(err)
}
want := "{\n \"n\": [\n 7\n ]\n}\nbeta\n"
if got := b.String(); got != want {
t.Errorf("output = %q, want %q", got, want)
}
})

t.Run("invalid expression errors", func(t *testing.T) {
// Given
var b bytes.Buffer
Expand Down