-
Notifications
You must be signed in to change notification settings - Fork 4
/
cmd_fnsize.go
93 lines (77 loc) · 1.89 KB
/
cmd_fnsize.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
package main
import (
"context"
"flag"
"fmt"
"os/exec"
"regexp"
)
type funcSizeRunner struct {
flagMod string
asJSON bool
messageRE *regexp.Regexp
filterRE *regexp.Regexp
}
func (r *funcSizeRunner) ExecCommand(_ context.Context, args []string) error {
fset := flag.NewFlagSet("funcSize", flag.ContinueOnError)
fset.StringVar(&r.flagMod, "mod", "", `-mod compiler flag(readonly|vendor)`)
fset.BoolVar(&r.asJSON, "json", false, `return result as JSON`)
filter := fset.String("filter", "", "regex to filter the results")
if err := fset.Parse(args); err != nil {
return err
}
args = fset.Args()
if len(args) == 0 {
args = []string{"."}
}
r.messageRE = regexp.MustCompile(`(.*) STEXT.* size=(\d+)`)
if *filter != "" {
r.filterRE = regexp.MustCompile(*filter)
}
for _, pkg := range args {
if err := r.process(pkg); err != nil {
fmt.Printf("%s: %v", pkg, err)
}
}
return nil
}
func (r *funcSizeRunner) process(pkg string) error {
cmd := exec.Command("go", r.getCmdArgs(pkg)...)
out, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("%v: %s", err, out)
}
type resultRow struct {
Fn string `json:"fn"`
Size string `json:"size"`
}
results := []resultRow{}
for _, submatches := range r.messageRE.FindAllStringSubmatch(string(out), -1) {
fn, size := submatches[1], submatches[2]
if r.passesFilter(fn) {
results = append(results, resultRow{
Fn: fn,
Size: size,
})
}
}
if r.asJSON {
marshalJSON(results)
return nil
}
for _, r := range results {
fmt.Printf("%s: %s bytes\n", r.Fn, r.Size)
}
return nil
}
func (r *funcSizeRunner) passesFilter(fn string) bool {
return r.filterRE == nil || r.filterRE.MatchString(fn)
}
func (r *funcSizeRunner) getCmdArgs(pkg string) []string {
args := []string{"build", "-gcflags", "-S"}
if r.flagMod != "" {
args = append(args, "-mod", r.flagMod)
}
args = append(args, pkg)
return args
}