Skip to content

Commit

Permalink
feat: support value mode
Browse files Browse the repository at this point in the history
  • Loading branch information
Bin-Huang committed Aug 16, 2022
1 parent 3dff4df commit 50f2536
Show file tree
Hide file tree
Showing 9 changed files with 200 additions and 23 deletions.
30 changes: 27 additions & 3 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].1
//go:generate go run github.com/Bin-Huang/[email protected].2
```

For example:

```go
//go:generate go run github.com/Bin-Huang/[email protected].1
//go:generate go run github.com/Bin-Huang/[email protected].2
type UserService struct {
baseService
userRepository *repositories.UserRepository
Expand All @@ -65,6 +65,30 @@ 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

Add `--value` parameter

```go
//go:generate newc --value
type Config struct {
debug bool
}
```

Generated code:

```go
// constructor_gen.go

// NewConfig Create a new Config
func NewConfig(debug bool) Config {
return Config{
debug: debug,
}
}
```

## Call an initializer

1. Add `--init` parameter
Expand Down Expand Up @@ -123,7 +147,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].1
//go:generate go run github.com/Bin-Huang/[email protected].2
```

## Sponsoring
Expand Down
30 changes: 27 additions & 3 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].1
//go:generate go run github.com/Bin-Huang/[email protected].2
```

比如这样:

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

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

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

使用 `--value` 参数

```go
//go:generate newc --value
type Config struct {
debug bool
}
```

生成代码:

```go
// constructor_gen.go

// NewConfig Create a new Config
func NewConfig(debug bool) Config {
return Config{
debug: debug,
}
}
```

## 想在构造时做些初始化?

1. 加上 `--init` 参数
Expand Down Expand Up @@ -123,7 +147,7 @@ func NewController(logger *zap.Logger, debug bool) *Controller {
就算其他同事没有安装这个工具,这么做也不会影响到他们的工作。因为 Go 会在必要时自动安装这个工具。

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

## 赞赏
Expand Down
19 changes: 10 additions & 9 deletions generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,15 @@ import (
{{ range .Constructors }}
// {{.Name}} Create a new {{.Struct}}
func {{.Name}}({{.Params}}) *{{.Struct}} {
{{ if .Init -}}
s := &{{.Struct}} {
func {{.Name}}({{.Params}}) {{if not .ValueFlag}}*{{end -}} {{.Struct}} {
{{ if .InitFlag -}}
s := {{if not .ValueFlag}}&{{end -}} {{.Struct}} {
{{.Fields}}
}
s.init()
return s
{{ else -}}
return &{{.Struct}} {
return {{if not .ValueFlag}}&{{end -}} {{.Struct}} {
{{.Fields}}
}
{{ end -}}
Expand Down Expand Up @@ -66,11 +66,12 @@ func GenerateCode(pkgName string, importInfos []ImportInfo, structInfos []Struct
fields = append(fields, fmt.Sprintf("%v: %v,", field.Name, toLowerCamel(field.Name)))
}
constructors = append(constructors, o{
"Name": "New" + strcase.ToCamel(structInfo.StructName),
"Struct": structInfo.StructName,
"Init": structInfo.Init,
"Params": strings.Join(params, ", "),
"Fields": strings.Join(fields, "\n"),
"Name": "New" + strcase.ToCamel(structInfo.StructName),
"Struct": structInfo.StructName,
"InitFlag": structInfo.InitFlag,
"ValueFlag": structInfo.ValueFlag,
"Params": strings.Join(params, ", "),
"Fields": strings.Join(fields, "\n"),
})
}
data["Constructors"] = constructors
Expand Down
20 changes: 12 additions & 8 deletions parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,8 @@ type ImportInfo struct {
// StructInfo the information of a struct
type StructInfo struct {
StructName string
Init bool
InitFlag bool
ValueFlag bool
Fields []StructField
}

Expand All @@ -92,6 +93,7 @@ func ParseCodeFile(filename string) ([]StructInfo, []ImportInfo, error) {
}

var initMode bool
var valueMode bool
if genDecl.Tok == token.TYPE {
if genDecl.Doc == nil {
continue
Expand All @@ -101,6 +103,7 @@ func ParseCodeFile(filename string) ([]StructInfo, []ImportInfo, error) {
if isMakeComment(doc.Text) {
needGen = true
initMode = isInitModeEnable(doc.Text)
valueMode = isValueModeEnable(doc.Text)
break
}
}
Expand Down Expand Up @@ -158,7 +161,8 @@ func ParseCodeFile(filename string) ([]StructInfo, []ImportInfo, error) {
structs = append(structs, StructInfo{
StructName: typeSpec.Name.Name,
Fields: structFields,
Init: initMode,
InitFlag: initMode,
ValueFlag: valueMode,
})
}
}
Expand All @@ -168,15 +172,15 @@ func ParseCodeFile(filename string) ([]StructInfo, []ImportInfo, error) {
// isMakeComment ...
func isMakeComment(s string) bool {
s = strings.TrimSpace(s)
if !strings.HasPrefix(s, "//go:generate") {
return false
}
s = strings.TrimLeft(s, "//go:generate")
s = strings.TrimSpace(s)
return strings.HasPrefix(s, "newc ") || strings.Contains(s, "github.com/Bin-Huang/newc")
return strings.HasPrefix(s, "//go:generate") && strings.Contains(s, "newc")
}

// isInitModeEnable check if this struct enable the init mode
func isInitModeEnable(s string) bool {
return strings.Contains(s, "init")
}

// isValueModeEnable check if this struct enable the value mode
func isValueModeEnable(s string) bool {
return strings.Contains(s, "value")
}
6 changes: 6 additions & 0 deletions test/config/config.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
package config

// Config ...
//go:generate go run ../../../newc --value
type Config struct {
Debug bool
}

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

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

35 changes: 35 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.

40 changes: 40 additions & 0 deletions test/unit-test/struct_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package unittest

import (
"reflect"
"testing"
)

func TestRefMode(t *testing.T) {
value := NewStructRef(false)
typeName := reflect.TypeOf(value).String()
if typeName != "*unittest.StructRef" {
t.Errorf("expected *unittest.StructRef, but got %v", typeName)
}
}

func TestValueMode(t *testing.T) {
value := NewStructValue(false)
typeName := reflect.TypeOf(value).String()
if typeName != "unittest.StructValue" {
t.Errorf("expected unittest.StructValue, but got %v", typeName)
}
}

func TestInitMode(t *testing.T) {
value := NewStructWithInit(false)
if value.Debug != true {
t.Errorf("NewStructWithInit should calling init method")
}
}

func TestValueInitMode(t *testing.T) {
value := NewStructValueWithInit(false)
if value.Debug != true {
t.Errorf("NewStructValueWithInit should calling init method")
}
typeName := reflect.TypeOf(value).String()
if typeName != "unittest.StructValueWithInit" {
t.Errorf("expected unittest.StructValueWithInit, but got %v", typeName)
}
}
33 changes: 33 additions & 0 deletions test/unit-test/structs.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package unittest

// StructRef ...
//go:generate go run ../../../newc
type StructRef struct {
Debug bool
}

// StructValue ...
//go:generate go run ../../../newc --value
type StructValue struct {
Debug bool
}

// StructWithInit ...
//go:generate go run ../../../newc --init
type StructWithInit struct {
Debug bool
}

func (s *StructWithInit) init() {
s.Debug = true
}

// StructValueWithInit ...
//go:generate go run ../../../newc --value --init
type StructValueWithInit struct {
Debug bool
}

func (s *StructValueWithInit) init() {
s.Debug = true
}

0 comments on commit 50f2536

Please sign in to comment.