-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Expand file tree
/
Copy pathindex.mjs
More file actions
211 lines (200 loc) · 10.1 KB
/
index.mjs
File metadata and controls
211 lines (200 loc) · 10.1 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
//Setup
export default async function({login, data, rest, q, account, imports}, {enabled = false, markdown = "inline", extras = false} = {}) {
//Plugin execution
try {
//Check if plugin is enabled and requirements are met
if ((!q.activity) || (!imports.metadata.plugins.activity.enabled(enabled, {extras})))
return null
//Context
let context = {mode:"user"}
if (q.repo) {
console.debug(`metrics/compute/${login}/plugins > activity > switched to repository mode`)
const {owner, repo} = data.user.repositories.nodes.map(({name:repo, owner:{login:owner}}) => ({repo, owner})).shift()
context = {...context, mode:"repository", owner, repo}
}
//Load inputs
let {limit, load, days, filter, visibility, timestamps, skipped, ignored} = imports.metadata.plugins.activity.inputs({data, q, account})
if (!days)
days = Infinity
skipped.push(...data.shared["repositories.skipped"])
ignored.push(...data.shared["users.ignored"])
const pages = Math.ceil(load / 100)
const codelines = 2
//Get user recent activity
console.debug(`metrics/compute/${login}/plugins > activity > querying api`)
const events = []
try {
for (let page = 1; page <= pages; page++) {
console.debug(`metrics/compute/${login}/plugins > activity > loading page ${page}/${pages}`)
events.push(...(context.mode === "repository" ? await rest.activity.listRepoEvents({owner:context.owner, repo:context.repo}) : await rest.activity.listEventsForAuthenticatedUser({username:login, per_page:100, page})).data)
}
}
catch {
console.debug(`metrics/compute/${login}/plugins > activity > no more page to load`)
}
console.debug(`metrics/compute/${login}/plugins > activity > ${events.length} events loaded`)
const payloadTypesToCustomTypes = {
CommitCommentEvent:"comment",
CreateEvent:"ref/create",
DeleteEvent:"ref/delete",
ForkEvent:"fork",
GollumEvent:"wiki",
IssueCommentEvent:"comment",
IssuesEvent:"issue",
MemberEvent:"member",
PublicEvent:"public",
PullRequestEvent:"pr",
PullRequestReviewEvent:"review",
PullRequestReviewCommentEvent:"comment",
PushEvent:"push",
ReleaseEvent:"release",
WatchEvent:"star",
}
//Extract activity events
const activity = (await Promise.all(
events
.filter(({actor}) => account === "organization" ? true : actor.login?.toLocaleLowerCase() === login.toLocaleLowerCase())
.filter(({created_at}) => Number.isFinite(days) ? new Date(created_at) > new Date(Date.now() - days * 24 * 60 * 60 * 1000) : true)
.filter(event => visibility === "public" ? event.public : true)
.map(event => ({event, customType:payloadTypesToCustomTypes[event.type]}))
.filter(({customType}) => !!customType) //Ignore events with an unknown type
.filter(({customType}) => filter.includes("all") || filter.includes(customType)) //Filter events based on user preference
.map(({event}) => event) //Discard customType, it will be re-assigned
.map(async ({type, payload, actor:{login:actor}, repo:{name:repo}, created_at}) => {
//See https://docs.github.com/en/free-pro-team@latest/developers/webhooks-and-events/github-event-types
const timestamp = new Date(created_at)
if (!imports.filters.repo(repo, skipped))
return null
//Get custom type from the previously delcared mapping, so that it acts as a single source of truth
const customType = payloadTypesToCustomTypes[type]
if (!customType) throw new Error(`Missing event mapping for type: ${type}`)
switch (type) {
//Commented on a commit
case "CommitCommentEvent": {
if (!["created"].includes(payload.action))
return null
const {comment:{user:{login:user}, commit_id:sha, body:content}} = payload
if (!imports.filters.text(user, ignored))
return null
return {type:customType, on:"commit", actor, timestamp, repo, content:await imports.markdown(content, {mode:markdown, codelines}), user, mobile:null, number:sha.substring(0, 7), title:""}
}
//Created a git branch or tag
case "CreateEvent": {
const {ref:name, ref_type:type} = payload
return {type:customType, actor, timestamp, repo, ref:{name, type}}
}
//Deleted a git branch or tag
case "DeleteEvent": {
const {ref:name, ref_type:type} = payload
return {type:customType, actor, timestamp, repo, ref:{name, type}}
}
//Forked repository
case "ForkEvent": {
const {forkee:{full_name:forked}} = payload
return {type:customType, actor, timestamp, repo, forked}
}
//Wiki changes
case "GollumEvent": {
const {pages} = payload
return {type:customType, actor, timestamp, repo, pages:pages.map(({title}) => title)}
}
//Commented on an issue
case "IssueCommentEvent": {
if (!["created"].includes(payload.action))
return null
const {issue:{user:{login:user}, title, number}, comment:{body:content, performed_via_github_app:mobile}} = payload
if (!imports.filters.text(user, ignored))
return null
return {type:customType, on:"issue", actor, timestamp, repo, content:await imports.markdown(content, {mode:markdown, codelines}), user, mobile, number, title}
}
//Issue event
case "IssuesEvent": {
if (!["opened", "closed", "reopened"].includes(payload.action))
return null
const {action, issue:{user:{login:user}, title, number, body:content}} = payload
if (!imports.filters.text(user, ignored))
return null
return {type:customType, actor, timestamp, repo, action, user, number, title, content:await imports.markdown(content, {mode:markdown, codelines})}
}
//Activity from repository collaborators
case "MemberEvent": {
if (!["added"].includes(payload.action))
return null
const {member:{login:user}} = payload
if (!imports.filters.text(user, ignored))
return null
return {type:customType, actor, timestamp, repo, user}
}
//Made repository public
case "PublicEvent": {
return {type:customType, actor, timestamp, repo}
}
//Pull requests events
case "PullRequestEvent": {
if (!["opened", "closed"].includes(payload.action))
return null
const {action, pull_request:{user:{login:user}, title, number, body:content, additions:added, deletions:deleted, changed_files:changed, merged}} = payload
if (!imports.filters.text(user, ignored))
return null
return {type:customType, actor, timestamp, repo, action:(action === "closed") && (merged) ? "merged" : action, user, title, number, content:await imports.markdown(content, {mode:markdown, codelines}), lines:{added, deleted}, files:{changed}}
}
//Reviewed a pull request
case "PullRequestReviewEvent": {
const {review:{state:review}, pull_request:{user:{login:user}, number, title}} = payload
if (!imports.filters.text(user, ignored))
return null
return {type:customType, actor, timestamp, repo, review, user, number, title}
}
//Commented on a pull request
case "PullRequestReviewCommentEvent": {
if (!["created"].includes(payload.action))
return null
const {pull_request:{user:{login:user}, title, number}, comment:{body:content, performed_via_github_app:mobile}} = payload
if (!imports.filters.text(user, ignored))
return null
return {type:customType, on:"pr", actor, timestamp, repo, content:await imports.markdown(content, {mode:markdown, codelines}), user, mobile, number, title}
}
//Pushed commits
case "PushEvent": {
let {size, ref, head, before} = payload
const [owner, repoName] = repo.split("/")
const res = await rest.repos.compareCommitsWithBasehead({owner, repo:repoName, basehead:`${before}...${head}`})
let {commits} = res.data
commits = commits.filter(({author:{email}}) => imports.filters.text(email, ignored))
if (!commits.length)
return null
if (commits.slice(-1).pop()?.commit.message.startsWith("Merge branch "))
commits = commits.slice(-1)
return {type:customType, actor, timestamp, repo, size, branch:ref.match(/refs.heads.(?<branch>.*)/)?.groups?.branch ?? null, commits:commits.reverse().map(({sha, message}) => ({sha:sha.substring(0, 7), message}))}
}
//Released
case "ReleaseEvent": {
if (!["published"].includes(payload.action))
return null
const {action, release:{name, tag_name, prerelease, draft, body:content}} = payload
return {type:customType, actor, timestamp, repo, action, name:name || tag_name, prerelease, draft, content:await imports.markdown(content, {mode:markdown, codelines})}
}
//Starred a repository
case "WatchEvent": {
if (!["started"].includes(payload.action))
return null
const {action} = payload
return {type:customType, actor, timestamp, repo, action}
}
//Unknown event
default: {
return null
}
}
}),
))
.filter(event => event)
.slice(0, limit)
//Results
return {timestamps, events:activity}
}
//Handle errors
catch (error) {
throw imports.format.error(error)
}
}