knife

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Jan 29, 2025 License: MIT Imports: 18 Imported by: 4

README

knife PkgGoDev

knife is a CLI tool for inspecting Go packages, focusing on listing type and object information.
It provides a -f option similar to go list, allowing you to customize output via Go templates.

Additionally, this repository offers several separate CLI tools that work similarly:

  • knife: The main CLI (comprehensive tool for listing and inspecting Go package objects)
  • cutter: A lightweight tool focusing on listing type information
  • typels: Lists types in a package
  • objls: Lists objects in a package
  • hagane: A template-based code generator

Table of Contents

  1. Installation
  2. Usage
    1. Common Options
    2. Functions for Templates
    3. Example Commands
  3. Related Tools
    1. cutter
    2. typels
    3. objls
    4. hagane
  4. License
  5. Author

Installation

knife
go install github.com/gostaticanalysis/knife/cmd/knife@latest
cutter
go install github.com/gostaticanalysis/knife/cmd/cutter@latest
typels
go install github.com/gostaticanalysis/knife/cmd/typels@latest
objls
go install github.com/gostaticanalysis/knife/cmd/objls@latest
hagane
go install github.com/gostaticanalysis/knife/cmd/hagane@latest

Usage

Common Options

knife works similarly to go list: You can specify a Go template using the -f option to customize the output.
For example:

knife -f "{{.}}" fmt

For more details, see Options.

Functions for Templates

Within the template specified by the -f flag, you can use various helper functions alongside the standard Go text/template package. For instance:

  • exported: Filters for exported items only
  • identical: Checks if two types are identical
  • implements: Checks if a type implements a given interface
  • typeof: Returns the type by name
  • pos: Retrieves the position (file and line) of a definition
  • br: Inserts a line break in the output

See the full list of available functions in Functions for a template.

Example Commands

Below are some common examples:

  1. List functions in the fmt package whose names begin with Print:

    knife -f "{{range exported .Funcs}}{{.Name}}{{br}}{{end}}" fmt | grep Print
    Print
    Printf
    Println
    
  2. List exported types in the fmt package:

    knife -f "{{range exported .Types}}{{.Name}}{{br}}{{end}}" fmt
    Formatter
    GoStringer
    ScanState
    Scanner
    State
    Stringer
    
  3. List functions in net/http whose first parameter is context.Context:

    knife -f '{{range exported .Funcs}}{{.Name}} {{with .Signature.Params}}{{index . 0}}{{end}}{{br}}{{end}}' net/http | grep context.Context
    NewRequestWithContext var ctx context.Context
    
  4. List variables in net/http that implement the error interface:

    knife -f '{{range exported .Vars}}{{if implements . (typeof "error")}}{{.Name}}{{br}}{{end}}{{end}}' net/http
    ErrAbortHandler
    ErrBodyNotAllowed
    ErrBodyReadAfterClose
    ...
    ErrWriteAfterFlush
    
  5. List the position of fields whose type is context.Context:

    knife -f '{{range .Types}}{{$t := .}}{{with struct .}}{{range .Fields}}{{if identical . (typeof "context.Context")}}{{$t.Name}} - {{pos .}}{{br}}{{end}}{{end}}{{end}}{{end}}' net/http
    Request - /usr/local/go/src/net/http/request.go:319:2
    http2ServeConnOpts - /usr/local/go/src/net/http/h2_bundle.go:3878:2
    ...
    
  6. Use an XPath expression to list AST node types (e.g., FuncDecl names starting with Print):

    knife -f '{{range .}}{{.Name}}:{{with .Scope}}{{.Names}}{{end}}{{br}}{{end}}' -xpath '//*[@type="FuncDecl"]/Name[starts-with(@Name, "Print")]' fmt
    Printf:[a err format n]
    Print:[a err n]
    Println:[a err n]
    

cutter

cutter is a simplified version of knife that focuses on listing types.
Usage is almost identical to knife:

cutter -f "{{range exported .Funcs}}{{.Name}}{{br}}{{end}}" fmt | grep Print
Print
Printf
Println
typels

typels lists types in a package:

typels -f interface io | grep Writer
io.ByteWriter
io.ReadWriter
io.WriterAt
io.WriterTo
io.StringWriter
io.Writer
objls

objls lists objects in a package:

objls -f const net/http | grep Status | head -5
net/http.StatusBadGateway
net/http.StatusMovedPermanently
net/http.StatusNotFound
net/http.StatusCreated
net/http.StatusForbidden
hagane

hagane is a template-based code generator that can produce Go code based on a specified template and source file(s):

hagane -template template.go.tmpl -o sample_mock.go -data '{"type":"DB"}' sample.go
  • -o: Output file path (defaults to stdout)
  • -f: Template format (defaults to {{.}})
  • -template: Template file (used if -f is not set)
  • -data: Extra data (JSON) passed into the template

For a complete example, see this hagane sample.


License

This project is licensed under the MIT License.

Contributions are always welcome! Feel free to open issues or PRs for bugs and enhancements.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Exported

func Exported(list any) any

func Methods

func Methods(v any) map[string]*Func

func NewTemplate

func NewTemplate(td *TempalteData) *template.Template

NewTemplate creates new a template with funcmap.

func Position

func Position(fset *token.FileSet, v any) token.Position

func Version added in v0.2.0

func Version() string

Version returns the version of knife.

Types

type ASTNode

type ASTNode struct {
	Node   ast.Node
	Scope  *Scope
	Type   *Type
	Name   string
	Object Object
	Value  constant.Value
}

func NewASTNode

func NewASTNode(typesInfo *types.Info, n ast.Node) *ASTNode

func (*ASTNode) BoolVal

func (n *ASTNode) BoolVal() bool

func (*ASTNode) Float32Val

func (n *ASTNode) Float32Val() float32

func (*ASTNode) Float64Val

func (n *ASTNode) Float64Val() float64

func (*ASTNode) Int64Val

func (n *ASTNode) Int64Val() int64

func (*ASTNode) Pos

func (n *ASTNode) Pos() token.Pos

func (*ASTNode) String

func (n *ASTNode) String() string

func (*ASTNode) StringVal

func (n *ASTNode) StringVal() string

func (*ASTNode) Uint64Val

func (n *ASTNode) Uint64Val() uint64

func (*ASTNode) Val

func (n *ASTNode) Val() any

type Array

type Array struct {
	TypesArray *types.Array
	Elem       *Type
	Len        int64
}

func NewArray

func NewArray(a *types.Array) *Array

func ToArray

func ToArray(t any) *Array

func (*Array) String

func (a *Array) String() string

type Basic

type Basic struct {
	TypesBasic *types.Basic
	Info       types.BasicInfo
	Kind       types.BasicKind
	Name       string
}

func NewBasic

func NewBasic(b *types.Basic) *Basic

func ToBasic

func ToBasic(t any) *Basic

func (*Basic) String

func (b *Basic) String() string

type Chan

type Chan struct {
	TypesChan *types.Chan
	Dir       types.ChanDir
	Elem      *Type
}

func NewChan

func NewChan(c *types.Chan) *Chan

func ToChan

func ToChan(t any) *Chan

func (*Chan) String

func (c *Chan) String() string

type Const

type Const struct {
	TypesConst *types.Const
	Exported   bool
	Name       string
	Package    *Package
	Type       *Type
	Value      constant.Value
}

func NewConst

func NewConst(c *types.Const) *Const

func (*Const) BoolVal

func (c *Const) BoolVal() bool

func (*Const) Float32Val

func (c *Const) Float32Val() float32

func (*Const) Float64Val

func (c *Const) Float64Val() float64

func (*Const) Int64Val

func (c *Const) Int64Val() int64

func (*Const) Pos

func (c *Const) Pos() token.Pos

func (*Const) String

func (c *Const) String() string

func (*Const) StringVal

func (c *Const) StringVal() string

func (*Const) TypesObject

func (c *Const) TypesObject() types.Object

func (*Const) Uint64Val

func (c *Const) Uint64Val() uint64

func (*Const) Val

func (c *Const) Val() any

type Field

type Field struct {
	TypesVar  *types.Var
	Struct    *Struct
	Tag       string
	Anonymous bool
	Exported  bool
	Name      string
	Type      *Type
}

func NewField

func NewField(s *Struct, v *types.Var, tag string) *Field

func (*Field) Pos

func (f *Field) Pos() token.Pos

func (*Field) String

func (f *Field) String() string

func (*Field) TypesObject

func (f *Field) TypesObject() types.Object

type Func

type Func struct {
	TypesFunc *types.Func
	Name      string
	Exported  bool
	Package   *Package
	Signature *Signature
}

func NewFunc

func NewFunc(f *types.Func) *Func

func (*Func) Pos

func (f *Func) Pos() token.Pos

func (*Func) String

func (f *Func) String() string

func (*Func) TypesObject

func (f *Func) TypesObject() types.Object

type Interface

type Interface struct {
	TypesInterface      *types.Interface
	Empty               bool
	Embeddeds           []*Type
	Methods             map[string]*Func
	MethodNames         []string
	ExplicitMethods     map[string]*Func
	ExplicitMethodNames []string
}

func NewInterface

func NewInterface(iface *types.Interface) *Interface

func ToInterface

func ToInterface(t any) *Interface

func (*Interface) String

func (i *Interface) String() string

type Knife

type Knife struct {
	// contains filtered or unexported fields
}

func New

func New(patterns ...string) (*Knife, error)

func (*Knife) Execute

func (k *Knife) Execute(w io.Writer, pkg *packages.Package, tmpl any, opt *Option) error

Execute outputs the pkg with the format.

func (*Knife) Packages

func (k *Knife) Packages() []*packages.Package

Packages returns packages.

func (*Knife) Position added in v0.3.0

func (k *Knife) Position(v any) token.Position

Position returns position of v.

type Map

type Map struct {
	TypesMap *types.Map
	Elem     *Type
	Key      *Type
}

func NewMap

func NewMap(m *types.Map) *Map

func ToMap

func ToMap(t any) *Map

func (*Map) String

func (m *Map) String() string

type Named

type Named struct {
	TypesNamed  *types.Named
	Methods     map[string]*Func
	MethodNames []string
	Object      *TypeName
}

func NewNamed

func NewNamed(n *types.Named) *Named

func ToNamed

func ToNamed(t any) *Named

func (*Named) String

func (c *Named) String() string

type Object

type Object interface {
	TypesObject() types.Object
}

func NewObject

func NewObject(o types.Object) Object

type Option

type Option struct {
	XPath     string
	ExtraData map[string]any
}

Option is a option of Execute.

type Package

type Package struct {
	TypesPackage *types.Package
	Name         string
	Path         string
	Imports      []*Package
	Funcs        map[string]*Func
	FuncNames    []string
	Vars         map[string]*Var
	VarNames     []string
	Consts       map[string]*Const
	ConstNames   []string
	Types        map[string]*TypeName
	TypeNames    []string
}

func NewPackage

func NewPackage(pkg *types.Package) *Package

func (*Package) Objects added in v0.3.0

func (pkg *Package) Objects() iter.Seq2[string, Object]

func (*Package) String

func (pkg *Package) String() string

type Pointer

type Pointer struct {
	TypesPointer *types.Pointer
	Elem         *Type
}

func NewPointer

func NewPointer(p *types.Pointer) *Pointer

func ToPointer

func ToPointer(t any) *Pointer

func (*Pointer) String

func (p *Pointer) String() string

type Scope

type Scope struct {
	TypesScope *types.Scope
	Parent     *Scope
	Children   []*Scope
	Pos        token.Pos
	End        token.Pos
	Objects    map[string]Object
	Names      []string
}

func NewScope

func NewScope(s *types.Scope) *Scope

func (*Scope) String

func (s *Scope) String() string

type Signature

type Signature struct {
	TypesSignature *types.Signature
	Recv           *Var
	Params         []*Var
	Results        []*Var
	Variadic       bool
}

func NewSignature

func NewSignature(s *types.Signature) *Signature

func ToSignature

func ToSignature(t any) *Signature

func (*Signature) String

func (s *Signature) String() string

type Slice

type Slice struct {
	TypesSlice *types.Slice
	Elem       *Type
}

func NewSlice

func NewSlice(s *types.Slice) *Slice

func ToSlice

func ToSlice(t any) *Slice

func (*Slice) String

func (s *Slice) String() string

type Struct

type Struct struct {
	TypesStruct *types.Struct
	Fields      map[string]*Field
	FieldNames  []string
}

func NewStruct

func NewStruct(s *types.Struct) *Struct

func ToStruct

func ToStruct(t any) *Struct

func (Struct) String

func (s Struct) String() string

type TempalteData

type TempalteData struct {
	Fset      *token.FileSet
	Files     []*ast.File
	TypesInfo *types.Info
	Pkg       *types.Package
	Extra     map[string]any
}

type Type

type Type struct {
	TypesType types.Type
}

func NewType

func NewType(t types.Type) *Type

func (*Type) Array

func (t *Type) Array() *Array

func (*Type) Basic

func (t *Type) Basic() *Basic

func (*Type) Chan

func (t *Type) Chan() *Chan

func (*Type) Interface

func (t *Type) Interface() *Interface

func (*Type) Map

func (t *Type) Map() *Map

func (*Type) Named

func (t *Type) Named() *Named

func (*Type) Pointer

func (t *Type) Pointer() *Pointer

func (*Type) Signature

func (t *Type) Signature() *Signature

func (*Type) Slice

func (t *Type) Slice() *Slice

func (*Type) String

func (t *Type) String() string

func (*Type) Struct

func (t *Type) Struct() *Struct

func (*Type) Underlying

func (t *Type) Underlying() *Type

type TypeName

type TypeName struct {
	TypesTypeName *types.TypeName
	Exported      bool
	IsAlias       bool
	Name          string
	Package       *Package
	Type          *Type
}

func NewTypeName

func NewTypeName(tn *types.TypeName) *TypeName

func (*TypeName) Pos

func (tn *TypeName) Pos() token.Pos

func (*TypeName) String

func (tn *TypeName) String() string

func (*TypeName) TypesObject

func (tn *TypeName) TypesObject() types.Object

type Var

type Var struct {
	TypesVar *types.Var
	Exported bool
	Name     string
	Type     *Type
	Package  *Package
}

func NewVar

func NewVar(v *types.Var) *Var

func (*Var) Pos

func (v *Var) Pos() token.Pos

func (*Var) String

func (v *Var) String() string

func (*Var) TypesObject

func (v *Var) TypesObject() types.Object

Directories

Path Synopsis
_examples
cmd

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
JackTT - Gopher 🇻🇳