packages

package
v0.0.0-...-7d1dc99 Latest Latest
Warning

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

Go to latest
Published: Aug 17, 2018 License: BSD-3-Clause Imports: 19 Imported by: 0

Documentation

Overview

Package packages loads Go packages for inspection and analysis.

NOTE: THIS PACKAGE IS NOT YET READY FOR WIDESPREAD USE:

  • The interface is still being revised and minor changes are likely.
  • The implementation depends on the Go 1.11 go command; support for earlier versions will be added soon.
  • We intend to finalize the API before Go 1.11 is released.

The Load function takes as input a list of patterns and return a list of Package structs describing individual packages matched by those patterns. The LoadMode controls the amount of detail in the loaded packages.

The patterns are used as arguments to the underlying build tool, such as the go command or Bazel, and are interpreted according to that tool's conventions.

The Package struct provides basic information about the package, including

  • ID, a unique identifier for the package in the returned set;
  • GoFiles, the names of the package's Go source files;
  • Imports, a map from source import strings to the Packages they name;
  • Types, the type information for the package's exported symbols;
  • Syntax, the parsed syntax trees for the package's source code; and
  • TypeInfo, the result of a complete type-check of the package syntax trees.

(See the documentation for type Package for the complete list of fields and more detailed descriptions.)

For example,

Load(nil, "bytes", "unicode...")

returns four Package structs describing the standard library packages bytes, unicode, unicode/utf16, and unicode/utf8. Note that one pattern can match multiple packages and that a package might be matched by multiple patterns: in general it is not possible to determine which packages correspond to which patterns.

Note that the list returned by Load contains only the packages matched by the patterns. Their dependencies can be found by walking the import graph using the Imports fields.

The Load function can be configured by passing a pointer to a Config as the first argument. A nil Config is equivalent to the zero Config, which causes Load to run in LoadFiles mode, collecting minimal information. See the documentation for type Config for details.

As noted earlier, the Config.Mode controls the amount of detail reported about the loaded packages, with each mode returning all the data of the previous mode with some extra added. See the documentation for type LoadMode for details.

Most tools should pass their command-line arguments (after any flags) uninterpreted to the loader, so that the loader can interpret them according to the conventions of the underlying build system. For example, this program prints the names of the source files for each package listed on the command line:

package main

import (
	"flag"
	"fmt"
	"log"

	"golang.org/x/tools/go/packages"
)

func main() {
	flag.Parse()
	pkgs, err := packages.Load(nil, flag.Args()...)
	if err != nil {
		log.Fatal(err)
	}
	for _, pkg := range pkgs {
		fmt.Print(pkg.ID, pkg.GoFiles)
	}
}

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	// Mode controls the level of information returned for each package.
	Mode LoadMode

	// Context specifies the context for the load operation.
	// If the context is cancelled, the loader may stop early
	// and return an ErrCancelled error.
	// If Context is nil, the load cannot be cancelled.
	Context context.Context

	// Dir is the directory in which to run the build system's query tool
	// that provides information about the packages.
	// If Dir is empty, the tool is run in the current directory.
	Dir string

	// Env is the environment to use when invoking the build system's query tool.
	// If Env is nil, the current environment is used.
	// As in os/exec's Cmd, only the last value in the slice for
	// each environment key is used. To specify the setting of only
	// a few variables, append to the current environment, as in:
	//
	//	opt.Env = append(os.Environ(), "GOOS=plan9", "GOARCH=386")
	//
	Env []string

	// Flags is a list of command-line flags to be passed through to
	// the build system's query tool.
	Flags []string

	// Error is called for each error encountered during parsing and type-checking.
	// It must be safe to call Error simultaneously from multiple goroutines.
	// In addition to calling Error, the loader records each error
	// in the corresponding Package's Errors list.
	// If Error is nil, the loader prints errors to os.Stderr.
	// To disable printing of errors, set opt.Error = func(error) {}.
	Error func(error)

	// Fset provides source position information for syntax trees and types.
	// If Fset is nil, the loader will create a new FileSet.
	Fset *token.FileSet

	// ParseFile is called to read and parse each file
	// when preparing a package's type-checked syntax tree.
	// It must be safe to call ParseFile simultaneously from multiple goroutines.
	// If ParseFile is nil, the loader will uses parser.ParseFile.
	//
	// Setting ParseFile to a custom implementation can allow
	// providing alternate file content in order to type-check
	// unsaved text editor buffers, or to selectively eliminate
	// unwanted function bodies to reduce the amount of work
	// done by the type checker.
	ParseFile func(fset *token.FileSet, filename string) (*ast.File, error)

	// If Tests is set, the loader includes not just the packages
	// matching a particular pattern but also any related test packages,
	// including test-only variants of the package and the test executable.
	//
	// For example, when using the go command, loading "fmt" with Tests=true
	// returns four packages, with IDs "fmt" (the standard package),
	// "fmt [fmt.test]" (the package as compiled for the test),
	// "fmt_test" (the test functions from source files in package fmt_test),
	// and "fmt.test" (the test binary).
	//
	// In build systems with explicit names for tests,
	// setting Tests may have no effect.
	Tests bool
}

An Config specifies details about how packages should be loaded. The zero value is a valid configuration. Calls to Load do not modify this struct.

type LoadMode

type LoadMode int

A LoadMode specifies the amount of detail to return when loading. Higher-numbered modes cause Load to return more information, but may be slower. Load may return more information than requested.

const (
	// LoadFiles finds the packages and computes their source file lists.
	// Package fields: ID, Name, Errors, GoFiles, and OtherFiles.
	LoadFiles LoadMode = iota

	// LoadImports adds import information for each package
	// and its dependencies.
	// Package fields added: Imports.
	LoadImports

	// LoadTypes adds type information for package-level
	// declarations in the packages matching the patterns.
	// Package fields added: Types, Fset, and IllTyped.
	// This mode uses type information provided by the build system when
	// possible, and may fill in the ExportFile field.
	LoadTypes

	// LoadSyntax adds typed syntax trees for the packages matching the patterns.
	// Package fields added: Syntax, and TypesInfo, for direct pattern matches only.
	LoadSyntax

	// LoadAllSyntax adds typed syntax trees for the packages matching the patterns
	// and all dependencies.
	// Package fields added: Types, Fset, Illtyped, Syntax, and TypesInfo,
	// for all packages in the import graph.
	LoadAllSyntax
)

type Package

type Package struct {
	// ID is a unique identifier for a package,
	// in a syntax provided by the underlying build system.
	//
	// Because the syntax varies based on the build system,
	// clients should treat IDs as opaque and not attempt to
	// interpret them.
	ID string

	// Name is the package name as it appears in the package source code.
	Name string

	// PkgPath is the package path as used by the go/types package.
	PkgPath string

	// Errors contains any errors encountered while parsing or type-checking the package.
	// Possible error types include *scanner.ErrorList and types.Error,
	// whose fields provide structured position information.
	// Error strings are typically of the form "file:line: message" or
	// "file:line:col: message".
	// TODO(adonovan): export packageError as packages.Error
	// and add that type to the list of structured errors.
	Errors []error

	// GoFiles lists the absolute file paths of the package's Go source files.
	GoFiles []string

	// CompiledGoFiles lists the absolute file paths of the package's source
	// files that were presented to the compiler.
	// This may differ from GoFiles if files are processed before compilation.
	CompiledGoFiles []string

	// OtherFiles lists the absolute file paths of the package's non-Go source files,
	// including assembly, C, C++, Fortran, Objective-C, SWIG, and so on.
	OtherFiles []string

	// ExportFile is the absolute path to a file containing type
	// information for the package as provided by the build system.
	ExportFile string

	// Imports maps import paths appearing in the package's Go source files
	// to corresponding loaded Packages.
	Imports map[string]*Package

	// Types provides type information for the package.
	// Modes LoadTypes and above set this field for packages matching the
	// patterns; type information for dependencies may be missing or incomplete.
	// Mode LoadSyntaxAll sets this field for all packages, including dependencies.
	Types *types.Package

	// Fset provides position information for Types, TypesInfo, and Syntax.
	// It is set only when Types is set.
	Fset *token.FileSet

	// IllTyped indicates whether the package has any type errors.
	// It is set only when Types is set.
	IllTyped bool

	// Syntax is the package's syntax trees, for the files listed in CompiledGoFiles.
	//
	// Mode LoadSyntax sets this field for packages matching the patterns.
	// Mode LoadSyntaxAll sets this field for all packages, including dependencies.
	Syntax []*ast.File

	// TypesInfo provides type information about the package's syntax trees.
	// It is set only when Syntax is set.
	TypesInfo *types.Info
}

A Package describes a loaded Go package.

func Load

func Load(cfg *Config, patterns ...string) ([]*Package, error)

Load loads and returns the Go packages named by the given patterns.

Config specifies loading options; nil behaves the same as an empty Config.

Load returns an error if any of the patterns was invalid as defined by the underlying build system. It may return an empty list of packages without an error, for instance for an empty expansion of a valid wildcard.

func (*Package) MarshalJSON

func (p *Package) MarshalJSON() ([]byte, error)

MarshalJSON returns the Package in its JSON form. For the most part, the structure fields are written out unmodified, and the type and syntax fields are skipped. The imports are written out as just a map of path to package id. The errors are written using a custom type that tries to preserve the structure of error types we know about.

This method exists to enable support for additional build systems. It is not intended for use by clients of the API and we may change the format.

func (*Package) String

func (p *Package) String() string

func (*Package) UnmarshalJSON

func (p *Package) UnmarshalJSON(b []byte) error

UnmarshalJSON reads in a Package from its JSON format. See MarshalJSON for details about the format accepted.

Directories

Path Synopsis
The gopackages command is a diagnostic tool that demonstrates how to use golang.org/x/tools/go/packages to load, parse, type-check, and print one or more Go packages.
The gopackages command is a diagnostic tool that demonstrates how to use golang.org/x/tools/go/packages to load, parse, type-check, and print one or more Go packages.

Jump to

Keyboard shortcuts

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