/
list.go
51 lines (43 loc) · 1 KB
/
list.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package list
import (
"encoding/json"
"fmt"
"io"
"os/exec"
"path"
)
type listEntry struct {
Dir string `json:"Dir"`
GoFiles []string `json:"GoFiles"`
}
func AllGoFiles() ([]string, error) {
golist := exec.Command("go", "list", "-json", "./...")
stdoutPipe, err := golist.StdoutPipe()
if err != nil {
return nil, fmt.Errorf("failed to setup output pipe: %w", err)
}
defer stdoutPipe.Close()
err = golist.Start()
if err != nil {
return nil, fmt.Errorf("failed start go list: %w", err)
}
allFiles := make([]string, 0, 50)
decoder := json.NewDecoder(stdoutPipe)
for {
var entry listEntry
if err := decoder.Decode(&entry); err != nil {
if err == io.EOF {
return allFiles, nil
}
return nil, fmt.Errorf("failed to decode entry: %w", err)
}
if len(entry.GoFiles) == 0 {
continue
}
files := make([]string, 0, len(entry.GoFiles))
for _, file := range entry.GoFiles {
files = append(files, path.Join(entry.Dir, file))
}
allFiles = append(allFiles, files...)
}
}