44

GitHub - henrylee2cn/aster: Golang coding efficiency engine.

 6 years ago
source link: https://github.com/henrylee2cn/aster
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

README.md

Aster GitHub release report card github issues github closed issues GoDoc view examples

Golang coding efficiency engine.

Status

Under development, not for production...

Feature

  • Convert the AST to reflect.Type-like types(Kind-Flags), as it would at runtime
  • Simpler, more natural way of metaprogramming
  • Collect and package common syntax node types
  • Provides easy-to-use traversal syntax node functionality
  • Easily fetch and modify syntax node information
  • ...

An Example

  • Set struct tag
package main

import (
	"flag"
	"fmt"

	"github.com/henrylee2cn/aster/aster"
	"github.com/henrylee2cn/goutil"
)

var (
	filename = flag.String("filename", "out/eg.structtag.go", "file name")
	src      = flag.String("src", `package test
	type S struct {
		Apple string
		BananaPeel,car,OrangeWater string
		E int
	}
	func F(){
		type M struct {
			N int
			lowerCase string
		}
	}
	`, "code text")
)

func setStructTag(n aster.Node) bool {
	if n.Kind() != aster.Struct {
		return true
	}
	for i := n.NumField() - 1; i >= 0; i-- {
		field := n.Field(i)
		if !aster.IsExported(field.Name()) {
			continue
		}
		field.Tags.Set(&aster.Tag{
			Key:     "json",
			Name:    goutil.SnakeString(field.Name()),
			Options: []string{"omitempty"},
		})
	}
	return true
}

func main() {
	flag.Parse()
	f, _ := aster.ParseFile(*filename, *src)
	f.Inspect(setStructTag)
	retCode, _ := f.Format()
    fmt.Println(retCode)
    _ = f.Store()
}
  • The output of the above program is:

    package test
    
    type S struct {
    	Apple       string `json:"apple,omitempty"`
    	BananaPeel  string `json:"banana_peel,omitempty"`
    	car         string
    	OrangeWater string `json:"orange_water,omitempty"`
    	E           int    `json:"e,omitempty"`
    }
    
    func F() {
    	type M struct {
    		N         int `json:"n,omitempty"`
    		lowerCase string
    	}
    }

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK