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

HW09 is completed #15

Open
wants to merge 6 commits into
base: master
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
115 changes: 115 additions & 0 deletions hw09_generator_of_validators/go-validate/generate.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
package main

import (
"bytes"
"go/format"
"text/template"
)

var goValidateTemplate = template.Must(template.New("go-validate").Parse(`
// generated by go-validate; DO NOT EDIT
package models

import (
"fmt"
"regexp"
"strconv"
"strings"
)

type ValidationError struct {
Field string
Err error
}

func ContainsInt(toFind int, searchingString string) bool {
for _, strValue := range strings.Split(searchingString, ",") {
invValue, err := strconv.Atoi(strValue)
if err != nil {
return false
}
if toFind == invValue {
return true
}
}
return false
}

func ContainsStr(toFind string, searchingString string) bool {
for _, value := range strings.Split(searchingString, ",") {
if toFind == value {
return true
}
}
return false
}

{{range $index, $struct := .}}
{{if $struct.Fields}}
func (structName {{$struct.Name}}) Validate() ([]ValidationError, error) {
errors := make([]ValidationError, 0)

{{range $index, $field := $struct.Fields}}

{{/* begin loop for slices */}}
{{$variableName := $field.Name | printf "%s.%s" "structName"}}
{{if $field.IsSlice}}
for _, value := range structName.{{$field.Name}} {
{{$variableName = "value"}}
{{end}}

{{range $index, $condition := $field.Conditions}}
{{if eq $condition.Name "len"}}
if len({{$variableName}}) != {{$condition.Value}} {
errors = append(errors, ValidationError{Field: "{{$field.Name}}", Err: fmt.Errorf("invalid {{$field.Name}} length")})
}
{{else if eq $condition.Name "min"}}
if {{$variableName}} < {{$condition.Value}} {
errors = append(errors, ValidationError{Field: "{{$field.Name}}", Err: fmt.Errorf("invalid {{$field.Name}} length")})
}
{{else if eq $condition.Name "max"}}
if {{$variableName}} > {{$condition.Value}} {
errors = append(errors, ValidationError{Field: "{{$field.Name}}", Err: fmt.Errorf("invalid {{$field.Name}} length")})
}
{{else if eq $condition.Name "regexp"}}
if re := regexp.MustCompile({{$condition.Value | printf "%q"}}); re.FindString({{$field.Type}}({{$variableName}})) == "" {
errors = append(errors, ValidationError{Field: "{{$field.Name}}", Err: fmt.Errorf("invalid {{$field.Name}} field, empty regexp")})
}
{{else if eq $condition.Name "in"}}
{{if eq $field.Type "int"}}
if !ContainsInt({{$field.Type}}({{$variableName}}), "{{$condition.Value}}") {
errors = append(errors, ValidationError{Field: "{{$field.Name}}", Err: fmt.Errorf("invalid {{$field.Name}} value in range")})
}
{{else if eq $field.Type "string"}}
if !ContainsStr({{$field.Type}}({{$variableName}}), "{{$condition.Value}}") {
errors = append(errors, ValidationError{Field: "{{$field.Name}}", Err: fmt.Errorf("invalid {{$field.Name}} value in range")})
}
{{end}}
{{end}}
{{end}}

{{/* end loop for slices */}}
{{if $field.IsSlice}}
}
{{end}}
{{end}}
return errors, nil
}
{{end}}
{{end}}
`))

func GenerateDocument(recvStruct []ParsedStruct) ([]byte, error) {
var buf bytes.Buffer
err := goValidateTemplate.Execute(&buf, recvStruct)
if err != nil {
return nil, err
}

document, err := format.Source(buf.Bytes())
if err != nil {
return nil, err
}

return document, nil
}
103 changes: 103 additions & 0 deletions hw09_generator_of_validators/go-validate/generate_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
package main

import (
"io/ioutil"
"testing"

"github.com/stretchr/testify/require"
)

func TestGenerate(t *testing.T) {
t.Run("generate document and compare with file", func(t *testing.T) {
defaultStruct := []ParsedStruct{
ParsedStruct{
Name: "User",
Fields: []Field{
Field{
Name: "ID",
Type: "string",
IsSlice: false,
Conditions: []Condition{
Condition{
Name: "len",
Value: "36",
},
},
},
Field{
Name: "Age",
Type: "int",
IsSlice: false,
Conditions: []Condition{
Condition{
Name: "min",
Value: "18",
},
Condition{
Name: "max",
Value: "50",
},
},
},
Field{
Name: "Email",
Type: "string",
IsSlice: false,
Conditions: []Condition{
Condition{
Name: "regexp",
Value: "^\\w+@\\w+\\.\\w+$",
},
},
},
Field{
Name: "Role",
Type: "UserRole",
IsSlice: false,
Conditions: []Condition{
Condition{
Name: "in",
Value: "admin,stuff",
},
},
},
Field{
Name: "Phones",
Type: "string",
IsSlice: true,
Conditions: []Condition{
Condition{
Name: "len",
Value: "11",
},
},
},
},
},
ParsedStruct{
Name: "App",
Fields: []Field{
Field{
Name: "Version",
Type: "string",
IsSlice: false,
Conditions: []Condition{
Condition{
Name: "len",
Value: "5",
},
},
},
},
},
}

document, err := GenerateDocument(defaultStruct)
require.Nil(t, err)

fileBytes, err := ioutil.ReadFile("testdata/test_models_validation_generated.go")
require.Nil(t, err)

require.Equal(t, fileBytes, document)
})
}
63 changes: 62 additions & 1 deletion hw09_generator_of_validators/go-validate/main.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,66 @@
package main

import (
"fmt"
"os"
"strings"
)

type ParsedDocument struct {
Structs []ParsedStruct
Aliases AliasedStructs
}

type ParsedStruct struct {
Name string
Fields []Field
}

type Field struct {
Name string
Type string
IsSlice bool
Conditions []Condition
}

type Condition struct {
Name string
Value string
}

type AliasedStructs map[string]string

func main() {
// Place your code here
if len(os.Args) < 2 {
fmt.Println("Usage: go-validate [module path]")
os.Exit(1)
}

filename := os.Args[1]
parsedStruct, err := ParseStruct(filename)
if err != nil {
fmt.Println(err)
os.Exit(1)
}

validatedStruct := ValidateStruct(parsedStruct)
document, err := GenerateDocument(validatedStruct)
if err != nil {
fmt.Println(err)
Copy link
Collaborator

Choose a reason for hiding this comment

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

log.Fatal?

os.Exit(1)
}

savedFilename := strings.TrimSuffix(filename, ".go")
f, err := os.Create(fmt.Sprintf("%s_validation_generated.go", savedFilename))
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer f.Close()

_, err = f.Write(document)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
}
Loading