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 ¶
- Variables
- type Context
- type Docs
- type Files
- type Func
- type MethodSet
- type Package
- func (p *Package) Docs() Docs
- func (p *Package) Files() Files
- func (p *Package) Funcs() []Func
- func (p *Package) MethodSet(name string) (MethodSet, error)
- func (p *Package) Methods() map[string]MethodSet
- func (p *Package) String() string
- func (p *Package) Structs() []Struct
- func (p *Package) Synopsis() string
- func (p *Package) ToAst() (*token.FileSet, *ast.Package, error)
- func (p *Package) ToDoc() (*doc.Package, error)
- func (p *Package) ToInfo() (*types.Info, *types.Package, error)
- func (p *Package) ToTypes() (*types.Package, error)
- func (p *Package) Vars() []Var
- type Struct
- type Var
Examples ¶
Constants ¶
This section is empty.
Variables ¶
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 ¶
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.
type Docs ¶
type Docs struct {
Package *Package
}
Docs groups the documentation related methods.
func (*Docs) Consts ¶
Consts returns declared constants in the go/doc package style, which groups by the entire const ( Const1 = 1, Const2 = .. ) blocks.
func (*Docs) Methods ¶
Methods returns declared methods of doc.Func types grouped in a map of string type names.
func (*Docs) Notes ¶
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.
type Files ¶
type Files struct {
Package *Package
}
Files groups operations on a packages files.
func (*Files) SourcePaths ¶
SourcePaths is like FilePaths but will include all files found by the build importer, .cc, .m, .s, etc while excluding test files.
type Func ¶
Func groups a types.Func and types.Signature, it will never be part of a method so Recv() will always be nul.
type MethodSet ¶
MethodSet represents a set of methods belonging to a named type.
func NewMethodSet ¶
NewMethodSet returns a initialized MethodSet.
type Package ¶
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 (*Package) 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) Funcs ¶
Funcs returns all the packages named functions from the packages outer most scope.
func (*Package) Methods ¶
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) ToAst ¶
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 ¶
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 ¶
ToInfo is like ToTypes but also returns a *types.Info that contains all the Info maps declared and ready to query.