Skip to content

fix: make code generation deterministic#13

Merged
connerohnesorge merged 2 commits intomainfrom
fix/deterministic-codegen
Jul 3, 2025
Merged

fix: make code generation deterministic#13
connerohnesorge merged 2 commits intomainfrom
fix/deterministic-codegen

Conversation

@connerohnesorge
Copy link
Owner

@connerohnesorge connerohnesorge commented Jul 3, 2025

Summary

  • Fix non-deterministic map iteration in generateGo function that caused generated Go code to have different key ordering on each run
  • Use existing sortMap function to ensure consistent ordering of ClassMapStr entries

Test plan

  • Verified code generation produces identical output across multiple runs
  • Tested on both simple and dashboard examples
  • All existing tests pass

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Refactor

    • Improved consistency in the ordering of generated map entries, ensuring they are now sorted in a predictable manner.
  • New Features

    • Added a debug handler for Tailwind classes with consistent class name generation for debugging purposes.
    • Introduced a function to detect if the default generator is using the debug handler.
  • Documentation

    • Updated multiple documentation examples and READMEs to rename code generation scripts from gen.go to build.go.
    • Enhanced documentation with details on the new debug handler and related functions.
  • New Component

    • Added a new reusable HTML page component with styled header, navigation, main content, and footer sections.

Fix non-deterministic map iteration in generateGo function that caused
generated Go code to have different key ordering on each run.

Changed from direct map iteration to using the existing sortMap function
to ensure consistent ordering of ClassMapStr entries.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
@coderabbitai
Copy link

coderabbitai bot commented Jul 3, 2025

Walkthrough

The generateGo function was updated to iterate over the cache map in a sorted order using a new sortMap function. This ensures that the generated Go code's map literal entries are consistently ordered by a numeric suffix from the Generated field, instead of being unordered as before. Additionally, a new DebugHandler type and an IsDev() function were added, with documentation updated accordingly. Various example and documentation files were updated to rename code generation script filenames from gen.go to build.go. A new template component function View() was added in the examples.

Changes

File(s) Change Summary
tw.go Modified generateGo to use sortMap(g.Cache()) for sorted iteration over cache map entries; added DebugHandler type and IsDev() function
README.md Added documentation for IsDev() function and DebugHandler type with its methods
doc/src/examples/basic.md Renamed code generation script references from gen.go to build.go
doc/src/examples/complex-webapp.md Renamed code generation script references from gen.go to build.go
doc/src/examples/tailwind-build.md Renamed example build scripts and usage commands from gen*.go to build*.go
doc/src/faq.md Updated GitHub Actions example to run go run ./build.go instead of gen.go
examples/README.md Updated code generation command from go run gen.go to go run build.go
examples/dashboard/README.md Updated code generation command from go run gen.go to go run build.go
examples/dashboard/build.go Removed trailing newline at end of file
examples/simple/views/view_templ.go Added new template component function View() rendering a styled HTML page

Sequence Diagram(s)

sequenceDiagram
    participant generateGo
    participant sortMap
    participant Cache

    generateGo->>Cache: Retrieve cache map
    generateGo->>sortMap: Pass cache map for sorting
    sortMap-->>generateGo: Return sorted keys and values
    loop For each sorted key
        generateGo->>generateGo: Access Generated and Merged fields
        generateGo->>generateGo: Construct map entry
    end
Loading

Possibly related PRs

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 golangci-lint (1.64.8)

level=warning msg="[runner] Can't run linter goanalysis_metalinter: buildir: failed to load package : could not load export data: no export data for "github.com/conneroisu/twerge""
level=error msg="Running error: can't run linter goanalysis_metalinter\nbuildir: failed to load package : could not load export data: no export data for "github.com/conneroisu/twerge""


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 753472a and 0a5d793.

📒 Files selected for processing (9)
  • README.md (7 hunks)
  • doc/src/examples/basic.md (3 hunks)
  • doc/src/examples/complex-webapp.md (3 hunks)
  • doc/src/examples/tailwind-build.md (8 hunks)
  • doc/src/faq.md (1 hunks)
  • examples/README.md (2 hunks)
  • examples/dashboard/README.md (1 hunks)
  • examples/dashboard/build.go (1 hunks)
  • examples/simple/views/view_templ.go (1 hunks)
✅ Files skipped from review due to trivial changes (6)
  • examples/dashboard/build.go
  • examples/dashboard/README.md
  • doc/src/examples/basic.md
  • doc/src/examples/complex-webapp.md
  • doc/src/faq.md
  • examples/README.md
🧰 Additional context used
🧬 Code Graph Analysis (1)
examples/simple/views/view_templ.go (1)
twerge.go (1)
  • It (55-57)
🪛 LanguageTool
README.md

[uncategorized] ~378-~378: Possible missing comma found.
Context: ...) It(s string) string ``` It returns a short unique CSS class name from the merged c...

(AI_HYDRA_LEO_MISSING_COMMA)

🪛 markdownlint-cli2 (0.17.2)
doc/src/examples/tailwind-build.md

310-310: Hard tabs
Column: 1

(MD010, no-hard-tabs)


313-313: Hard tabs
Column: 1

(MD010, no-hard-tabs)


316-316: Hard tabs
Column: 1

(MD010, no-hard-tabs)


317-317: Hard tabs
Column: 1

(MD010, no-hard-tabs)


318-318: Hard tabs
Column: 1

(MD010, no-hard-tabs)


321-321: Hard tabs
Column: 1

(MD010, no-hard-tabs)


322-322: Hard tabs
Column: 1

(MD010, no-hard-tabs)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: checks
🔇 Additional comments (3)
doc/src/examples/tailwind-build.md (1)

18-18: Consistent renaming of build scripts

The renaming from gen.go to build.go (and its variants) is applied consistently throughout the documentation. This improves clarity by using a more descriptive filename that better represents the script's purpose.

Also applies to: 215-215, 295-298, 310-310, 317-317, 322-322, 364-364, 408-408, 433-433, 531-534

README.md (1)

254-254: Well-documented additions for debugging support

The new IsDev() function and DebugHandler type are properly documented with clear descriptions, appropriate warnings about production usage, and complete method signatures. The documentation follows the existing format and integrates seamlessly with the API reference.

Also applies to: 258-262, 289-297, 338-388

examples/simple/views/view_templ.go (1)

1-527: Generated file looks correct

This templ-generated file properly uses twerge.It() to wrap CSS classes throughout the template, which aligns with the library's intended usage pattern. The generated code includes appropriate error handling and buffer management.

Note: As this is a generated file marked with "DO NOT EDIT", no manual modifications should be made to it.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate Unit Tests
  • Create PR with Unit Tests
  • Post Copyable Unit Tests in a Comment
  • Commit Unit Tests in branch fix/deterministic-codegen

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
🪧 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai auto-generate unit tests to generate unit tests for this PR.
  • @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

@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 (1)
tw.go (1)

216-230: Consider edge case handling for non-standard Generated field formats.

The extractNumber function handles the common case well, but there's a potential edge case: if the Generated field doesn't follow the expected "tw-{num}" format (e.g., contains no hyphens or non-numeric suffixes), it returns 0, which could group unexpected formats together at the beginning of the sort order.

Consider adding a comment to document this behavior:

// extractNumber extracts the numeric part from "tw-{num}"
+// Returns 0 for non-standard formats, grouping them at the beginning
func extractNumber(generated string) int {

Or alternatively, you could make the sorting more robust by falling back to string comparison for non-standard formats:

func extractNumber(generated string) int {
	// Split by "-" and get the last part
	parts := strings.Split(generated, "-")
	if len(parts) < 2 {
-		return 0
+		return -1 // Sort non-standard formats before numbered ones
	}

	// Convert to int
	num, err := strconv.Atoi(parts[len(parts)-1])
	if err != nil {
-		return 0
+		return -1 // Sort non-numeric suffixes before numbered ones
	}

	return num
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2efa4fa and 753472a.

📒 Files selected for processing (1)
  • tw.go (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: checks
  • GitHub Check: MacOS Build (aarch64-darwin)
🔇 Additional comments (2)
tw.go (2)

174-182: LGTM! Deterministic code generation achieved.

The modification correctly addresses the non-deterministic map iteration issue by using sortMap(g.Cache()) to ensure consistent ordering. The implementation properly iterates over sorted keys and uses indexed access to the aligned values slice, which will produce identical output across multiple runs.


192-213: Well-implemented sorting function with proper alignment.

The sortMap function correctly:

  • Extracts keys from the map
  • Sorts them by numeric suffix using extractNumber
  • Creates an aligned values slice maintaining the sorted order
  • Returns both slices for consistent iteration

This approach ensures deterministic ordering while maintaining the relationship between keys and their corresponding values.

- Rename gen.go to build.go in dashboard and simple examples
- Update all documentation references from gen.go to build.go
- Update command examples in README files and documentation
- Maintain consistent naming convention across examples

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
@connerohnesorge connerohnesorge merged commit da866ca into main Jul 3, 2025
8 checks passed
@connerohnesorge connerohnesorge deleted the fix/deterministic-codegen branch July 3, 2025 12:37
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.

1 participant