srcutil

package module
v0.0.0-...-6a9c8a3 Latest Latest
Warning

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

Go to latest
Published: Apr 16, 2017 License: BSD-3-Clause, MIT Imports: 15 Imported by: 0

README

Go Package: srcutil

About | Go Doc

Get:

go get -u github.com/cstockton/go-srcutil

Example:

pkg, err := srcutil.Import("io")
if err != nil {	log.Fatal(err) }
fmt.Printf("// %s: %s\n", pkg, pkg.Doc)

vars := pkg.Vars()
for _, v := range vars {
  fmt.Printf("var %v %v\n", v.Name(), v.Type())
}

Output

// io: Package io provides basic interfaces to I/O primitives.
var EOF error
var ErrClosedPipe error
var ErrNoProgress error
var ErrShortBuffer error
var ErrShortWrite error
var ErrUnexpectedEOF error

About

Package srcutil provides utilities for working with Go source code. The Go standard library provides a powerful suite of packages "go/{ast,doc,...}" which are used by the Go tool chain to compile Go programs. As you initially try to find your way around you hit a small dependency barrier and have to learn a small portion of each package. There is a fantastic write up and collection of examples that I used to learn (or shamelessly copy pasta'd) while creating this package, currently maintained by:

  Alan Donovan (https://github.com/golang/example/tree/master/gotypes)

In the mean time this package can help you get started with some common use cases.

Bugs and Patches

Feel free to report bugs and submit pull requests.

Documentation

Overview

Package srcutil provides utilities for working with Go source code. The Go standard library provides a powerful suite of packages "go/{ast,doc,...}" which are used by the Go tool chain to compile Go programs. As you initially try to find your way around you hit a small dependency barrier and have to learn a small portion of each package. There is a fantastic write up and collection of examples that I used to learn (or shamelessly copy pasta'd) while creating this package, currently maintained by:

Alan Donovan (https://github.com/golang/example/tree/master/gotypes)

In the mean time this package can help you get started with some common use cases.

Example
pkg, err := srcutil.Import("io")
if err != nil {
	log.Fatal(err)
}
fmt.Printf("// %s: %s\n", pkg, pkg.Doc)

vars := pkg.Vars()
for _, v := range vars {
	fmt.Printf("var %v %v\n", v.Name(), v.Type())
}
Output:

// io: Package io provides basic interfaces to I/O primitives.
var EOF error
var ErrClosedPipe error
var ErrNoProgress error
var ErrShortBuffer error
var ErrShortWrite error
var ErrUnexpectedEOF error

Index

Examples

Constants

This section is empty.

Variables

View Source
var (

	// DefaultContext is a Context configured as if you were in the directory of
	// the source code calling this library and working normally. It uses the
	// currently configured GOROOT, GOPATH and the source dir is set to your
	// current working directory.
	DefaultContext = FromWorkDir()

	// DefaultParseMode adds ParseComments to the default parser.Mode used in the
	// go/parser package.
	DefaultParseMode = parser.ParseComments

	// DefaultImportMode is the same as the default build.ImportMode used in the
	// go/build package.
	DefaultImportMode = build.ImportMode(0)
)

Functions

This section is empty.

Types

type Context

type Context struct {
	build.Context

	// SourceDir defines where the code lives relative for operations you perform.
	// For example if you call Context.Import("reflect") it will attempt to import
	// that as if the calling package was SourceDir. So if a vendor/ directory
	// existing within SourceDir with a reflect package that would be imported
	// instead.
	SourceDir string
}

Context is not something you need to interact with for common use cases, instead calling the top level functions that return Package types directly which will use the DefaultContext.

This structure is like build.Context except it includes the ImportMode and a SourceDir that will default to the current working directory. It sits at the top of this packages dependency hierarchy as it loads the top level useful object, Package.

func FromDir

func FromDir(fromDir string) *Context

FromDir returns a Context configured with the SourceDir set to the given dir. It uses the default build.ImportMode and build.Default for build.Context and your GOROOT and GOPATH from the environment to determine the location of packages and the standard library.

func FromStandard

func FromStandard() *Context

FromStandard returns a Context configured to only contain the Go standard library, to do this it simply excludes your GOPATH and sets the SourceDir to the GOROOT/src.

func FromWorkDir

func FromWorkDir() *Context

FromWorkDir is like FromDir except it sets the Source dir to your working directory. It is used as the DefaultContext.

func (*Context) Import

func (c *Context) Import(pkgName string) (*Package, error)

Import will behave just like using a import declaration from code residing within the SourceDir of this Context. If you did not explicitly set the SourceDir it will use your current working directory.

func (*Context) String

func (c *Context) String() string

String implements fmt.Stringer.

type Docs

type Docs struct {
	Package *Package
}

Docs groups the documentation related methods.

func (*Docs) Consts

func (d *Docs) Consts() []doc.Value

Consts returns declared constants in the go/doc package style, which groups by the entire const ( Const1 = 1, Const2 = .. ) blocks.

func (*Docs) Examples

func (d *Docs) Examples() []doc.Example

Examples returns a slice of doc.Example for each declared Go example.

func (*Docs) Funcs

func (d *Docs) Funcs() []doc.Func

Funcs returns a slice of doc.Func representing exported functions.

func (*Docs) Methods

func (d *Docs) Methods() map[string][]doc.Func

Methods returns declared methods of doc.Func types grouped in a map of string type names.

func (*Docs) Notes

func (d *Docs) Notes() map[string][]doc.Note

Notes returns all marked comments starting with "MARKER(uid): note body." as described in the go/doc package. I.E.:

// TODO(cstockton): Fix this.
// BUG(cstockton): Broken.

func (*Docs) Types

func (d *Docs) Types() []doc.Type

Types returns a slice of doc.Type representing exported functions.

func (*Docs) Vars

func (d *Docs) Vars() []doc.Value

Vars returns declared variables in the go/doc package style, which groups the by the var ( Var1 = 1, Var2 = .. ) blocks.

type Files

type Files struct {
	Package *Package
}

Files groups operations on a packages files.

func (*Files) Names

func (pf *Files) Names() []string

Names returns a sorted slice of file names for this package.

func (*Files) Paths

func (pf *Files) Paths() []string

Paths returns a sorted slice of full file paths for this package.

func (*Files) SourcePaths

func (pf *Files) SourcePaths() []string

SourcePaths is like FilePaths but will include all files found by the build importer, .cc, .m, .s, etc while excluding test files.

func (*Files) TestPaths

func (pf *Files) TestPaths() []string

TestPaths is like FilePaths but will include only test files.

type Func

type Func struct {
	*types.Func
	*types.Signature
}

Func groups a types.Func and types.Signature, it will never be part of a method so Recv() will always be nul.

func NewFunc

func NewFunc(typeFunc *types.Func) Func

NewFunc returns a Function, typeFunc must not be nil.

func (Func) String

func (f Func) String() string

String implements fmt.Stringer.

type MethodSet

type MethodSet struct {
	Name    string
	Obj     types.Object
	Methods map[string]Func
}

MethodSet represents a set of methods belonging to a named type.

func NewMethodSet

func NewMethodSet(name string, obj types.Object) MethodSet

NewMethodSet returns a initialized MethodSet.

func (MethodSet) Len

func (m MethodSet) Len() int

Len returns the current number of Method's within this MethodSet.

func (MethodSet) Names

func (m MethodSet) Names() []string

Names returns the names of the methods in this MethodSet.

type Package

type Package struct {
	build.Package
	// contains filtered or unexported fields
}

A Package here has the same meaning as in Go. It embeds a build.Package and provides methods to centralize some of the common operations for working with Go source code and makes it easy to create some of the lower level compiler toolchain primitives like ast, types and parser packages. It should be safe for concurrent use from multiple Goroutines.

You should not create Package values with composite literals, instead use one of the functions in this package so it may be initialized safely.

func Import

func Import(pkgName string) (*Package, error)

Import is shorthand for FromWorkDir().Import("pkgname").

func (*Package) Docs

func (p *Package) Docs() Docs

Docs returns a Docs struct to perform common operations related to documentation using the go/doc

Example
pkg, err := srcutil.Import("io")
if err != nil {
	log.Fatal(err)
}
docs := pkg.Docs()

consts := docs.Consts()
fmt.Printf("// %v", consts[0].Doc)
fmt.Printf("const(\n  %v\n)\n\n", strings.Join(consts[0].Names, "\n  "))

vars := docs.Vars()
for _, v := range vars {
	fmt.Printf("// %v", doc.Synopsis(consts[0].Doc))
	fmt.Printf("var %v\n", v.Names[0])
}
fmt.Print("\n")

types := docs.Types()
for _, typ := range types {
	if strings.Contains(typ.Name, "Reader") {
		fmt.Printf("// %v\n", doc.Synopsis(typ.Doc))
		for _, f := range typ.Funcs {
			fmt.Printf("// %v\n", doc.Synopsis(f.Doc))
		}
	}
}
Output:

// Seek whence values.
const(
  SeekStart
  SeekCurrent
  SeekEnd
)

// Seek whence values.var EOF
// Seek whence values.var ErrClosedPipe
// Seek whence values.var ErrNoProgress
// Seek whence values.var ErrShortBuffer
// Seek whence values.var ErrShortWrite
// Seek whence values.var ErrUnexpectedEOF

// ByteReader is the interface that wraps the ReadByte method.
// A LimitedReader reads from R but limits the amount of data returned to just N bytes.
// A PipeReader is the read half of a pipe.
// Pipe creates a synchronous in-memory pipe.
// Reader is the interface that wraps the basic Read method.
// LimitReader returns a Reader that reads from r but stops with EOF after n bytes.
// MultiReader returns a Reader that's the logical concatenation of the provided input readers.
// TeeReader returns a Reader that writes to w what it reads from r.
// ReaderAt is the interface that wraps the basic ReadAt method.
// ReaderFrom is the interface that wraps the ReadFrom method.
// RuneReader is the interface that wraps the ReadRune method.
// SectionReader implements Read, Seek, and ReadAt on a section of an underlying ReaderAt.
// NewSectionReader returns a SectionReader that reads from r starting at offset off and stops with EOF after n bytes.

func (*Package) Files

func (p *Package) Files() Files

Files returns a sorted slice of full file paths for this package.

func (*Package) Funcs

func (p *Package) Funcs() []Func

Funcs returns all the packages named functions from the packages outer most scope.

func (*Package) MethodSet

func (p *Package) MethodSet(name string) (MethodSet, error)

MethodSet returns the set of methods for the given name.

func (*Package) Methods

func (p *Package) Methods() map[string]MethodSet

Methods returns a map keyed off of the name type with a value of MethodSet. Only types with at least one method are included.

Example
pkg, err := srcutil.Import("bufio")
if err != nil {
	log.Fatal(err)
}
pkgMethods := pkg.Methods()

printer := func(methodSet srcutil.MethodSet) {
	fmt.Printf("type %v (%d methods)\n", methodSet.Name, methodSet.Len())
	for _, name := range methodSet.Names() {
		method := methodSet.Methods[name]
		fmt.Printf("  %v%v\n    returns %v\n", name, method.Params(), method.Results())
	}
}
printer(pkgMethods["Reader"])
Output:

type Reader (18 methods)
  Buffered()
    returns (int)
  Discard(n int)
    returns (discarded int, err error)
  Peek(n int)
    returns ([]byte, error)
  Read(p []byte)
    returns (n int, err error)
  ReadByte()
    returns (byte, error)
  ReadBytes(delim byte)
    returns ([]byte, error)
  ReadLine()
    returns (line []byte, isPrefix bool, err error)
  ReadRune()
    returns (r rune, size int, err error)
  ReadSlice(delim byte)
    returns (line []byte, err error)
  ReadString(delim byte)
    returns (string, error)
  Reset(r io.Reader)
    returns ()
  UnreadByte()
    returns (error)
  UnreadRune()
    returns (error)
  WriteTo(w io.Writer)
    returns (n int64, err error)
  fill()
    returns ()
  readErr()
    returns (error)
  reset(buf []byte, r io.Reader)
    returns ()
  writeBuf(w io.Writer)
    returns (int64, error)

func (*Package) String

func (p *Package) String() string

String implements fmt.Stringer.

func (*Package) Structs

func (p *Package) Structs() []Struct

Structs returns all the packages named structs from the package scope.

func (*Package) Synopsis

func (p *Package) Synopsis() string

Synopsis implements fmt.Stringer.

func (*Package) ToAst

func (p *Package) ToAst() (*token.FileSet, *ast.Package, error)

ToAst provides access to an associated pair of *token.FileSet and ast.Package. A new pair is created each call and a nil pointer will be returned when error is non-nil.

func (*Package) ToDoc

func (p *Package) ToDoc() (*doc.Package, error)

ToDoc provides access to a *doc.Package. A new *doc.Package will be created each call and a nil pointer will be returned when error is non-nil.

func (*Package) ToInfo

func (p *Package) ToInfo() (*types.Info, *types.Package, error)

ToInfo is like ToTypes but also returns a *types.Info that contains all the Info maps declared and ready to query.

func (*Package) ToTypes

func (p *Package) ToTypes() (*types.Package, error)

ToTypes provides access to a *types.Package. A new *types.Package will be created each call and a nil pointer will be returned when error is non-nil.

func (*Package) Vars

func (p *Package) Vars() []Var

Vars returns all the packages named variables from the package scope.

type Struct

type Struct struct {
	*types.Struct
	Named *types.Named
}

Struct represents a named struct.

func NewStruct

func NewStruct(typeStruct *types.Struct, typeNamed *types.Named) Struct

NewStruct returns a Struct, typeStruct must not be nil.

type Var

type Var struct {
	*types.Var
	Named *types.Named
}

Var represents a packages top level named variable.

func NewVar

func NewVar(typeVar *types.Var, typeNamed *types.Named) Var

NewVar returns a Var, typeVar must not be nil.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL