Debian Codegraph @

imports/scan.go

raw symbols SCIP
1 // Copyright 2018 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 package imports
6
7 import (
8 "fmt"
9 "os"
10 "path/filepath"
11 "sort"
12 "strconv"
13 "strings"
14 )
15
16 func ScanDir(dir string, tags map[string]bool) ([]string, []string, error) {
17 infos, err := os.ReadDir(dir)
18 if err != nil {
19 return nil, nil, err
20 }
21 var files []string
22 for _, info := range infos {
23 name := info.Name()
24 if info.Type().IsRegular() && !strings.HasPrefix(name, "_") && strings.HasSuffix(name, ".go") && MatchFile(name, tags) {
25 files = append(files, filepath.Join(dir, name))
26 }
27 }
28 return scanFiles(files, tags, false)
29 }
30
31 func ScanFiles(files []string, tags map[string]bool) ([]string, []string, error) {
32 return scanFiles(files, tags, true)
33 }
34
35 func scanFiles(files []string, tags map[string]bool, explicitFiles bool) ([]string, []string, error) {
36 imports := make(map[string]bool)
37 testImports := make(map[string]bool)
38 numFiles := 0
39 Files:
40 for _, name := range files {
41 r, err := os.Open(name)
42 if err != nil {
43 return nil, nil, err
44 }
45 var list []string
46 data, err := ReadImports(r, false, &list)
47 r.Close()
48 if err != nil {
49 return nil, nil, fmt.Errorf("reading %s: %v", name, err)
50 }
51
52 // import "C" is implicit requirement of cgo tag.
53 // When listing files on the command line (explicitFiles=true)
54 // we do not apply build tag filtering but we still do apply
55 // cgo filtering, so no explicitFiles check here.
56 // Why? Because we always have, and it's not worth breaking
57 // that behavior now.
58 for _, path := range list {
59 if path == `"C"` && !tags["cgo"] && !tags["*"] {
60 continue Files
61 }
62 }
63
64 if !explicitFiles && !ShouldBuild(data, tags) {
65 continue
66 }
67 numFiles++
68 m := imports
69 if strings.HasSuffix(name, "_test.go") {
70 m = testImports
71 }
72 for _, p := range list {
73 q, err := strconv.Unquote(p)
74 if err != nil {
75 continue
76 }
77 m[q] = true
78 }
79 }
80 if numFiles == 0 {
81 return nil, nil, ErrNoGo
82 }
83 return keys(imports), keys(testImports), nil
84 }
85
86 var ErrNoGo = fmt.Errorf("no Go source files")
87
88 // TODO: replace with maps.Keys from go1.23
89 func keys(m map[string]bool) []string {
90 var list []string
91 for k := range m {
92 list = append(list, k)
93 }
94 sort.Strings(list)
95 return list
96 }