forked from nicklegan/github-org-member-contribution-action
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
327 lines (292 loc) · 10.9 KB
/
index.js
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
const arraySort = require('array-sort')
const core = require('@actions/core')
const github = require('@actions/github')
const stringify = require('csv-stringify/lib/sync')
const {GitHub} = require('@actions/github/lib/utils')
const {retry} = require('@octokit/plugin-retry')
const {throttling} = require('@octokit/plugin-throttling')
const MyOctokit = GitHub.plugin(throttling, retry)
const eventPayload = require(process.env.GITHUB_EVENT_PATH)
const org = core.getInput('org', {required: false}) || eventPayload.organization.login
const token = core.getInput('token', {required: true})
///////////////// added by nadeem ///////////////////
const fs = require('fs');
const readline = require('readline');
/////////////////////////////////////////////////////
// API throttling
const octokit = new MyOctokit({
auth: token,
request: {
retries: 3,
retryAfter: 180
},
throttle: {
onRateLimit: (retryAfter, options, octokit) => {
octokit.log.warn(`Request quota exhausted for request ${options.method} ${options.url}`)
if (options.request.retryCount === 0) {
// only retries once
octokit.log.info(`Retrying after ${retryAfter} seconds!`)
return true
}
},
onAbuseLimit: (retryAfter, options, octokit) => {
// does not retry, only logs a warning
octokit.log.warn(`Abuse detected for request ${options.method} ${options.url}`)
}
}
})
///////////////// added by nadeem ///////////////////////////
// Query all commits of given user in all Repos of org from given time
async function getAllBranchComits(uid,from,uniqueOids) {
let paginationMember = null
const query = `query ($org: String!, $uid: ID, $from: GitTimestamp, $after: String) {
organization(login: $org) {
repositories(first: 30, after: $after) {
nodes {
name
refs(refPrefix: "refs/heads/", last: 100) {
edges {
node {
name
target {
... on Commit {
history(author: { id: $uid }, since: $from) {
edges {
node {
oid
}
}
}
}
}
}
}
}
}
pageInfo {
hasNextPage
endCursor
}
}
}
}`
try {
let hasNextPageMember = false
let getComitResult = null
do {
getComitResult = await octokit.graphql({
query,
org,
uid: uid,
from,
after: paginationMember
})
//const ComitObj = getComitResult.organization.repositories.nodes
hasNextPageMember = getComitResult.organization.repositories.pageInfo.hasNextPage
if (hasNextPageMember) {
paginationMember = getComitResult.organization.repositories.pageInfo.endCursor
} else {
paginationMember = null
}
const oidSet = new Set();
getComitResult.organization.repositories.nodes.forEach((repo) => {
repo.refs.edges.forEach((edge) => {
if (edge.node.target.history.edges.length > 0) {
edge.node.target.history.edges.forEach((historyEdge) => {
const oid = historyEdge.node.oid
oidSet.add(oid)
})
}
})
})
uniqueOids.push(...Array.from(oidSet))
} while (hasNextPageMember)
} catch (error) {
core.setFailed(error.message)
}
//console.log(uniqueOids);
}
/////////////////////////////////////////////////////////////
// Query all org member contributions
async function getMemberActivity(orgid, from, to,contribArray,uniqueOids) {
console.log(`gathering result from the date: ${from}`)
let paginationMember = null
const query = `query ($org: String! $orgid: ID $cursorID: String $from: DateTime, $to: DateTime) {
organization(login: $org ) {
membersWithRole(first: 25, after: $cursorID) {
nodes {
login
contributionsCollection (organizationID: $orgid, from: $from, to: $to) {
hasAnyContributions
totalCommitContributions
totalIssueContributions
totalPullRequestContributions
totalPullRequestReviewContributions
totalRepositoriesWithContributedIssues
totalRepositoriesWithContributedCommits
totalRepositoriesWithContributedPullRequests
totalRepositoriesWithContributedPullRequestReviews
}
}
pageInfo {
hasNextPage
endCursor
}
}
}
}`
try {
let hasNextPageMember = false
let getMemberResult = null
let getUserIdResult = null //// added by nadeem
do {
getMemberResult = await octokit.graphql({
query,
org,
orgid,
from,
to,
cursorID: paginationMember
})
const membersObj = getMemberResult.organization.membersWithRole.nodes
hasNextPageMember = getMemberResult.organization.membersWithRole.pageInfo.hasNextPage
for (const member of membersObj) {
if (hasNextPageMember) {
paginationMember = getMemberResult.organization.membersWithRole.pageInfo.endCursor
} else {
paginationMember = null
}
const userName = member.login
const activeContrib = member.contributionsCollection.hasAnyContributions
//////////////////////// added by nadeem ////////////////////////////////////////////
try {
// Find user id for member
const idquery = `query ($username: String!) {
user(login: $username) {
id
}
}`
getUserIdResult = await octokit.graphql({
query: idquery,
username: userName
})
} catch (error) {
core.setFailed(error.message)
}
const id = getUserIdResult.user.id
await getAllBranchComits(id,from,uniqueOids)
const commitContrib = uniqueOids.length
uniqueOids = []
//////////////////////////////////////////////////////////////////////////
//const commitContrib = member.contributionsCollection.totalCommitContributions
const issueContrib = member.contributionsCollection.totalIssueContributions
const prContrib = member.contributionsCollection.totalPullRequestContributions
const prreviewContrib = member.contributionsCollection.totalPullRequestReviewContributions
const repoIssueContrib = member.contributionsCollection.totalRepositoriesWithContributedIssues
const repoCommitContrib = member.contributionsCollection.totalRepositoriesWithContributedCommits
const repoPullRequestContrib = member.contributionsCollection.totalRepositoriesWithContributedPullRequests
const repoPullRequestReviewContrib = member.contributionsCollection.totalRepositoriesWithContributedPullRequestReviews
// Push all member contributions from query to array
contribArray.push({userName, activeContrib, commitContrib, issueContrib, prContrib, prreviewContrib, repoIssueContrib, repoCommitContrib, repoPullRequestContrib, repoPullRequestReviewContrib})
console.log(userName)
}
} while (hasNextPageMember)
} catch (error) {
core.setFailed(error.message)
}
}
;(async () => {
try {
// Find orgid for organization
const query = `query ($org: String!) {
organization(login: $org) {
id
}
}`
getOrgIdResult = await octokit.graphql({
query,
org
})
// Detect if input is day amount or historic interval and set date variables
const fromdate = core.getInput('fromdate', {required: false}) || ''
const todate = core.getInput('todate', {required: false}) || ''
const orgid = getOrgIdResult.organization.id
let to
let from
let days
let columnDate
let fileDate
let logDate
const regex = '([0-9]{4}-[0-9]{2}-[0-9]{2})'
const flags = 'i'
const re = new RegExp(regex, flags)
if (re.test(fromdate, todate) !== true) {
days = core.getInput('days', {required: true}) || '30'
to = new Date()
from = new Date()
from.setDate(to.getDate() - days)
columnDate = `<${days} days`
fileDate = `${days}-days`
logDate = `${days} days`
} else {
to = new Date(todate).toISOString()
from = new Date(fromdate).toISOString()
days = `${from.substr(0, 10)} to ${to.substr(0, 10)}`
columnDate = days
fileDate = `${from.substr(0, 10)}-to-${to.substr(0, 10)}`
logDate = days
}
// Take time, orgid parameters and init array to get all member contributions
const contribArray = []
const uniqueOids = []
console.log(`Retrieving ${logDate} of member contribution data for the ${org} organization:`)
await getMemberActivity(orgid, from, to,contribArray,uniqueOids)
// Set sorting settings and add header to array
const columns = {
userName: 'Member',
activeContrib: `Has active contributions (${columnDate})`,
commitContrib: `Commits created (${columnDate})`,
issueContrib: `Issues opened (${columnDate})`,
prContrib: `PRs opened (${columnDate})`,
prreviewContrib: `PR reviews (${columnDate})`,
repoIssueContrib: `Issue spread (${columnDate})`,
repoCommitContrib: `Commit spread (${columnDate})`,
repoPullRequestContrib: `PR spread (${columnDate})`,
repoPullRequestReviewContrib: `PR review spread (${columnDate})`
}
const sortColumn = core.getInput('sort', {required: false}) || 'commitContrib'
const sortArray = arraySort(contribArray, sortColumn, {reverse: true})
sortArray.unshift(columns)
// Convert array to csv
const csv = stringify(sortArray, {
cast: {
boolean: function (value) {
return value ? 'TRUE' : 'FALSE'
}
}
})
// Prepare path/filename, repo/org context and commit name/email variables
const reportPath = `reports/${org}-${from}-to-${new Date().toISOString().substring(0, 19) + 'Z'}-${fileDate}.csv`
//const reportPath = `/tmp/${org}-${new Date().toISOString().substring(0, 19) + 'Z'}-${fileDate}.csv`
const committerName = core.getInput('committer-name', {required: false}) || 'github-actions'
const committerEmail = core.getInput('committer-email', {required: false}) || '[email protected]'
const {owner, repo} = github.context.repo
// Push csv to repo
const opts = {
owner,
repo,
path: reportPath,
message: `${new Date().toISOString().slice(0, 10)} Member contribution report`,
content: Buffer.from(csv).toString('base64'),
committer: {
name: committerName,
email: committerEmail
}
}
//fs.writeFileSync(reportPath, csv);
console.log(`Pushing final CSV report to repository path: ${reportPath}`)
await octokit.rest.repos.createOrUpdateFileContents(opts)
} catch (error) {
core.setFailed(error.message)
}
})()