Skip to content
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

最低限のドキュメントを追加 #62

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 55 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,55 @@
# dynamodb-repo
# DynamoDB Repo

## Quick Start

Go言語の環境が整っていることを前提とします。

`dynamodb-repo` を導入します。
```bash
$ go get github.com/go-generalize/dynamodb-repo
```

`package` と `struct` を適宜定義したファイルを作ります。

<details>
<summary>クリックしてファイル例を表示</summary>

```golang
package model

import dda "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute"

//go:generate dynamodb-repo -disable-meta Name
//NOTE: go generateの最後の引数は生成したい struct 名を指定する

type CustomStruct struct {
Value int
Str string
}

// Name RangeKeyあり
type Name struct {
ID int64 `dynamo:"id,hash" auto:""`
Count int `dynamo:"count,range"`
Created dda.UnixTime `dynamo:"created"`
Desc string `dynamo:"description"`
Desc2 string `dynamo:"description2"`
Done bool `dynamo:"done"`
PriceList []int `dynamo:"priceList"`
Array []*CustomStruct `dynamo:"customs"`
}
```

</details>

最後に `go generate` をすると、適宜ファイルが生成されます。
```bash
$ go generate
```

ファイルが生成されたことを確認します。

```
$ ls
constant.go misc.go name.go name_gen.go
```
4 changes: 4 additions & 0 deletions generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ func (g *generator) setting() {
g.RepositoryStructName = strcase.ToLowerCamel(g.RepositoryInterfaceName)
}

// generates "(.*)_gen.go"
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

https://golang.org/doc/effective_go.html#commentary

各種コメントは // Name で始めなければいけないという制約があるので(今回の場合 // generate ) 修正お願いできますでしょうか

func (g *generator) generate(writer io.Writer) {
g.setting()
funcMap := g.setFuncMap()
Expand All @@ -119,6 +120,7 @@ func (g *generator) generate(writer io.Writer) {
}
}

// generates "constant.go"
func (g *generator) generateConstant(writer io.Writer) {
contents := getFileContents("constant")

Expand All @@ -129,6 +131,7 @@ func (g *generator) generateConstant(writer io.Writer) {
}
}

// generates "misc.go"
func (g *generator) generateMisc(writer io.Writer) {
contents := getFileContents("misc")

Expand All @@ -139,6 +142,7 @@ func (g *generator) generateMisc(writer io.Writer) {
}
}

// define functions in template files
func (g *generator) setFuncMap() template.FuncMap {
return template.FuncMap{
"Parse": func(fieldType string) string {
Expand Down
10 changes: 10 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ var (
isShowVersion = flag.Bool("v", false, "print version")
)

// Entry Point
func main() {
flag.Parse()

Expand All @@ -42,6 +43,7 @@ func main() {
}
}

// Entry point of generating process
func run(structName, prefix string, isDisableMeta bool) error {
disableMeta = &isDisableMeta
fs := token.NewFileSet()
Expand All @@ -51,6 +53,7 @@ func run(structName, prefix string, isDisableMeta bool) error {
panic(err)
}

// traverse for each package whose name doesn't have suffix "_test"
for name, v := range pkgs {
if strings.HasSuffix(name, "_test") {
continue
Expand All @@ -62,12 +65,14 @@ func run(structName, prefix string, isDisableMeta bool) error {
return nil
}

// main routine for generating process
func traverse(pkg *ast.Package, fs *token.FileSet, structName, prefix string) error {
gen := &generator{PackageName: pkg.Name}
for name, file := range pkg.Files {
gen.FileName = strings.TrimSuffix(filepath.Base(name), ".go")
gen.GeneratedFileName = gen.FileName + "_gen"

// process for each type declaration
for _, decl := range file.Decls {
genDecl, ok := decl.(*ast.GenDecl)
if !ok {
Expand All @@ -83,6 +88,7 @@ func traverse(pkg *ast.Package, fs *token.FileSet, structName, prefix string) er
if !ok {
continue
}

name := typeSpec.Name.Name

if name != structName {
Expand All @@ -105,6 +111,7 @@ func traverse(pkg *ast.Package, fs *token.FileSet, structName, prefix string) er
return xerrors.Errorf("no such struct: %s", structName)
}

// process for types whose name is `structName`
func generate(gen *generator, fs *token.FileSet, structType *ast.StructType) error {
var metaList map[string]*field.Field
if !*disableMeta {
Expand Down Expand Up @@ -189,6 +196,7 @@ func generate(gen *generator, fs *token.FileSet, structType *ast.StructType) err
gen.FieldInfos = append(gen.FieldInfos, fieldInfo)
continue
}
// turn `dynamo:"id,hash"` into string{"id", "hash"} as `sp`
sp := strings.Split(dynamoTag.Value(), ",")
fieldInfo.Tags = &FieldParsedTags{
Raw: sp,
Expand Down Expand Up @@ -254,6 +262,7 @@ func generate(gen *generator, fs *token.FileSet, structType *ast.StructType) err
gen.UniqueFields = nil
}

// precondition: `gen` (is a Generate) is ready to generate files
if gen.EnableCreateTime || gen.EnableUpdateTime {
if !(gen.EnableCreateTime && gen.EnableUpdateTime) {
return xerrors.New("requires both CreatedAt and UpdatedAt")
Expand Down Expand Up @@ -319,6 +328,7 @@ func parseTags(tags []string) *FieldParsedTags {
return p
}

// handles field metadata such as `dynamo:"id,hash"`
func keyFieldHandle(gen *generator, label string, keyKind KeyKind, name, typeName, pos string) error {
switch keyKind {
case KeyKindHash:
Expand Down
3 changes: 3 additions & 0 deletions misc.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ var (
UpdateTime = "UpdateTime"
)

// content of the template file as string
func getFileContents(name string) string {
fp, err := statikFS.Open("/" + name + ".go.tmpl")
if err != nil {
Expand All @@ -30,6 +31,7 @@ func getFileContents(name string) string {
return string(contents)
}

// convert input AST node to go-style declaration string
func getTypeName(typ ast.Expr) string {
switch v := typ.(type) {
case *ast.SelectorExpr:
Expand All @@ -49,6 +51,7 @@ func getTypeName(typ ast.Expr) string {
}
}

// check if input name is valid as identifier
func dynamoTagCheck(pos string, label string) error {
if label == "" {
return nil
Expand Down