Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add pos flag #26

Merged
merged 1 commit into from
Jan 29, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion _examples/mockgen/main.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion ast.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ func (n *ASTNode) Uint64Val() uint64 {

}

func (n *ASTNode) Val() interface{} {
func (n *ASTNode) Val() any {
return constant.Val(n.Value)
}

Expand Down
2 changes: 1 addition & 1 deletion cmd/hagane/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ func run() (rerr error) {
return errors.New("does not find package")
}

var tmpl interface{} = flagFormat
var tmpl any = flagFormat
if flagTemplate != "" {
tmpl, err = os.ReadFile(flagTemplate)
if err != nil {
Expand Down
6 changes: 3 additions & 3 deletions cmd/knife/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ func run(args []string) error {
opt.ExtraData = extraData
}

var tmpl interface{} = flagFormat
var tmpl any = flagFormat
if flagTemplate != "" {
tmpl, err = os.ReadFile(flagTemplate)
if err != nil {
Expand All @@ -83,8 +83,8 @@ func run(args []string) error {
return nil
}

func parseExtraData(extraData string) (map[string]interface{}, error) {
m := map[string]interface{}{}
func parseExtraData(extraData string) (map[string]any, error) {
m := map[string]any{}
kvs := strings.Split(extraData, ",")
for i := range kvs {
kv := strings.Split(strings.TrimSpace(kvs[i]), ":")
Expand Down
14 changes: 12 additions & 2 deletions cmd/objls/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"fmt"
"io"
"os"
"path/filepath"

"github.com/newmo-oss/gogroup"

Expand All @@ -17,11 +18,13 @@ import (
var (
flagFilter string
flagExported bool
flagPos bool
)

func init() {
flag.StringVar(&flagFilter, "f", "all", "object filter(all|const|func|var)")
flag.BoolVar(&flagExported, "exported", true, "filter only exported object")
flag.BoolVar(&flagPos, "pos", false, "print position")
flag.Parse()
}

Expand Down Expand Up @@ -56,8 +59,15 @@ func run(ctx context.Context, args []string) error {
}

if match(flagFilter, obj) {
if _, err := fmt.Fprintf(&buf, "%s.%s\n", pkg.Path, name); err != nil {
return err
if flagPos {
pos := c.Position(obj)
if _, err := fmt.Fprintf(&buf, "%s.%s(%s:%d)\n", pkg.Path, name, filepath.Base(pos.Filename), pos.Line); err != nil {
return err
}
} else {
if _, err := fmt.Fprintf(&buf, "%s.%s\n", pkg.Path, name); err != nil {
return err
}
}
}
}
Expand Down
14 changes: 12 additions & 2 deletions cmd/typels/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"fmt"
"io"
"os"
"path/filepath"

"github.com/newmo-oss/gogroup"

Expand All @@ -17,11 +18,13 @@ import (
var (
flagFilter string
flagExported bool
flagPos bool
)

func init() {
flag.StringVar(&flagFilter, "f", "all", "object filter(all|interface|func|struct|chan|array|slice|map)")
flag.BoolVar(&flagExported, "exported", true, "filter only exported types")
flag.BoolVar(&flagPos, "pos", false, "print position")
flag.Parse()
}

Expand Down Expand Up @@ -57,8 +60,15 @@ func run(ctx context.Context, args []string) error {
}

if typ.Exported && match(flagFilter, typ) {
if _, err := fmt.Fprintf(&buf, "%s.%s\n", pkg.Path, name); err != nil {
return err
if flagPos {
pos := c.Position(typ)
if _, err := fmt.Fprintf(&buf, "%s.%s(%s:%d)\n", pkg.Path, name, filepath.Base(pos.Filename), pos.Line); err != nil {
return err
}
} else {
if _, err := fmt.Fprintf(&buf, "%s.%s\n", pkg.Path, name); err != nil {
return err
}
}
}
}
Expand Down
9 changes: 9 additions & 0 deletions cutter/cutter.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,15 @@ func (c *Cutter) Packages() []*packages.Package {
return c.pkgs
}

// Position returns position of v.
func (c *Cutter) Position(v any) token.Position {
n, ok := v.(interface{ Pos() token.Pos })
if ok && c.fset != nil {
return c.fset.Position(n.Pos())
}
return token.Position{}
}

// KnifePackages returns knife packages.
func (c *Cutter) KnifePackages() []*knife.Package {
return c.knifePkgs
Expand Down
30 changes: 24 additions & 6 deletions knife.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
_ "embed"
"fmt"
"go/ast"
"go/token"
"io"
"strings"

Expand All @@ -21,14 +22,18 @@ func Version() string {
}

type Knife struct {
fset *token.FileSet
pkgs []*packages.Package
ins map[*packages.Package]*inspector.Inspector
}

func New(patterns ...string) (*Knife, error) {
mode := packages.NeedFiles | packages.NeedSyntax |
packages.NeedTypes | packages.NeedDeps | packages.NeedTypesInfo
cfg := &packages.Config{Mode: mode}
cfg := &packages.Config{
Fset: token.NewFileSet(),
Mode: mode,
}

pkgs, err := packages.Load(cfg, patterns...)
if err != nil {
Expand All @@ -40,22 +45,35 @@ func New(patterns ...string) (*Knife, error) {
ins[pkg] = inspector.New(pkg.Syntax)
}

return &Knife{pkgs: pkgs, ins: ins}, nil
return &Knife{
fset: cfg.Fset,
pkgs: pkgs,
ins: ins,
}, nil
}

// Packages returns packages.
func (k *Knife) Packages() []*packages.Package {
return k.pkgs
}

// Position returns position of v.
func (k *Knife) Position(v any) token.Position {
n, ok := v.(interface{ Pos() token.Pos })
if ok && k.fset != nil {
return k.fset.Position(n.Pos())
}
return token.Position{}
}

// Option is a option of Execute.
type Option struct {
XPath string
ExtraData map[string]interface{}
ExtraData map[string]any
}

// Execute outputs the pkg with the format.
func (k *Knife) Execute(w io.Writer, pkg *packages.Package, tmpl interface{}, opt *Option) error {
func (k *Knife) Execute(w io.Writer, pkg *packages.Package, tmpl any, opt *Option) error {

var tmplStr string
switch tmpl := tmpl.(type) {
Expand Down Expand Up @@ -85,7 +103,7 @@ func (k *Knife) Execute(w io.Writer, pkg *packages.Package, tmpl interface{}, op
return fmt.Errorf("template parse: %w", err)
}

var data interface{}
var data any

switch {
case opt != nil && opt.XPath != "":
Expand All @@ -104,7 +122,7 @@ func (k *Knife) Execute(w io.Writer, pkg *packages.Package, tmpl interface{}, op
return nil
}

func (k *Knife) evalXPath(pkg *packages.Package, xpath string) (interface{}, error) {
func (k *Knife) evalXPath(pkg *packages.Package, xpath string) (any, error) {
e := astquery.New(pkg.Fset, pkg.Syntax, k.ins[pkg])
v, err := e.Eval(xpath)
if err != nil {
Expand Down
10 changes: 5 additions & 5 deletions objects.go
Original file line number Diff line number Diff line change
Expand Up @@ -303,19 +303,19 @@ func (c *Const) Uint64Val() uint64 {

}

func (c *Const) Val() interface{} {
func (c *Const) Val() any {
return constant.Val(c.Value)
}

func Position(fset *token.FileSet, v interface{}) token.Position {
func Position(fset *token.FileSet, v any) token.Position {
n, ok := v.(interface{ Pos() token.Pos })
if ok && fset != nil {
return fset.Position(n.Pos())
}
return token.Position{}
}

func Exported(list interface{}) interface{} {
func Exported(list any) any {
v := reflect.ValueOf(list)
switch v.Kind() {
case reflect.Slice, reflect.Array:
Expand All @@ -326,7 +326,7 @@ func Exported(list interface{}) interface{} {
panic("unexpected kind")
}

func exportedSlice(v reflect.Value) interface{} {
func exportedSlice(v reflect.Value) any {
result := reflect.MakeSlice(v.Type(), 0, 0)
for i := 0; i < v.Len(); i++ {
elm := v.Index(i)
Expand All @@ -337,7 +337,7 @@ func exportedSlice(v reflect.Value) interface{} {
return result.Interface()
}

func exportedMap(v reflect.Value) interface{} {
func exportedMap(v reflect.Value) any {
result := reflect.MakeMap(v.Type())
for _, key := range v.MapKeys() {
elm := v.MapIndex(key)
Expand Down
18 changes: 9 additions & 9 deletions template.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ type TempalteData struct {
Files []*ast.File
TypesInfo *types.Info
Pkg *types.Package
Extra map[string]interface{}
Extra map[string]any
}

// NewTemplate creates new a template with funcmap.
Expand All @@ -44,24 +44,24 @@ func newFuncMap(td *TempalteData) template.FuncMap {
"signature": ToSignature,
"slice": ToSlice,
"struct": ToStruct,
"len": func(v interface{}) int { return reflect.ValueOf(v).Len() },
"cap": func(v interface{}) int { return reflect.ValueOf(v).Cap() },
"len": func(v any) int { return reflect.ValueOf(v).Len() },
"cap": func(v any) int { return reflect.ValueOf(v).Cap() },
"last": td.last,
"exported": Exported,
"methods": Methods,
"names": td.names,
"implements": implements,
"identical": identical,
"under": under,
"pos": func(v interface{}) token.Position { return Position(td.Fset, v) },
"pos": func(v any) token.Position { return Position(td.Fset, v) },
"objectof": func(s string) Object { return td.objectOf(s) },
"typeof": func(s string) *Type { return td.typeOf(s) },
"doc": func(v interface{}) string { return td.doc(cmaps, v) },
"data": func(k string) interface{} { return td.Extra[k] },
"doc": func(v any) string { return td.doc(cmaps, v) },
"data": func(k string) any { return td.Extra[k] },
}
}

func (td *TempalteData) names(slice interface{}) string {
func (td *TempalteData) names(slice any) string {
vs := reflect.ValueOf(slice)
switch vs.Kind() {
case reflect.Slice, reflect.Array:
Expand Down Expand Up @@ -149,7 +149,7 @@ func (td *TempalteData) typeOf(s string) *Type {
return NewType(obj.TypesObject().Type())
}

func (td *TempalteData) doc(cmaps comment.Maps, v interface{}) string {
func (td *TempalteData) doc(cmaps comment.Maps, v any) string {
node, ok := v.(interface{ Pos() token.Pos })
if !ok {
return ""
Expand All @@ -168,7 +168,7 @@ func (td *TempalteData) doc(cmaps comment.Maps, v interface{}) string {
return ""
}

func (td *TempalteData) last(v interface{}) interface{} {
func (td *TempalteData) last(v any) any {
_v := reflect.ValueOf(v)
return _v.Index(_v.Len() - 1).Interface()
}
Loading
Loading