Skip to content

Commit

Permalink
initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
mobiletoly committed Jun 22, 2021
1 parent 7f00d40 commit d1fe987
Show file tree
Hide file tree
Showing 5 changed files with 286 additions and 45 deletions.
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License

Copyright (c) 2021 Toly Pochkin.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
160 changes: 159 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,159 @@
# gobetter
# GO Better

This project is an attempt to address lack of required fields in Go's struct types. As you are aware, when you create a
structure in Go - you cannot specify required fields. For example, if we have a structure for Person such as

```
type Person struct {
FirstName string
LastName string
Age int
Description string // optional field
}
```

then normally this is how you will create the instance of this structure:

```
var person = Person{
FirsName: "Joe",
LastName: "Doe",
Age: 40,
}
```

This is all good unless you have a different places where you have to create a `Person` structure, then when you
add new fields, it will become a challenge to scan through code to find all occurrences of creating Person. One of
the suggestion you can normally find is to create a construction function with arguments representing required fields.
In this case you can create and fill `Person` structure with `NewPerson()` constructor. Here is an example:

```
func NewPerson(firstName string, lastName string, age int) Person {
return Person{
FirstName = firstName,
LastName = lastName,
Age = age,
}
}
```

The typical will be be `person := NewPerson("Joe", "Doe", 40)`
This is actually not a bad solution, but unfortunately it means that you have to manually update your `NewPerson`
function every time when you add or remove fields. Moreover, because Go does not have named parameters, you
need to be very careful when you move fields within the structure or add a new one, because you might start
passing wrong values. E.g. if you swap FirstName and LastName in Person structure then suddenly your call to `NewPerson`
will be resulting in FirstName being "Doe" and LastName being "Joe". Compiler does not help us here.

So the approach I would like to use is to create a simple struct wrapper for every required field, such as

```
// structures for arguments
type PersonFirstNameArg struct {
Arg string
}
type PersonLastNameArgArg struct {
Arg string
}
type PersonAgeArgArg struct {
Arg int
}
// single-argument constructor for every argument structure
func PersonFirstName(arg string) PersonFirstNameArg {
return PersonFirstNameArg{Arg: arg}
}
func PersonLastName(arg string) PersonLastNameArg {
return PersonLastNameArg{Arg: arg}
}
func PersonAge(arg int) PersonAgeArg {
return PersonAgeArg{Arg: arg}
}
```

then constructor function is going to look like

```
func NewPerson(
argFirstName PersonFirstNameArg,
argLastName PersonLastNameArg,
argAge PersonAgeArg,
) Person {
return Person{
FirstName: argFirstName.Arg,
LastName: argLastName.Arg,
Age: argAge.Arg,
}
}
```

Here is typical call to create a new instance of Person struct

```
person := NewPerson(
PersonFirstName("Joe"),
PersonLastName("Doe"),
PersonAge(40),
)
```

that is it! Now we have required fields and compiler will guarantee (with compiler-time errors) that we pass
parameters in correct order.

But, you don't want to do this work manually, especially if you have to deal with many large structures. That is why
we have depeveloper a tool called `gobetter` to generate all this structs and constructors for you.

### Pre-requisites

You have to install two tools:

First one is `goimports` (if you don't have it already installed). It will be used by gobetter to optimize imports
and perform proper formatting.

```shell
go get -u golang.org/x/tools/cmd/goimports
```

Then you must install `gobetter` itself:

```shell
go get -u github.com/mobiletoly/gobetter
```

### Usage

Tool is very easy to use. First you have to add `go:generate` comment into a file with a structures you want to create
required parameters for, after that you can mark required fields with a special comment. E.g. this is how your
data structure that you use to serialize/deserialize JSON is going to look like

```
//go:generate gobetter $GOFILE
package main
...
type Person struct { //+constructor
FirstName string `json:"first_name"` //+required
LastName string `json:"last_name"` //+required
Age int `json:"age"` //+required
Description string `json:"description"`
}
```

`+constructor` comment serves as a flag and must be on the same line as struct (you can add more text to this comment
but flag needs to be a separate word). It instructs gobetter to generate argument structures and constructor for this
structure.

`+required` flag in comment hints gobetter that structure field is required and must be added to constructor.

All you have to do now is to run `go generate` tool to generate go files that will be containing argument structures
as well as constructors for your structures.

```shell
go generate ./...
```

For example if you have a file in example package `example/main.go` then new file `example/main_gob.go` will be
generated, and it will contain argument structures and constructors for structures from `main.go` file.
38 changes: 14 additions & 24 deletions example/main.go
Original file line number Diff line number Diff line change
@@ -1,34 +1,24 @@
//go:generate gobetter $GOFILE
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
// Person is not marked with +constructor flag
type Person 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
}

func test() {
var z *ast.Scope = nil
println(z)
// AnotherPerson is not marked with +constructor flag
type AnotherPerson struct {
FirstName, LastName string //+required
Age int `json:"age"` //+required
}
74 changes: 74 additions & 0 deletions example/main_gob.go

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

38 changes: 18 additions & 20 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ type StructParser struct {
fileSet *token.FileSet
fileContent []byte
whitespaceRegexp *regexp.Regexp
constructorRegexp *regexp.Regexp
flagRequiredRegexp *regexp.Regexp
}

Expand All @@ -28,33 +29,14 @@ type GobBuilder struct {
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")
Expand Down Expand Up @@ -116,6 +98,7 @@ func NewStructParser(fileSet *token.FileSet, fileContent []byte) StructParser {
fileSet: fileSet,
fileContent: fileContent,
whitespaceRegexp: regexp.MustCompile(`\s+`),
constructorRegexp: regexp.MustCompile("\\b+constructor\\b"),
flagRequiredRegexp: regexp.MustCompile("\\b+required\\b"),
}
}
Expand All @@ -130,6 +113,14 @@ func (sp *StructParser) fieldRequired(field *ast.Field) bool {
return sp.flagRequiredRegexp.MatchString(field.Comment.Text())
}

func (sp *StructParser) constructorRequired(st *ast.StructType) bool {
begin := st.Struct
endLine := sp.fileSet.File(begin).Line(begin) + 1
end := sp.fileSet.File(begin).LineStart(endLine)
result := string(sp.fileContent[sp.fileSet.Position(begin).Offset:sp.fileSet.Position(end).Offset])
return sp.constructorRegexp.MatchString(result)
}

func fileNameWithoutExt(fileName string) string {
return strings.TrimSuffix(fileName, filepath.Ext(fileName))
}
Expand Down Expand Up @@ -192,8 +183,11 @@ func main() {
if !ok {
return true
}
fmt.Printf("Struct type declaration found : %s\n", ts.Name.Name)
if !sp.constructorRequired(st) {
return true
}

fmt.Printf("Generate constructor for %s\n", ts.Name.Name)
structName := ts.Name.Name

for _, field := range st.Fields.List {
Expand All @@ -220,4 +214,8 @@ func main() {
if err = ioutil.WriteFile(outFilename, []byte(result), os.FileMode(0644)); err != nil {
panic(err)
}
z := exec.Command("goimports", "-w", outFilename)
if err := z.Run(); err != nil {
log.Fatal(err)
}
}

0 comments on commit d1fe987

Please sign in to comment.