-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
executable file
·278 lines (231 loc) · 7.74 KB
/
Copy pathmain.go
File metadata and controls
executable file
·278 lines (231 loc) · 7.74 KB
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
///bin/sh -c true; exec /usr/bin/env go run "$0" "$@"
// vim:ts=4:sts=4:sw=4:noet
// args: harisekhon
//
// Author: Hari Sekhon
// Date: 2024-09-08 02:24:45 +0200 (Sun, 08 Sep 2024)
//
// https///github.com/HariSekhon/GitHub-Commit-Times-Graph
//
// License: see accompanying Hari Sekhon LICENSE file
//
// If you're using my code you're welcome to connect with me on LinkedIn and optionally send me feedback to help steer this or other code I publish
//
// https://www.linkedin.com/in/HariSekhon
//
//go:build !debug
// +build !debug
package main
import (
"context"
"flag"
"fmt"
"image/color"
"log"
"os"
"strings"
"github.com/google/go-github/v41/github"
"golang.org/x/oauth2"
"gonum.org/v1/plot"
"gonum.org/v1/plot/plotter"
"gonum.org/v1/plot/vg"
"gonum.org/v1/plot/vg/vgsvg"
"gonum.org/v1/plot/vg/draw"
)
// Fetch all commits from a repository with pagination
func fetchCommits(client *github.Client, owner, repo string) ([]*github.RepositoryCommit, error) {
var allCommits []*github.RepositoryCommit
opt := &github.CommitsListOptions{ListOptions: github.ListOptions{PerPage: 100}}
for {
commits, resp, err := client.Repositories.ListCommits(context.Background(), owner, repo, opt)
if err != nil {
return nil, err
}
allCommits = append(allCommits, commits...)
if resp.NextPage == 0 {
break
}
opt.Page = resp.NextPage
}
return allCommits, nil
}
// Fetch all public, non-fork repositories for a user with pagination
func fetchUserRepos(client *github.Client, user string) ([]*github.Repository, error) {
var allRepos []*github.Repository
opt := &github.RepositoryListOptions{Type: "public", ListOptions: github.ListOptions{PerPage: 100}}
for {
repos, resp, err := client.Repositories.List(context.Background(), user, opt)
if err != nil {
return nil, err
}
for _, repo := range repos {
if !repo.GetFork() {
allRepos = append(allRepos, repo)
}
}
if resp.NextPage == 0 {
break
}
opt.Page = resp.NextPage
}
return allRepos, nil
}
// Process commits and aggregate by hour
func processCommits(commits []*github.RepositoryCommit, usernameFilter string) [24]int {
hourlyCommits := [24]int{}
for _, commit := range commits {
if commit.Commit == nil || commit.Commit.Committer == nil {
continue
}
if usernameFilter != "" && commit.Commit.Committer.GetName() != usernameFilter && commit.Commit.Committer.GetEmail() != usernameFilter {
continue
}
commitTime := commit.Commit.Committer.GetDate()
hour := commitTime.Hour()
hourlyCommits[hour]++
}
return hourlyCommits
}
// Generate a bar graph and save it as an SVG file
func generateGraph(hourlyCommits [24]int, outputFile, usernameFilter, repoFilter string) error {
p := plot.New()
// Set the graph title based on the filter type
if usernameFilter != "" {
p.Title.Text = fmt.Sprintf("GitHub Commits by Hour for %s", usernameFilter)
} else if repoFilter != "" {
p.Title.Text = fmt.Sprintf("GitHub Commits by Hour for Repos under %s", repoFilter)
} else {
p.Title.Text = "GitHub Commits by Hour"
}
p.X.Label.Text = "Hour of Day (UTC)"
p.Y.Label.Text = "Number of Commits"
// Create the bar data
values := make(plotter.Values, 24)
for i := 0; i < 24; i++ {
values[i] = float64(hourlyCommits[i])
}
barChart, err := plotter.NewBarChart(values, vg.Points(20))
if err != nil {
return err
}
// Set the bar color to blue
barChart.Color = color.RGBA{R: 0, G: 0, B: 255, A: 255} // Blue color
p.Add(barChart)
// Set the x-axis labels to represent hours (0-23)
p.NominalX("00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23")
// Create the SVG canvas with the correct width and height
width := vg.Inch * 10
height := vg.Inch * 4
canvas := vgsvg.New(width, height)
// Draw the plot on the canvas
p.Draw(draw.New(canvas))
// Save the SVG to the file
w, err := os.Create(outputFile)
if err != nil {
return err
}
defer w.Close()
_, err = canvas.WriteTo(w)
if err != nil {
return err
}
fmt.Printf("Graph saved to %s\n", outputFile)
return nil
}
// Show usage help
func showUsage() {
fmt.Println("Usage: go run main.go [options] [<username>] <repo1> <repo2> ...")
fmt.Println("Options:")
fmt.Println(" --user <username/email> Filter commits by a specific username or email")
fmt.Println(" --repo <owner/repo> Filter commits by specific repository (format: 'owner/repo')")
fmt.Println(" -o, --output <file> Output file for the graph (default: graph.svg)")
fmt.Println(" -h, --help Show this help message")
fmt.Println("Repos:")
fmt.Println(" Provide repositories in the format 'owner/repo'.")
fmt.Println(" If only 'owner' is provided, fetches all public non-fork repos for that user.")
os.Exit(0)
}
func main() {
var userFilter, repoFilter, outputFile string
flag.StringVar(&userFilter, "user", "", "Filter commits by a specific username or email")
flag.StringVar(&repoFilter, "repo", "", "Filter commits by specific repository (format: 'owner/repo')")
flag.StringVar(&outputFile, "output", "graph.svg", "Output file for the graph")
helpFlag := flag.Bool("help", false, "Show help")
flag.BoolVar(helpFlag, "h", false, "Show help")
flag.Parse()
if *helpFlag {
showUsage()
}
repoArgs := flag.Args()
if len(repoArgs) == 0 && repoFilter == "" && userFilter == "" {
fmt.Println("Error: No repositories, username, or repo filter provided.")
showUsage()
}
token := os.Getenv("GITHUB_TOKEN")
if token == "" {
log.Fatal("Error: GITHUB_TOKEN environment variable is not set.")
}
ctx := context.Background()
ts := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: token})
tc := oauth2.NewClient(ctx, ts)
client := github.NewClient(tc)
hourlyCommits := [24]int{}
if repoFilter != "" {
parts := strings.Split(repoFilter, "/")
if len(parts) != 2 {
log.Fatalf("Invalid repository format: %s (expected 'owner/repo')", repoFilter)
}
owner := parts[0]
repo := parts[1]
fmt.Printf("Fetching commits from %s/%s...\n", owner, repo)
commits, err := fetchCommits(client, owner, repo)
if err != nil {
log.Fatalf("Error fetching commits from %s/%s: %v", owner, repo, err)
}
repoHourlyCommits := processCommits(commits, userFilter)
for hour := 0; hour < 24; hour++ {
hourlyCommits[hour] += repoHourlyCommits[hour]
}
} else {
for _, repoArg := range repoArgs {
if strings.Contains(repoArg, "/") {
parts := strings.Split(repoArg, "/")
if len(parts) != 2 {
log.Fatalf("Invalid repository format: %s (expected 'owner/repo')", repoArg)
}
owner := parts[0]
repo := parts[1]
fmt.Printf("Fetching commits from %s/%s...\n", owner, repo)
commits, err := fetchCommits(client, owner, repo)
if err != nil {
log.Fatalf("Error fetching commits from %s/%s: %v", owner, repo, err)
}
repoHourlyCommits := processCommits(commits, userFilter)
for hour := 0; hour < 24; hour++ {
hourlyCommits[hour] += repoHourlyCommits[hour]
}
} else {
user := repoArg
fmt.Printf("Fetching public non-fork repos for user %s...\n", user)
repos, err := fetchUserRepos(client, user)
if err != nil {
log.Fatalf("Error fetching repos for user %s: %v", user, err)
}
for _, repo := range repos {
fmt.Printf("Fetching commits from %s/%s...\n", user, repo.GetName())
commits, err := fetchCommits(client, user, repo.GetName())
if err != nil {
log.Fatalf("Error fetching commits from %s/%s: %v", user, repo.GetName(), err)
}
repoHourlyCommits := processCommits(commits, userFilter)
for hour := 0; hour < 24; hour++ {
hourlyCommits[hour] += repoHourlyCommits[hour]
}
}
}
}
}
if err := generateGraph(hourlyCommits, outputFile, userFilter, repoFilter); err != nil {
log.Fatalf("Error generating graph: %v", err)
}
}