-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
270 lines (227 loc) · 7.27 KB
/
main.go
File metadata and controls
270 lines (227 loc) · 7.27 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
package main
import (
"embed"
"encoding/json"
"flag"
"fmt"
"log"
"net/http"
"os"
"strings"
"text/template"
"time"
)
//go:embed templates/*
var templates embed.FS
type SearchResult struct {
Items []Content `json:"items"`
}
type Statistics struct {
PRsCount int `json:"prs_count"`
PRStats []Content `json:"pr_stats"`
IssuesCount int `json:"issues_count"`
IssueStats []Content `json:"issue_stats"`
CommitsCount int `json:"commits_count,omitempty"`
CommitStats []Content `json:"commit_stats,omitempty"`
}
type Content struct {
Title string `json:"title"`
URL string `json:"html_url"`
CreatedAt string `json:"created_at"`
}
// API doc: https://docs.github.com/en/rest/search?apiVersion=2022-11-28#search-issues-and-pull-requests
func getContributorStatistics(repoOwner, repoName, contributorUsername, startDate, endDate string,
includeCommits bool, authToken string, debug bool) (Statistics, error) {
baseURL := "https://api.github.com/search/issues"
client := &http.Client{}
var commitsData []Content
var commitsCount int
if includeCommits {
// Commits
commitsURL := fmt.Sprintf("%s?q=repo:%s/%s+type:commit+author:%s+created:%s..%s",
baseURL, repoOwner, repoName, contributorUsername, startDate, endDate)
// Create the HTTP request
commitsReq, err := http.NewRequest("GET", commitsURL, nil)
if err != nil {
return Statistics{}, err
}
// Conditionally set the authentication token in the request header
if authToken != "" {
commitsReq.Header.Set("Authorization", "token "+authToken)
}
// Measure the time taken for the commits request
startTime := time.Now()
// Send the request
if debug {
fmt.Printf("Commit HTTP Request URL: %s\n", commitsURL)
}
commitsResp, err := client.Do(commitsReq)
elapsedTime := time.Since(startTime)
if err != nil {
return Statistics{}, err
}
defer commitsResp.Body.Close()
var searchResult SearchResult
if err := decodeResponse(commitsResp, &searchResult); err != nil {
return Statistics{}, err
}
commitsData = searchResult.Items
commitsCount = len(commitsData)
fmt.Printf("Commits request took %s\n", elapsedTime)
}
// Pull Requests
prsURL := fmt.Sprintf("%s?q=repo:%s/%s+type:pr+author:%s+created:%s..%s",
baseURL, repoOwner, repoName, contributorUsername, startDate, endDate)
// Measure the time taken for the PRs request
startTime := time.Now()
if debug {
fmt.Printf("PR HTTP Request URL: %s\n", prsURL)
}
prsData, err := fetchAllPages(prsURL, authToken, debug)
elapsedTime := time.Since(startTime)
if err != nil {
return Statistics{}, err
}
prsCount := len(prsData)
fmt.Printf("PRs request took %s\n", elapsedTime)
// Issues
issuesURL := fmt.Sprintf("%s?q=repo:%s/%s+type:issue+author:%s+created:%s..%s",
baseURL, repoOwner, repoName, contributorUsername, startDate, endDate)
// Measure the time taken for the issues request
startTime = time.Now()
if debug {
fmt.Printf("Issue HTTP Request URL: %s\n", issuesURL)
}
issuesData, err := fetchAllPages(issuesURL, authToken, debug)
elapsedTime = time.Since(startTime)
if err != nil {
return Statistics{}, err
}
issuesCount := len(issuesData)
fmt.Printf("Issues request took %s\n", elapsedTime)
// Create the statistics
statistics := Statistics{
PRsCount: prsCount,
PRStats: prsData,
IssuesCount: issuesCount,
IssueStats: issuesData,
}
if includeCommits {
statistics.CommitsCount = commitsCount
statistics.CommitStats = commitsData
}
return statistics, nil
}
func fetchAllPages(url string, authToken string, debug bool) ([]Content, error) {
var allData []Content
client := &http.Client{}
for url != "" {
// Create the HTTP request
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
// Conditionally set the authentication token in the request header
if authToken != "" {
req.Header.Set("Authorization", "token "+authToken)
}
// Send the request
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var searchResult SearchResult
if err := decodeResponse(resp, &searchResult); err != nil {
return nil, err
}
allData = append(allData, searchResult.Items...)
// Check if there is a next page
linkHeader := resp.Header.Get("Link")
nextURL := extractNextPageURL(linkHeader)
url = nextURL
if debug {
fmt.Printf("next HTTP Request URL: %s\n", url)
}
time.Sleep(time.Millisecond * 10)
}
return allData, nil
}
func extractNextPageURL(linkHeader string) string {
links := strings.Split(linkHeader, ",")
for _, link := range links {
components := strings.Split(strings.TrimSpace(link), ";")
if len(components) == 2 && strings.TrimSpace(components[1]) == `rel="next"` {
url := strings.Trim(components[0], "<>")
return url
}
}
return ""
}
func decodeResponse(resp *http.Response, target interface{}) error {
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("response returned status %d", resp.StatusCode)
}
return json.NewDecoder(resp.Body).Decode(target)
}
func generateHTML(statistics Statistics, filename string) error {
tmpl, err := template.ParseFS(templates, "templates/template.html")
if err != nil {
return err
}
f, err := os.Create(filename)
if err != nil {
return err
}
defer f.Close()
return tmpl.Execute(f, statistics)
}
func validateTime(startTime, endTime string) {
// Parse the start and end dates from the command line flags
sDate, err := time.Parse("2006-01-02", startTime)
if err != nil {
log.Fatalf("Invalid start date format: %s", err)
}
eDate, err := time.Parse("2006-01-02", endTime)
if err != nil {
log.Fatalf("Invalid end date format: %s", err)
}
// Ensure that the end date is after the start date
if eDate.Before(sDate) {
log.Fatal("End date must be after start date")
}
}
func main() {
// Get the current time and calculate the start and end dates for the most recent month
currentTime := time.Now()
startDate := currentTime.AddDate(0, -1, 0).Format("2006-01-02")
endDate := currentTime.Format("2006-01-02")
// Command line flags
repoOwner := flag.String("repoOwner", "TencentBlueKing", "Repository owner")
repoName := flag.String("repoName", "bk-bcs", "Repository name")
contributorUsername := flag.String("contributorUsername", "fireyun", "Contributor username")
startDateFlag := flag.String("startDate", startDate, "Start date (format: YYYY-MM-DD)")
endDateFlag := flag.String("endDate", endDate, "End date (format: YYYY-MM-DD)")
filename := flag.String("filename", "statistics.html", "Output filename")
includeCommits := flag.Bool("includeCommits", false, "Include commit data in statistics")
authToken := flag.String("authToken", "", "GitHub authentication token")
debug := flag.Bool("debug", true, "Enable debug mode to print HTTP request URLs")
flag.Parse()
validateTime(*startDateFlag, *endDateFlag)
if *debug {
fmt.Println("Debug mode is enabled")
flag.VisitAll(func(f *flag.Flag) {
fmt.Printf("flag -%s=%s\n", f.Name, f.Value)
})
}
statistics, err := getContributorStatistics(*repoOwner, *repoName, *contributorUsername, *startDateFlag,
*endDateFlag, *includeCommits, *authToken, *debug)
if err != nil {
log.Fatal(err)
}
err = generateHTML(statistics, *filename)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Statistics generated successfully. Please check the file: %s\n", *filename)
}