-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
282 lines (244 loc) · 6.57 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
package main
import (
"bufio"
"bytes"
"encoding/json"
"flag"
"fmt"
"io"
"log/slog"
"os"
"path/filepath"
"runtime/debug"
"slices"
"time"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/plumbing"
"github.com/go-git/go-git/v5/plumbing/object"
"github.com/pkg/browser"
)
type LHcommit struct {
ShortHash string `json:"hash"`
Author string `json:"author"`
Date time.Time `json:"date"`
Email string `json:"email"`
Net int `json:"net"`
runningTotal int
}
var (
repoPath = "." // pwd is default
)
func getLogger(logLevel string) *slog.Logger {
levelVar := slog.LevelVar{}
if logLevel != "" {
if err := levelVar.UnmarshalText([]byte(logLevel)); err != nil {
panic(fmt.Sprintf("Invalid log level %s: %v", logLevel, err))
}
}
return slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{
Level: levelVar.Level(),
}))
}
func main() {
slog.SetDefault(getLogger(os.Getenv("LOGLEVEL")))
var chartPath string
var startHash string
var chartName string
var autoOpenChart bool
buildInfo, ok := debug.ReadBuildInfo()
if !ok {
slog.Error("debug.ReadBuildInfo() failed")
return
}
version := buildInfo.Main.Version
slog.Info("lesshero", "version", version)
flag.StringVar(&chartPath, "o", "lesshero.html", "path to html chart output")
flag.StringVar(&startHash, "s", "", "start hash else will start from HEAD and go backwards in time")
flag.StringVar(&chartName, "n", "", "chart title, useful when using jsonl, default is repo remote")
flag.BoolVar(&autoOpenChart, "b", false, "auto open chart in default browser")
flag.Usage = func() {
fmt.Fprintf(flag.CommandLine.Output(), "Usage of %s:\n", os.Args[0])
fmt.Fprintf(flag.CommandLine.Output(), " %s [options] [git repo path]\n", os.Args[0])
flag.PrintDefaults()
fmt.Fprintf(flag.CommandLine.Output(), "\nhttps://github.com/kaihendry/lesshero/releases/tag/%s\n", version)
}
flag.Parse()
if flag.Arg(0) != "" {
repoPath = flag.Arg(0)
}
if filepath.Ext(repoPath) == ".jsonl" {
slog.Info("reading from jsonl", "file", repoPath)
f, err := os.Open(repoPath)
if err != nil {
slog.Error("opening jsonl file", "error", err)
return
}
err = visualise(f, chartPath, chartName, autoOpenChart)
if err != nil {
slog.Error("visualising jsonl argument", "error", err)
}
return
}
slog.Info("analyzing", "repo", repoPath, "count", fmt.Sprintf("git -C %s rev-list --all --count", repoPath), "chartPath", chartPath)
r, err := git.PlainOpen(repoPath)
if err != nil {
panic(err)
}
// show the current branch
ref, err := r.Head()
if err != nil {
panic(err)
}
slog.Info("default branch", "branch", ref.Name().String())
startCommit, err := r.CommitObject(ref.Hash())
if err != nil {
panic(err)
}
if startHash != "" {
rev := plumbing.Revision(startHash)
hash, err := r.ResolveRevision(rev)
if err != nil {
panic(err)
}
startCommit, err = r.CommitObject(*hash)
if err != nil {
panic(err)
}
}
slog.Info("start commit", "hash", startCommit.Hash.String(), "startHash", startHash)
buf := &bytes.Buffer{}
err = getCommits(r, startCommit, buf)
if err != nil {
panic(err)
}
err = visualise(buf, chartPath, getOrigin(r), autoOpenChart)
if err != nil {
slog.Error("visualising", "error", err)
}
}
func getOrigin(r *git.Repository) (gitSrc string) {
remotes, err := r.Remotes()
if err != nil {
slog.Error("getting remotes", "error", err)
return ""
}
for _, remote := range remotes {
r := remote.Config()
if r.Name == "origin" {
gitSrc = r.URLs[0]
}
}
return gitSrc
}
func visualise(r io.Reader, chartPath string, chartName string, autoOpenChart bool) error {
commits, err := parseLHjson(r)
if err != nil {
slog.Error("parsing JSON", "error", err)
return err
}
for i := 0; i < len(commits); i++ {
slog.Debug("commit", "hash", commits[i].ShortHash, "net", commits[i].Net, "date", commits[i].Date, "running total", commits[i].runningTotal)
}
if chartPath != "" {
err := chartHero(commits, chartName, chartPath)
if err != nil {
slog.Error("creating chart", "error", err)
}
}
if autoOpenChart {
err = browser.OpenFile(chartPath)
if err != nil {
slog.Error("charthero open", "err", err)
return err
}
}
return nil
}
func parseLHjson(r io.Reader) ([]LHcommit, error) {
input, err := io.ReadAll(r)
if err != nil {
return nil, err
}
lineCount := countLines(bytes.NewReader(input))
commits := make([]LHcommit, 0, lineCount)
slog.Debug("line count", "count", lineCount, "commits before appending", len(commits))
scanner := bufio.NewScanner(bytes.NewReader(input))
for scanner.Scan() {
line := scanner.Text()
commit := LHcommit{}
err := json.Unmarshal([]byte(line), &commit)
if err != nil {
slog.Error("unmarshalling JSON", "line", line, "error", err)
continue
}
commits = append(commits, commit)
}
total := 0
for _, commit := range commits {
slog.Debug("adding", "commit", commit.ShortHash, "net", commit.Net, "date", commit.Date)
total += commit.Net
}
slog.Info("summary", "count", total, "commits", len(commits))
slices.Reverse(commits)
for i := 0; i < len(commits); i++ {
slog.Debug("commit", "hash", commits[i].ShortHash, "net", commits[i].Net, "date", commits[i].Date)
commits[i].runningTotal = commits[i].Net
if i > 0 {
commits[i].runningTotal += commits[i-1].runningTotal
}
}
return commits, nil
}
func countLines(r io.Reader) int {
scanner := bufio.NewScanner(r)
lineCount := 0
for scanner.Scan() {
lineCount++
}
if err := scanner.Err(); err != nil {
fmt.Fprintf(os.Stderr, "Error counting lines: %v\n", err)
}
return lineCount
}
func getCommits(r *git.Repository, commit *object.Commit, w io.Writer) (err error) {
// follow the commit history via .Parent until the first commit https://github.com/go-git/go-git/issues/465#issuecomment-2121988320
err = printJSON(commit, w)
if err != nil {
return err
}
for {
if commit.NumParents() == 0 {
slog.Warn("no more parents", "hash", commit.Hash.String())
break
}
commit, err = commit.Parents().Next()
if err != nil {
return err
}
err = printJSON(commit, w)
if err != nil {
return err
}
}
return nil
}
func printJSON(c *object.Commit, w io.Writer) error {
lh := &LHcommit{
ShortHash: c.Hash.String()[:7],
Author: c.Author.Name,
Date: c.Author.When,
Email: c.Author.Email,
Net: getFstats(c),
}
return json.NewEncoder(io.MultiWriter(os.Stdout, w)).Encode(lh)
}
func getFstats(c *object.Commit) (total int) {
fStats, err := c.Stats()
if err != nil {
return 0
}
for _, fStat := range fStats {
total += fStat.Addition - fStat.Deletion
}
return total
}