Skip to content

renxzen/go-getters

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

7 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

go-getters

A Go code generator that automatically creates getter methods for struct fields.

Features

  • Generate getter methods for exported struct fields
  • Handle pointer fields to primitive types with proper nil checking
  • Support for custom types and package-qualified types
  • Clean, readable generated code with proper zero values
  • Comprehensive test suite with golden file testing

Installation

From Source

git clone https://github.com/renxzen/go-getters.git
cd go-getters
make install

Using Go Install

go install github.com/renxzen/go-getters/cmd/go-getters@latest

Usage

Command Line

# Generate getters for specific structs
go-getters -structs="User,Product" -input=./models -output=getters.go

# Generate getters for structs in current directory
go-getters -structs="MyStruct"

# Show help
go-getters -help

Command Line Options

  • -input string - Path to directory containing Go files (default ".")
  • -output string - Output file name (default "getters.gen.go"). The file will be created in the input directory.
  • -structs string - Comma-separated list of struct names to generate getters for (required)
  • -help - Show help message

Examples

# Basic usage
go-getters -structs="User,Product"

# Specify input and output paths
go-getters -input=./models -output=getters.go -structs="User,Product,Order"

With go generate

You can integrate go-getters into your build process using go generate by adding generate comments to your Go files:

package main

//go:generate go-getters -structs=Example -output=getters.gen.go

type Example struct {
	Name   string
	Value  int
	Active bool
}

Then run:

go generate ./...

This will automatically generate the getter methods for the specified structs. You can also use multiple generate comments for different structs or configurations:

//go:generate go-getters -structs=User,Product -input=./models -output=user_getters.gen.go
//go:generate go-getters -structs=Order -input=./models -output=order_getters.gen.go

type User struct {
	ID    int
	Name  string
	Email string
}

type Product struct {
	ID    int
	Name  string
	Price float64
}

As a Library

package main

import (
    "fmt"
    "os"

    "github.com/renxzen/go-getters/pkg/generator"
)

func main() {
    result, err := generator.GenerateGetters("./models", []string{"User", "Product"})
    if err != nil {
        panic(err)
    }

    err = os.WriteFile("getters.gen.go", result, 0644)
    if err != nil {
        panic(err)
    }

    fmt.Println("Getters generated successfully!")
}

Project Structure

This project follows the Go project-layout standard:

go-getters/
├── cmd/
│   └── go-getters/          # Main application
│       └── main.go
├── pkg/                     # Public library code
│   ├── generator/           # Main generator interface
│   │   └── generator.go
│   ├── parser/              # Go source code parsing
│   │   └── parser.go
│   ├── strutils/            # String utility functions
│   │   └── strutils.go
│   └── types/               # Shared data structures
│       └── types.go
├── test/                    # Test files and test data
│   ├── generator_test.go
│   ├── testdata/
│   └── README.md
├── Makefile                 # Build automation
├── go.mod
└── README.md

Development

Prerequisites

  • Go 1.24.5 or later
  • Make

Building

# Build the binary for the current platform
make build

Installation

# Install the binary to your GOPATH
make install

# Uninstall the binary
make uninstall

Testing

# Run all tests with coverage
make test

# Update golden test files
make test/update

Code Generation

# Run go generate to update examples using the installed binary
make generate

# Run go generate with a local build of the binary
make generate/local

Code Quality

# Tidy go.mod and go.sum files
make tidy

# Lint the project (requires golangci-lint)
make lint

Cleaning

# Clean build artifacts
make clean

Examples

Input Struct

type User struct {
    ID       int
    Name     *string
    Email    string
    Age      *int
    IsActive bool
}

Generated Output

package main

// Code generated by go-getters; DO NOT EDIT.

func (s *User) GetID() int {
    if s != nil {
        return s.ID
    }
    return 0
}

func (s *User) GetName() string {
    if s != nil && s.Name != nil {
        return *s.Name
    }
    return ""
}

func (s *User) GetEmail() string {
    if s != nil {
        return s.Email
    }
    return ""
}

func (s *User) GetAge() int {
    if s != nil && s.Age != nil {
        return *s.Age
    }
    return 0
}

func (s *User) GetIsActive() bool {
    if s != nil {
        return s.IsActive
    }
    return false
}

Architecture

The generator is built with a modular architecture:

  • Parser Package: Handles parsing Go source files and extracting struct information
  • Types Package: Defines shared data structures used across packages
  • Codegen Package: Handles the actual code generation logic
  • Generator Package: Provides the main public API that orchestrates parsing and code generation

This separation allows for:

  • Better testability of individual components
  • Easier maintenance and extension
  • Clear separation of concerns
  • Reusable components for other tools

Testing

The project uses golden file testing to ensure consistent output generation.

Test Structure

  • test/generator_test.go - Main test file with golden file tests
  • test/testdata/ - Directory containing test input files and golden files
    • structs.go - Test struct definitions
    • *.golden - Golden files containing expected output

Running Tests

# Run all tests with coverage
make test

# Update golden files (when output changes are intentional)
make test/update

Golden File Testing

Golden file testing compares the actual output of the generator against pre-stored "golden" files containing the expected output. This approach:

  1. Ensures consistency - Any changes to output are immediately detected
  2. Simplifies maintenance - Easy to update expected output when changes are intentional
  3. Provides clear diffs - Test failures show exactly what changed
  4. Supports multiple scenarios - Each test case can have its own golden file

Adding New Tests

  1. Add a new test case to the tests slice in generator_test.go
  2. Run make test/update to generate the golden file
  3. Verify the generated output is correct
  4. Run make test to ensure the test passes

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests for new functionality
  5. Run make lint to ensure code quality
  6. Submit a pull request

License

MIT License - see LICENSE file for details.

About

Go code generation tool for nil-safe getters

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published