github.com/onsi/ginkgo@v1.16.6-0.20211118180735-4e1925ba4c95/ginkgo/outline/import.go (about) 1 // Copyright 2013 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // Most of the required functions were available in the 6 // "golang.org/x/tools/go/ast/astutil" package, but not exported. 7 // They were copied from https://github.com/golang/tools/blob/2b0845dc783e36ae26d683f4915a5840ef01ab0f/go/ast/astutil/imports.go 8 9 package outline 10 11 import ( 12 "go/ast" 13 "strconv" 14 "strings" 15 ) 16 17 // packageNameForImport returns the package name for the package. If the package 18 // is not imported, it returns nil. "Package name" refers to `pkgname` in the 19 // call expression `pkgname.ExportedIdentifier`. Examples: 20 // (import path not found) -> nil 21 // "import example.com/pkg/foo" -> "foo" 22 // "import fooalias example.com/pkg/foo" -> "fooalias" 23 // "import . example.com/pkg/foo" -> "" 24 func packageNameForImport(f *ast.File, path string) *string { 25 spec := importSpec(f, path) 26 if spec == nil { 27 return nil 28 } 29 name := spec.Name.String() 30 if name == "<nil>" { 31 // If the package name is not explicitly specified, 32 // make an educated guess. This is not guaranteed to be correct. 33 lastSlash := strings.LastIndex(path, "/") 34 if lastSlash == -1 { 35 name = path 36 } else { 37 name = path[lastSlash+1:] 38 } 39 } 40 if name == "." { 41 name = "" 42 } 43 return &name 44 } 45 46 // importSpec returns the import spec if f imports path, 47 // or nil otherwise. 48 func importSpec(f *ast.File, path string) *ast.ImportSpec { 49 for _, s := range f.Imports { 50 if importPath(s) == path { 51 return s 52 } 53 } 54 return nil 55 } 56 57 // importPath returns the unquoted import path of s, 58 // or "" if the path is not properly quoted. 59 func importPath(s *ast.ImportSpec) string { 60 t, err := strconv.Unquote(s.Path.Value) 61 if err != nil { 62 return "" 63 } 64 return t 65 }