generator

package
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Jun 22, 2025 License: MIT Imports: 10 Imported by: 0

README

Value Object Generator

Overview

The Value Object Generator is a tool for generating value objects in the ServiceLib library. It generates code for both string-based and struct-based value objects, along with their corresponding test files.

Usage

Command-Line Tool

The generator can be used as a command-line tool:

go run cmd/generate/main.go -config path/to/config.json -templates path/to/templates -output path/to/output

Options:

  • -config: Path to the configuration file (required)
  • -templates: Directory containing the templates (default: "templates")
  • -output: Directory where the generated code will be written (default: ".")
Configuration File

The configuration file is a JSON file that contains an array of value object configurations. Each configuration has the following fields:

  • Name: The name of the value object (e.g., "Email")
  • Package: The package name (e.g., "contact")
  • Type: The type of value object ("string" or "struct")
  • BaseType: The base type for string-based value objects (e.g., "string")
  • Description: A description of the value object
  • Fields: A map of field names to field types (for struct-based value objects)
  • Validations: A map of field names to validation functions
  • Imports: A list of additional imports

Example configuration file:

[
  {
    "Name": "PostalCode",
    "Package": "contact",
    "Type": "string",
    "BaseType": "string",
    "Description": "a postal code value object",
    "Validations": {
      "PostalCode": "if len(trimmedValue) < 5 {\n\t\treturn \"\", errors.New(\"postal code is too short\")\n\t}\n\n\tif len(trimmedValue) > 10 {\n\t\treturn \"\", errors.New(\"postal code is too long\")\n\t}"
    },
    "Imports": []
  },
  {
    "Name": "Currency",
    "Package": "measurement",
    "Type": "struct",
    "Description": "a currency value object",
    "Fields": {
      "Code": "string",
      "Symbol": "string",
      "Name": "string"
    },
    "Validations": {
      "Code": "if v.Code == \"\" {\n\t\treturn errors.New(\"currency code cannot be empty\")\n\t}\n\n\tif len(v.Code) != 3 {\n\t\treturn errors.New(\"currency code must be 3 characters\")\n\t}",
      "Symbol": "if v.Symbol == \"\" {\n\t\treturn errors.New(\"currency symbol cannot be empty\")\n\t}"
    },
    "Imports": [
      "errors"
    ]
  }
]
Programmatic Usage

The generator can also be used programmatically:

import "github.com/abitofhelp/servicelib/valueobject/generator"

func main() {
    // Create a generator
    gen := generator.NewGenerator("templates", "output")

    // Create a value object configuration
    config := generator.ValueObjectConfig{
        Name:        "Email",
        Package:     "contact",
        Type:        generator.StringBased,
        BaseType:    "string",
        Description: "an email address value object",
        Validations: map[string]string{
            "Email": `if !strings.Contains(trimmedValue, "@") {
                return "", errors.New("invalid email format: missing @ symbol")
            }`,
        },
        Imports: []string{"errors"},
    }

    // Generate the value object
    if err := gen.Generate(config); err != nil {
        panic(err)
    }
}

Templates

The generator uses the following templates:

  • string_value_object.tmpl: Template for string-based value objects
  • string_value_object_test.tmpl: Template for string-based value object tests
  • struct_value_object.tmpl: Template for struct-based value objects
  • struct_value_object_test.tmpl: Template for struct-based value object tests

These templates are located in the templates directory.

Generated Code

The generator generates the following files for each value object:

  • <package>/<name>.go: The value object implementation
  • <package>/<name>_test.go: The value object tests

The generated code follows the ServiceLib coding standards and includes:

  • A constructor function that validates the input and returns a new instance
  • Methods for String(), Equals(), IsEmpty(), and Validate()
  • Additional methods for struct-based value objects: ToMap() and MarshalJSON()
  • Comprehensive tests for all methods

Documentation

Overview

Package generator provides code generation tools for value objects.

Package generator provides code generation tools for value objects.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Execute

func Execute()

Execute executes the command.

Types

type GenerateCommand

type GenerateCommand struct {
	// ConfigFile is the path to the configuration file.
	ConfigFile string
	// TemplateDir is the directory containing the templates.
	TemplateDir string
	// OutputDir is the directory where the generated code will be written.
	OutputDir string
}

GenerateCommand is a command-line tool for generating value objects.

func NewGenerateCommand

func NewGenerateCommand() *GenerateCommand

NewGenerateCommand creates a new GenerateCommand.

func (*GenerateCommand) ParseFlags

func (c *GenerateCommand) ParseFlags()

ParseFlags parses the command-line flags.

func (*GenerateCommand) Run

func (c *GenerateCommand) Run() error

Run runs the command.

type Generator

type Generator struct {
	// TemplateDir is the directory containing the templates.
	TemplateDir string
	// OutputDir is the directory where the generated code will be written.
	OutputDir string
}

Generator generates code for value objects.

func NewGenerator

func NewGenerator(templateDir, outputDir string) *Generator

NewGenerator creates a new Generator.

func (*Generator) Generate

func (g *Generator) Generate(config ValueObjectConfig) error

Generate generates code for a value object.

type ValueObjectConfig

type ValueObjectConfig struct {
	// Name is the name of the value object (e.g., "Email").
	Name string
	// Package is the package name (e.g., "contact").
	Package string
	// Type is the type of value object (string or struct).
	Type ValueObjectType
	// Fields is a map of field names to field types (for struct-based value objects).
	Fields map[string]string
	// Validations is a map of field names to validation functions.
	Validations map[string]string
	// Imports is a list of additional imports.
	Imports []string
	// BaseType is the base type for string-based value objects (e.g., "string").
	BaseType string
	// Description is a description of the value object.
	Description string
}

ValueObjectConfig contains the configuration for generating a value object.

type ValueObjectType

type ValueObjectType string

ValueObjectType represents the type of value object to generate.

const (
	// StringBased represents a string-based value object.
	StringBased ValueObjectType = "string"
	// StructBased represents a struct-based value object.
	StructBased ValueObjectType = "struct"
)

Jump to

Keyboard shortcuts

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