💄 small improvements to GitHub docs indexing

This commit is contained in:
Nate Sesti 2024-01-21 20:45:39 -08:00
parent cfd5426e12
commit b619f9a6cf
8 changed files with 127 additions and 15 deletions

View file

@ -28,17 +28,25 @@ class DocsContextProvider extends BaseContextProvider {
const chunks = await retrieveDocs(
query,
vector,
this.options?.nRetrieve || 15
this.options?.nRetrieve || 8
);
console.log(chunks);
return [
...chunks.map((chunk) => ({
name: chunk.otherMetadata?.title || chunk.filepath,
description: new URL(chunk.filepath, query).toString(),
content: chunk.content,
})),
...chunks
.map((chunk) => ({
name: chunk.filepath
.split("/")
.slice(1)
.join("/")
.split("/tree/main/")
.slice(1)
.join("/"), // chunk.otherMetadata?.title || chunk.filepath,
description: new URL(chunk.filepath, query).toString(),
content: chunk.content,
}))
.reverse(),
{
name: "Instructions",
description: "Instructions",

View file

@ -10,8 +10,8 @@ function cleanFragment(fragment: string | undefined): string | undefined {
// Remove leading and trailing whitespaces
fragment = fragment.trim();
// If there's a (, remove everything after it
const parenIndex = fragment.indexOf("(");
// If there's a ](, which would mean a link, remove everything after it
const parenIndex = fragment.indexOf("](");
if (parenIndex !== -1) {
fragment = fragment.slice(0, parenIndex);
}

View file

@ -1,3 +1,4 @@
import { Octokit } from "@octokit/rest";
import cheerio from "cheerio";
import fetch from "node-fetch";
// const HCCrawler = require("headless-chrome-crawler");
@ -17,7 +18,9 @@ const IGNORE_PATHS_ENDING_IN = [
"changelog.html",
];
function shouldFilterPath(pathname: string): boolean {
const GITHUB_PATHS_TO_TRAVERSE = ["/blob/", "/tree/"];
function shouldFilterPath(pathname: string, baseUrl: URL): boolean {
if (pathname.includes("#")) {
pathname = pathname.slice(0, pathname.indexOf("#"));
}
@ -25,13 +28,23 @@ function shouldFilterPath(pathname: string): boolean {
if (pathname.endsWith("/")) {
pathname = pathname.slice(0, -1);
}
if (baseUrl.hostname === "github.com") {
if (
pathname.split("/").length > 3 &&
!GITHUB_PATHS_TO_TRAVERSE.some((path) => pathname.includes(path))
)
return true;
return false;
}
if (IGNORE_PATHS_ENDING_IN.some((path) => pathname.endsWith(path)))
return true;
return false;
}
async function crawlLinks(path: string, baseUrl: URL, visited: Set<string>) {
if (visited.has(path) || shouldFilterPath(path)) {
if (visited.has(path) || shouldFilterPath(path, baseUrl)) {
return;
}
visited.add(path);
@ -62,7 +75,53 @@ async function crawlLinks(path: string, baseUrl: URL, visited: Set<string>) {
);
}
async function crawlGithubRepo(baseUrl: URL) {
const octokit = new Octokit({
auth: undefined,
});
const [_, owner, repo] = baseUrl.pathname.split("/");
let dirContentsConfig = {
owner: owner,
repo: repo,
};
const tree = await octokit.request(
"GET /repos/{owner}/{repo}/git/trees/{tree_sha}",
{
owner,
repo,
tree_sha: "main",
headers: {
"X-GitHub-Api-Version": "2022-11-28",
},
recursive: "true",
}
);
const paths = tree.data.tree
.filter(
(file) => file.type === "blob" && file.path?.endsWith(".md")
// ||
// file.path?.endsWith(".rst") ||
// file.path?.split("/").includes("documentation") ||
// file.path?.split("/").includes("docs") ||
// file.path?.split("/").includes("doc") ||
// file.path?.split("/").includes("examples") ||
// file.path?.split("/").includes("example")
)
.map((file) => baseUrl.pathname + "/tree/main/" + file.path);
return paths;
}
export async function crawlSubpages(baseUrl: URL) {
// Special case for GitHub repos
if (baseUrl.hostname === "github.com") {
return crawlGithubRepo(baseUrl);
}
// First, check if the parent of the path redirects to the same page
const parentUrl = new URL(baseUrl);
parentUrl.pathname = parentUrl.pathname.split("/").slice(0, -1).join("/");

View file

@ -53,7 +53,7 @@ export async function* indexDocs(
for (let i = 0; i < subpaths.length; i++) {
const subpath = subpaths[i];
yield {
progress: 1 / (subpaths.length + 1),
progress: 100 / (subpaths.length + 1),
desc: `${subpath}`,
};

View file

@ -1,3 +1,4 @@
import { Octokit } from "@octokit/rest";
import { NodeHtmlMarkdown, PostProcessResult } from "node-html-markdown";
const nhm = new NodeHtmlMarkdown(
@ -21,10 +22,42 @@ const nhm = new NodeHtmlMarkdown(
const STRIP_BEFORE = ["\n# "];
const STRIP_AFTER_AND_INCLUDING = ["Was this page helpful?"];
const octokit = new Octokit({
auth: undefined,
});
async function retrieveGitHubBlob(url: URL): Promise<string | undefined> {
const [_, owner, repo, _tree, _main, ...path] = url.pathname.split("/");
const response = await octokit.repos.getContent({
owner,
repo,
path: path.join("/"),
});
if (response.status !== 200) {
return undefined;
}
const content = Buffer.from(
(response.data as any).content || "",
"base64"
).toString();
const fileExtension = url.pathname.split(".").slice(-1)[0];
if (fileExtension === "md") {
return content;
}
return `\`\`\`${fileExtension} title=${path.join("/")}\n${content}\n\`\`\``;
}
export async function convertURLToMarkdown(
url: URL
): Promise<string | undefined> {
try {
if (url.hostname === "github.com") {
return await retrieveGitHubBlob(url);
}
const response = await fetch(url);
if (!response.ok) {
@ -55,7 +88,7 @@ export async function convertURLToMarkdown(
return markdown;
} catch (err) {
console.error(err);
throw new Error("Error converting URL to markdown");
console.error("Error converting URL to markdown", err);
return undefined;
}
}

View file

@ -26,7 +26,7 @@ const FileIcon = ({ filename, height, width }) => {
return (
<div
dangerouslySetInnerHTML={{ __html: sanitizedSVG }}
style={{ width: width, height: height, fill: color }}
style={{ width: width, height: height, fill: color, flexShrink: 0 }}
/>
);
};

View file

@ -109,7 +109,13 @@ const ContextItemsPeek = (props: ContextItemsPeekProps) => {
}}
>
<FileIcon
filename={contextItem.description.split(" ").shift()}
filename={
contextItem.description
.split(" ")
.shift()
.split("#")
.shift() || ""
}
height="1.6em"
width="1.6em"
></FileIcon>

View file

@ -74,6 +74,12 @@ function DropdownIcon(props: {
className?: string;
type: ComboBoxItemType;
}) {
if (props.type === "action") {
return (
<PlusIcon className={props.className} height="1.2em" width="1.2em" />
);
}
const Icon = ICONS_FOR_DROPDOWN[props.provider];
const iconClass = `${props.className} flex-shrink-0`;
if (!Icon) {