forked from github/docs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
git-utils.js
243 lines (223 loc) · 6.34 KB
/
git-utils.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
#!/usr/bin/env node
import crypto from 'crypto'
import fs from 'fs/promises'
import Github from './github.js'
const github = Github()
// https://docs.github.com/rest/reference/git#get-a-reference
export async function getCommitSha(owner, repo, ref) {
try {
const { data } = await github.git.getRef({
owner,
repo,
ref,
})
return data.object.sha
} catch (err) {
console.log('error getting tree')
throw err
}
}
// https://docs.github.com/rest/reference/git#list-matching-references
export async function listMatchingRefs(owner, repo, ref) {
try {
// if the ref is found, this returns an array of objects;
// if the ref is not found, this returns an empty array
const { data } = await github.git.listMatchingRefs({
owner,
repo,
ref,
})
return data
} catch (err) {
console.log('error getting tree')
throw err
}
}
// https://docs.github.com/rest/reference/git#get-a-commit
export async function getTreeSha(owner, repo, commitSha) {
try {
const { data } = await github.git.getCommit({
owner,
repo,
commit_sha: commitSha,
})
return data.tree.sha
} catch (err) {
console.log('error getting tree')
throw err
}
}
// https://docs.github.com/rest/reference/git#get-a-tree
export async function getTree(owner, repo, ref) {
const commitSha = await getCommitSha(owner, repo, ref)
const treeSha = await getTreeSha(owner, repo, commitSha)
try {
const { data } = await github.git.getTree({
owner,
repo,
tree_sha: treeSha,
recursive: 1,
})
// only return files that match the patterns in allowedPaths
// skip actions/changes files
return data.tree
} catch (err) {
console.log('error getting tree')
throw err
}
}
// https://docs.github.com/rest/reference/git#get-a-blob
export async function getContentsForBlob(owner, repo, sha) {
const { data } = await github.git.getBlob({
owner,
repo,
file_sha: sha,
})
// decode blob contents
return Buffer.from(data.content, 'base64')
}
// https://docs.github.com/rest/reference/repos#get-repository-content
export async function getContents(owner, repo, ref, path) {
try {
const { data } = await github.repos.getContent({
owner,
repo,
ref,
path,
})
if (!data.content) {
const blob = await getContentsForBlob(owner, repo, data.sha)
// decode Base64 encoded contents
return Buffer.from(blob, 'base64').toString()
}
// decode Base64 encoded contents
return Buffer.from(data.content, 'base64').toString()
} catch (err) {
console.log(`error getting ${path} from ${owner}/${repo} at ref ${ref}`)
throw err
}
}
// https://docs.github.com/en/rest/reference/pulls#list-pull-requests
export async function listPulls(owner, repo) {
try {
const { data } = await github.pulls.list({
owner,
repo,
per_page: 100,
})
return data
} catch (err) {
console.log(`error listing pulls in ${owner}/${repo}`)
throw err
}
}
export async function createIssueComment(owner, repo, pullNumber, body) {
try {
const { data } = await github.issues.createComment({
owner,
repo,
issue_number: pullNumber,
body,
})
return data
} catch (err) {
console.log(`error creating a review comment on PR ${pullNumber} in ${owner}/${repo}`)
throw err
}
}
// Search for a string in a file in code and return the array of paths to files that contain string
export async function getPathsWithMatchingStrings(
strArr,
org,
repo,
{ cache = true, forceDownload = false } = {}
) {
const perPage = 100
const paths = new Set()
for (const str of strArr) {
try {
const q = `q=${str}+in:file+repo:${org}/${repo}`
let currentPage = 1
let totalCount = 0
let currentCount = 0
do {
const data = await searchCode(q, perPage, currentPage, cache, forceDownload)
data.items.map((el) => paths.add(el.path))
totalCount = data.total_count
currentCount += data.items.length
currentPage++
} while (currentCount < totalCount)
} catch (err) {
console.log(`error searching for ${str} in ${org}/${repo}`)
throw err
}
}
return paths
}
async function searchCode(q, perPage, currentPage, cache = true, forceDownload = false) {
const cacheKey = `searchCode-${q}-${perPage}-${currentPage}`
const tempFilename = `/tmp/searchCode-${crypto
.createHash('md5')
.update(cacheKey)
.digest('hex')}.json`
if (!forceDownload && cache) {
try {
return JSON.parse(await fs.readFile(tempFilename, 'utf8'))
} catch (error) {
if (error.code !== 'ENOENT') {
throw error
}
console.log(`Cache miss on ${tempFilename} (${cacheKey})`)
}
}
try {
const { data } = await secondaryRateLimitRetry(github.rest.search.code, {
q,
per_page: perPage,
page: currentPage,
})
if (cache) {
await fs.writeFile(tempFilename, JSON.stringify(data))
console.log(`Wrote search results to ${tempFilename}`)
}
return data
} catch (err) {
console.log(`error searching for ${q} in code`)
throw err
}
}
async function secondaryRateLimitRetry(callable, args, maxAttempts = 10, sleepTime = 1000) {
try {
const response = await callable(args)
return response
} catch (err) {
// If you get a secondary rate limit error (403) you'll get a data
// response that includes:
//
// {
// documentation_url: 'https://docs.github.com/en/free-pro-team@latest/rest/overview/resources-in-the-rest-api#secondary-rate-limits',
// message: 'You have exceeded a secondary rate limit. Please wait a few minutes before you try again.'
// }
//
// Let's look for that an manually self-recurse, under certain conditions
const lookFor = 'You have exceeded a secondary rate limit.'
if (
err.status &&
err.status === 403 &&
err.response?.data?.message.includes(lookFor) &&
maxAttempts > 0
) {
console.warn(
`Got secondary rate limit blocked. Sleeping for ${
sleepTime / 1000
} seconds. (attempts left: ${maxAttempts})`
)
return new Promise((resolve) => {
setTimeout(() => {
resolve(secondaryRateLimitRetry(callable, args, maxAttempts - 1, sleepTime * 2))
}, sleepTime)
})
}
throw err
}
}