forked from golang/vscode-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
262 lines (239 loc) · 5.47 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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
// Copyright 2024 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.
// The package vscgo is an implementation of
// github.com/golang/vscode-go/vscgo. This is in
// a separate internal package, so
// github.com/golang/vscode-go/extension can import.
package vscgo
import (
"bufio"
"flag"
"fmt"
"log"
"os"
"runtime/debug"
"strings"
"time"
"golang.org/x/telemetry/counter"
)
type command struct {
usage string
short string
flags *flag.FlagSet
hasArgs bool
run func(args []string) error
}
func (c command) name() string {
name, _, _ := strings.Cut(c.usage, " ")
return name
}
var allCommands []*command
func init() {
allCommands = []*command{
{
usage: "inc_counters",
short: "increment telemetry counters",
run: runIncCounters,
},
{
usage: "dump-pprof <profile>",
short: "convert a pprof profile to a JSON file",
hasArgs: true,
run: runPprofDump,
},
{
usage: "serve-pprof <addr> <profile>",
short: "serve a pprof profile",
hasArgs: true,
run: runPprofServe,
},
{
usage: "version",
short: "print version information",
run: runVersion,
},
{
usage: "help <command>",
short: "show help for a command",
hasArgs: true,
run: runHelp, // accesses allCommands.
},
}
for _, cmd := range allCommands {
name := cmd.name()
if cmd.flags == nil {
cmd.flags = flag.NewFlagSet(name, flag.ExitOnError)
}
cmd.flags.Usage = func() {
help(name)
}
}
}
func Main() {
counter.Open()
log.SetFlags(0)
flag.Usage = usage
flag.Parse()
args := flag.Args()
var cmd *command
if len(args) > 0 {
cmd = findCommand(args[0])
}
if cmd == nil {
flag.Usage()
os.Exit(2)
}
cmd.flags.Parse(args[1:]) // will exit on error
args = cmd.flags.Args()
if !cmd.hasArgs && len(args) > 0 {
help(cmd.name())
failf("\ncommand %q does not accept any arguments.\n", cmd.name())
}
if err := cmd.run(args); err != nil {
failf("%v\n", err)
}
}
func output(msgs ...interface{}) {
fmt.Fprintln(flag.CommandLine.Output(), msgs...)
}
func usage() {
printCommand := func(cmd *command) {
output(fmt.Sprintf("\t%s\t%s", cmd.name(), cmd.short))
}
output("vscgo is a helper tool for the VS Code Go extension, written in Go.")
output()
output("Usage:")
output()
output("\tvscgo <command> [arguments]")
output()
output("The commands are:")
output()
for _, cmd := range allCommands {
printCommand(cmd)
}
output()
output(`Use "vscgo help <command>" for details about any command.`)
output()
}
func failf(format string, args ...any) {
fmt.Fprintf(os.Stderr, format, args...)
os.Exit(1)
}
func findCommand(name string) *command {
for _, cmd := range allCommands {
if cmd.name() == name {
return cmd
}
}
return nil
}
func help(name string) {
cmd := findCommand(name)
if cmd == nil {
failf("unknown command %q\n", name)
}
output(fmt.Sprintf("Usage: vscgo %s", cmd.usage))
output()
output(fmt.Sprintf("%s is used to %s.", cmd.name(), cmd.short))
anyflags := false
cmd.flags.VisitAll(func(*flag.Flag) {
anyflags = true
})
if anyflags {
output()
output("Flags:")
output()
cmd.flags.PrintDefaults()
}
}
// runIncCounters increments telemetry counters read from stdin.
func runIncCounters(_ []string) error {
scanner := bufio.NewScanner(os.Stdin)
if counterFile := os.Getenv("TELEMETRY_COUNTER_FILE"); counterFile != "" {
return printCounter(counterFile, scanner)
}
return runIncCountersImpl(scanner, counter.Add)
}
func printCounter(fname string, scanner *bufio.Scanner) (rerr error) {
f, err := os.OpenFile(fname, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
if err != nil {
return err
}
defer func() {
if err := f.Close(); rerr == nil {
rerr = err
}
}()
return runIncCountersImpl(scanner, func(name string, count int64) {
fmt.Fprintln(f, name, count)
})
}
const (
incCountersBadInput = "inc_counters_bad_input"
)
func incCountersInputLength(n int) string {
const name = "inc_counters_num_input"
for i := 1; i < 8; i *= 2 {
if n < i {
return fmt.Sprintf("%s:<%d", name, i)
}
}
return name + ":>=8"
}
func incCountersDuration(duration time.Duration) string {
const name = "inc_counters_duration"
switch {
case duration < 10*time.Millisecond:
return name + ":<10ms"
case duration < 100*time.Millisecond:
return name + ":<100ms"
case duration < 1*time.Second:
return name + ":<1s"
case duration < 10*time.Second:
return name + ":<10s"
}
return name + ":>=10s"
}
func runIncCountersImpl(scanner *bufio.Scanner, incCounter func(name string, count int64)) error {
start := time.Now()
linenum := 0
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if line == "" {
continue
}
var name string
var count int64
if _, err := fmt.Sscanf(line, "%s %d", &name, &count); err != nil || count < 0 {
incCounter(incCountersBadInput, 1)
return fmt.Errorf("invalid line: %q", line)
}
linenum++
incCounter(name, int64(count))
}
incCounter(incCountersInputLength(linenum), 1)
incCounter(incCountersDuration(time.Since(start)), 1)
return nil
}
func runVersion(_ []string) error {
info, ok := debug.ReadBuildInfo()
if !ok {
fmt.Println("vscgo: unknown")
fmt.Println("go: unknown")
return nil
}
fmt.Println("vscgo:", info.Main.Version)
fmt.Println("go:", info.GoVersion)
return nil
}
func runHelp(args []string) error {
switch len(args) {
case 1:
help(args[0])
default:
flag.Usage()
failf("too many arguments to \"help\"")
}
return nil
}