Skip to content

Conversation

@eynopv
Copy link
Owner

@eynopv eynopv commented Apr 9, 2025

Summary by CodeRabbit

  • New Features

    • Introduced an option to enable colorized JSON output, enhancing readability by applying color highlights to keys and values.
  • Tests

    • Expanded test coverage to ensure consistent and correct behavior for both colorized and plain JSON outputs across various data types, including additional scenarios for colored integers, strings, booleans, and lists.

@coderabbitai
Copy link

coderabbitai bot commented Apr 9, 2025

Walkthrough

The changes update the JSON formatting functionality to include an optional colorized output. The formatJson function and the Formatter.Json method now accept an additional boolean flag controlling colorization. The previous reliance on json.MarshalIndent has been replaced with a custom recursive formatting approach using type-specific helper functions. The test suite has been updated accordingly to include the new useColor flag and validate the colorized outputs for various JSON types.

Changes

File Summary
pkg/printer/formatter.go Updated formatJson and Formatter.Json signatures with an added colorized boolean parameter; replaced json.MarshalIndent with a custom recursive formatting process; introduced helper functions (formatJsonKey, formatJsonStringValue, etc.) for type-specific formatting.
pkg/printer/formatter_test.go Modified test cases by adding a useColor field to the test struct; added and adjusted test cases to validate colorized JSON output for various data types; renamed a test case (from checking an unmarshalable value to "colored nil").

Sequence Diagram(s)

sequenceDiagram
    participant C as Client
    participant F as Formatter.Json
    participant Fmt as formatJson
    participant H as Helper Functions

    C->>F: Call Json(j, colorized)
    F->>Fmt: Invokes formatJson(j, colorized)
    Fmt->>H: Format JSON key via formatJsonKey(key, colorized)
    alt Process each JSON value by type
        Fmt->>H: Call formatJsonStringValue/NumberValue/BoolValue/NilValue based on type
    end
    H-->>Fmt: Return formatted value
    Fmt-->>F: Return complete formatted JSON string
    F-->>C: Return (colorized) JSON output
Loading

📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ebb5aeb and 765f94a.

📒 Files selected for processing (1)
  • pkg/printer/formatter_test.go (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
pkg/printer/formatter_test.go (2)
pkg/printer/colors.go (5)
  • Yellow (27-29)
  • Cyan (39-41)
  • Green (23-25)
  • Magenta (35-37)
  • Red (19-21)
pkg/printer/formatter.go (1)
  • Formatter (14-16)
🔇 Additional comments (8)
pkg/printer/formatter_test.go (8)

177-180: Good addition of the useColor field in the test structure

The addition of the useColor field to the test case struct properly supports testing both colorized and non-colorized JSON formatting, aligning with the feature's requirements.


202-207: Well-structured test case for empty JSON objects

This test case appropriately handles the edge case of empty JSON objects, which is important for robust testing.


208-215: Good test coverage for colored integer values

The test correctly verifies that integers are displayed with cyan coloring in the JSON output.


216-223: Good test coverage for colored string values

The test correctly verifies that strings are displayed with green coloring in the JSON output.


224-231: Good test coverage for colored boolean values

The test correctly verifies that boolean values are displayed with magenta coloring in the JSON output.


232-239: Good test coverage for colored float values

The test correctly verifies that floating-point values are displayed with cyan coloring in the JSON output.


240-247: Good test coverage for colored nil values

The test correctly verifies that nil values are displayed as "null" with red coloring in the JSON output.


268-270: Good implementation of formatter instantiation

The test correctly creates the Formatter with the appropriate colored value from the test case, ensuring that each test uses the correct configuration.

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

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: 1

🧹 Nitpick comments (2)
pkg/printer/formatter_test.go (1)

191-201: Consider renaming or merging duplicate "nested" tests.
The “nested” test case appears twice with the same content and non-colorized output. It could be beneficial to unify these two test cases under a single scenario or rename one to differentiate them.

Also applies to: 209-218

pkg/printer/formatter.go (1)

179-179: Remove or replace debug statement.
The fmt.Printf("%T\n", vv) call appears to be leftover debugging. Consider removing it or switching to a structured logger if needed.

 fmt.Printf("%T\n", vv)
- sb.WriteString(formatValue(vv, level))
+ sb.WriteString(formatValue(vv, level))
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 459345c and f3c813d.

📒 Files selected for processing (2)
  • pkg/printer/formatter.go (3 hunks)
  • pkg/printer/formatter_test.go (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
pkg/printer/formatter_test.go (2)
pkg/printer/colors.go (5)
  • Yellow (27-29)
  • Cyan (39-41)
  • Green (23-25)
  • Magenta (35-37)
  • Red (19-21)
pkg/printer/formatter.go (1)
  • Formatter (14-16)
pkg/printer/formatter.go (1)
pkg/printer/colors.go (5)
  • Yellow (27-29)
  • Green (23-25)
  • Cyan (39-41)
  • Magenta (35-37)
  • Red (19-21)
🪛 GitHub Actions: .github/workflows/ci.yml
pkg/printer/formatter_test.go

[error] 279-279: Test_formatJson/colored_list failed: expected equal; got: {"list": [1, "string", false, null]}; want: {"list": [1, "string", false, null, {"one": 1, "two": 2}]}

🔇 Additional comments (4)
pkg/printer/formatter_test.go (3)

177-180: Good addition of fields to the test case struct.
These new fields (name, json, useColor, want) enhance the flexibility of the test suite by permitting distinct inputs and colorization settings for thorough JSON formatting tests.


202-207: Comprehensive coverage for empty maps.
Covering edge cases like empty maps is crucial. This test scenario helps confirm that the formatter handles empty JSON objects gracefully.


277-277: Correct usage of the formatter with color-enabled tests.
Instantiating Formatter{colored: tt.useColor} is consistent with the updated design and ensures the test logic toggles color output properly.

pkg/printer/formatter.go (1)

162-193: Handle unrecognized data types or confirm limited type usage.
If this code is intended to support additional Go types (e.g., int64, uint, custom structs), it will silently produce "". Verify that only these specific types (string, number, bool, nil, map, slice) will be passed in or handle others gracefully.

Would you like a script to check for potential calls passing unsupported types to Formatter.Json across your codebase?

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: 1

🔭 Outside diff range comments (1)
pkg/printer/formatter_test.go (1)

191-218: ⚠️ Potential issue

Duplicate test case: remove redundant "nested" test case.

There are two identical test cases named "nested" with the same input and expected output. The second instance (lines 209-218) should be removed to avoid redundancy.

-	{
-		name: "nested",
-		json: map[string]any{
-			"user": map[string]any{
-				"id":   1,
-				"name": "Bob",
-			},
-		},
-		useColor: false,
-		want:     "{\n  \"user\": {\n    \"id\": 1,\n    \"name\": \"Bob\"\n  }\n}",
-	},
🧹 Nitpick comments (1)
pkg/printer/formatter.go (1)

161-192: Consider improving array formatting for better readability of complex arrays.

The current implementation doesn't add newlines or proper indentation for array elements, which could make the output less readable for complex arrays with nested structures. Consider enhancing the array formatting to add newlines and indentation when elements are maps or arrays themselves.

 case []any:
     sb := strings.Builder{}
     sb.WriteString("[")
+
+    hasComplexElements := false
+    for _, vv := range v {
+        switch vv.(type) {
+        case map[string]any, []any:
+            hasComplexElements = true
+            break
+        }
+    }
+
+    padding := strings.Repeat("  ", level+1)
 
     for i, vv := range v {
+        isComplex := false
+        switch vv.(type) {
+        case map[string]any, []any:
+            isComplex = true
+        }
+
+        if hasComplexElements && isComplex {
+            sb.WriteString("\n")
+            sb.WriteString(padding)
+        }
+
         sb.WriteString(formatValue(vv, level))
 
         if i != len(v)-1 {
-            sb.WriteString(", ")
+            if hasComplexElements {
+                sb.WriteString(",\n")
+                sb.WriteString(padding)
+            } else {
+                sb.WriteString(", ")
+            }
         }
     }
+
+    if hasComplexElements {
+        sb.WriteString("\n")
+        sb.WriteString(strings.Repeat("  ", level))
+    }
 
     sb.WriteString("]")
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f3c813d and ebb5aeb.

📒 Files selected for processing (2)
  • pkg/printer/formatter.go (3 hunks)
  • pkg/printer/formatter_test.go (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
pkg/printer/formatter_test.go (2)
pkg/printer/colors.go (5)
  • Yellow (27-29)
  • Cyan (39-41)
  • Green (23-25)
  • Magenta (35-37)
  • Red (19-21)
pkg/printer/formatter.go (1)
  • Formatter (14-16)
pkg/printer/formatter.go (1)
pkg/printer/colors.go (5)
  • Yellow (27-29)
  • Green (23-25)
  • Cyan (39-41)
  • Magenta (35-37)
  • Red (19-21)
🔇 Additional comments (2)
pkg/printer/formatter.go (2)

30-32: Function signature inconsistency with AI summary.

The AI summary indicates that the method signature was updated to func (f Formatter) Json(j map[string]any, colorized bool) string, but the implementation still uses the original signature and passes the struct's colored field instead. This implementation is correct and matches how the function is called in tests, but the summary is inaccurate.


116-240: LGTM: Effective implementation of colorized JSON formatting.

The implementation effectively handles different JSON value types and applies appropriate colorization based on the type. The recursive approach with type-specific helper functions is clean and maintainable.

@eynopv eynopv merged commit 06ab251 into master Apr 13, 2025
3 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