Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Conversation

@CorentinGS
Copy link
Owner

@CorentinGS CorentinGS commented Feb 2, 2025

This PR should resolve #18 but needs more work to support Nags notation

Summary by CodeRabbit

  • New Features

    • Enhanced the chess game output with a complete PGN format, now displaying detailed game tags, move history, comments, and variations for a richer gameplay representation.
  • Bug Fixes

    • Improved move command handling to prevent runtime errors, ensuring smoother game updates and stability.
  • Tests

    • Expanded test coverage with new scenarios to validate the accuracy of the game output, ensuring consistent and reliable performance.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 2, 2025

Warning

Rate limit exceeded

@CorentinGS has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 12 minutes and 4 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 7ac84a6 and 6683974.

📒 Files selected for processing (2)
  • game.go (3 hunks)
  • move.go (1 hunks)

Walkthrough

The changes refactor the game's output logic by updating the String() method to generate a complete PGN representation using a strings.Builder. A new helper function, writeMoves(), formats moves, comments, and variations recursively. The UnmarshalText() method is updated to correctly parse PGN data, and a nil-check has been added in the SetCommand() method of the move struct. In addition, a comprehensive test suite for the PGN output has been introduced in game_test.go.

Changes

File(s) Change Summary
game.go Updated String() method to build a complete PGN representation including tags, moves, comments, and variations; improved UnmarshalText() to parse PGN.
game_test.go Added TestGameString to validate various PGN output scenarios including different move structures, comments, variations, and game outcomes.
move.go Added a nil-check in the SetCommand() method to initialize the command map before use, preventing potential runtime errors.

Sequence Diagram(s)

sequenceDiagram
    participant Game
    participant Builder
    participant MoveFormatter

    Game->>Builder: Initialize strings.Builder
    Game->>Builder: Append tag pairs
    alt Moves exist?
        Game->>MoveFormatter: Call writeMoves() with moves, comments, variations
        MoveFormatter-->>Game: Return formatted moves string
        Game->>Builder: Append moves string
    end
    Builder-->>Game: Return complete PGN string via String()
Loading

Assessment against linked issues

Objective Addressed Explanation
Game.String() returns PGN, not FEN [#18]

Poem

I'm a happy rabbit on a code-filled spree,
Hopping through tags and moves with glee.
PGN now sings where FEN once lay,
Carrots and code brighten the day.
A joyful leap in every bit of play!
🥕🐇


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 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. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @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.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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
Contributor

@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: 0

🧹 Nitpick comments (4)
game.go (3)

358-444: Consider refactoring for lower cognitive complexity.

Static analysis flagged the writeMoves function with a cognitive complexity of 24, exceeding recommended thresholds. Extracting tasks into smaller helper functions (e.g., handling comments, variations, and sub-variation logic) can improve readability and maintainability without losing clarity.

🧰 Tools
🪛 golangci-lint (1.62.2)

360-360: cognitive complexity 24 of func writeMoves is high (> 20)

(gocognit)


401-401: S1009: should omit nil check; len() for map[string]string is defined as zero

(gosimple)


401-401: Remove redundant nil-check for command.

In Go, calling len(nilMap) returns 0, so explicitly checking currentMove.command != nil before len(currentMove.command) > 0 is unnecessary. Removing the extra check simplifies the logic.

-if currentMove.command != nil && len(currentMove.command) > 0 {
+if len(currentMove.command) > 0 {
🧰 Tools
🪛 golangci-lint (1.62.2)

401-401: S1009: should omit nil check; len() for map[string]string is defined as zero

(gosimple)


452-463: Validate partial PGN data.

UnmarshalText correctly constructs a reader and calls PGN. Consider expanding negative tests (e.g., invalid PGN tokens) to ensure robust error handling. This function already returns errors from PGN(r), so coverage looks sufficient, but you can add more edge-case tests if the parser is prone to partial read edge cases.

game_test.go (1)

1015-1176: Improve subtest naming for clarity.

The subtests "GameStringWithDifferentResults" appear thrice (lines 1082, 1091, and 1100). Having identical names can confuse some test runners or hamper debugging. Rename them to distinguish White/Black/Draw results.

Otherwise, these tests provide comprehensive coverage of the PGN rendering logic and are highly commendable.

-    name: "GameStringWithDifferentResults",
+    name: "GameStringWithWhiteWinResult",

-    name: "GameStringWithDifferentResults",
+    name: "GameStringWithBlackWinResult",

-    name: "GameStringWithDifferentResults",
+    name: "GameStringWithDrawResult",
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ca3054d and 17c88a1.

📒 Files selected for processing (3)
  • game.go (3 hunks)
  • game_test.go (1 hunks)
  • move.go (1 hunks)
🧰 Additional context used
🪛 golangci-lint (1.62.2)
game.go

360-360: cognitive complexity 24 of func writeMoves is high (> 20)

(gocognit)


401-401: S1009: should omit nil check; len() for map[string]string is defined as zero

(gosimple)

🔇 Additional comments (3)
game.go (2)

25-29: No issues with the added imports.


337-356: Add fallback for empty move list.

The method gracefully handles the scenario where rootMove has no children by simply appending the outcome string. However, if rootMove is nil (in a pathological case) or incorrectly initialized, you might risk a panic when accessing len(g.rootMove.children). Consider adding a fallback so that an uninitialized rootMove yields just the outcome string.

move.go (1)

75-77: Properly initialize command map.

This ensures you never write to a nil map, preventing runtime panics. If concurrency is a concern, consider using synchronization or concurrent-safe data structures since multiple goroutines could modify command simultaneously.

coderabbitai bot added a commit that referenced this pull request Feb 2, 2025
Docstrings generation was requested by @CorentinGS.

* #19 (comment)

The following files were modified:

* `game.go`
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 2, 2025

Note

Generated docstrings for this pull request at #20

Copy link
Contributor

@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: 0

🧹 Nitpick comments (2)
game.go (2)

358-444: Consider breaking down the complex writeMoves function.

While the implementation is correct, the function has high cognitive complexity (23). Consider extracting the following into helper functions to improve readability and maintainability:

  • Move encoding logic (lines 385-394)
  • Comment handling (lines 397-407)
  • Variation handling (lines 419-428)

Example refactor:

 func writeMoves(node *Move, moveNum int, isWhite bool, sb *strings.Builder, subVariation bool) {
     if node == nil {
         return
     }
 
     var currentMove *Move
     if subVariation {
         currentMove = node
     } else {
         if len(node.children) == 0 {
             return
         }
         currentMove = node.children[0]
     }
 
     writeMoveNumber(moveNum, isWhite, subVariation, sb)
-    // Encode the move using your AlgebraicNotation.
-    if node.Parent() == nil {
-        sb.WriteString(AlgebraicNotation{}.Encode(node.Position(), currentMove))
-    } else {
-        moveStr := AlgebraicNotation{}.Encode(node.Parent().Position(), currentMove)
-        sb.WriteString(moveStr)
-    }
+    writeMoveEncoding(node, currentMove, sb)
 
-    // Append a comment if present.
-    if currentMove.comments != "" {
-        sb.WriteString(" {" + currentMove.comments + "}")
-    }
+    writeComments(currentMove, sb)
 
-    if len(currentMove.command) > 0 {
-        sb.WriteString(" {")
-        for key, value := range currentMove.command {
-            sb.WriteString(" [%" + key + " " + value + "]")
-        }
-        sb.WriteString(" }")
-    }
+    writeCommands(currentMove, sb)
 
     if !subVariation {
         sb.WriteString(" ")
     } else if len(currentMove.children) > 0 {
         sb.WriteString(" ")
     }
 
-    // Process any variations
-    if len(node.children) > 1 {
-        for i := 1; i < len(node.children); i++ {
-            variation := node.children[i]
-            sb.WriteString("(")
-            writeMoves(variation, moveNum, isWhite, sb, true)
-            sb.WriteString(") ")
-        }
-    }
+    writeVariations(node, moveNum, isWhite, sb)
 
     if len(currentMove.children) > 0 {
         var nextMoveNum int
         var nextIsWhite bool
         if isWhite {
             nextMoveNum = moveNum
             nextIsWhite = false
         } else {
             nextMoveNum = moveNum + 1
             nextIsWhite = true
         }
         writeMoves(currentMove, nextMoveNum, nextIsWhite, sb, false)
     }
 }

+func writeMoveNumber(moveNum int, isWhite bool, subVariation bool, sb *strings.Builder) {
+    if isWhite {
+        sb.WriteString(fmt.Sprintf("%d. ", moveNum))
+    } else if subVariation {
+        sb.WriteString(fmt.Sprintf("%d... ", moveNum))
+    }
+}
+
+func writeMoveEncoding(node *Move, currentMove *Move, sb *strings.Builder) {
+    if node.Parent() == nil {
+        sb.WriteString(AlgebraicNotation{}.Encode(node.Position(), currentMove))
+    } else {
+        moveStr := AlgebraicNotation{}.Encode(node.Parent().Position(), currentMove)
+        sb.WriteString(moveStr)
+    }
+}
+
+func writeComments(move *Move, sb *strings.Builder) {
+    if move.comments != "" {
+        sb.WriteString(" {" + move.comments + "}")
+    }
+}
+
+func writeCommands(move *Move, sb *strings.Builder) {
+    if len(move.command) > 0 {
+        sb.WriteString(" {")
+        for key, value := range move.command {
+            sb.WriteString(" [%" + key + " " + value + "]")
+        }
+        sb.WriteString(" }")
+    }
+}
+
+func writeVariations(node *Move, moveNum int, isWhite bool, sb *strings.Builder) {
+    if len(node.children) > 1 {
+        for i := 1; i < len(node.children); i++ {
+            variation := node.children[i]
+            sb.WriteString("(")
+            writeMoves(variation, moveNum, isWhite, sb, true)
+            sb.WriteString(") ")
+        }
+    }
+}
🧰 Tools
🪛 golangci-lint (1.62.2)

360-360: cognitive complexity 23 of func writeMoves is high (> 20)

(gocognit)


409-409: Track the TODO for Nags support.

The comment indicates that Nags notation support is incomplete. Would you like me to create an issue to track this enhancement?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 17c88a1 and 7ac84a6.

📒 Files selected for processing (2)
  • game.go (3 hunks)
  • game_test.go (1 hunks)
🧰 Additional context used
🪛 golangci-lint (1.62.2)
game.go

360-360: cognitive complexity 23 of func writeMoves is high (> 20)

(gocognit)

🔇 Additional comments (3)
game.go (2)

336-356: Well-structured PGN output implementation!

The String() method efficiently uses strings.Builder to generate a proper PGN representation, correctly handling tag pairs, moves, and game outcome.


454-464: Clean and correct UnmarshalText implementation!

The implementation properly handles PGN parsing and error propagation.

game_test.go (1)

1015-1176: Excellent test coverage for PGN output!

The test suite is comprehensive and well-structured, covering all important aspects of PGN notation:

  • Basic game states
  • Move notation
  • Comments and variations
  • Tag pairs
  • Game outcomes
  • Complex scenarios with nested variations

Docstrings generation was requested by @CorentinGS.

* #19 (comment)

The following files were modified:

* `game.go`

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: Corentin Giaufer Saubert <[email protected]>
@codecov
Copy link

codecov bot commented Feb 2, 2025

Codecov Report

Attention: Patch coverage is 81.98198% with 20 lines in your changes missing coverage. Please review.

Project coverage is 74.35%. Comparing base (ca3054d) to head (6683974).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
game.go 84.61% 14 Missing and 2 partials ⚠️
move.go 42.85% 4 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main      #19      +/-   ##
==========================================
+ Coverage   73.96%   74.35%   +0.38%     
==========================================
  Files          27       27              
  Lines        5078     5186     +108     
==========================================
+ Hits         3756     3856     +100     
- Misses       1188     1194       +6     
- Partials      134      136       +2     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@CorentinGS CorentinGS merged commit 776f4ec into main Feb 2, 2025
11 checks passed
@CorentinGS CorentinGS deleted the fix/game_pgn branch February 3, 2025 09:04
@coderabbitai coderabbitai bot mentioned this pull request Feb 5, 2025
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.

Game.String() returns FEN, not PGN

2 participants