All Projects → powerflyco → sts

powerflyco / sts

Licence: MIT license
sts: struct to struct transformers generator.

Programming Languages

go
31211 projects - #10 most used programming language

Projects that are alternatives of or similar to sts

gomatch
Library created for testing JSON against patterns.
Stars: ✭ 41 (+127.78%)
Mutual labels:  matcher
ethereum-regex
Ξ Regular expression for matching Ethereum (ETH) addresses.
Stars: ✭ 19 (+5.56%)
Mutual labels:  matcher
go-localize
i18n (Internationalization and localization) engine written in Go, used for translating locale strings.
Stars: ✭ 45 (+150%)
Mutual labels:  go-generate
Micromatch
Contributing Pull requests and stars are always welcome. For bugs and feature requests, please create an issue. Please read the contributing guide for advice on opening issues, pull requests, and coding standards.
Stars: ✭ 1,979 (+10894.44%)
Mutual labels:  matcher
regenny
A reverse engineering tool to interactively reconstruct structures and generate header files
Stars: ✭ 58 (+222.22%)
Mutual labels:  structures
dart-more
More Dart — Literally.
Stars: ✭ 81 (+350%)
Mutual labels:  matcher
expectest
Crate provides matchers and matcher functions for unit testing.
Stars: ✭ 25 (+38.89%)
Mutual labels:  matcher
jest-puppe-shots
A Jest plugin for creating screenshots of React components with a little help of Puppeteer
Stars: ✭ 86 (+377.78%)
Mutual labels:  matcher
Mergo
Written by Dario Castañé.
Stars: ✭ 1,808 (+9944.44%)
Mutual labels:  structures
jest-expect-contain-deep
Assert deeply nested values in Jest
Stars: ✭ 68 (+277.78%)
Mutual labels:  matcher
sharpy
Simulation of High Aspect Ratio aeroplanes and wind turbines in Python: a nonlinear aeroelastic code
Stars: ✭ 81 (+350%)
Mutual labels:  structures
apart
Get all your structure and rip it apart.
Stars: ✭ 26 (+44.44%)
Mutual labels:  structures
embd-go
embd-go is an embeddable command-line tool for embedding data files in Go source code, specially crafted for easy use with `go generate`.
Stars: ✭ 24 (+33.33%)
Mutual labels:  go-generate
Mockk
mocking library for Kotlin
Stars: ✭ 4,214 (+23311.11%)
Mutual labels:  matcher
cryptaddress.now
A minimal service to detect which cryptocurrency an address corresponds to.
Stars: ✭ 23 (+27.78%)
Mutual labels:  matcher
bash-glob
Bash-powered globbing for node.js. Alternative to node-glob. Does not work on Windows 9 and lower.
Stars: ✭ 13 (-27.78%)
Mutual labels:  matcher
spec-pattern
Specification design pattern for JavaScript and TypeScript with bonus classes
Stars: ✭ 43 (+138.89%)
Mutual labels:  matcher
ccrawl
clang-based search engine for C/C++ data structures, classes, prototypes & macros
Stars: ✭ 82 (+355.56%)
Mutual labels:  structures
java-8-matchers
Hamcrest Matchers for Java 8 features
Stars: ✭ 23 (+27.78%)
Mutual labels:  matcher
lessram
Pure PHP implementation of array data structures that use less memory.
Stars: ✭ 20 (+11.11%)
Mutual labels:  structures

sts: struct to struct: generator of transformation functions

codecov GitHub release (latest SemVer) Travis (.org) GoDoc Go Report Card

Install

go get -u github.com/powerflyco/sts/cmd/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 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.
  2. Field type matching.
  3. Generations pair of functions: forward SourceType2DestType and reverse DestType2SourceType.

Other implementations.

There is a plugin 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, 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.

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

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

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

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 and convertibility.

  • 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

<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 package.

Step 3

On the last step sts creates a file with name <source>_to_<dest>.sts.go with pair of ready-to-use functions for each pair of structures passed as a parameters to sts.

// source_to_dest.sts.go

// Code generated by sts v0.0.4-alpha-dev. DO NOT EDIT.

package output

import (
	"github.com/powerflyco/sts/examples"
	"github.com/powerflyco/sts/examples/dest"
)

func Source2Dest(src examples.Source) dest.Dest {
	return dest.Dest{
		I64:       int64(src.I1),
		B:         Int2Bool(src.I2),
		Nt:        TimeTimePtr2NullsTime(src.PT),
		JsonField: src.JJ,
		DB:        int64(src.D),
	}
}
func Dest2Source(src dest.Dest) examples.Source {
	return examples.Source{
		I1: int(src.I64),
		I2: Bool2Int(src.B),
		PT: NullsTime2TimeTimePtr(src.Nt),
		JJ: src.JsonField,
		D:  int32(src.DB),
	}
}
func SourcePtr2DestPtr(src *examples.Source) *dest.Dest { /*...*/ }
func DestPtr2SourcePtr(src *dest.Dest) *examples.Source { /*...*/ }
func SourceList2DestList(src []examples.Source) []dest.Dest { /*...*/ }
func DestList2SourceList(src []dest.Dest) []examples.Source { /*...*/ }
func SourceList2DestPtrList(src []examples.Source) []*dest.Dest { /*...*/ }
func DestPtrList2SourceList(src []*dest.Dest) []examples.Source { /*...*/ }
func SourcePtrList2DestList(src []*examples.Source) []dest.Dest { /*...*/ }
func DestList2SourcePtrList(src []dest.Dest) []*examples.Source { /*...*/ }
func SourcePtrList2DestPtrList(src []*examples.Source) []*dest.Dest { /*...*/ }
func DestPtrList2SourcePtrList(src []*dest.Dest) []*examples.Source { /*...*/ }

full example see in examples package.

go generate

Go has a command go generate (blog|proposal). This command allows to run tools mentioned in special comments in Go code, like this:

//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.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].