sts

package module
v0.0.6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 6, 2020 License: MIT Imports: 17 Imported by: 0

README

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/ekhabarov/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/ekhabarov/sts/examples"
	"github.com/ekhabarov/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.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrEmptyLeftType  = errors.New("left type is empty")
	ErrEmptyRightType = errors.New("right type is empty")
	ErrEmptyLeftField = errors.New("left field is empty")
	ErrEmptRightField = errors.New("right field is empty")
	ErrEmptyTag       = errors.New("empty tag")
)
View Source
var (
	ErrIncorectSourceParam = errors.New(`incorrect source, ` + format)
	ErrIncorectDestParam   = errors.New(`incorrect destination, ` + format)
)
View Source
var ErrConfigMapNotFound = errors.New(`"map" node not found in config`)

Functions

func Run

func Run(

	src, dst string,
	sourceTag string,
	validDstTags string,
	outputDir string,
	hpkg string,
	version string,
	debug bool,
	cfgmap *FieldConfig,
) (string, []byte, error)

Tags to inspect: * sts * custom

Types

type Field

type Field struct {
	// internal type info.
	Type types.Type
	// Equals true if field is a pointer.
	IsPointer bool
	// Field tags with values.
	Tags Tags
	// Order inside structure. It's used for printing fields with correct order.
	Ord uint8
}

Field contains information about one structure field without field name.

func (Field) String

func (fi Field) String() string

type FieldConfig

type FieldConfig struct {
	// If true, match all fields by Name, even if those fields not in map.
	// Default: false.
	AllMatched bool
	// Field connections.
	FieldMap map[string]string
}

func LoadFieldConfigMap

func LoadFieldConfigMap(path string) (*FieldConfig, error)

type Fields

type Fields map[string]Field

Fields is a set of fields of one structure. Key is field name.

func Lookup

func Lookup(f *File, name string) (Fields, error)

Lookup return structure by name from parsed source file or an error if structure with such name not found.

func (Fields) String

func (s Fields) String() string

String return structure information as a string.

type File

type File struct {
	Package string
	Structs map[string]Fields
}

File contains structures from parsed file.

func Parse

func Parse(path string, tags []string) (*File, error)

Parse gets path to source file, imports whole file package and run inspect functions on given file. Parsing whole package is necessary because structures and field types can be defined in different files. Function returns list of structures with information their about fields.

type Tags

type Tags map[string]string

Represents field tags with values.

Directories

Path Synopsis
cmd
sts
nulls
Package nulls contains wrappers for representing dummy null types.
Package nulls contains wrappers for representing dummy null types.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL