-
Notifications
You must be signed in to change notification settings - Fork 4
/
packages.go
280 lines (261 loc) · 7.25 KB
/
packages.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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
package pkg
import (
"encoding/json"
"errors"
"fmt"
"go/ast"
"go/parser"
"go/token"
"io/ioutil"
"log"
"math"
"os"
"path/filepath"
"sync"
"github.com/fatih/color"
"github.com/olekukonko/tablewriter"
)
// Package is a single package as determined by go list.
type Package struct {
Name string
FullName string
Imports []string
ImportCount float64
DependedOnByCount float64
DependedOnByNames []string
Stability float64
Abstractness float64
DistanceFromMedian float64
Dir string
GoFiles []string
}
// MarshalJSON returns a JSON encoding of Package
func (p Package) MarshalJSON() ([]byte, error) {
j := struct {
Name string
FullName string
Imports []string
ImportCount float64
DependedOnByCount float64
DependedOnByNames []string
Stability *float64 `json:",omitempty"`
Abstractness float64
DistanceFromMedian *float64 `json:",omitempty"`
Dir string
GoFiles []string
}{
Name: p.Name,
FullName: p.FullName,
Imports: p.Imports,
ImportCount: p.ImportCount,
DependedOnByCount: p.DependedOnByCount,
DependedOnByNames: p.DependedOnByNames,
Abstractness: p.Abstractness,
Dir: p.Dir,
GoFiles: p.GoFiles,
}
if !math.IsNaN(p.Stability) {
j.Stability = &p.Stability
}
if !math.IsNaN(p.DistanceFromMedian) {
j.DistanceFromMedian = &p.DistanceFromMedian
}
return json.Marshal(j)
}
// Packages represents a collection of packages.
type Packages struct {
packageMap map[string]Package
packageNames []string
semaphore int
}
// NewPackages returns a new initialized package collection.
func NewPackages(parallel int) *Packages {
return &Packages{
packageMap: make(map[string]Package),
packageNames: make([]string, 0),
semaphore: parallel,
}
}
// GatherDependedOnByCount looks for packages which import other packages in the project.
func (pkg *Packages) GatherDependedOnByCount() {
for _, v := range pkg.packageMap {
imports := v.Imports
for _, i := range imports {
if p, ok := pkg.packageMap[i]; ok {
p.DependedOnByCount++
if len(p.DependedOnByNames) < 1 {
p.DependedOnByNames = make([]string, 0)
}
p.DependedOnByNames = append(p.DependedOnByNames, v.FullName)
pkg.packageMap[p.FullName] = p
}
}
}
}
// CalculateInstability will calculate the instability metric for all packages.
func (pkg *Packages) CalculateInstability() {
for k, v := range pkg.packageMap {
v.Stability = v.ImportCount / (v.ImportCount + v.DependedOnByCount)
pkg.packageMap[k] = v
}
}
// CalculateDistance will calculate the distance from the main sequence for all packages.
// 0: As far away from the main sequence as possible
// 1: Close as possible
// 0,0: Zone of Pain
// 1,1: Zone of Uselessness
func (pkg *Packages) CalculateDistance() {
for k, v := range pkg.packageMap {
v.DistanceFromMedian = abs(v.Stability + v.Abstractness - 1)
pkg.packageMap[k] = v
}
}
func abs(a float64) float64 {
if a < 0 {
return -a
}
return a
}
// CalculateAbstractnessOfPackages will walk all the files in the package
// and analyses abstractness.
func (pkg *Packages) CalculateAbstractnessOfPackages() error {
for k, p := range pkg.packageMap {
var wg sync.WaitGroup
funcCount := 0.0
abstractsCount := 0.0
// fmt.Printf("Scanning %s go file(s) in package %s.\n", keyName.Sprint(len(p.GoFiles)), keyName.Sprint(p.FullName))
sem := make(chan int, pkg.semaphore)
errChan := make(chan error, len(p.GoFiles))
funcChan := make(chan float64, len(p.GoFiles))
absChan := make(chan float64, len(p.GoFiles))
wg.Add(len(p.GoFiles))
for _, f := range p.GoFiles {
go parseGoFile(f, p.Dir, funcChan, absChan, sem, errChan, &wg)
} // go files in packages
wg.Wait()
// Need to close the channels here to be able to for on them.
close(funcChan)
close(absChan)
close(errChan)
errorList := make([]error, 0)
for e := range errChan {
errorList = append(errorList, e)
}
if len(errorList) > 0 {
fmt.Printf("%d error(s) processing pkg %s\n", len(errorList), p.FullName)
fmt.Println("listing error(s):")
for _, e := range errorList {
fmt.Println(e)
}
fmt.Println("Please fix these before continuing.")
return errors.New("unable to process all files")
}
for a := range absChan {
abstractsCount += a
}
for a := range funcChan {
funcCount += a
}
if funcCount == 0 {
funcCount = 1
}
p.Abstractness = abstractsCount / (funcCount + abstractsCount)
pkg.packageMap[k] = p
} // packages
return nil
}
func parseGoFile(fh, dir string,
funcChan, absChan chan float64,
sem chan int,
errChan chan error,
wg *sync.WaitGroup) {
defer wg.Done()
sem <- 1
defer func() { <-sem }()
funcCount := 0.0
abstractsCount := 0.0
fset := token.NewFileSet()
if len(fh) < 1 {
fmt.Println("skipping folder... file is empty:", dir)
return
}
/* #nosec */
data, err := ioutil.ReadFile(filepath.Join(dir, fh))
if err != nil {
errChan <- err
return
}
node, err := parser.ParseFile(fset, fh, data, 0)
if err != nil {
errChan <- err
return
}
ast.Inspect(node, func(n ast.Node) bool {
switch n.(type) {
case *ast.FuncDecl:
funcCount++
case *ast.InterfaceType:
abstractsCount++
case *ast.StructType:
// This right now calculates structs towards abstractness.
// I have no easy way to find receivers for structs yet
// so I'm counting all structs towards interfaces. If there are
// implementations in these packages they would even out this count.
abstractsCount++
}
return true
})
funcChan <- funcCount
absChan <- abstractsCount
}
var keyName = color.New(color.FgWhite, color.Bold)
var yellow = color.New(color.FgYellow)
var red = color.New(color.FgRed)
var green = color.New(color.FgGreen, color.Bold)
// Display displays the analysed information in a pretty way...
// TODO: Add multiple display options and Graph generation.
func (pkg *Packages) Display(colorMode bool) {
table := tablewriter.NewWriter(os.Stdout)
table.SetHeader([]string{"NAME", "STABILITY", "ABSTRACTNESS", "DISTANCE"})
for _, pname := range pkg.packageNames {
p := pkg.packageMap[pname]
c := &color.Color{}
if p.Stability < 0.5 {
c = green
} else if p.Stability >= 0.5 && p.Stability < 1 {
c = yellow
} else if p.Stability == 1 {
c = red
}
stability := fmt.Sprintf("%.1f", p.Stability)
abstractness := fmt.Sprintf("%.1f", p.Abstractness)
distance := fmt.Sprintf("%.1f", p.DistanceFromMedian)
row := []string{p.FullName, stability, abstractness, distance}
if colorMode {
row = []string{p.FullName, c.Sprint(stability), keyName.Sprint(abstractness), keyName.Sprint(distance)}
}
table.Append(row)
}
table.Render()
}
// Dump dumps the connections between packages in a JSON format
// for other tools to process.
func (pkg *Packages) Dump() {
pkgs := make([]Package, 0)
for _, p := range pkg.packageMap {
pkgs = append(pkgs, p)
}
var packages = struct {
Packages []Package `json:"packages"`
}{
Packages: pkgs,
}
data, err := json.Marshal(packages)
if err != nil {
log.Fatal("error marshaling to json: ", err)
}
err = ioutil.WriteFile(".effrit_package_data.json", data, 0666)
if err != nil {
log.Fatal("error while writing json file: ", err)
}
}