Skip to content

feat: list with JSON output#27

Merged
feloy merged 2 commits intokortex-hub:mainfrom
feloy:list-json
Mar 9, 2026
Merged

feat: list with JSON output#27
feloy merged 2 commits intokortex-hub:mainfrom
feloy:list-json

Conversation

@feloy
Copy link
Contributor

@feloy feloy commented Mar 9, 2026

adds JSON output to the list command, using the WorkspacesList interface defined in https://github.com/kortex-hub/kortex-cli-api v0.1.3

@coderabbitai
Copy link

coderabbitai bot commented Mar 9, 2026

📝 Walkthrough

Walkthrough

Adds a new --output (-o) flag to the workspace list command that accepts "json" and, when set, emits workspace data as indented JSON via a new outputJSON helper; also updates go.mod and adds tests covering flag validation and JSON output.

Changes

Cohort / File(s) Summary
Dependency Management
go.mod
Replaced single require with a require block and added indirect module github.com/kortex-hub/kortex-cli-api/cli/go v0.0.0-20260309100818-e0ea254e6f13; existing github.com/spf13/cobra v1.10.2 preserved.
Workspace list CLI
pkg/cmd/workspace_list.go
Adds --output/-o flag and output string field; validates allowed formats in PreRun; branches run to call new outputJSON when json requested; implements outputJSON to map internal instances to API workspaces and marshal to indented JSON.
Tests
pkg/cmd/workspace_list_test.go
Extends PreRun tests for output flag (valid/invalid, short/long flags) and adds E2E-style JSON-output tests (empty list and single workspace) that parse and validate api.WorkspacesList JSON output.

Sequence Diagram(s)

mermaid
sequenceDiagram
participant User
participant CLI as "kortex-cli (cmd)"
participant Cmd as "workspaceListCmd"
participant Instances as "instances pkg"
participant API as "api types"
participant Stdout as "stdout"
User->>CLI: run workspace list [--output json]
CLI->>Cmd: execute command
Cmd->>Instances: fetch instances list
Instances-->>Cmd: return instances
alt output == "json"
Cmd->>API: map instances -> WorkspacesList
Cmd->>Stdout: marshal & write JSON
else
Cmd->>Stdout: render human-readable list
end

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title 'feat: list with JSON output' clearly and specifically describes the main change: adding JSON output capability to the list command.
Description check ✅ Passed The description is directly related to the changeset, explaining that JSON output is added to the list command using the WorkspacesList interface from kortex-cli-api v0.1.3.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (1)
pkg/cmd/workspace_list_test.go (1)

62-99: Exercise preRun directly in these unit-style cases.

These subtests only assert that Execute() returns nil, so they would still pass if preRun stopped persisting workspaceListCmd.output and the command silently fell back to text output on an empty store. Calling preRun directly and checking manager / output would cover the added state change much more precisely.

Based on learnings, "Command tests should have two types of tests: unit tests that test the preRun method directly, and E2E tests that test full command execution via rootCmd.Execute()" and "In unit tests for commands, use t.Run() for subtests within a parent test function and verify struct fields are set correctly after preRun execution".

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/cmd/workspace_list_test.go` around lines 62 - 99, The tests currently
only call rootCmd.Execute(), which doesn't verify preRun mutated command state;
instead, instantiate the workspace list command via NewRootCmd() and locate the
workspaceListCmd instance, call its preRun method directly (or the method
exposed for setup) with a fresh context and args, then assert the command's
fields (workspaceListCmd.manager and workspaceListCmd.output) are set as
expected for each flag case (no output, --output json, -o json); keep the
existing Execute() E2E tests but add these unit-style subtests to validate
preRun behavior and ensure manager/output are persisted correctly.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@pkg/cmd/workspace_list.go`:
- Around line 21-27: preRun currently passes the raw storageDir flag value into
instances.NewManager without normalization; update the preRun handler (the
function that reads the --storage flag) to call filepath.Abs(storageDir) and use
the resulting absolute path (or return/log an error if Abs fails) before passing
it into instances.NewManager so all storage paths are deterministic; reference
the storageDir variable in preRun and the call to instances.NewManager to locate
where to perform the normalization.
- Around line 116-124: The JSON output write ignores possible errors from
fmt.Fprintln; update the code after calling json.MarshalIndent to capture and
return any write error from writing to cmd.OutOrStdout() (i.e., replace the
fmt.Fprintln call with writing that checks the returned error and returns
fmt.Errorf or the raw error), so failures when the stdout consumer closes early
are propagated; keep the existing JSON marshalling error handling around
json.MarshalIndent and ensure the function (where this appears) returns the
write error instead of always returning nil.

---

Nitpick comments:
In `@pkg/cmd/workspace_list_test.go`:
- Around line 62-99: The tests currently only call rootCmd.Execute(), which
doesn't verify preRun mutated command state; instead, instantiate the workspace
list command via NewRootCmd() and locate the workspaceListCmd instance, call its
preRun method directly (or the method exposed for setup) with a fresh context
and args, then assert the command's fields (workspaceListCmd.manager and
workspaceListCmd.output) are set as expected for each flag case (no output,
--output json, -o json); keep the existing Execute() E2E tests but add these
unit-style subtests to validate preRun behavior and ensure manager/output are
persisted correctly.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 7fcd63f4-6528-43bf-a047-e2afc8b77b7a

📥 Commits

Reviewing files that changed from the base of the PR and between 2bcefa0 and b0f4659.

⛔ Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
📒 Files selected for processing (3)
  • go.mod
  • pkg/cmd/workspace_list.go
  • pkg/cmd/workspace_list_test.go

feloy added 2 commits March 9, 2026 13:45
Signed-off-by: Philippe Martin <phmartin@redhat.com>
Signed-off-by: Philippe Martin <phmartin@redhat.com>
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

♻️ Duplicate comments (1)
pkg/cmd/workspace_list.go (1)

116-124: ⚠️ Potential issue | 🟡 Minor

Return JSON write failures instead of dropping them.

Line 123 ignores the error from fmt.Fprintln, so a broken pipe or closed stdout still reports success. Writing through json.NewEncoder(...).Encode(...) fixes that and also avoids the extra buffer copy.

Suggested fix
-	// Marshal to JSON with indentation
-	jsonData, err := json.MarshalIndent(workspacesList, "", "  ")
-	if err != nil {
-		return fmt.Errorf("failed to marshal workspaces to JSON: %w", err)
-	}
-
-	// Output the JSON to stdout
-	fmt.Fprintln(cmd.OutOrStdout(), string(jsonData))
-	return nil
+	encoder := json.NewEncoder(cmd.OutOrStdout())
+	encoder.SetIndent("", "  ")
+	if err := encoder.Encode(workspacesList); err != nil {
+		return fmt.Errorf("failed to write workspaces as JSON: %w", err)
+	}
+	return nil
#!/bin/bash
set -euo pipefail

sed -n '116,124p' pkg/cmd/workspace_list.go
rg -n -C2 'fmt\.Fprintln\(cmd\.OutOrStdout\(\), string\(jsonData\)\)' pkg/cmd/workspace_list.go
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/cmd/workspace_list.go` around lines 116 - 124, The code currently
marshals workspacesList to a buffer and calls fmt.Fprintln(cmd.OutOrStdout(),
string(jsonData)) which ignores write errors; replace this with
json.NewEncoder(cmd.OutOrStdout()).Encode(workspacesList) (or call
encoder.Encode on the already-created jsonData source) so the write error is
returned and not dropped—update the function that performs the output (the block
using json.MarshalIndent and fmt.Fprintln) to use
json.NewEncoder(cmd.OutOrStdout()).Encode(...) and return any error from Encode
instead of discarding it.
🧹 Nitpick comments (1)
pkg/cmd/workspace_list_test.go (1)

62-133: Test preRun() directly in the unit-test section.

These cases currently execute the full command, so a failure in run() can mask whether preRun() handled --output correctly. Please instantiate workspaceListCmd, call preRun() directly, and assert the parsed state (output, manager) there; keep rootCmd.Execute() coverage in the E2E block.

As per coding guidelines: "Command tests should have two types of tests: unit tests that test the preRun method directly, and E2E tests that test full command execution via rootCmd.Execute()" and "In unit tests for commands, use t.Run() for subtests within a parent test function and verify struct fields are set correctly after preRun execution".

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/cmd/workspace_list_test.go` around lines 62 - 133, The tests are
exercising the full command (rootCmd.Execute()) so failures in run() can hide
whether preRun() parsed flags correctly; modify the unit tests to instantiate
workspaceListCmd directly, call its preRun(cmd, args) method, and assert the
command's fields (output and manager) are set as expected (e.g., output ==
"json" or error for invalid formats) instead of relying only on
rootCmd.Execute(); keep existing E2E Execute() tests separate. Locate
workspaceListCmd, its preRun and run methods and replace the subtests that
currently call rootCmd.Execute() with calls that construct workspaceListCmd, set
Flags/Args as needed, call preRun(), and assert workspaceListCmd.output and
workspaceListCmd.manager (or expected error) to validate flag parsing.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@pkg/cmd/workspace_list.go`:
- Around line 116-124: The code currently marshals workspacesList to a buffer
and calls fmt.Fprintln(cmd.OutOrStdout(), string(jsonData)) which ignores write
errors; replace this with
json.NewEncoder(cmd.OutOrStdout()).Encode(workspacesList) (or call
encoder.Encode on the already-created jsonData source) so the write error is
returned and not dropped—update the function that performs the output (the block
using json.MarshalIndent and fmt.Fprintln) to use
json.NewEncoder(cmd.OutOrStdout()).Encode(...) and return any error from Encode
instead of discarding it.

---

Nitpick comments:
In `@pkg/cmd/workspace_list_test.go`:
- Around line 62-133: The tests are exercising the full command
(rootCmd.Execute()) so failures in run() can hide whether preRun() parsed flags
correctly; modify the unit tests to instantiate workspaceListCmd directly, call
its preRun(cmd, args) method, and assert the command's fields (output and
manager) are set as expected (e.g., output == "json" or error for invalid
formats) instead of relying only on rootCmd.Execute(); keep existing E2E
Execute() tests separate. Locate workspaceListCmd, its preRun and run methods
and replace the subtests that currently call rootCmd.Execute() with calls that
construct workspaceListCmd, set Flags/Args as needed, call preRun(), and assert
workspaceListCmd.output and workspaceListCmd.manager (or expected error) to
validate flag parsing.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 68af2bb5-37f3-4e22-bb10-e82a7e5d35d6

📥 Commits

Reviewing files that changed from the base of the PR and between b0f4659 and 201bff3.

⛔ Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
📒 Files selected for processing (3)
  • go.mod
  • pkg/cmd/workspace_list.go
  • pkg/cmd/workspace_list_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • go.mod

@feloy feloy merged commit e6609e6 into kortex-hub:main Mar 9, 2026
6 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants