Skip to content

Commit

Permalink
feat: field skipping
Browse files Browse the repository at this point in the history
  • Loading branch information
Bin-Huang committed Aug 16, 2022
1 parent 50f2536 commit 5cd9ccc
Show file tree
Hide file tree
Showing 11 changed files with 139 additions and 18 deletions.
32 changes: 27 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,13 +49,13 @@ See [more examples here](https://github.com/Bin-Huang/newc/tree/master/test)
Without manual installation, just add this comment line to the struct. Go will automatically install this tool if missing.

```go
//go:generate go run github.com/Bin-Huang/[email protected].2
//go:generate go run github.com/Bin-Huang/[email protected].3
```

For example:

```go
//go:generate go run github.com/Bin-Huang/[email protected].2
//go:generate go run github.com/Bin-Huang/[email protected].3
type UserService struct {
baseService
userRepository *repositories.UserRepository
Expand All @@ -65,7 +65,7 @@ type UserService struct {

This is very useful, especially in teamwork. **It can run without manual installation. It doesn't break the work of other people who don't have installed this tool in collaboration.**

## Return value instead reference
## How to return value instead reference?

Add `--value` parameter

Expand All @@ -89,7 +89,7 @@ func NewConfig(debug bool) Config {
}
```

## Call an initializer
## How to call an initializer in constructor?

1. Add `--init` parameter
2. Write an `init` method for the struct
Expand Down Expand Up @@ -123,6 +123,28 @@ func NewController(logger *zap.Logger, debug bool) *Controller {
}
```

## How to ignore some fields when generating constructor code?

Add a tag `newc:"-"` to fields that need to be ignored

```go
type Forbidden struct {
Msg string
Status int `newc:"-"`
}
```

Generated code:

```go
// NewForbidden Create a new Forbidden
func NewForbidden(msg string) *Forbidden {
return &Forbidden{
Msg: msg,
}
}
```

## If you think the `go:generate` comment is too long...

Some suggestions:
Expand All @@ -147,7 +169,7 @@ Don't worry about the imports, variable naming, and code style in the generated
It doesn't break the work of other people who don't have installed this tool in collaboration. Go will automatically install this tool if missing.

```go
//go:generate go run github.com/Bin-Huang/[email protected].2
//go:generate go run github.com/Bin-Huang/[email protected].3
```

## Sponsoring
Expand Down
30 changes: 26 additions & 4 deletions README_zh.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,13 +49,13 @@ func NewUserService(baseService baseService, userRepository *repositories.UserRe
无需手动安装,只需要给结构体添加下面这行注释就行。Go 会在缺失时自动下载这个工具。

```go
//go:generate go run github.com/Bin-Huang/[email protected].2
//go:generate go run github.com/Bin-Huang/[email protected].3
```

比如这样:

```go
//go:generate go run github.com/Bin-Huang/[email protected].2
//go:generate go run github.com/Bin-Huang/[email protected].3
type UserService struct {
baseService
userRepository *repositories.UserRepository
Expand All @@ -65,7 +65,7 @@ type UserService struct {

这个方式非常有用,尤其在团队开发中。**就算其他同事没有安装这个工具,这么做也能正常运行,不会影响到其他人的工作**

## 返回结构体的值,而不是引用
## 如何返回结构体的值,而不是引用

使用 `--value` 参数

Expand Down Expand Up @@ -123,6 +123,28 @@ func NewController(logger *zap.Logger, debug bool) *Controller {
}
```

## 如果在生成构造器时忽略掉一些字段?

给需要忽略的字段添加 `newc:"-"` 标签

```go
type Forbidden struct {
Msg string
Status int `newc:"-"`
}
```

生成代码:

```go
// NewForbidden Create a new Forbidden
func NewForbidden(msg string) *Forbidden {
return &Forbidden{
Msg: msg,
}
}
```

## 如果你觉得这条注释太长……

一些建议:
Expand All @@ -147,7 +169,7 @@ func NewController(logger *zap.Logger, debug bool) *Controller {
就算其他同事没有安装这个工具,这么做也不会影响到他们的工作。因为 Go 会在必要时自动安装这个工具。

```go
//go:generate go run github.com/Bin-Huang/[email protected].2
//go:generate go run github.com/Bin-Huang/[email protected].3
```

## 赞赏
Expand Down
3 changes: 3 additions & 0 deletions generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,9 @@ func GenerateCode(pkgName string, importInfos []ImportInfo, structInfos []Struct
params := []string{}
fields := []string{}
for _, field := range structInfo.Fields {
if field.Skipped {
continue
}
params = append(params, fmt.Sprintf("%v %v", toLowerCamel(field.Name), field.Type))
fields = append(fields, fmt.Sprintf("%v: %v,", field.Name, toLowerCamel(field.Name)))
}
Expand Down
17 changes: 13 additions & 4 deletions parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,9 @@ type StructInfo struct {

// StructField the information of a struct field
type StructField struct {
Name string
Type string
Name string
Type string
Skipped bool
}

// ParseCodeFile parse structs and imports in a code file
Expand Down Expand Up @@ -154,8 +155,9 @@ func ParseCodeFile(filename string) ([]StructInfo, []ImportInfo, error) {
fieldName = strings.TrimPrefix(fieldName, "*")
}
structFields = append(structFields, StructField{
Type: fieldType,
Name: fieldName,
Type: fieldType,
Name: fieldName,
Skipped: isSkippedField(field),
})
}
structs = append(structs, StructInfo{
Expand Down Expand Up @@ -184,3 +186,10 @@ func isInitModeEnable(s string) bool {
func isValueModeEnable(s string) bool {
return strings.Contains(s, "value")
}

func isSkippedField(field *ast.Field) bool {
if field.Tag == nil {
return false
}
return strings.Contains(field.Tag.Value, `newc:"-"`)
}
5 changes: 0 additions & 5 deletions test/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,3 @@ package config
type Config struct {
Debug bool
}

// DebugConfig ...
type DebugConfig struct {
Debug bool
}
12 changes: 12 additions & 0 deletions test/errors/constructor_gen.go

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

19 changes: 19 additions & 0 deletions test/errors/errors.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package errors

import "fmt"

// Forbidden ...
//go:generate go run ../../../newc --value --init
type Forbidden struct {
Msg string `bson:"msg" json:"msg"`
Status int `bson:"status" json:"status" newc:"-"`
}

func (e *Forbidden) init() {
e.Status = 403
}

// Error ...
func (e Forbidden) Error() string {
return fmt.Sprintf("forbidden")
}
12 changes: 12 additions & 0 deletions test/errors/errors_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package errors

import (
"testing"
)

func TestNewForbidden(t *testing.T) {
value := NewForbidden("msg")
if value.Status != 403 {
t.Errorf("NewForbidden should calling init method")
}
}
9 changes: 9 additions & 0 deletions test/unit-test/constructor_gen.go

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

7 changes: 7 additions & 0 deletions test/unit-test/struct_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,10 @@ func TestValueInitMode(t *testing.T) {
t.Errorf("expected unittest.StructValueWithInit, but got %v", typeName)
}
}

func TestSkipped(t *testing.T) {
value := NewSkipeed("msg")
if value.Status != 403 {
t.Errorf("NewSkipeed should calling init method")
}
}
11 changes: 11 additions & 0 deletions test/unit-test/structs.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,14 @@ type StructValueWithInit struct {
func (s *StructValueWithInit) init() {
s.Debug = true
}

// Skipeed ...
//go:generate go run ../../../newc --value --init
type Skipeed struct {
Msg string `bson:"msg" json:"msg"`
Status int `bson:"status" json:"status" newc:"-"`
}

func (e *Skipeed) init() {
e.Status = 403
}

0 comments on commit 5cd9ccc

Please sign in to comment.