Coder Social home page Coder Social logo

goaccessor's Introduction

goaccessor

Go Reference License: MIT

中文介绍

goaccessor is a Go tool designed to automate the generation of getter and setter boilerplate code for your types and variables.

Usage

go install github.com/yujiachen-y/goaccessor@latest

After installing goaccessor, you can use it in the command line interface (CLI) or with //go:generate directives. Check out the Examples section for more information.

Examples

You can find a runnable 'book' example in the example folder.

Consider the file book.go:

package main

//go:generate goaccessor --target Book --getter --setter
type Book struct {
    Title  string
    Author string
}

When we run go generate, it creates a new file book_goaccessor.go:

// Code generated by "goaccessor --target Book --getter --setter". DO NOT EDIT.

package main

func (b *Book) GetTitle() string {
    return b.Title
}

func (b *Book) SetTitle(title string) {
    b.Title = title
}

func (b *Book) GetAuthor() string {
    return b.Author
}

func (b *Book) SetAuthor(author string) {
    b.Author = author
}

Top-level variables

goaccessor isn't just for struct types; it can also handle top-level constants and variables. For instance:

//go:generate goaccessor --target books --getter --setter
var books = map[string]*Book {
    ...
}

After executing go generate, we get:

func GetBooks() map[string]*Book {
    return books
}

func SetBooks(newBooks map[string]*Book) {
    books = newBooks
}

Complex cases

In certain cases, you might want to export specific fields of a top-level variable with a prefix:

//go:generate goaccessor --target bestSellingBook --field --getter --include Author --prefix BestSelling
var bestSellingBook = &Book{ ... }

This directive will generate:

func GetBestSellingAuthor() string {
    return bestSellingBook.Author
}

Options

Here are the available options for goaccessor:

Option Short option Description
--target -t Specify the target to be handled.
--getter -g Generate getter for the target.
--setter -s Generate setter for the target.
--accessor -a Generate both getter and setter for the target.
--pure-getter -pg Generate getter without 'Get' prefix for the target.
--prefix -p Add a prefix to the generated methods/functions.
--field -f Apply the flag (getter, setter, accessor) to each field of the target (only applicable for struct type variables).
--include -i Generate methods only for the specified fields (fields should be comma-separated).
--exclude -e Exclude specified fields from method generation (fields should be comma-separated).

Remember, when using the --pure-getter option, the generated getter methods won't have a 'Get' prefix. For instance, for a Book struct with a Title field, the getter will be Title() instead of GetTitle().

Dependency Management

If you do not want to install goaccessor and want to use it as a dependency for your project, follow these steps:

  1. Go to your project directory and add the goaccessor dependency via go mod:
go get github.com/yujiachen-y/goaccessor@latest
  1. Create a new file named tools.go (or any other name you like) with the following code:
//go:build tools

package main

import (
	_ "github.com/yujiachen-y/goaccessor"
)
  1. If you want to use the goaccessor CLI command, use go run github.com/yujiachen-y/goaccessor@latest instead.

  2. If you use go:generate directives to generate code, change the directives like this:

//go:generate go run github.com/yujiachen-y/goaccessor@latest -target book
var book Book
  1. Note: even though goaccessor is a dependency of your project, it will not—and should not—be a part of your project's build result. We use a build flag in tools.go to ensure goaccessor is ignored during build.

goaccessor's People

Contributors

yujiachen-y avatar

Stargazers

Glenn Nagel avatar  avatar  avatar Clayton Kehoe avatar Etherdrake avatar  avatar

Watchers

 avatar

Forkers

guanstart yasv98

goaccessor's Issues

Imports can't be recolved when type is a slice

Decorate a struct definition like so:

//go:generate go run github.com/yujiachen-y/goaccessor@latest -g -s -t MyType
func MyType struct {
     x int
     y int
     s string
     t []otherPackageInMyProject.CustomType
}

The accessors for t generate successfully but the import for otherPackageInMyProject.CustomType does not resolve. If the type isn't a slice, the import resolves.

Include version number in generated output

It would be good if the goaccessor could print out the version number of the package so it can be pinned in tooldeps and help manage version control.

I've linked a PR with a possible way to do this here

Add option to return a copy of data

It is useful when you generate an accessor for global variable like slice or map. In order to improve safety I would like to return a copy of that type.

Example of modification global variable

var data = []string{"1", "2", "3"}

func Get() []string { return data }

func main() {
	ddd := Get()

	ddd[0] = "X"
	fmt.Println(Get())
}

So in that case I would like to specify behaviour that will copy slice (in Get) before return:

func Get()[]string{
  res := make([]string, len(data))
  copy(res, data)
  return res
}

Run go fmt before writing to file

It would be good if generator.go could run go fmt on the code lines before writing to file. This would prevent having to add a go:generate go fmt _filename_.go as part of the generate commands or having the generated output fail lint checks.

I've made this change in a forked version of the repository here which could be a way to add this change. It changes the writeFile function to format the code lines before writing to a file.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.