Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(wip): schema struct gen #80

Open
wants to merge 8 commits into
base: master
Choose a base branch
from

Conversation

gm0stache
Copy link

@gm0stache gm0stache commented Feb 9, 2025

ok, basic idea is working:

  • in the /ssgtest pkg you will find a file with some struct definitions + the go gen cmd
  • execute go generate ./ssgtest/some_test.go in the project root
    • you will find two generated files with types that have the same field names, but are type of ZogSchema 🎉

open 2dos:

  • add tests
  • add more fine-grained schema types to the field
    • e.g. source field has type string -> generated field should have StringSchema type

=> how do you like it?

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Launched a command-line interface that supports an "ssg" command to enable automated schema generation.
    • Enabled automatic code generation for schemas based on defined data structures.
  • Tests

    • Added sample examples demonstrating how to use the new schema generation functionality via directive-based commands.

Copy link
Contributor

coderabbitai bot commented Feb 9, 2025

Walkthrough

This pull request introduces a new command-line application entry point in the main package that processes arguments to execute specific commands. When the "ssg" command is provided, control is passed to a schema generator function in the ssg package. The generator analyzes Go source code using AST parsing to collect struct metadata and generate corresponding Go files from a template. Additionally, new test types and go:generate directives in a test package validate the schema generation functionality.

Changes

File(s) Change Summary
cmd/zog/main.go
cmd/zog/ssg/generator.go
Added a new main package with a main function that checks command-line arguments. Introduced schema generation logic in the ssg package, including functionality for AST parsing, metadata aggregation, field type conversion, and code generation based on a template.
ssgtest/some_test.go Introduced test types with go:generate directives to validate schema generation. Defined sample structs (with and without JSON annotations) as examples for generating schema files.

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant M as Main (cmd/zog/main.go)
    participant S as SchemaGen (cmd/zog/ssg/generator.go)

    U->>M: Execute application with "ssg" command
    M->>S: Call Run(osArgs)
    S->>S: Retrieve GOFILE & GOLINE environment variables
    S->>S: Parse Go file and aggregate struct metadata via AST
    S->>S: Generate output file using predefined template
    S-->>M: Return generation result or error
    M-->>U: Display output or error message
Loading

Poem

Hopping through code with a twitch of my nose,
I found new commands where the schema grows.
With AST magic and templates so neat,
My hoppy heart skips a joyful beat.
Bugs beware, I'm on a code-filled ride! 🐰
Carrots and commits by my side.


📜 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 e33286c and 8146af7.

📒 Files selected for processing (1)
  • cmd/zog/ssg/generator.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • cmd/zog/ssg/generator.go

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

🧹 Nitpick comments (4)
cmd/zog/ssg/generator.go (3)

35-39: Handle direct invocation gracefully.
Currently, the logic depends on the GOFILE environment variable, which is set automatically by go:generate. If users call this tool directly (not via go:generate), GOFILE won't be set and will trigger a fatal error. Consider adding a usage message or fallback behavior to make direct invocation more user-friendly.


62-83: Avoid potential fragility in matching the struct declaration line.
Relying on fset.Position(x.Pos()).Line == genLine+1 may skip the target struct if extra blank or comment lines appear. Consider a more robust approach, such as matching the type name directly or scanning for the first encountered type after the directive.


197-216: Implement narrower schema type mappings.
The placeholder code defaults all field types to zog.ZogSchema. Mapping known primitives (e.g., string, int) to specialized schema types will increase clarity and correctness, especially once the package moves beyond an initial proof-of-concept.

ssgtest/some_test.go (1)

1-1: Consider renaming the package for clarity.
Using package main in a test file may be confusing if you plan to run tests with “go test”. To keep consistency, consider placing these structs in a ssgtest or similar package name.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e1a84bf and e33286c.

📒 Files selected for processing (3)
  • cmd/zog/main.go (1 hunks)
  • cmd/zog/ssg/generator.go (1 hunks)
  • ssgtest/some_test.go (1 hunks)

Comment on lines +11 to +16
switch os.Args[1] {
case "ssg":
ssg.Run(os.Args[2:])
default:
fmt.Println("Unknown command")
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Prevent potential index out-of-range panic.
Calling os.Args[1] directly can crash if no arguments are passed. Ensure that len(os.Args) > 1 before switching on os.Args[1].

Apply this fix:

 func main() {
+	if len(os.Args) < 2 {
+		fmt.Println("Usage: zog [ssg]")
+		os.Exit(1)
+	}
 	switch os.Args[1] {
 	case "ssg":
 		ssg.Run(os.Args[2:])
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
switch os.Args[1] {
case "ssg":
ssg.Run(os.Args[2:])
default:
fmt.Println("Unknown command")
}
func main() {
if len(os.Args) < 2 {
fmt.Println("Usage: zog [ssg]")
os.Exit(1)
}
switch os.Args[1] {
case "ssg":
ssg.Run(os.Args[2:])
default:
fmt.Println("Unknown command")
}
}

@Oudwins
Copy link
Owner

Oudwins commented Feb 11, 2025

Hey! Thanks for making this first draft!

I see what you meant when you said we were talking past each other. Now I think I get what you were going for, you are supposed to pass the generated struct's to the z.Struct() constructor.

type userSchemaType {
   Name ZogSchema
...
}
type User struct {
 Name string
....
}
userSchema := z.Struct(userSchemaType{
// this is type safe
Name: z.String()...
})

Right?

@gm0stache
Copy link
Author

you are welcome!

... yes! that is exactly what i want to archive. how do you like the idea + technical approach here?

@Oudwins
Copy link
Owner

Oudwins commented Mar 7, 2025

Sorry for taking so long reply. I have been thinking about it. Honestly, I was not sure I liked it for a long while. And I still want to think about it a little more. But there is a massive benefit to this approach I had not thought of:

It allows us to have typesafe Omit, Pick and Extend methods. Which is VERY nice.

So let me think about it a bit more and get back to you

@gm0stache
Copy link
Author

@Oudwins thanks for your response!
there is no hurry. take your time 😃

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