本文整理匯總了Golang中golang.org/x/tools/go/loader.Config.ImportWithTests方法的典型用法代碼示例。如果您正苦於以下問題:Golang Config.ImportWithTests方法的具體用法?Golang Config.ImportWithTests怎麽用?Golang Config.ImportWithTests使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類golang.org/x/tools/go/loader.Config
的用法示例。
在下文中一共展示了Config.ImportWithTests方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: TestStdlib
func TestStdlib(t *testing.T) {
defer func(saved func(format string, args ...interface{})) {
logf = saved
}(logf)
logf = t.Errorf
ctxt := build.Default // copy
// Enumerate $GOROOT packages.
saved := ctxt.GOPATH
ctxt.GOPATH = "" // disable GOPATH during AllPackages
pkgs := buildutil.AllPackages(&ctxt)
ctxt.GOPATH = saved
// Throw in a number of go.tools packages too.
pkgs = append(pkgs,
"golang.org/x/tools/cmd/godoc",
"golang.org/x/tools/refactor/lexical")
// Load, parse and type-check the program.
conf := loader.Config{Build: &ctxt}
for _, path := range pkgs {
conf.ImportWithTests(path)
}
iprog, err := conf.Load()
if err != nil {
t.Fatalf("Load failed: %v", err)
}
// This test ensures that Structure doesn't panic and that
// its internal sanity-checks against go/types don't fail.
for pkg, info := range iprog.AllPackages {
_ = Structure(iprog.Fset, pkg, &info.Info, info.Files)
}
}
示例2: loadProgram
// loadProgram loads the specified set of packages (plus their tests)
// and all their dependencies, from source, through the specified build
// context. Only packages in pkgs will have their functions bodies typechecked.
func loadProgram(ctxt *build.Context, pkgs map[string]bool) (*loader.Program, error) {
conf := loader.Config{
Build: ctxt,
SourceImports: true,
ParserMode: parser.ParseComments,
// TODO(adonovan): enable this. Requires making a lot of code more robust!
AllowErrors: false,
}
// Optimization: don't type-check the bodies of functions in our
// dependencies, since we only need exported package members.
conf.TypeCheckFuncBodies = func(p string) bool {
return pkgs[p] || pkgs[strings.TrimSuffix(p, "_test")]
}
if Verbose {
var list []string
for pkg := range pkgs {
list = append(list, pkg)
}
sort.Strings(list)
for _, pkg := range list {
fmt.Fprintf(os.Stderr, "Loading package: %s\n", pkg)
}
}
for pkg := range pkgs {
if err := conf.ImportWithTests(pkg); err != nil {
return nil, err
}
}
return conf.Load()
}
示例3: NewUnexporter
// Create unexporter
func NewUnexporter(o *Config) (*unexporter, error) {
var conf loader.Config
for _, package_name := range buildutil.AllPackages(&build.Default) {
conf.ImportWithTests(package_name)
}
program, err := conf.Load()
if err != nil {
return nil, err
}
if program.Package(o.Pkg) == nil {
return nil, errors.New(fmt.Sprintf("'%s' is not a valid package", o.Pkg))
}
if o.Debug {
pkg := program.Package(o.Pkg).Pkg
fmt.Printf("finding unused identifiers for %s (%s)\n", pkg.Name(), pkg.Path())
}
unexporter := &unexporter{
Program: program,
MainPackage: program.Package(o.Pkg),
Verbose: o.Debug,
}
unexporter.run()
return unexporter, nil
}
示例4: TestLoad_FromImports_Success
func TestLoad_FromImports_Success(t *testing.T) {
var conf loader.Config
conf.ImportWithTests("fmt")
conf.ImportWithTests("errors")
prog, err := conf.Load()
if err != nil {
t.Errorf("Load failed unexpectedly: %v", err)
}
if prog == nil {
t.Fatalf("Load returned a nil Program")
}
if got, want := created(prog), "errors_test fmt_test"; got != want {
t.Errorf("Created = %q, want %s", got, want)
}
if got, want := imported(prog), "errors fmt"; got != want {
t.Errorf("Imported = %s, want %s", got, want)
}
// Check set of transitive packages.
// There are >30 and the set may grow over time, so only check a few.
want := map[string]bool{
"strings": true,
"time": true,
"runtime": true,
"testing": true,
"unicode": true,
}
for _, path := range all(prog) {
delete(want, path)
}
if len(want) > 0 {
t.Errorf("AllPackages is missing these keys: %q", keys(want))
}
}
示例5: ExampleConfig_Import
// This example imports three packages, including the tests for one of
// them, and loads all their dependencies.
func ExampleConfig_Import() {
// ImportWithTest("strconv") causes strconv to include
// internal_test.go, and creates an external test package,
// strconv_test.
// (Compare with the example of CreateFromFiles.)
var conf loader.Config
conf.Import("unicode/utf8")
conf.Import("errors")
conf.ImportWithTests("strconv")
prog, err := conf.Load()
if err != nil {
log.Fatal(err)
}
printProgram(prog)
printFilenames(prog.Fset, prog.Package("strconv"))
printFilenames(prog.Fset, prog.Package("strconv_test"))
// Output:
// created: [strconv_test]
// imported: [errors strconv unicode/utf8]
// initial: [errors strconv strconv_test unicode/utf8]
// all: [bufio bytes errors flag fmt io log math math/rand os reflect runtime runtime/pprof runtime/trace sort strconv strconv_test strings sync sync/atomic syscall testing text/tabwriter time unicode unicode/utf8]
// strconv.Files: [atob.go atof.go atoi.go decimal.go doc.go extfloat.go ftoa.go isprint.go itoa.go quote.go internal_test.go]
// strconv_test.Files: [atob_test.go atof_test.go atoi_test.go decimal_test.go example_test.go fp_test.go ftoa_test.go itoa_test.go quote_test.go strconv_test.go]
}
示例6: invalidProgram
func invalidProgram(name string) *loader.Program {
var ldr loader.Config
ldr.ParserMode = goparser.ParseComments
ldr.ImportWithTests("github.com/go-swagger/go-swagger/fixtures/goparsing/" + name)
prog, err := ldr.Load()
if err != nil {
log.Fatal(err)
}
return prog
}
示例7: reduceScope
// reduceScope is called for one-shot queries that need only a single
// typed package. It attempts to guess the query package from pos and
// reduce the analysis scope (set of loaded packages) to just that one
// plus (the exported parts of) its dependencies. It leaves its
// arguments unchanged on failure.
//
// TODO(adonovan): this is a real mess... but it's fast.
//
func reduceScope(pos string, conf *loader.Config) {
fqpos, err := fastQueryPos(pos)
if err != nil {
return // bad query
}
// TODO(adonovan): fix: this gives the wrong results for files
// in non-importable packages such as tests and ad-hoc packages
// specified as a list of files (incl. the oracle's tests).
_, importPath, err := guessImportPath(fqpos.fset.File(fqpos.start).Name(), conf.Build)
if err != nil {
return // can't find GOPATH dir
}
if importPath == "" {
return
}
// Check that it's possible to load the queried package.
// (e.g. oracle tests contain different 'package' decls in same dir.)
// Keep consistent with logic in loader/util.go!
cfg2 := *conf.Build
cfg2.CgoEnabled = false
bp, err := cfg2.Import(importPath, "", 0)
if err != nil {
return // no files for package
}
// Check that the queried file appears in the package:
// it might be a '// +build ignore' from an ad-hoc main
// package, e.g. $GOROOT/src/net/http/triv.go.
if !pkgContainsFile(bp, fqpos.fset.File(fqpos.start).Name()) {
return // not found
}
conf.TypeCheckFuncBodies = func(p string) bool { return p == importPath }
// Ignore packages specified on command line.
conf.CreatePkgs = nil
conf.ImportPkgs = nil
// Instead load just the one containing the query position
// (and possibly its corresponding tests/production code).
// TODO(adonovan): set 'augment' based on which file list
// contains
_ = conf.ImportWithTests(importPath) // ignore error
}
示例8: lint
func lint(pkgs []string, tags []string) error {
ctx := build.Default
for _, tag := range tags {
ctx.BuildTags = append(ctx.BuildTags, tag)
}
conf := loader.Config{
Build: &ctx,
}
gotoolCtx := gotool.Context{
BuildContext: ctx,
}
for _, name := range gotoolCtx.ImportPaths(pkgs) {
conf.ImportWithTests(name)
}
prog, err := conf.Load()
if err != nil {
return err
}
foundError := false
for _, pkg := range prog.InitialPackages() {
if pkg.Errors != nil {
fmt.Printf("%s: %#v", pkg.String(), pkg.Errors)
foundError = true
}
}
if foundError {
return fmt.Errorf("Found some initializing errors")
}
for _, pkg := range prog.InitialPackages() {
for _, file := range pkg.Files {
ast.Walk(walkForFunctions{
FileSet: prog.Fset,
}, file)
}
}
return nil
}
示例9: importQueryPackage
// importQueryPackage finds the package P containing the
// query position and tells conf to import it.
// It returns the package's path.
func importQueryPackage(pos string, conf *loader.Config) (string, error) {
fqpos, err := fastQueryPos(pos)
if err != nil {
return "", err // bad query
}
filename := fqpos.fset.File(fqpos.start).Name()
// This will not work for ad-hoc packages
// such as $GOROOT/src/net/http/triv.go.
// TODO(adonovan): ensure we report a clear error.
_, importPath, err := guessImportPath(filename, conf.Build)
if err != nil {
return "", err // can't find GOPATH dir
}
if importPath == "" {
return "", fmt.Errorf("can't guess import path from %s", filename)
}
// Check that it's possible to load the queried package.
// (e.g. oracle tests contain different 'package' decls in same dir.)
// Keep consistent with logic in loader/util.go!
cfg2 := *conf.Build
cfg2.CgoEnabled = false
bp, err := cfg2.Import(importPath, "", 0)
if err != nil {
return "", err // no files for package
}
switch pkgContainsFile(bp, filename) {
case 'T':
conf.ImportWithTests(importPath)
case 'X':
conf.ImportWithTests(importPath)
importPath += "_test" // for TypeCheckFuncBodies
case 'G':
conf.Import(importPath)
default:
return "", fmt.Errorf("package %q doesn't contain file %s",
importPath, filename)
}
conf.TypeCheckFuncBodies = func(p string) bool { return p == importPath }
return importPath, nil
}
示例10: ParsePathsFromArgs
// ParsePathsFromArgs parses arguments from command line and looks at import
// paths to rename objects.
func ParsePathsFromArgs() {
flag.Parse()
for _, dir := range flag.Args() {
var conf loader.Config
conf.ParserMode = parser.ParseComments
conf.ImportWithTests(dir)
prog, err := conf.Load()
if err != nil {
panic(err)
}
r := renamer{prog, map[*token.File]bool{}}
r.parse()
if !*dryRun {
r.write()
}
}
}
示例11: importQueryPackage
// importQueryPackage finds the package P containing the
// query position and tells conf to import it.
// It returns the package's path.
func importQueryPackage(pos string, conf *loader.Config) (string, error) {
fqpos, err := fastQueryPos(conf.Build, pos)
if err != nil {
return "", err // bad query
}
filename := fqpos.fset.File(fqpos.start).Name()
_, importPath, err := guessImportPath(filename, conf.Build)
if err != nil {
// Can't find GOPATH dir.
// Treat the query file as its own package.
importPath = "command-line-arguments"
conf.CreateFromFilenames(importPath, filename)
} else {
// Check that it's possible to load the queried package.
// (e.g. guru tests contain different 'package' decls in same dir.)
// Keep consistent with logic in loader/util.go!
cfg2 := *conf.Build
cfg2.CgoEnabled = false
bp, err := cfg2.Import(importPath, "", 0)
if err != nil {
return "", err // no files for package
}
switch pkgContainsFile(bp, filename) {
case 'T':
conf.ImportWithTests(importPath)
case 'X':
conf.ImportWithTests(importPath)
importPath += "_test" // for TypeCheckFuncBodies
case 'G':
conf.Import(importPath)
default:
// This happens for ad-hoc packages like
// $GOROOT/src/net/http/triv.go.
return "", fmt.Errorf("package %q doesn't contain file %s",
importPath, filename)
}
}
conf.TypeCheckFuncBodies = func(p string) bool { return p == importPath }
return importPath, nil
}
示例12: loadProgram
func (u *Unexporter) loadProgram(pkgPath string) (err error) {
wd, err := os.Getwd()
if err != nil {
return err
}
bpkg, err := u.ctxt.Import(pkgPath, wd, build.ImportComment)
if err != nil {
return err
}
_, rev, _ := importgraph.Build(u.ctxt)
pkgs := rev.Search(bpkg.ImportPath)
conf := loader.Config{
Build: u.ctxt,
ParserMode: parser.ParseComments,
AllowErrors: false,
}
// Optimization: don't type-check the bodies of functions in our
// dependencies, since we only need exported package members.
conf.TypeCheckFuncBodies = func(p string) bool {
return pkgs[p] || pkgs[strings.TrimSuffix(p, "_test")]
}
for pkg := range pkgs {
conf.ImportWithTests(pkg)
}
u.prog, err = conf.Load()
if err != nil {
return
}
for p, info := range u.prog.AllPackages {
if p.Path() == bpkg.ImportPath {
u.pkgInfo = info
break
}
}
return
}
示例13: TestLoad_MissingInitialPackage_AllowErrors
func TestLoad_MissingInitialPackage_AllowErrors(t *testing.T) {
var conf loader.Config
conf.AllowErrors = true
conf.Import("nosuchpkg")
conf.ImportWithTests("errors")
prog, err := conf.Load()
if err != nil {
t.Errorf("Load failed unexpectedly: %v", err)
}
if prog == nil {
t.Fatalf("Load returned a nil Program")
}
if got, want := created(prog), "errors_test"; got != want {
t.Errorf("Created = %s, want %s", got, want)
}
if got, want := imported(prog), "errors"; got != want {
t.Errorf("Imported = %s, want %s", got, want)
}
}
示例14: newAppScanner
// newAppScanner creates a new api parser
func newAppScanner(opts *Opts, includes, excludes packageFilters) (*appScanner, error) {
var ldr loader.Config
ldr.ParserMode = goparser.ParseComments
ldr.ImportWithTests(opts.BasePath)
prog, err := ldr.Load()
if err != nil {
return nil, err
}
input := opts.Input
if input == nil {
input = new(spec.Swagger)
input.Swagger = "2.0"
}
if input.Paths == nil {
input.Paths = new(spec.Paths)
}
if input.Definitions == nil {
input.Definitions = make(map[string]spec.Schema)
}
if input.Responses == nil {
input.Responses = make(map[string]spec.Response)
}
return &appScanner{
MainPackage: opts.BasePath,
prog: prog,
input: input,
loader: &ldr,
operations: collectOperationsFromInput(input),
definitions: input.Definitions,
responses: input.Responses,
scanModels: opts.ScanModels,
classifier: &programClassifier{
Includes: includes,
Excludes: excludes,
},
}, nil
}
示例15: classifierProgram
func classifierProgram() *loader.Program {
var ldr loader.Config
ldr.ParserMode = goparser.ParseComments
ldr.Build = &gobuild.Default
ldr.ImportWithTests("github.com/go-swagger/go-swagger/fixtures/goparsing/classification")
ldr.ImportWithTests("github.com/go-swagger/go-swagger/fixtures/goparsing/classification/models")
ldr.ImportWithTests("github.com/go-swagger/go-swagger/fixtures/goparsing/classification/operations")
prog, err := ldr.Load()
if err != nil {
log.Fatal(err)
}
return prog
}