-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmain.go
233 lines (205 loc) · 5.54 KB
/
main.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
package main
import (
"bufio"
"bytes"
"flag"
"fmt"
"go/build"
"io"
"io/ioutil"
"log"
"os"
"os/exec"
"path"
"path/filepath"
"runtime"
"sort"
"strconv"
"strings"
)
func usage() {
fmt.Fprintln(os.Stderr, "Usage: binstale [command names]")
flag.PrintDefaults()
}
func main() {
flag.Usage = usage
flag.Parse()
// Populate filter, a set of binaries that user wants use.
// Also keep track which filters have been matched (to print warnings at the end if not matched).
filter := make(filter)
if args := flag.Args(); len(args) != 0 {
for _, arg := range args {
filter[arg] = notMatched
}
}
// Find all commands and determine if they're stale or up to date.
commands, err := commands(filter)
if err != nil {
log.Fatalln(err)
}
// Find binaries in GOPATH/bin directories.
commandNames, err := binaries(filter)
if err != nil {
log.Fatalln(err)
}
// Print output.
for commandName, matched := range filter {
binary := binaryName(commandName)
if matched {
continue
}
fmt.Fprintf(os.Stderr, "cannot find binary %q in any of:\n", binary)
workspaces := filepath.SplitList(build.Default.GOPATH)
for i, workspace := range workspaces {
path := filepath.Join(workspace, "bin", binary)
switch i {
case 0:
fmt.Fprintf(os.Stderr, "\t%s (from $GOPATH)\n", path)
default:
fmt.Fprintf(os.Stderr, "\t%s\n", path)
}
}
if len(workspaces) == 0 {
fmt.Fprintln(os.Stderr, "\t($GOPATH not set)")
}
}
sort.Strings(commandNames)
for _, commandName := range commandNames {
fmt.Println(commandName)
for _, importPathStatus := range commands[commandName] {
fmt.Printf("\t%s\n", importPathStatus)
}
if len(commands[commandName]) == 0 {
fmt.Printf("\t(no source package found)\n")
}
}
// If any of the filters weren't matched, exit with code 1.
for _, matched := range filter {
if matched {
continue
}
os.Exit(1)
}
}
type importPathStatus struct {
importPath string
stale bool
reason string
}
func (ips importPathStatus) String() string {
switch ips.stale {
case false:
return "up to date: " + ips.importPath
case true:
return "stale: " + ips.importPath + " (" + ips.reason + ")"
}
panic("unreachable")
}
// commands finds all commands matching filter in all GOPATH workspaces (not GOROOT),
// determines if they're stale or up to date, and returns the results.
func commands(filter filter) (map[string][]importPathStatus, error) {
var commands = make(map[string][]importPathStatus) // Command name -> list of import paths with statuses.
args := []string{"go", "list", "-e", "-f", `{{if (and (not .Error) (not .Goroot) (eq .Name "main"))}}{{.ImportPath}} {{.Stale}} {{.StaleReason}}{{end}}`}
switch {
case len(filter) == 0:
// Look for all packages.
args = append(args, "all")
default:
// Look for packages with matching suffixes only.
// For a small number of filters (typical), this is faster than all packages.
for commandName := range filter {
args = append(args, "..."+commandName)
}
}
out, err := exec.Command(args[0], args[1:]...).Output()
if err != nil {
return nil, fmt.Errorf("failed to run go list: %v", err)
}
br := bufio.NewReader(bytes.NewReader(out))
for {
line, err := br.ReadString('\n')
if err == io.EOF {
break
} else if err != nil {
return nil, err
}
line = line[:len(line)-1] // Trim trailing newline.
importPathStaleReason := strings.Split(line, "\t")
importPath := importPathStaleReason[0]
stale, err := strconv.ParseBool(importPathStaleReason[1])
if err != nil {
return nil, err
}
reason := importPathStaleReason[2]
commandName := path.Base(importPath)
commands[commandName] = append(commands[commandName],
importPathStatus{
importPath: importPath,
stale: stale,
reason: reason,
},
)
}
return commands, nil
}
// filter is a set of binaries that user wants use.
// It keeps track which filters have been matched.
type filter map[string]matched
// matched represents whether a filter has been matched.
type matched bool
const (
notMatched matched = false
didMatch matched = true
)
// binaries finds binaries in GOPATH/bin directories, filtering results with filter if it's not empty,
// and returns the command names corresponding to those binaries.
func binaries(filter filter) (commandNames []string, err error) {
workspaces := filepath.SplitList(build.Default.GOPATH)
for _, workspace := range workspaces {
gobin := filepath.Join(workspace, "bin")
fis, err := ioutil.ReadDir(gobin)
if os.IsNotExist(err) {
continue
} else if err != nil {
return nil, err
}
for _, fi := range fis {
commandName, ok := commandName(fi)
if !ok {
continue
}
// If user specified a list of command names, filter out command names that don't match.
if len(filter) != 0 {
if _, ok := filter[commandName]; !ok {
continue
}
filter[commandName] = didMatch
}
commandNames = append(commandNames, commandName)
}
}
return commandNames, nil
}
// commandName returns the name of Go command that would've resulted in this binary file, if possible.
func commandName(fi os.FileInfo) (commandName string, ok bool) {
if fi.IsDir() {
return "", false
}
if strings.HasPrefix(fi.Name(), ".") {
return "", false
}
if runtime.GOOS == "windows" {
if !strings.HasSuffix(fi.Name(), ".exe") {
return "", false
}
return fi.Name()[:len(fi.Name())-4], true
}
return fi.Name(), true
}
// binaryName returns the name of binary for the given command name.
func binaryName(commandName string) string {
if runtime.GOOS == "windows" {
return commandName + ".exe"
}
return commandName
}