-
Notifications
You must be signed in to change notification settings - Fork 49
/
goweight.go
84 lines (71 loc) · 1.78 KB
/
goweight.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
package pkg
import (
"io/ioutil"
"log"
"os"
"os/exec"
"regexp"
"sort"
"strings"
"github.com/dustin/go-humanize"
"github.com/mattn/go-zglob"
"github.com/thoas/go-funk"
)
var moduleRegex = regexp.MustCompile("packagefile (.*)=(.*)")
func run(cmd []string) string {
out, err := exec.Command(cmd[0], cmd[1:]...).CombinedOutput()
if err != nil {
log.Fatal(err)
}
os.Remove("goweight-bin-target")
return string(out)
}
func processModule(line string) *ModuleEntry {
captures := moduleRegex.FindAllStringSubmatch(line, -1)
if captures == nil {
return nil
}
path := captures[0][2]
stat, _ := os.Stat(path)
sz := uint64(stat.Size())
return &ModuleEntry{
Path: path,
Name: captures[0][1],
Size: sz,
SizeHuman: humanize.Bytes(sz),
}
}
type ModuleEntry struct {
Path string `json:"path"`
Name string `json:"name"`
Size uint64 `json:"size"`
SizeHuman string `json:"size_human"`
}
type GoWeight struct {
BuildCmd []string
}
func NewGoWeight() *GoWeight {
return &GoWeight{
BuildCmd: []string{"go", "build", "-o", "goweight-bin-target", "-work", "-a"},
}
}
func (g *GoWeight) BuildCurrent() string {
d := strings.Split(strings.TrimSpace(run(g.BuildCmd)), "\n")[0]
return strings.Split(strings.TrimSpace(d), "=")[1]
}
func (g *GoWeight) Process(work string) []*ModuleEntry {
files, err := zglob.Glob(work + "**/importcfg")
if err != nil {
log.Fatal(err)
}
allLines := funk.Uniq(funk.FlattenDeep(funk.Map(files, func(file string) []string {
f, err := ioutil.ReadFile(file)
if err != nil {
return []string{}
}
return strings.Split(string(f), "\n")
})))
modules := funk.Compact(funk.Map(allLines, processModule)).([]*ModuleEntry)
sort.Slice(modules, func(i, j int) bool { return modules[i].Size > modules[j].Size })
return modules
}