Skip to content

Commit

Permalink
Initial commit.
Browse files Browse the repository at this point in the history
  • Loading branch information
Evgeny Khabarov committed Mar 5, 2020
1 parent 29e41dc commit fbf8d5c
Show file tree
Hide file tree
Showing 47 changed files with 2,693 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
*.coverprofile
138 changes: 138 additions & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
run:
skip-dirs:

# default is true. Enables skipping of directories:
# vendor$, third_party$, testdata$, examples$, Godeps$, builtin$
skip-dirs-use-default: true


# all available settings of specific linters
linters-settings:
dogsled:
# checks assignments with too many blank identifiers; default is 2
max-blank-identifiers: 2
dupl:
# tokens count to trigger issue, 150 by default
threshold: 150
errcheck:
# report about not checking of errors in type assertions: `a := b.(MyStruct)`;
# default is false: such cases aren't reported by default.
check-type-assertions: true

# report about assignment of errors to blank identifier: `num, _ := strconv.Atoi(numStr)`;
# default is false: such cases aren't reported by default.
check-blank: true

funlen:
lines: 100
statements: 45
gocognit:
# minimal code complexity to report, 30 by default (but we recommend 10-20)
min-complexity: 10
goconst:
# minimal length of string constant, 3 by default
min-len: 3
# minimal occurrences count to trigger, 3 by default
min-occurrences: 3
gocyclo:
# minimal code complexity to report, 30 by default (but we recommend 10-20)
min-complexity: 18
gofmt:
# simplify code: gofmt with `-s` option, true by default
simplify: true
goimports:
# put imports beginning with prefix after 3rd-party packages;
# it's a comma-separated list of prefixes
local-prefixes: github.com/ekhabarov/sts
golint:
# minimal confidence for issues, default is 0.8
min-confidence: 0.8
gomnd:
settings:
mnd:
# the list of enabled checks, see https://github.com/tommy-muehle/go-mnd/#checks for description.
checks: argument,case,condition,operation,return,assign
govet:
# report about shadowed variables
check-shadowing: true

# settings per analyzer
settings:
printf: # analyzer name, run `go tool vet help` to see all analyzers
funcs: # run `go tool vet help printf` to see available settings for `printf` analyzer
- (github.com/golangci/golangci-lint/pkg/logutils.Log).Infof
- (github.com/golangci/golangci-lint/pkg/logutils.Log).Warnf
- (github.com/golangci/golangci-lint/pkg/logutils.Log).Errorf
- (github.com/golangci/golangci-lint/pkg/logutils.Log).Fatalf

# enable or disable analyzers by name
enable:
- atomicalign
enable-all: false
disable:
- shadow
disable-all: false
lll:
# max line length, lines longer will be reported. Default is 120.
# '\t' is counted as 1 character by default, and can be changed with the tab-width option
line-length: 80
# tab width in spaces. Default to 1.
tab-width: 1
maligned:
# print struct with more effective memory layout or not, false by default
suggest-new: true
misspell:
# Correct spellings using locale preferences for US or UK.
# Default is to use a neutral variety of English.
# Setting locale to US will correct the British spelling of 'colour' to 'color'.
locale: US
ignore-words:
- someword
nakedret:
# make an issue if func has more lines of code than this setting and it has naked returns; default is 30
max-func-lines: 30

linters:
disable-all: true
enable:
- bodyclose
- deadcode
- depguard
- dogsled
- dupl
- errcheck
- funlen
- gochecknoinits
- goconst
- gocritic
- gocyclo
- gofmt
- goimports
- golint
# - gomnd
- goprintffuncname
- gosec
- gosimple
- govet
- ineffassign
- interfacer
- lll
- misspell
- nakedret
- rowserrcheck
- scopelint
- staticcheck
- structcheck
- stylecheck
- typecheck
- unconvert
- unparam
- unused
- varcheck
- whitespace
issues:
# Excluding configuration per-path, per-linter, per-text and per-source
exclude-rules:
- path: _test\.go
linters:
- gomnd
31 changes: 31 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
language: go

cache:
directories:
- $GOPATH/pkg/mod

env:
- GO111MODULE=on

go:
- 1.12.x
- 1.13.x
- 1.14.x
- tip

before_install:
- GO111MODULE=off go get github.com/onsi/gomega
- GO111MODULE=off go get github.com/onsi/ginkgo/ginkgo
- go mod download
- go mod verify

script:
- ginkgo -r -race -coverprofile=coverage.txt -covermode=atomic

matrix:
fast_finish: true
allow_failures:
- go: tip

after_success:
- bash <(curl -s https://codecov.io/bash)
184 changes: 184 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
# sts: struct to struct: generator of transformation functions

[![codecov](https://codecov.io/gh/ekhabarov/sts/branch/master/graph/badge.svg)](https://codecov.io/gh/ekhabarov/sts)
[![GitHub release (latest SemVer)](https://img.shields.io/github/v/release/ekhabarov/sts)](https://github.com/ekhabarov/sts/releases)
[![Travis (.org)](https://img.shields.io/travis/ekhabarov/sts)](https://travis-ci.org/ekhabarov/sts)
[![GoDoc](https://godoc.org/https://godoc.org/github.com/ekhabarov/sts?status.svg)](https://godoc.org/github.com/ekhabarov/sts)

<!-- vim-markdown-toc GFM -->

* [Install](#install)
* [Motivation](#motivation)
* [Idea](#idea)
* [Other implementations.](#other-implementations)
* [How](#how)
* [Step 1](#step-1)
* [Step 2](#step-2)
* [Example matcher](#example-matcher)
* [Int2Bool, NullsTime2TimeTimePtr wait, what?](#int2bool-nullstime2timetimeptr-wait-what)
* [go generate](#go-generate)
* [License](#license)

<!-- vim-markdown-toc -->

## Install

```shell
go get -u github.com/ekhabarov/sts
```

## Motivation
Working on integration between one app and different APIs (most of them,
fortunately, have Go clients) includes pretty much code which transforms one
structure into another, because for Go two structures with identical field set
and identical types are different types. Identical types could be converted one
into another with simple conversion: `targetType(destType)`, but having
[identical](https://golang.org/ref/spec#Type_identity) type is too rare case.

That means it's necessary to write such transformations manually, which is, from
one hand is tediously from another one is straightforward.

## Idea
The idea is as simple as possible: produce set of functions which allow convert
one type into another.

It can be done within three steps:

1. Source code analyze.
1. Field type matching.
1. Generations pair of functions: forward `SourceType2DestType` and reverse `DestType2SourceType`.

### Other implementations.
There is a [plugin](http://github.com/bold-commerce/protoc-gen-struct-transformer) for Protobuf with the same idea.

## How

### Step 1
On first step `sts` have to obtain information about structures which will be
involved into transformation process by analyzing source code files contained
these structures. To achieve this, packages [go/ast](https://golang.org/pkg/go/ast), [go/types](https://golang.org/pkg/go/types), etc., from
standard library can be used.

Using these packages `sts` builds a map with data types information. For details
see [parser.go](./parser.go).

### Step 2
Information from previous step is passes to matcher. Matcher lookups two
structures by name (structures names are passed via CLI params, see examples
below), source (left) and destination (right). Then it builds field pairs using
next rules:

* field on the left structure with `sts` tag will be matched with field on right side by right-side field name equals to `sts` tag value.
* if right-side field not found by name, then `sts` tag value will be compared with value of provided tag list.
* any fields without `sts` or other source tags will be skipped.

#### Example matcher
Let's say we have two structures

```go
type Source struct {
I int
S string
I1 int `sts:"I64"`
I2 int `sts:"B"`
PT *time.Time `sts:"Nt"`
JJ string `sts:"json_field"`
D int32 `sts:"db_field"`
}
```

and

```go
type Dest struct {
I int
S string
I64 int64
B bool
Nt nulls.Time
JsonField string `json:"json_field"`
DB int64 `db:"db_field"`
}
```

after run a command

```shell
sts -src /path/to/src.go:Source -dst /path/to/dst.go:Dest -o ./output -dt json,db
```

matcher consider next combinations


Source | Destination | Conversion | Note
-------|-------------|-------------------------|------
`I` | `--` | `--` | source field has not tag
`S` | `--` | `--` | source field has not tag
`I1` | `I64` | direct | matched `sts` tag value and field name
`I2` | `B` | `Int2Bool` | matched `sts` tag value and field name
`PT` | `Nt` | `NullsTime2TimeTimePtr` | matched `sts` tag value and field name
`JJ` | `JsonField` | none | matched `sts` tag value and `json` tag value. `json` tag passed via `-dt` CLI parameter.
`DB` | `D` | direct | matched `sts` tag value and `db` tag value. `db` tag passed via `-dt` CLI parameter.


##### Int2Bool, NullsTime2TimeTimePtr wait, what?
Matcher uses type info provided by `go/types` package. When it compares field it
also checks paired field for [assignability](https://golang.org/pkg/go/types/#AssignableTo) and [convertibility](https://golang.org/pkg/go/types/#ConvertibleTo).
* Assignability shows can one field be assigned to another without any conversion.
* Convertibility shows can one field be directly converted to another one.

But in cases when fields in pair are not `assignable` and are not `convertable`,
the tool just generate conversion function with name of format

```go
<SourceType>2<DestType>
// and
<DestType>2<SourceType>
```

that means it's necessary to write these helper functions manually. Fortunately,
quantity of such function should be low. Number of examples can be found in
[examples](./examples/output/helpers.go) package.


## go generate
Go has a command `go generate` ([blog](https://blog.golang.org/generate)|[proposal](https://docs.google.com/document/d/1V03LUfjSADDooDMhe-_K59EgpTEm3V8uvQRuNMAEnjg/edit)).
This command allows to run tools mentioned in special comments in Go code, like
this:

```go
//go:generate sts -src $GOFILE:Source -dst $GOFILE:Dest -o ./output -dt json,db
type Source struct {
I int
...
```
after `go generate ./...` will be run, it in turn, will run `sts` tool with
given parameters. `$GOFILE` variable will be replaced with a path to current
`.go` file by `go generate` tool.
## License
MIT License
Copyright (c) 2020 Evgeny Khabarov
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.
Loading

0 comments on commit fbf8d5c

Please sign in to comment.