vendor: update golang.org/x/tools including goimports formatting changes

A recent change was introduced in goimports improving how it sort and
format imports in https://go-review.googlesource.com/c/tools/+/116795

This commit updates the vendored version of the golang.org/x/tools
repository to include these changes.
This commit is contained in:
Cezar Sa Espinola 2018-10-16 09:53:46 -03:00 committed by Isaev Denis
parent 889e38c2fa
commit 0e2be20016
12 changed files with 7989 additions and 7658 deletions

5
Gopkg.lock generated
View File

@ -549,7 +549,7 @@
[[projects]] [[projects]]
branch = "master" branch = "master"
digest = "1:1c24352e1722a8954fe7c95bcb12d878ef9883b01fe3e0e801f62e8cbf9621a0" digest = "1:1f0808c71cfd0b33831391bc26c7ba2862138bfaa10b7f8ed695b2a0c67f896c"
name = "golang.org/x/tools" name = "golang.org/x/tools"
packages = [ packages = [
"go/ast/astutil", "go/ast/astutil",
@ -561,9 +561,10 @@
"go/types/typeutil", "go/types/typeutil",
"imports", "imports",
"internal/fastwalk", "internal/fastwalk",
"internal/gopathwalk",
] ]
pruneopts = "UT" pruneopts = "UT"
revision = "7ca132754999accbaa5c1735eda29e7ce0f3bf03" revision = "5d4988d199e2aeefda3528f599e06410c43caa29"
[[projects]] [[projects]]
digest = "1:342378ac4dcb378a5448dd723f0784ae519383532f5e70ade24132c4c8693202" digest = "1:342378ac4dcb378a5448dd723f0784ae519383532f5e70ade24132c4c8693202"

35
vendor/golang.org/x/tools/go/types/typeutil/callee.go generated vendored Normal file
View File

@ -0,0 +1,35 @@
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package typeutil
import (
"go/ast"
"go/types"
)
// StaticCallee returns the target (function or method) of a static
// function call, if any. It returns nil for calls to builtin.
func StaticCallee(info *types.Info, call *ast.CallExpr) *types.Func {
var obj types.Object
switch fun := call.Fun.(type) {
case *ast.Ident:
obj = info.Uses[fun] // type, var, builtin, or declared func
case *ast.SelectorExpr:
if sel, ok := info.Selections[fun]; ok {
obj = sel.Obj() // method or field
} else {
obj = info.Uses[fun.Sel] // qualified identifier?
}
}
if f, ok := obj.(*types.Func); ok && !interfaceMethod(f) {
return f
}
return nil
}
func interfaceMethod(f *types.Func) bool {
recv := f.Type().(*types.Signature).Recv()
return recv != nil && types.IsInterface(recv.Type())
}

View File

@ -5,8 +5,6 @@
package imports package imports
import ( import (
"bufio"
"bytes"
"context" "context"
"fmt" "fmt"
"go/ast" "go/ast"
@ -24,7 +22,7 @@ import (
"sync" "sync"
"golang.org/x/tools/go/ast/astutil" "golang.org/x/tools/go/ast/astutil"
"golang.org/x/tools/internal/fastwalk" "golang.org/x/tools/internal/gopathwalk"
) )
// Debug controls verbose logging. // Debug controls verbose logging.
@ -471,17 +469,9 @@ func init() {
// Directory-scanning state. // Directory-scanning state.
var ( var (
// scanGoRootOnce guards calling scanGoRoot (for $GOROOT) // scanOnce guards calling scanGoDirs and assigning dirScan
scanGoRootOnce sync.Once scanOnce sync.Once
// scanGoPathOnce guards calling scanGoPath (for $GOPATH) dirScan map[string]*pkg // abs dir path => *pkg
scanGoPathOnce sync.Once
// populateIgnoreOnce guards calling populateIgnore
populateIgnoreOnce sync.Once
ignoredDirs []os.FileInfo
dirScanMu sync.Mutex
dirScan map[string]*pkg // abs dir path => *pkg
) )
type pkg struct { type pkg struct {
@ -531,195 +521,27 @@ func distance(basepath, targetpath string) int {
return strings.Count(p, string(filepath.Separator)) + 1 return strings.Count(p, string(filepath.Separator)) + 1
} }
// guarded by populateIgnoreOnce; populates ignoredDirs. // scanGoDirs populates the dirScan map for GOPATH and GOROOT.
func populateIgnore() { func scanGoDirs() map[string]*pkg {
for _, srcDir := range build.Default.SrcDirs() { result := make(map[string]*pkg)
if srcDir == filepath.Join(build.Default.GOROOT, "src") { var mu sync.Mutex
continue
}
populateIgnoredDirs(srcDir)
}
}
// populateIgnoredDirs reads an optional config file at <path>/.goimportsignore add := func(srcDir, dir string) {
// of relative directories to ignore when scanning for go files. mu.Lock()
// The provided path is one of the $GOPATH entries with "src" appended. defer mu.Unlock()
func populateIgnoredDirs(path string) {
file := filepath.Join(path, ".goimportsignore") if _, dup := result[dir]; dup {
slurp, err := ioutil.ReadFile(file) return
if Debug { }
if err != nil { importpath := filepath.ToSlash(dir[len(srcDir)+len("/"):])
log.Print(err) result[dir] = &pkg{
} else { importPath: importpath,
log.Printf("Read %s", file) importPathShort: VendorlessPath(importpath),
} dir: dir,
}
if err != nil {
return
}
bs := bufio.NewScanner(bytes.NewReader(slurp))
for bs.Scan() {
line := strings.TrimSpace(bs.Text())
if line == "" || strings.HasPrefix(line, "#") {
continue
}
full := filepath.Join(path, line)
if fi, err := os.Stat(full); err == nil {
ignoredDirs = append(ignoredDirs, fi)
if Debug {
log.Printf("Directory added to ignore list: %s", full)
}
} else if Debug {
log.Printf("Error statting entry in .goimportsignore: %v", err)
}
}
}
func skipDir(fi os.FileInfo) bool {
for _, ignoredDir := range ignoredDirs {
if os.SameFile(fi, ignoredDir) {
return true
}
}
return false
}
// shouldTraverse reports whether the symlink fi, found in dir,
// should be followed. It makes sure symlinks were never visited
// before to avoid symlink loops.
func shouldTraverse(dir string, fi os.FileInfo) bool {
path := filepath.Join(dir, fi.Name())
target, err := filepath.EvalSymlinks(path)
if err != nil {
return false
}
ts, err := os.Stat(target)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return false
}
if !ts.IsDir() {
return false
}
if skipDir(ts) {
return false
}
// Check for symlink loops by statting each directory component
// and seeing if any are the same file as ts.
for {
parent := filepath.Dir(path)
if parent == path {
// Made it to the root without seeing a cycle.
// Use this symlink.
return true
}
parentInfo, err := os.Stat(parent)
if err != nil {
return false
}
if os.SameFile(ts, parentInfo) {
// Cycle. Don't traverse.
return false
}
path = parent
}
}
var testHookScanDir = func(dir string) {}
type goDirType string
const (
goRoot goDirType = "$GOROOT"
goPath goDirType = "$GOPATH"
)
var scanGoRootDone = make(chan struct{}) // closed when scanGoRoot is done
// scanGoDirs populates the dirScan map for the given directory type. It may be
// called concurrently (and usually is, if both directory types are needed).
func scanGoDirs(which goDirType) {
if Debug {
log.Printf("scanning %s", which)
defer log.Printf("scanned %s", which)
}
for _, srcDir := range build.Default.SrcDirs() {
isGoroot := srcDir == filepath.Join(build.Default.GOROOT, "src")
if isGoroot != (which == goRoot) {
continue
}
testHookScanDir(srcDir)
srcV := filepath.Join(srcDir, "v")
srcMod := filepath.Join(srcDir, "mod")
walkFn := func(path string, typ os.FileMode) error {
if path == srcV || path == srcMod {
return filepath.SkipDir
}
dir := filepath.Dir(path)
if typ.IsRegular() {
if dir == srcDir {
// Doesn't make sense to have regular files
// directly in your $GOPATH/src or $GOROOT/src.
return nil
}
if !strings.HasSuffix(path, ".go") {
return nil
}
dirScanMu.Lock()
defer dirScanMu.Unlock()
if _, dup := dirScan[dir]; dup {
return nil
}
if dirScan == nil {
dirScan = make(map[string]*pkg)
}
importpath := filepath.ToSlash(dir[len(srcDir)+len("/"):])
dirScan[dir] = &pkg{
importPath: importpath,
importPathShort: VendorlessPath(importpath),
dir: dir,
}
return nil
}
if typ == os.ModeDir {
base := filepath.Base(path)
if base == "" || base[0] == '.' || base[0] == '_' ||
base == "testdata" || base == "node_modules" {
return filepath.SkipDir
}
fi, err := os.Lstat(path)
if err == nil && skipDir(fi) {
if Debug {
log.Printf("skipping directory %q under %s", fi.Name(), dir)
}
return filepath.SkipDir
}
return nil
}
if typ == os.ModeSymlink {
base := filepath.Base(path)
if strings.HasPrefix(base, ".#") {
// Emacs noise.
return nil
}
fi, err := os.Lstat(path)
if err != nil {
// Just ignore it.
return nil
}
if shouldTraverse(dir, fi) {
return fastwalk.TraverseLink
}
}
return nil
}
if err := fastwalk.Walk(srcDir, walkFn); err != nil {
log.Printf("goimports: scanning directory %v: %v", srcDir, err)
} }
} }
gopathwalk.Walk(add, gopathwalk.Options{Debug: Debug, ModulesEnabled: false})
return result
} }
// VendorlessPath returns the devendorized version of the import path ipath. // VendorlessPath returns the devendorized version of the import path ipath.
@ -868,25 +690,8 @@ func findImportGoPath(ctx context.Context, pkgName string, symbols map[string]bo
// in the current Go file. Return rename=true when the other Go files // in the current Go file. Return rename=true when the other Go files
// use a renamed package that's also used in the current file. // use a renamed package that's also used in the current file.
// Read all the $GOPATH/src/.goimportsignore files before scanning directories. // Scan $GOROOT and each $GOPATH.
populateIgnoreOnce.Do(populateIgnore) scanOnce.Do(func() { dirScan = scanGoDirs() })
// Start scanning the $GOROOT asynchronously, then run the
// GOPATH scan synchronously if needed, and then wait for the
// $GOROOT to finish.
//
// TODO(bradfitz): run each $GOPATH entry async. But nobody
// really has more than one anyway, so low priority.
scanGoRootOnce.Do(func() {
go func() {
scanGoDirs(goRoot)
close(scanGoRootDone)
}()
})
if !fileInDir(filename, build.Default.GOROOT) {
scanGoPathOnce.Do(func() { scanGoDirs(goPath) })
}
<-scanGoRootDone
// Find candidate packages, looking only at their directory names first. // Find candidate packages, looking only at their directory names first.
var candidates []pkgDistance var candidates []pkgDistance

View File

@ -56,6 +56,7 @@ func main() {
mustOpen(api("go1.8.txt")), mustOpen(api("go1.8.txt")),
mustOpen(api("go1.9.txt")), mustOpen(api("go1.9.txt")),
mustOpen(api("go1.10.txt")), mustOpen(api("go1.10.txt")),
mustOpen(api("go1.11.txt")),
) )
sc := bufio.NewScanner(f) sc := bufio.NewScanner(f)
fullImport := map[string]string{} // "zip.NewReader" => "archive/zip" fullImport := map[string]string{} // "zip.NewReader" => "archive/zip"

View File

@ -34,18 +34,8 @@ func sortImports(fset *token.FileSet, f *ast.File) {
continue continue
} }
// Identify and sort runs of specs on successive lines. // Sort and regroup all imports.
i := 0 sortSpecs(fset, f, d.Specs)
specs := d.Specs[:0]
for j, s := range d.Specs {
if j > i && fset.Position(s.Pos()).Line > 1+fset.Position(d.Specs[j-1].End()).Line {
// j begins a new run. End this one.
specs = append(specs, sortSpecs(fset, f, d.Specs[i:j])...)
i = j
}
}
specs = append(specs, sortSpecs(fset, f, d.Specs[i:])...)
d.Specs = specs
// Deduping can leave a blank line before the rparen; clean that up. // Deduping can leave a blank line before the rparen; clean that up.
if len(d.Specs) > 0 { if len(d.Specs) > 0 {

File diff suppressed because it is too large Load Diff

View File

@ -18,6 +18,11 @@ import (
// symlink named in the call may be traversed. // symlink named in the call may be traversed.
var TraverseLink = errors.New("fastwalk: traverse symlink, assuming target is a directory") var TraverseLink = errors.New("fastwalk: traverse symlink, assuming target is a directory")
// SkipFiles is a used as a return value from WalkFuncs to indicate that the
// callback should not be called for any other files in the current directory.
// Child directories will still be traversed.
var SkipFiles = errors.New("fastwalk: skip remaining files in directory")
// Walk is a faster implementation of filepath.Walk. // Walk is a faster implementation of filepath.Walk.
// //
// filepath.Walk's design necessarily calls os.Lstat on each file, // filepath.Walk's design necessarily calls os.Lstat on each file,

View File

@ -0,0 +1,13 @@
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build darwin freebsd openbsd netbsd
package fastwalk
import "syscall"
func direntNamlen(dirent *syscall.Dirent) uint64 {
return uint64(dirent.Namlen)
}

View File

@ -0,0 +1,24 @@
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build linux
// +build !appengine
package fastwalk
import (
"bytes"
"syscall"
"unsafe"
)
func direntNamlen(dirent *syscall.Dirent) uint64 {
const fixedHdr = uint16(unsafe.Offsetof(syscall.Dirent{}.Name))
nameBuf := (*[unsafe.Sizeof(dirent.Name)]byte)(unsafe.Pointer(&dirent.Name[0]))
nameLen := bytes.IndexByte(nameBuf[:dirent.Reclen-fixedHdr], 0)
if nameLen < 0 {
panic("failed to find terminating 0 byte in dirent")
}
return uint64(nameLen)
}

View File

@ -20,8 +20,16 @@ func readDir(dirName string, fn func(dirName, entName string, typ os.FileMode) e
if err != nil { if err != nil {
return err return err
} }
skipFiles := false
for _, fi := range fis { for _, fi := range fis {
if fi.Mode().IsRegular() && skipFiles {
continue
}
if err := fn(dirName, fi.Name(), fi.Mode()&os.ModeType); err != nil { if err := fn(dirName, fi.Name(), fi.Mode()&os.ModeType); err != nil {
if err == SkipFiles {
skipFiles = true
continue
}
return err return err
} }
} }

View File

@ -8,7 +8,6 @@
package fastwalk package fastwalk
import ( import (
"bytes"
"fmt" "fmt"
"os" "os"
"syscall" "syscall"
@ -32,6 +31,7 @@ func readDir(dirName string, fn func(dirName, entName string, typ os.FileMode) e
buf := make([]byte, blockSize) // stack-allocated; doesn't escape buf := make([]byte, blockSize) // stack-allocated; doesn't escape
bufp := 0 // starting read position in buf bufp := 0 // starting read position in buf
nbuf := 0 // end valid data in buf nbuf := 0 // end valid data in buf
skipFiles := false
for { for {
if bufp >= nbuf { if bufp >= nbuf {
bufp = 0 bufp = 0
@ -62,7 +62,14 @@ func readDir(dirName string, fn func(dirName, entName string, typ os.FileMode) e
} }
typ = fi.Mode() & os.ModeType typ = fi.Mode() & os.ModeType
} }
if skipFiles && typ.IsRegular() {
continue
}
if err := fn(dirName, name, typ); err != nil { if err := fn(dirName, name, typ); err != nil {
if err == SkipFiles {
skipFiles = true
continue
}
return err return err
} }
} }
@ -106,10 +113,7 @@ func parseDirEnt(buf []byte) (consumed int, name string, typ os.FileMode) {
} }
nameBuf := (*[unsafe.Sizeof(dirent.Name)]byte)(unsafe.Pointer(&dirent.Name[0])) nameBuf := (*[unsafe.Sizeof(dirent.Name)]byte)(unsafe.Pointer(&dirent.Name[0]))
nameLen := bytes.IndexByte(nameBuf[:], 0) nameLen := direntNamlen(dirent)
if nameLen < 0 {
panic("failed to find terminating 0 byte in dirent")
}
// Special cases for common things: // Special cases for common things:
if nameLen == 1 && nameBuf[0] == '.' { if nameLen == 1 && nameBuf[0] == '.' {

209
vendor/golang.org/x/tools/internal/gopathwalk/walk.go generated vendored Normal file
View File

@ -0,0 +1,209 @@
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package gopathwalk is like filepath.Walk but specialized for finding Go
// packages, particularly in $GOPATH and $GOROOT.
package gopathwalk
import (
"bufio"
"bytes"
"fmt"
"go/build"
"golang.org/x/tools/internal/fastwalk"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
)
// Options controls the behavior of a Walk call.
type Options struct {
Debug bool // Enable debug logging
ModulesEnabled bool // Search module caches. Also disables legacy goimports ignore rules.
}
// Walk walks Go source directories ($GOROOT, $GOPATH, etc) to find packages.
// For each package found, add will be called (concurrently) with the absolute
// paths of the containing source directory and the package directory.
func Walk(add func(srcDir string, dir string), opts Options) {
for _, srcDir := range build.Default.SrcDirs() {
walkDir(srcDir, add, opts)
}
}
func walkDir(srcDir string, add func(string, string), opts Options) {
if opts.Debug {
log.Printf("scanning %s", srcDir)
}
w := &walker{
srcDir: srcDir,
srcV: filepath.Join(srcDir, "v"),
srcMod: filepath.Join(srcDir, "mod"),
add: add,
opts: opts,
}
w.init()
if err := fastwalk.Walk(srcDir, w.walk); err != nil {
log.Printf("goimports: scanning directory %v: %v", srcDir, err)
}
if opts.Debug {
defer log.Printf("scanned %s", srcDir)
}
}
// walker is the callback for fastwalk.Walk.
type walker struct {
srcDir string // The source directory to scan.
srcV, srcMod string // vgo-style module cache dirs. Optional.
add func(string, string) // The callback that will be invoked for every possible Go package dir.
opts Options // Options passed to Walk by the user.
ignoredDirs []os.FileInfo // The ignored directories, loaded from .goimportsignore files.
}
// init initializes the walker based on its Options.
func (w *walker) init() {
if !w.opts.ModulesEnabled {
w.ignoredDirs = w.getIgnoredDirs(w.srcDir)
}
}
// getIgnoredDirs reads an optional config file at <path>/.goimportsignore
// of relative directories to ignore when scanning for go files.
// The provided path is one of the $GOPATH entries with "src" appended.
func (w *walker) getIgnoredDirs(path string) []os.FileInfo {
file := filepath.Join(path, ".goimportsignore")
slurp, err := ioutil.ReadFile(file)
if w.opts.Debug {
if err != nil {
log.Print(err)
} else {
log.Printf("Read %s", file)
}
}
if err != nil {
return nil
}
var ignoredDirs []os.FileInfo
bs := bufio.NewScanner(bytes.NewReader(slurp))
for bs.Scan() {
line := strings.TrimSpace(bs.Text())
if line == "" || strings.HasPrefix(line, "#") {
continue
}
full := filepath.Join(path, line)
if fi, err := os.Stat(full); err == nil {
ignoredDirs = append(ignoredDirs, fi)
if w.opts.Debug {
log.Printf("Directory added to ignore list: %s", full)
}
} else if w.opts.Debug {
log.Printf("Error statting entry in .goimportsignore: %v", err)
}
}
return ignoredDirs
}
func (w *walker) shouldSkipDir(fi os.FileInfo) bool {
for _, ignoredDir := range w.ignoredDirs {
if os.SameFile(fi, ignoredDir) {
return true
}
}
return false
}
func (w *walker) walk(path string, typ os.FileMode) error {
if !w.opts.ModulesEnabled && (path == w.srcV || path == w.srcMod) {
return filepath.SkipDir
}
dir := filepath.Dir(path)
if typ.IsRegular() {
if dir == w.srcDir {
// Doesn't make sense to have regular files
// directly in your $GOPATH/src or $GOROOT/src.
return fastwalk.SkipFiles
}
if !strings.HasSuffix(path, ".go") {
return nil
}
w.add(w.srcDir, dir)
return fastwalk.SkipFiles
}
if typ == os.ModeDir {
base := filepath.Base(path)
if base == "" || base[0] == '.' || base[0] == '_' ||
base == "testdata" || (!w.opts.ModulesEnabled && base == "node_modules") {
return filepath.SkipDir
}
fi, err := os.Lstat(path)
if err == nil && w.shouldSkipDir(fi) {
return filepath.SkipDir
}
return nil
}
if typ == os.ModeSymlink {
base := filepath.Base(path)
if strings.HasPrefix(base, ".#") {
// Emacs noise.
return nil
}
fi, err := os.Lstat(path)
if err != nil {
// Just ignore it.
return nil
}
if w.shouldTraverse(dir, fi) {
return fastwalk.TraverseLink
}
}
return nil
}
// shouldTraverse reports whether the symlink fi, found in dir,
// should be followed. It makes sure symlinks were never visited
// before to avoid symlink loops.
func (w *walker) shouldTraverse(dir string, fi os.FileInfo) bool {
path := filepath.Join(dir, fi.Name())
target, err := filepath.EvalSymlinks(path)
if err != nil {
return false
}
ts, err := os.Stat(target)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return false
}
if !ts.IsDir() {
return false
}
if w.shouldSkipDir(ts) {
return false
}
// Check for symlink loops by statting each directory component
// and seeing if any are the same file as ts.
for {
parent := filepath.Dir(path)
if parent == path {
// Made it to the root without seeing a cycle.
// Use this symlink.
return true
}
parentInfo, err := os.Stat(parent)
if err != nil {
return false
}
if os.SameFile(ts, parentInfo) {
// Cycle. Don't traverse.
return false
}
path = parent
}
}