generated from OtusGolang/home_work
-
Notifications
You must be signed in to change notification settings - Fork 0
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
ezhk
wants to merge
6
commits into
master
Choose a base branch
from
hw09_generator_of_validators
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
103
hw09_generator_of_validators/go-validate/generate_test.go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
}) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
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) | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
log.Fatal?