Skip to content

feat: add gen idea infra point #2

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion examples/examples_test.go → examples/base/base_test.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package examples
package base

import (
"testing"
Expand Down
2 changes: 1 addition & 1 deletion examples/business.go → examples/base/business.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package examples
package base

import (
"time"
Expand Down
2 changes: 1 addition & 1 deletion examples/translator.go → examples/base/translator.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package examples
package base

import (
"bytes"
Expand Down
2 changes: 1 addition & 1 deletion examples/user.go → examples/base/user.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package examples
package base

import "github.com/9ssi7/rapidval"

Expand Down
10 changes: 10 additions & 0 deletions examples/structured/user.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package structured

//go:generate go run ../../rapidval/main.go -type=User -input=$GOFILE
type User struct {
ID int64 `json:"id" validate:"min=1"`
Username string `json:"username" validate:"required,min=3,max=50"`
Email string `json:"email" validate:"required,email"`
Age int `json:"age" validate:"min=0,max=150"`
IsActive bool `json:"is_active"`
}
81 changes: 81 additions & 0 deletions examples/structured/user_validate.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

186 changes: 186 additions & 0 deletions gen/generator.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
package gen

import (
"flag"
"fmt"
"go/ast"
"go/parser"
"go/token"
"os"
"path/filepath"
"strings"
"text/template"
)

var (
typeName = flag.String("type", "", "type name to generate validator for")
input = flag.String("input", "", "input file path")
)

// Helper structs for template
type FieldInfo struct {
Name string
Type string
Rules map[string]string
}

func parseValidateTag(tag string) map[string]string {
rules := make(map[string]string)
if tag == "" {
return rules
}

tag = strings.Trim(tag, "`")
for _, tagPart := range strings.Split(tag, " ") {
if strings.HasPrefix(tagPart, `validate:"`) {
validations := strings.Trim(strings.TrimPrefix(tagPart, `validate:"`), `"`)
for _, validation := range strings.Split(validations, ",") {
if strings.Contains(validation, "=") {
parts := strings.Split(validation, "=")
rules[parts[0]] = parts[1]
} else {
rules[validation] = ""
}
}
}
}
return rules
}

func Run() {
flag.Parse()

if *typeName == "" {
fmt.Println("Please provide type name with -type flag")
os.Exit(1)
}

if *input == "" {
fmt.Println("Please provide input file path with -input flag")
os.Exit(1)
}

// Get working directory
wd, err := os.Getwd()
if err != nil {
fmt.Printf("Error getting working directory: %v\n", err)
os.Exit(1)
}

// Construct absolute input path
absInputPath := filepath.Join(wd, *input)

// Parse the input file
fset := token.NewFileSet()
node, err := parser.ParseFile(fset, absInputPath, nil, parser.ParseComments)
if err != nil {
fmt.Printf("Error parsing file: %v\n", err)
os.Exit(1)
}

// Get package name from input file
packageName := node.Name.Name

// Get output directory (same as input file)
outDir := filepath.Dir(absInputPath)

// Find the struct
var structType *ast.StructType
ast.Inspect(node, func(n ast.Node) bool {
if td, ok := n.(*ast.TypeSpec); ok {
if td.Name.Name == *typeName {
structType = td.Type.(*ast.StructType)
return false
}
}
return true
})

// Create output file in same directory as input
outPath := filepath.Join(outDir, fmt.Sprintf("%s_validate.go", strings.ToLower(*typeName)))
f, err := os.Create(outPath)
if err != nil {
fmt.Printf("Error creating output file: %v\n", err)
os.Exit(1)
}
defer f.Close()

// Collect field information
var fields []FieldInfo
for _, field := range structType.Fields.List {
if field.Tag != nil {
fieldInfo := FieldInfo{
Name: field.Names[0].Name,
Type: fmt.Sprint(field.Type),
Rules: parseValidateTag(field.Tag.Value),
}
fields = append(fields, fieldInfo)
}
}

// Execute template with helper functions
tmplFuncs := template.FuncMap{
"hasRule": func(rules map[string]string, rule string) bool {
_, exists := rules[rule]
return exists
},
"getRule": func(rules map[string]string, rule string) string {
return rules[rule]
},
}

t := template.Must(template.New("validator").Funcs(tmplFuncs).Parse(validatorTemplate))
err = t.Execute(f, struct {
TypeName string
PackageName string
Fields []FieldInfo
}{
TypeName: *typeName,
PackageName: packageName,
Fields: fields,
})
if err != nil {
panic(err)
}
}

var validatorTemplate = `
// Code generated by validator generator; DO NOT EDIT.
package {{.PackageName}}

import (
"fmt"
"regexp"
)

var emailRegex = regexp.MustCompile(` + "`" + `^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$` + "`" + `)

func (u *{{.TypeName}}) Validate() error {
{{range .Fields}}
{{if .Rules}}
// Validate {{.Name}}
{{if hasRule .Rules "required"}}
if {{if eq .Type "string"}}u.{{.Name}} == ""{{else}}u.{{.Name}} == 0{{end}} {
return fmt.Errorf("{{.Name}} is required")
}
{{end}}
{{if hasRule .Rules "min"}}
if {{if eq .Type "string"}}len(u.{{.Name}}) < {{getRule .Rules "min"}}{{else}}u.{{.Name}} < {{getRule .Rules "min"}}{{end}} {
return fmt.Errorf("{{.Name}} must be at least {{getRule .Rules "min"}}")
}
{{end}}
{{if hasRule .Rules "max"}}
if {{if eq .Type "string"}}len(u.{{.Name}}) > {{getRule .Rules "max"}}{{else}}u.{{.Name}} > {{getRule .Rules "max"}}{{end}} {
return fmt.Errorf("{{.Name}} must be at most {{getRule .Rules "max"}}")
}
{{end}}
{{if hasRule .Rules "email"}}
if !emailRegex.MatchString(u.{{.Name}}) {
return fmt.Errorf("{{.Name}} must be a valid email address")
}
{{end}}
{{end}}
{{end}}
return nil
}
`
7 changes: 7 additions & 0 deletions rapidval/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package main

import "github.com/9ssi7/rapidval/gen"

func main() {
gen.Run()
}