Skip to content

Latest commit

 

History

History
90 lines (69 loc) · 1.87 KB

README.md

File metadata and controls

90 lines (69 loc) · 1.87 KB

Example: Tag

The example uses the tag option to match three models.

./domain/domain.go

// Package domain contains business logic models.
package domain

// Account represents a user account.
type Account struct {
	ID       int    `api:"user_id"`
	Name     string `api:"name"`
	Email    string `other:"email"`
	Username string `api:"username" other:"tag"`
	Password string // The password field will not be copied.
}

./models/model.go

// Package models contains data storage models (i.e database).
package models

// Account represents the data model for account.
type Account struct {
	ID       int    `api:"id"`
	Name     string `api:"name"`
	Password string
	Email    string `other:"email"`
}

// User represents the data model for a user.
type User struct {
	UserID   int    `api:"user_id"`
	Username string `api:"username,omitempty"`
}

YML

# Define where the code is generated.
generated:
  setup: ./setup.go
  output: ../copygen.go

# Templates and custom options aren't used for this example.

Go

Match all fields (.*) according to their respective api tag.

// Copygen defines the functions that are generated.
type Copygen interface {
	// tag .* api
	ModelsToDomain(*models.Account, *models.User) *domain.Account
}

Use pointers to avoid allocations.

Output

copygen -yml path/to/yml

// Code generated by github.com/switchupcb/copygen
// DO NOT EDIT.

// Package copygen contains the setup information for copygen generated code.
package copygen

import (
	"github.com/switchupcb/copygen/examples/tag/domain"
	"github.com/switchupcb/copygen/examples/tag/models"
)

// ModelsToDomain copies a *models.Account, *models.User to a *domain.Account.
func ModelsToDomain(tA *domain.Account, fA *models.Account, fU *models.User) {
	// *domain.Account fields
	tA.ID = fU.UserID
	tA.Name = fA.Name
	tA.Username = fU.Username
}