From 7f00d40bf26339718bb68056b2bba83744a564d4 Mon Sep 17 00:00:00 2001 From: Toly Pochkin Date: Tue, 22 Jun 2021 17:07:31 +0300 Subject: [PATCH] initial commit --- .gitignore | 26 ++++++ README.md | 1 + example/main.go | 34 ++++++++ go.mod | 6 ++ go.sum | 29 +++++++ main.go | 223 ++++++++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 319 insertions(+) create mode 100644 .gitignore create mode 100644 README.md create mode 100644 example/main.go create mode 100644 go.mod create mode 100644 go.sum create mode 100644 main.go diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..cc4a9f6 --- /dev/null +++ b/.gitignore @@ -0,0 +1,26 @@ +.DS_Store + +# Idea +.idea/ +*.iml + +# Binaries for programs and plugins +/gobetter +*.exe +*.exe~ +*.dll +*.so +*.dylib + +# Test binary, built with `go test -c` +*.test + +# Output of the go coverage tool, specifically when used with LiteIDE +*.out + +# Dependency directories (remove the comment below to include it) +# vendor/ + +.env +.docker_build/ +bin/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..7de3543 --- /dev/null +++ b/README.md @@ -0,0 +1 @@ +# gobetter diff --git a/example/main.go b/example/main.go new file mode 100644 index 0000000..c7f7438 --- /dev/null +++ b/example/main.go @@ -0,0 +1,34 @@ +package example + +//go:generate gobetter main.go + +import ( + "go/ast" + "strings" +) + +// DummyInterface for interface +type DummyInterface interface{} + +// HelloStruct comment +type HelloStruct struct { //+constructor + FirstName, LastName string //+required + Age int `json:"age"` //+required + Description *string `json:"description"` + Tags []int `json:"tags"` + ZZ func(a1, a2 int, + a3 *string) interface{} //+required + Test strings.Builder //+required + test2 *ast.Scope +} + +type AnotherStruct struct { //+constructor + FieldAlpha string // +required + FieldBeta string + FieldGamma HelloStruct // +required +} + +func test() { + var z *ast.Scope = nil + println(z) +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..f08a20a --- /dev/null +++ b/go.mod @@ -0,0 +1,6 @@ +module github.com/mobiletoly/gobetter + +go 1.16 + +require ( +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..cf83176 --- /dev/null +++ b/go.sum @@ -0,0 +1,29 @@ +github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/mod v0.4.2 h1:Gz96sIWK3OalVv/I/qNygP42zyoKp3xptRVCWRFEBvo= +golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210510120138-977fb7262007 h1:gG67DSER+11cZvqIMb8S8bt0vZtiN6xWYARwirrOSfE= +golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210616094352-59db8d763f22 h1:RqytpXGR1iVNX7psjB3ff8y7sNFinVFvkx1c8SjBkio= +golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.1.3 h1:L69ShwSZEyCsLKoAxDKeMvLDZkumEe8gXUZAjab0tX8= +golang.org/x/tools v0.1.3/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= diff --git a/main.go b/main.go new file mode 100644 index 0000000..2f7cf9a --- /dev/null +++ b/main.go @@ -0,0 +1,223 @@ +package main + +import ( + "fmt" + "go/ast" + "go/parser" + "go/token" + "io/ioutil" + "log" + "os" + "os/exec" + "path/filepath" + "regexp" + "strings" +) + +type StructParser struct { + fileSet *token.FileSet + fileContent []byte + whitespaceRegexp *regexp.Regexp + flagRequiredRegexp *regexp.Regexp +} + +type GobBuilder struct { + common strings.Builder + constructorDef strings.Builder + constructorBody strings.Builder + astFile *ast.File +} + +// HelloStruct comment +type HelloStruct struct { //+constructor + // First and last names + FirstName string //+required + // Age + Age int `json:"age"` //+required + // Description + Description *string `json:"description"` + Tags []int `json:"tags"` + // Pointer to function + ZZ func(a1, a2 int, + a3 *string) interface{} //+required + + Test strings.Builder //+required + test2 *ast.Scope +} + +func (bld *GobBuilder) appendPackage(filename string) { + bld.common.WriteString("// Code generated by gobetter; DO NOT EDIT.\n\n") + bld.common.WriteString(fmt.Sprintf("//go:generate goimports -w %s\n\n", filename)) + bld.common.WriteString(fmt.Sprintf("package %s\n\n", bld.astFile.Name.Name)) +} + +func (bld *GobBuilder) appendImports() { + bld.common.WriteString("import (\n") + for _, i := range bld.astFile.Imports { + fmt.Println(i.Path.Value) + bld.common.WriteString(fmt.Sprintf("\t%s\n", i.Path.Value)) + } + bld.common.WriteString(")\n\n") +} + +func (bld *GobBuilder) appendArgStruct(structName string, fieldName string, fieldType string) (structArgName string) { + structArgName = structName + fieldName + "Arg" + bld.common.WriteString(fmt.Sprintf("// %s represents field %s of struct %s\n", structArgName, fieldName, structName)) + bld.common.WriteString(fmt.Sprintf("type %s struct {\n", structArgName)) + bld.common.WriteString(fmt.Sprintf("\tArg %s\n}\n", fieldType)) + bld.common.WriteString(fmt.Sprintf("// %s%s creates argument for field %s\n", structName, fieldName, fieldName)) + bld.common.WriteString(fmt.Sprintf("func %s%s(arg %s) %s {\n", structName, fieldName, + fieldType, structArgName)) + bld.common.WriteString(fmt.Sprintf("\treturn %s{Arg: arg}\n}\n\n", structArgName)) + return +} + +func (bld *GobBuilder) appendArgStructConstructor(structName string, fieldName string, fieldType string) (structArgName string) { + structArgName = structName + fieldName + "Arg" + bld.common.WriteString(fmt.Sprintf("func %s%s(arg %s) %s {\n", structName, fieldName, + fieldType, structArgName)) + bld.common.WriteString(fmt.Sprintf("\treturn %s{Arg: arg}\n}\n\n", structArgName)) + return +} + +func (bld *GobBuilder) appendBeginConstructorDef(structName string) { + bld.constructorDef.WriteString(fmt.Sprintf("// New%s creates new instance of %s struct\n", structName, structName)) + bld.constructorDef.WriteString(fmt.Sprintf("func New%s(\n", structName)) +} + +func (bld *GobBuilder) appendBeginConstructorBody(structName string) { + bld.constructorBody.WriteString(fmt.Sprintf("\treturn %s{\n", structName)) +} + +func (bld *GobBuilder) appendConstructorArg(fieldName string, structArgName string) { + argName := "arg" + fieldName + bld.constructorDef.WriteString(fmt.Sprintf("\t%s %s,\n", argName, structArgName)) + bld.constructorBody.WriteString(fmt.Sprintf("\t\t%s: %s.Arg,\n", fieldName, argName)) +} + +func (bld *GobBuilder) Build() string { + return bld.common.String() +} + +func (bld *GobBuilder) AcceptStruct(structName string) { + if bld.constructorDef.Len() > 0 { + bld.common.WriteString(bld.constructorDef.String()) + bld.common.WriteString(fmt.Sprintf(") %s {\n", structName)) + bld.common.WriteString(bld.constructorBody.String()) + bld.common.WriteString("\t}\n") + bld.common.WriteString("}\n") + bld.constructorDef.Reset() + bld.constructorBody.Reset() + } +} + +func NewStructParser(fileSet *token.FileSet, fileContent []byte) StructParser { + return StructParser{ + fileSet: fileSet, + fileContent: fileContent, + whitespaceRegexp: regexp.MustCompile(`\s+`), + flagRequiredRegexp: regexp.MustCompile("\\b+required\\b"), + } +} + +func (sp *StructParser) fieldTypeText(field *ast.Field) string { + begin := sp.fileSet.Position(field.Type.Pos()).Offset + end := sp.fileSet.Position(field.Type.End()).Offset + return sp.whitespaceRegexp.ReplaceAllString(string(sp.fileContent[begin:end]), " ") +} + +func (sp *StructParser) fieldRequired(field *ast.Field) bool { + return sp.flagRequiredRegexp.MatchString(field.Comment.Text()) +} + +func fileNameWithoutExt(fileName string) string { + return strings.TrimSuffix(fileName, filepath.Ext(fileName)) +} + +func outputFilename(inFilename string) string { + path := filepath.Dir(inFilename) + ext := filepath.Ext(inFilename) + outFilename := fmt.Sprintf("%s/%s_gob%s", path, fileNameWithoutExt(filepath.Base(inFilename)), ext) + return outFilename +} + +func parseCommandLineArgs() (inFilename string, outFilename string) { + if len(os.Args) < 2 { + _, _ = fmt.Fprintln(os.Stderr, "Error: filename is required") + os.Exit(1) + } + inFilename = os.Args[1] + if _, err := os.Stat(inFilename); os.IsNotExist(err) { + _, _ = fmt.Fprintf(os.Stderr, "File %s does not exist\n", inFilename) + os.Exit(1) + } + + _, err := exec.LookPath("goimports") + if err != nil { + _, _ = fmt.Fprintln(os.Stderr, "Error: \"goimports\" executable does not exist") + _, _ = fmt.Fprintln(os.Stderr, "You must install it to continue with gobetter:\n"+ + " go get golang.org/x/tools/cmd/goimports") + os.Exit(1) + } + + outFilename = outputFilename(inFilename) + println("Input file: " + inFilename) + println("Output file: " + outFilename) + return +} + +func main() { + + inFilename, outFilename := parseCommandLineArgs() + fileContent, err := ioutil.ReadFile(inFilename) + fset := token.NewFileSet() + astFile, err := parser.ParseFile(fset, inFilename, nil, parser.ParseComments) + if err != nil { + log.Fatal(err) + } + sp := NewStructParser(fset, fileContent) + + gobBld := GobBuilder{ + astFile: astFile, + } + gobBld.appendPackage(filepath.Base(outFilename)) + gobBld.appendImports() + + ast.Inspect(astFile, func(n ast.Node) bool { + ts, ok := n.(*ast.TypeSpec) + if !ok { + return true + } + st, ok := ts.Type.(*ast.StructType) + if !ok { + return true + } + fmt.Printf("Struct type declaration found : %s\n", ts.Name.Name) + + structName := ts.Name.Name + + for _, field := range st.Fields.List { + fieldTypeText := sp.fieldTypeText(field) + for _, fieldName := range field.Names { + requiredField := sp.fieldRequired(field) + + if requiredField { + structArgName := gobBld.appendArgStruct(structName, fieldName.Name, fieldTypeText) + if gobBld.constructorDef.Len() == 0 { + gobBld.appendBeginConstructorDef(structName) + gobBld.appendBeginConstructorBody(structName) + } + gobBld.appendConstructorArg(fieldName.Name, structArgName) + } + } + } + + gobBld.AcceptStruct(structName) + return true + }) + + result := gobBld.Build() + if err = ioutil.WriteFile(outFilename, []byte(result), os.FileMode(0644)); err != nil { + panic(err) + } +}