-
Notifications
You must be signed in to change notification settings - Fork 226
Expand file tree
/
Copy pathcode-search-api.ts
More file actions
70 lines (62 loc) · 2.16 KB
/
code-search-api.ts
File metadata and controls
70 lines (62 loc) · 2.16 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
import { retry } from "@octokit/plugin-retry";
import { throttling } from "@octokit/plugin-throttling";
import { Octokit } from "@octokit/rest";
import { Progress, CancellationToken } from "vscode";
import { showAndLogWarningMessage } from "../helpers";
import { Credentials } from "../common/authentication";
export async function getCodeSearchRepositories(
query: string,
progress: Progress<{
message?: string | undefined;
increment?: number | undefined;
}>,
token: CancellationToken,
credentials: Credentials,
): Promise<string[]> {
let nwos: string[] = [];
const octokit = await provideOctokitWithThrottling(credentials);
for await (const response of octokit.paginate.iterator(
octokit.rest.search.code,
{
q: query,
per_page: 100,
},
)) {
nwos.push(...response.data.map((item) => item.repository.full_name));
// calculate progress bar: 80% of the progress bar is used for the code search
const totalNumberOfRequests = Math.ceil(response.data.total_count / 100);
// Since we have a maximum of 1000 responses of the api, we can use a fixed increment whenever the totalNumberOfRequests would be greater than 10
const increment =
totalNumberOfRequests < 10 ? 80 / totalNumberOfRequests : 8;
progress.report({ increment });
if (token.isCancellationRequested) {
nwos = [];
break;
}
}
return [...new Set(nwos)];
}
async function provideOctokitWithThrottling(
credentials: Credentials,
): Promise<Octokit> {
const MyOctokit = Octokit.plugin(throttling);
const auth = await credentials.getAccessToken();
const octokit = new MyOctokit({
auth,
retry,
throttle: {
onRateLimit: (retryAfter: number, options: any): boolean => {
void showAndLogWarningMessage(
`Rate Limit detected for request ${options.method} ${options.url}. Retrying after ${retryAfter} seconds!`,
);
return true;
},
onSecondaryRateLimit: (_retryAfter: number, options: any): void => {
void showAndLogWarningMessage(
`Secondary Rate Limit detected for request ${options.method} ${options.url}`,
);
},
},
});
return octokit;
}