-
-
Notifications
You must be signed in to change notification settings - Fork 362
/
GitHubUtils.ts
260 lines (231 loc) · 8.15 KB
/
GitHubUtils.ts
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
import { basename } from "path"
import { components as OctokitOpenApiTypes } from "@octokit/openapi-types"
import { filepathContentsMapToUpdateGitHubBranch, BranchCreationConfig } from "memfs-or-file-map-to-github-branch"
import { sentence, href } from "../../runner/DangerUtils"
import { GitHubPRDSL, GitHubUtilsDSL } from "./../../dsl/GitHubDSL"
import { debug } from "../../debug"
export type GetContentResponseData =
| OctokitOpenApiTypes["schemas"]["content-file"]
| OctokitOpenApiTypes["schemas"]["content-symlink"]
| OctokitOpenApiTypes["schemas"]["content-submodule"]
export function isFileContents(
response: GetContentResponseData
): response is OctokitOpenApiTypes["schemas"]["content-file"] {
return response.type === "file"
}
const d = debug("GitHub::Utils")
import { Octokit as GitHub } from "@octokit/rest"
// We need to curry in access to the GitHub PR metadata
const utils = (pr: GitHubPRDSL | undefined, api: GitHub): GitHubUtilsDSL => {
/**
* Converts a set of filepaths into a sentence'd set of hrefs for the
* current PR. Can be configured to just show the name (instead of full filepath), to
* change the github repo or branch.
*
*/
const fileLinks = (paths: string[], useBasename: boolean = true, repoSlug?: string, branch?: string): string => {
// To support enterprise github, we need to handle custom github domains
// this can be pulled out of the repo url metadata
const githubRoot = pr && pr.head.repo.html_url.split(pr.head.repo.owner.login)[0]
const slug = repoSlug || (pr && pr.head.repo.full_name)
const ref = branch || (pr && pr.head.ref)
const toHref = (path: string) => `${githubRoot}${slug}/blob/${ref}/${path}`
// As we should only be getting paths we can ignore the nullability
const hrefs = paths.map(p => href(toHref(p), useBasename ? basename(p) : p)) as string[]
return sentence(hrefs)
}
return {
fileLinks,
fileContents: fileContentsGenerator(api, pr && pr.head.repo.full_name, pr && pr.head.ref),
createUpdatedIssueWithID: createUpdatedIssueWithIDGenerator(api),
createOrAddLabel: createOrAddLabel(pr, api),
createOrUpdatePR: createOrUpdatePR(pr, api),
}
}
/** Generates the fileContents function, needed so that Peril can re-create this func for an event */
export const fileContentsGenerator = (
api: GitHub,
defaultRepoSlug: string | undefined,
defaultRef: string | undefined
) => async (path: string, repoSlug?: string, ref?: string): Promise<string> => {
// Use the current state of PR if no repo/ref is passed
if (!repoSlug) {
repoSlug = defaultRepoSlug
}
if (!ref) {
ref = defaultRef
}
if (!repoSlug) {
throw new Error("You used fileContentsGenerator in a non-PR without specifying the repoSlug")
}
const opts = {
ref,
path,
repo: repoSlug.split("/")[1],
owner: repoSlug.split("/")[0],
}
try {
// response of getContent() can be one of 4 things. We are interested in file responses only
// https://docs.github.com/en/rest/reference/repos#get-repository-content
const response = await api.repos.getContent(opts)
if (!response || !response.data) {
return ""
}
if (Array.isArray(response.data)) {
// If we get an array, we have a directory
return ""
}
if (isFileContents(response.data) && response.data.content) {
const buffer = Buffer.from(response.data.content, response.data.encoding)
return buffer.toString()
} else {
return ""
}
} catch {
return ""
}
}
/** Generates the createUpdatedIssueWithID function, needed so that Peril can re-create this func for an event */
export const createUpdatedIssueWithIDGenerator = (api: GitHub) => async (
id: string,
content: string,
settings: { title: string; open: boolean; owner: string; repo: string }
) => {
// Could also scope:
// by author
// by label
const uniqueHeader = `Danger-Issue-ID-${id.replace(/ /g, "_")}`
const q = `user:${settings.owner} repo:${settings.repo} ${uniqueHeader}`
const { data: searchResults } = await api.search.issuesAndPullRequests({ q })
d(`Got ${searchResults.total_count} for ${uniqueHeader}`)
const body = `${content}\n\n${uniqueHeader}`
const { repo, owner, title } = settings
const state = settings.open ? "open" : "closed"
if (searchResults.total_count > 0 && searchResults.items[0]) {
const issueToUpdate = searchResults.items[0]
d(`Found: ${issueToUpdate}`)
const { data: issue } = await api.issues.update({
body,
owner,
repo,
title,
issue_number: issueToUpdate.number,
state,
})
return issue.html_url
} else {
const { data: issue } = await api.issues.create({ body, owner, repo, title })
return issue.html_url
}
}
interface PRCreationConfig {
/** PR title */
title: string
/** PR body */
body: string
/** The danger in danger/danger-js - defaults to the PR base name if undefined */
owner?: string
/** The danger-js in danger/danger-js - defaults to the PR base repo if undefined */
repo?: string
/** A message for the commit */
commitMessage: string
/** The name of the branch on the repo */
newBranchName: string
/** Base branch for the new branch e.g. what should Danger create the new branch from */
baseBranch: string
}
export const createOrUpdatePR = (pr: GitHubPRDSL | undefined, api: GitHub) => async (
config: PRCreationConfig,
fileMap: any
) => {
const repo = config.repo || (pr && pr.base.repo.name)
if (!repo) {
throw new Error("You need to set a `repo` in the config for `createOrUpdatePR`")
}
const owner = config.owner || (pr && pr.base.user.login)
if (!owner) {
throw new Error("You need to set a `owner` in the config for `createOrUpdatePR`")
}
const branchSettings: BranchCreationConfig = {
fullBaseBranch: `heads/${config.baseBranch}`,
fullBranchReference: `heads/${config.newBranchName}`,
message: config.commitMessage,
owner,
repo,
}
d("Creating a branch")
await filepathContentsMapToUpdateGitHubBranch(api, fileMap, branchSettings)
d("Getting open PRs")
const prs = await api.pulls.list({ repo, owner, state: "open" })
const existingPR = prs.data.find(pr => pr.base.ref === config.newBranchName)
if (existingPR) {
d("Updating existing PR")
return await api.pulls.update({
pull_number: existingPR.number,
base: config.baseBranch,
owner,
repo,
title: config.title,
body: config.body,
})
} else {
d("Creating a new PR")
return await api.pulls.create({
base: config.baseBranch,
head: config.newBranchName,
owner,
repo,
title: config.title,
body: config.body,
})
}
}
export const createOrAddLabel = (pr: GitHubPRDSL | undefined, api: GitHub) => async (
labelConfig: { name: string; color: string; description: string },
repoConfig?: { owner: string; repo: string; id: number }
) => {
// Create or re-use an existing label
if (!repoConfig && !pr) {
throw new Error("To use createOrAddLabel without a PR you need to add a repoConfig arg")
}
const config = repoConfig || (pr && { owner: pr.base.repo.owner.login, repo: pr.base.repo.name, id: pr.number })!
d("Checking for existing labels")
let label: any = null
try {
const existingLabels = await api.paginate("GET /repos/:owner/:repo/labels", {
owner: config.owner,
repo: config.repo,
})
label = existingLabels.find((l: any) => l.name == labelConfig.name)
} catch (e) {
d("api.issues.getLabels gave an error", e)
}
// Create the label if it doesn't exist yet
if (!label) {
d("no label found, creating a new one for this repo")
try {
await api.issues.createLabel({
owner: config.owner,
repo: config.repo,
name: labelConfig.name,
color: labelConfig.color,
description: labelConfig.description,
})
} catch (e) {
d("api.issues.createLabel gave an error", e)
}
}
d("adding a label to this pr")
// Then add the label
try {
await api.issues.addLabels({
owner: config.owner,
repo: config.repo,
issue_number: config.id,
labels: [labelConfig.name],
})
} catch (e) {
d("api.issues.addLabels gave an error", e)
}
}
export default utils