vogen

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Jan 1, 2025 License: MIT Imports: 7 Imported by: 0

README

vogen - Value Object Generator in golang

All Contributors

Go Reference Coverage reviewdog MultiPlatformUnitTest

The vogen library is to generate value objects in golang. The vogen will automatically generate files with Value Objects defined.

The vogen automatically generates Getter, Constructor, Constructor with Validation, and Equal() based on metadata (vogen.ValueObject).

Supported OS and go version

  • OS: Linux, macOS, Windows
  • Go: 1.22 or later

Example

Implement a value object metadata

Firstly, write your value object metadata. Here is an example: gen/main.go

package main

import (
	"fmt"
	"path/filepath"

	"github.com/nao1215/vogen"
)

//go:generate go run main.go

func main() {
	// Step 1: Create a Vogen instance with custom file path and package name.
	// By default, the file path is "value_objects.go" and the package name is "vo".
	gen, err := vogen.New(
		vogen.WithFilePath(filepath.Join("testdata", "example_output.go")),
		vogen.WithPackageName("vo_example"),
	)
	if err != nil {
		fmt.Printf("Failed to create Vogen instance: %v\n", err)
		return
	}

	// Step 2: Append the ValueObject definition
	if err := gen.AppendValueObjects(
		vogen.ValueObject{
			StructName: "Person",
			Fields: []vogen.Field{
				{
					Name: "Name", Type: "string",
					Comments: []string{"Name is the name of the person."},
					Validators: []vogen.Validator{
						vogen.NewStringLengthValidator(0, 120),
					},
				},
				{
					Name: "Age", Type: "int",
					Comments: []string{"Age is the age of the person."},
					Validators: []vogen.Validator{
						vogen.NewPositiveValueValidator(),
						vogen.NewMaxValueValidator(120),
					}},
			},
			Comments: []string{
				"Person is a Value Object to describe the feature of vogen.",
				"This is sample comment.",
			},
		},
	); err != nil {
		fmt.Printf("Failed to append ValueObject: %v\n", err)
		return
	}

	// Step 3: Generate the code
	if err := gen.Generate(); err != nil {
		fmt.Printf("Failed to generate code: %v\n", err)
		return
	}
}

If you run 'go generate ./...', the following code will be generated in the example_vo.go file.

// Code generated by vogen. DO NOT EDIT.
package vo_example

import (
	"fmt"
)

// Person is a Value Object to describe the feature of vogen.
// This is sample comment.
type Person struct {
	// Name is the name of the person.
	name string
	// Age is the age of the person.
	age int
}

// NewPerson creates a new instance of Person.
func NewPerson(name string, age int) Person {
	return Person{name: name, age: age}
}

// NewPersonStrictly creates a new instance of Person with validation.
func NewPersonStrictly(name string, age int) (Person, error) {
	o := Person{name: name, age: age}
	if len(o.name) < 0 || len(o.name) > 120 {
		return fmt.Errorf("struct 'Person' field 'Name' length is out of range: %d", len(o.name))
	}
	if o.age < 0 {
		return fmt.Errorf("struct 'Person' field 'Age' value is negative: %d", age)
	}
	if o.age > 120 {
		return fmt.Errorf("struct 'Person' field 'Age' value exceeds the maximum value: %d", age)
	}
	return o, nil
}

// Name returns the name field.
func (o Person) Name() string {
	return o.name
}

// Age returns the age field.
func (o Person) Age() int {
	return o.age
}

// Equal checks if two Person objects are equal.
func (o Person) Equal(other Person) bool {
	return o.Name() == other.Name() && o.Age() == other.Age()
}

// Address represents a value object.
type Address struct {
	city string
}

// NewAddress creates a new instance of Address.
func NewAddress(city string) Address {
	return Address{city: city}
}

// City returns the city field.
func (o Address) City() string {
	return o.city
}

// Equal checks if two Address objects are equal.
func (o Address) Equal(other Address) bool {
	return o.City() == other.City()
}

Validation list

Validator Description
NewPositiveValueValidator() Check if the value is positive.
NewNegativeValueValidator() Check if the value is negative.
NewMaxValueValidator(max int) Check if the value is less than to the maximum value.
NewMinValueValidator(min int) Check if the value is greater than to the minimum value.
NewStringLengthValidator(min, max int) Check if the length of the string is within the specified range.

License

MIT License

Contribution

First off, thanks for taking the time to contribute! See CONTRIBUTING.md for more information. Contributions are not only related to development. For example, GitHub Star motivates me to develop! Please feel free to contribute to this project.

Contributors ✨

Thanks goes to these wonderful people (emoji key):

CHIKAMATSU Naohiro
CHIKAMATSU Naohiro

💻

This project follows the all-contributors specification. Contributions of any kind welcome!

Documentation

Overview

Package vogen provides a code generator for Value Objects in Go. Value Objects are immutable objects that represent a value.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrStructNameEmpty is an error that occurs when the StructName is not set.
	ErrStructNameEmpty = errors.New("vogen: ValueObject 'StructName() is not set")
	// ErrInvalidField is an error that occurs when the Field is not set.
	ErrInvalidField = errors.New("vogen: ValueObject 'Field' is not set")
	// ErrInvalidFieldName is an error that occurs when the Field 'Name' is not set.
	ErrInvalidFieldName = errors.New("vogen: ValueObject 'Field.Name' is not set")
	// ErrInvalidFieldType is an error that occurs when the Field 'Type' is not set.
	ErrInvalidFieldType = errors.New("vogen: ValueObject 'Field.Type' is not set")
	// ErrInvalidFilePath is an error that occurs when the file path is not set.
	ErrInvalidFilePath = errors.New("vogen: file path is not set")
	// ErrInvalidPackageName is an error that occurs when the package name is not set.
	ErrInvalidPackageName = errors.New("vogen: package name is not set")
)

Functions

This section is empty.

Types

type Field

type Field struct {
	// Name is the name of the field to be generated.
	// The name specified in Name is always converted to 'lowerCamelCase'.
	// Required field.
	Name string
	// Type is the type of the field to be generated.
	// Type can be a primitive type or a Defined type. If you specify a Defined type, you must specify package import.
	// Required field.
	Type string
	// Comments is the field comment to be generated.
	// No need to add '//' to indicate the start of a comment.
	// Optional Field. If not specified, the field comment is to be empty.
	Comments []string
	// Validators is the list of validators to be generated.
	// The validation code is written within the New method. No check is made to see if the validation can be performed.
	// For example, it is possible to generate code that performs minimum value validation (incorrect code) for a string type.
	// Optional Field.
	Validators []Validator
}

Field is set to the metadata of the field to be automatically generated.

type MaxValueValidator

type MaxValueValidator struct {
	// contains filtered or unexported fields
}

MaxValueValidator is a Max Value Validator.

type MinValueValidator

type MinValueValidator struct {
	// contains filtered or unexported fields
}

MinValueValidator is a Min Value Validator.

type NegativeValueValidator

type NegativeValueValidator struct{}

NegativeValueValidator is a Negative Value Validator.

type Option

type Option func(*Vogen) error

Option is a parameter to be specified when creating a new Vogen struct.

func WithFilePath

func WithFilePath(filePath string) Option

WithFilePath specifies the file path to be generated.

func WithPackageName

func WithPackageName(packageName string) Option

WithPackageName specifies the package name to be generated.

type PositiveValueValidator

type PositiveValueValidator struct{}

PositiveValueValidator is a Positive Value Validator.

type RangeValueValidator

type RangeValueValidator struct {
	// contains filtered or unexported fields
}

RangeValueValidator is a Range Value Validator.

type StringLengthValidator

type StringLengthValidator struct {
	// contains filtered or unexported fields
}

StringLengthValidator is a String Length Validator.

type Validator

type Validator interface {
	// contains filtered or unexported methods
}

Validator represents a validator.

func NewMaxValueValidator

func NewMaxValueValidator(m int) Validator

NewMaxValueValidator returns a new Max Value Validator. MaxValueValidator checks if the value exceeds the maximum value.

func NewMinValueValidator

func NewMinValueValidator(m int) Validator

NewMinValueValidator returns a new Min Value Validator. MinValueValidator checks if the value is less than the minimum value.

func NewNegativeValueValidator

func NewNegativeValueValidator() Validator

NewNegativeValueValidator returns a new Negative Value Validator. NegativeValueValidator checks if the value is negative.

func NewPositiveValueValidator

func NewPositiveValueValidator() Validator

NewPositiveValueValidator returns a new Positive Value Validator.

func NewRangeValueValidator

func NewRangeValueValidator(minV, maxV int) Validator

NewRangeValueValidator returns a new Range Value Validator. RangeValueValidator checks if the value is out of range.

func NewStringLengthValidator

func NewStringLengthValidator(minL, maxL int) Validator

NewStringLengthValidator returns a new String Length Validator. StringLengthValidator checks if the string length is out of range.

type ValueObject

type ValueObject struct {
	// StructName is the name of the struct to be generated.
	// Required field.
	StructName string
	// Fields is the list of fields to be generated.
	// Required field.
	Fields []Field
	// Comments is the struct comment to be generated.
	// No need to add '//' to indicate the start of a comment.
	// Optional Field. If not specified, the struct comment is automatically generated.
	Comments []string
	// Imports is the list of imports to be generated.
	// Optional Field.
	Imports []string
}

ValueObject is set to the metadata of the ValueObject to be automatically generated.

type Vogen

type Vogen struct {
	// contains filtered or unexported fields
}

Vogen is the main struct of the vogen package. Vogen generates a ValueObject based on the metadata set in ValueObject.

func New

func New(opts ...Option) (*Vogen, error)

New creates a new Vogen struct.

func (*Vogen) AppendValueObjects

func (vo *Vogen) AppendValueObjects(vos ...ValueObject) error

AppendValueObjects appends ValueObjects to the Vogen struct.

func (*Vogen) Generate

func (vo *Vogen) Generate() error

Generate generates ValueObject code and writes it to the specified file path.

Example
package main

import (
	"fmt"
	"path/filepath"

	"github.com/nao1215/vogen"
)

func main() {
	// Step 1: Create a Vogen instance with custom file path and package name
	gen, err := vogen.New(
		vogen.WithFilePath(filepath.Join("testdata", "example_output.go")),
		vogen.WithPackageName("vo_example"),
	)
	if err != nil {
		fmt.Printf("Failed to create Vogen instance: %v\n", err)
		return
	}

	// Step 2: Append the ValueObject definition
	if err := gen.AppendValueObjects(
		vogen.ValueObject{
			StructName: "Person",
			Fields: []vogen.Field{
				{
					Name: "Name", Type: "string",
					Comments: []string{"Name is the name of the person."},
					Validators: []vogen.Validator{
						vogen.NewStringLengthValidator(0, 120),
					},
				},
				{
					Name: "Age", Type: "int",
					Comments: []string{"Age is the age of the person."},
					Validators: []vogen.Validator{
						vogen.NewPositiveValueValidator(),
						vogen.NewMaxValueValidator(120),
					}},
			},
			Comments: []string{
				"Person is a Value Object to describe the feature of vogen.",
				"This is sample comment.",
			},
		},
		// Use auto generated comments.
		vogen.ValueObject{
			StructName: "Address",
			Fields: []vogen.Field{
				{Name: "City", Type: "string"},
			},
		},
	); err != nil {
		fmt.Printf("Failed to append ValueObject: %v\n", err)
		return
	}

	// Step 3: Generate the code
	if err := gen.Generate(); err != nil {
		fmt.Printf("Failed to generate code: %v\n", err)
		return
	}

	fmt.Println("Code generated successfully. Check 'example_output.go' for the output.")
}
Output:

Code generated successfully. Check 'example_output.go' for the output.

Jump to

Keyboard shortcuts

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