Elffuss BraidHub

kikocis/continue public

main · 2.5 KiBRawPermalink
1import { URL } from "node:url";
2
3import { Octokit } from "@octokit/rest";
4
5import { PageData } from "./DocsCrawler";
6
7class GitHubCrawler {
8 private readonly markdownRegex = new RegExp(/\.(md|mdx)$/);
9 private octokit: Octokit;
10 private FILES_TO_SKIP = [/TEMPLATE\.md$/, /template\.md$/];
11
12 constructor(
13 private readonly startUrl: URL,
14 private readonly githubToken: string | undefined,
15 ) {
16 this.octokit = new Octokit({ auth: this.githubToken });
17 }
18
19 async *crawl(): AsyncGenerator<PageData> {
20 console.debug(
21 `[${
22 (this.constructor as any).name
23 }] Crawling GitHub repo: ${this.startUrl.toString()}`,
24 );
25 const [_, owner, repo] = this.startUrl.pathname.split("/");
26 const branch = await this.getGithubRepoDefaultBranch(owner, repo);
27
28 const paths = await this.getGitHubRepoPaths(owner, repo, branch);
29
30 for await (const path of paths) {
31 if (this.FILES_TO_SKIP.some((skip) => skip.test(path))) {
32 continue;
33 }
34 const content = await this.getGithubRepoFileContent(path, owner, repo);
35
36 const fullUrl = new URL(this.startUrl.toString());
37 fullUrl.pathname += `/tree/${branch}/${path}`;
38 yield { path, url: fullUrl.toString(), content: content ?? "" };
39 }
40 }
41
42 private async getGithubRepoDefaultBranch(
43 owner: string,
44 repo: string,
45 ): Promise<string> {
46 const repoInfo = await this.octokit.repos.get({ owner, repo });
47 return repoInfo.data.default_branch;
48 }
49
50 private async getGitHubRepoPaths(
51 owner: string,
52 repo: string,
53 branch: string,
54 ) {
55 const tree = await this.octokit.request(
56 "GET /repos/{owner}/{repo}/git/trees/{tree_sha}",
57 {
58 owner,
59 repo,
60 tree_sha: branch,
61 headers: { "X-GitHub-Api-Version": "2022-11-28" },
62 recursive: "true",
63 },
64 );
65
66 return tree.data.tree
67 .filter(
68 (file: any) =>
69 file.type === "blob" && this.markdownRegex.test(file.path ?? ""),
70 )
71 .map((file: any) => file.path);
72 }
73
74 private async getGithubRepoFileContent(
75 path: string,
76 owner: string,
77 repo: string,
78 ) {
79 try {
80 const response = await this.octokit.repos.getContent({
81 owner,
82 repo,
83 path,
84 headers: { Accept: "application/vnd.github.raw+json" },
85 });
86 return response.data as unknown as string;
87 } catch (error) {
88 console.debug("Error fetching file contents:", error);
89 return null;
90 }
91 }
92}
93
94export default GitHubCrawler;