-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
349 lines (292 loc) · 8.06 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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
package main
import (
"encoding/csv"
"encoding/json"
"flag"
"fmt"
"os"
"os/exec"
"sort"
"strconv"
"strings"
"github.com/olekukonko/tablewriter"
)
const (
_additions = "Additions"
_deletions = "Deletions"
_commits = "Commits"
_files = "Files"
_outputTypeTable = "table"
_outputTypeJSON = "json"
_outputTypeCSV = "csv"
_sortByCommits = "commits"
_sortByAdditions = "additions"
_sortByDeletions = "deletions"
_sortByFiles = "files"
_outputUsage = "output type: " + _outputTypeTable + "/" + _outputTypeCSV + "/" + _outputTypeJSON + "(default is " + _outputTypeTable + ")"
_mergeNameUsage = "merge contributor stats with same email username"
)
var (
_sortByUsage = `sort by: ` + strings.Join([]string{_sortByCommits, _sortByAdditions, _sortByDeletions, _sortByDeletions}, ",") + `
accepts multiple values separated by commas, sort is stable
sort is applied in the given order left to right`
_headers = []string{"Contributor", "Commits", "Additions", "Deletions", "Files"}
)
// Stats represents git activity stats of a contributor.
type Stats struct {
NameEmail string
FileNames map[string]struct{}
Counts map[string]string
}
func main() {
var outputType string
flag.StringVar(&outputType, "output", _outputTypeTable, _outputUsage)
flag.StringVar(&outputType, "o", _outputTypeTable, _outputUsage)
mergeNameFlag := flag.Bool("merge-name", false, _mergeNameUsage)
var sortBy string
flag.StringVar(&sortBy, "sort-by", "commits", _sortByUsage)
flag.StringVar(&sortBy, "s", "commits", _sortByUsage)
flag.Usage = func() {
fmt.Printf("Print the stats of all contributors of a git repository.\n")
fmt.Printf("The command must be run in a git repository.\n\n")
fmt.Printf("Usage:\n\n\t%v\n\n", "gitstats [options]")
fmt.Println(`The options are:
-output, -o
` + _outputUsage + `
-sort-by, -s
` + _sortByUsage + `
The flags are:
-merge-name
` + _mergeNameUsage)
}
flag.Parse()
if isGitRepo() == false {
fmt.Println("gitstats must be run in a git repository. Type gitstats -h for help.")
return
}
stats := findCommits()
stats = findContributorStats(stats)
if *mergeNameFlag {
stats = mergeNames(stats)
}
stats = sortStats(sortBy, stats)
switch outputType {
case _outputTypeTable:
printTable(_headers, stats)
case _outputTypeCSV:
printCSV(_headers, stats)
case _outputTypeJSON:
printJSON(_headers, stats)
default:
printTable(_headers, stats)
}
}
func isGitRepo() bool {
args := []string{"status"}
cmd := exec.Command("git", args...)
_, err := cmd.CombinedOutput()
if err != nil {
return false
}
return true
}
func printCSV(headers []string, stats []Stats) {
w := csv.NewWriter(os.Stdout)
w.Write(headers)
for _, v := range stats {
w.Write([]string{v.NameEmail, v.Counts[_commits], v.Counts[_additions], v.Counts[_deletions], v.Counts[_files]})
}
w.Flush()
}
func printJSON(headers []string, stats []Stats) {
b, _ := json.Marshal(stats)
fmt.Println(string(b))
}
func printTable(headers []string, stats []Stats) {
table := tablewriter.NewWriter(os.Stdout)
table.SetHeader(headers)
table.SetRowLine(true)
table.SetRowSeparator("-")
table.SetColumnSeparator("|")
rows := make([][]string, 0)
for _, v := range stats {
row := make([]string, 0)
row = append(row, v.NameEmail, v.Counts[_commits], v.Counts[_additions], v.Counts[_deletions], v.Counts[_files])
rows = append(rows, row)
}
table.AppendBulk(rows)
table.Render()
}
func findCommits() []Stats {
args := []string{"--no-pager", "shortlog", "-sne", "--all"}
cmd := exec.Command("git", args...)
out, err := cmd.CombinedOutput()
if err != nil {
fmt.Println("unable to get commit details: git", args, ":", err)
return nil
}
stats := make([]Stats, 0)
lines := strings.Split(string(out), "\n")
// line format: <number of commits> <Name email>
// e.g.: 20 Peter Quill <[email protected]>
for _, line := range lines {
x := Stats{FileNames: make(map[string]struct{}, 0), Counts: make(map[string]string)}
line = strings.TrimSpace(line)
if line == "" {
break
}
// number of commits
i := 0
for {
if !(line[i] >= '0' && line[i] <= '9') {
break
}
x.Counts[_commits] += string(line[i])
i++
}
// name email
x.NameEmail = strings.TrimSpace(line[i:])
stats = append(stats, x)
}
return stats
}
func findContributorStats(stats []Stats) []Stats {
argTmpl := "git --no-pager log --author=\"AUTHOR\" --format=tformat: --numstat --all"
for i := 0; i < len(stats); i++ {
arg := strings.Replace(argTmpl, "AUTHOR", stats[i].NameEmail, 1)
cmd := exec.Command("sh", "-c", arg)
out, err := cmd.Output()
if err != nil {
fmt.Println("unable to get contributor stats: git", cmd.Args, ":", err)
return nil
}
lines := strings.Split(strings.TrimSpace(string(out)), "\n")
// record fileNames to count unique file names
fileNames := make(map[string]struct{})
additions, deletions := 0, 0
// line format: <additions> <deletions> <filename>
// e.g.: 18 3 README.md
// sum up for all files
for _, line := range lines {
line = strings.TrimSpace(line)
if line == "" {
continue
}
// addition
j, s := 0, ""
for {
if !(line[j] >= '0' && line[j] <= '9') {
break
}
s += string(line[j])
j++
}
line = strings.TrimSpace(line[j:])
n, _ := strconv.Atoi(s)
additions += n
// deletion
j, s = 0, ""
for {
if !(line[j] >= '0' && line[j] <= '9') {
break
}
s += string(line[j])
j++
}
line = strings.TrimSpace(line[j:])
n, _ = strconv.Atoi(s)
deletions += n
// filename
fileNames[line] = struct{}{}
}
stats[i].FileNames = fileNames
stats[i].Counts[_additions] = strconv.Itoa(additions)
stats[i].Counts[_deletions] = strconv.Itoa(deletions)
stats[i].Counts[_files] = strconv.Itoa(len(fileNames))
}
return stats
}
func mergeNames(stats []Stats) []Stats {
m := make(map[string][]Stats)
for _, v := range stats {
userName := findUserName(v.NameEmail)
if _, ok := m[userName]; !ok {
m[userName] = make([]Stats, 0)
}
m[userName] = append(m[userName], v)
}
mergedStats := make([]Stats, 0)
for _, v := range m {
x := Stats{FileNames: make(map[string]struct{}), Counts: make(map[string]string)}
// commits, additions, deletions
c, a, d := 0, 0, 0
// filenames
fm := make(map[string]struct{})
nameEmails := make([]string, 0)
for _, w := range v {
i, _ := strconv.Atoi(w.Counts[_commits])
c += i
i, _ = strconv.Atoi(w.Counts[_additions])
a += i
i, _ = strconv.Atoi(w.Counts[_deletions])
d += i
for name := range w.FileNames {
fm[name] = struct{}{}
}
nameEmails = append(nameEmails, w.NameEmail)
}
x.NameEmail = strings.Join(nameEmails, "; ")
x.Counts[_commits] = strconv.Itoa(c)
x.Counts[_additions] = strconv.Itoa(a)
x.Counts[_deletions] = strconv.Itoa(d)
x.Counts[_files] = strconv.Itoa(len(fm))
mergedStats = append(mergedStats, x)
}
return mergedStats
}
func findUserName(nameEmail string) string {
parts := strings.Split(strings.TrimSpace(nameEmail), "<")
parts = strings.Split(strings.TrimSpace(parts[1]), "@")
return strings.ToLower(strings.TrimSpace(parts[0]))
}
func sortStats(sortBy string, stats []Stats) []Stats {
sortFields := strings.Split(sortBy, ",")
// last one wins
for _, v := range sortFields {
switch v {
case _sortByCommits:
sort.SliceStable(stats,
func(i, j int) bool {
a, _ := strconv.Atoi(stats[i].Counts[_commits])
b, _ := strconv.Atoi(stats[j].Counts[_commits])
return a > b
},
)
case _sortByAdditions:
sort.SliceStable(stats,
func(i, j int) bool {
a, _ := strconv.Atoi(stats[i].Counts[_additions])
b, _ := strconv.Atoi(stats[j].Counts[_additions])
return a > b
},
)
case _sortByDeletions:
sort.SliceStable(stats,
func(i, j int) bool {
a, _ := strconv.Atoi(stats[i].Counts[_deletions])
b, _ := strconv.Atoi(stats[j].Counts[_deletions])
return a > b
},
)
case _sortByFiles:
sort.SliceStable(stats,
func(i, j int) bool {
a, _ := strconv.Atoi(stats[i].Counts[_files])
b, _ := strconv.Atoi(stats[j].Counts[_files])
return a > b
},
)
}
}
return stats
}