From 954bd5f563a278c04f40f0ec40bfbe27fc497afb Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 21 Nov 2024 11:58:48 -0800 Subject: [PATCH] python and typescript crawlers --- core/index.d.ts | 29 +++++ core/indexing/docs/suggestions/index.ts | 115 +++++++++++------- .../suggestions/packageCrawlers/Python.ts | 39 ++++-- .../docs/suggestions/packageCrawlers/TsJs.ts | 40 ++++-- 4 files changed, 159 insertions(+), 64 deletions(-) diff --git a/core/index.d.ts b/core/index.d.ts index 0646edc54..de1adb893 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1190,3 +1190,32 @@ export interface BrowserSerializedContinueConfig { experimental?: ExperimentalConfig; analytics?: AnalyticsConfig; } + +// DOCS SUGGESTIONS AND PACKAGE INFO +export interface FilePathAndName { + path: string; + name: string; +} +export type ParsedPackageInfo = { + language: string; + name: string; + version: string; + packageFile: FilePathAndName; +}; + +export type PackageDetails = { + docsLink?: string; + title?: string; + description?: string; +}; + +export type PackageDetailsSuccess = PackageDetails & { + docsLink: string; +}; + +export type PackageDocsResult = { + packageInfo: ParsedPackageInfo; +} & ( + | { error: string; details?: never } + | { details: PackageDetailsSuccess; error?: never } +); diff --git a/core/indexing/docs/suggestions/index.ts b/core/indexing/docs/suggestions/index.ts index d3d68aca2..5699cd761 100644 --- a/core/indexing/docs/suggestions/index.ts +++ b/core/indexing/docs/suggestions/index.ts @@ -1,12 +1,12 @@ -// write me an interface PackageCrawler that contains: -// 1. property `language` to store a given language like "python" or "typescript" -// 2. has a method `getPackageFiles` which takes a list of file names and decides which ones match package/dependency files (e.g. package.json for typescript, requirements.txt for python, etc) -// 3. has a method `parsePackageFile` which returns a list of package name and version from a relevant package file, in a standardized format like semver -// 4. has a method `getDocumentationLink` to check for documentation link for a given package (e.g. GET `https://registry.npmjs.org/` and find docs field for typescript, documentation link in the package metadata for PyPi, etc.) -// Then, write typescript classes to implement this typescript interface for the languages "python" and "typescript" - -import { IDE } from "../../.."; +import { + FilePathAndName, + IDE, + PackageDetails, + PackageDocsResult, + ParsedPackageInfo, +} from "../../.."; import { walkDir } from "../../walkDir"; + import { PythonPackageCrawler } from "./packageCrawlers/Python"; import { TypeScriptPackageCrawler } from "./packageCrawlers/TsJs"; @@ -14,19 +14,14 @@ const PACKAGE_CRAWLERS = [TypeScriptPackageCrawler, PythonPackageCrawler]; export interface PackageCrawler { language: string; - getPackageFiles(fileNames: string[]): string[]; - parsePackageFile(fileContent: string, filePath: string): PackageInfo[]; - getDocumentationLink(packageName: string): Promise; + getPackageFiles(files: FilePathAndName[]): FilePathAndName[]; + parsePackageFile( + file: FilePathAndName, + contents: string, + ): ParsedPackageInfo[]; + getPackageDetails(packageInfo: ParsedPackageInfo): Promise; } -export type PackageInfo = { - name: string; - version: string; - foundInFilepath: string; -}; -export type PackageDocsResult = PackageInfo & - ({ error: string; link?: never } | { link: string; error?: never }); - export async function getAllSuggestedDocs(ide: IDE) { const workspaceDirs = await ide.getWorkspaceDirs(); const results = await Promise.all( @@ -35,16 +30,26 @@ export async function getAllSuggestedDocs(ide: IDE) { }), ); const allPaths = results.flat(); // TODO only get files, not dirs. Not critical for now - const allFiles = allPaths.map((path) => path.split("/").pop()!); - const packageFilesByLanguage: Record = {}; + const allFiles = allPaths.map((path) => ({ + path, + name: path.split(/[\\/]/).pop()!, + })); + + // Build map of language -> package files + const packageFilesByLanguage: Record = {}; for (const Crawler of PACKAGE_CRAWLERS) { const crawler = new Crawler(); const packageFilePaths = crawler.getPackageFiles(allFiles); packageFilesByLanguage[crawler.language] = packageFilePaths; } + // Get file contents for all unique package files const uniqueFilePaths = Array.from( - new Set(Object.values(packageFilesByLanguage).flat()), + new Set( + Object.values(packageFilesByLanguage).flatMap((files) => + files.map((file) => file.path), + ), + ), ); const fileContentsArray = await Promise.all( uniqueFilePaths.map(async (path) => { @@ -56,40 +61,68 @@ export async function getAllSuggestedDocs(ide: IDE) { fileContentsArray.map(({ path, contents }) => [path, contents]), ); - const packagesByLanguage: Record = {}; + // Parse package files and build map of language -> packages + const packagesByLanguage: Record = {}; PACKAGE_CRAWLERS.forEach((Crawler) => { const crawler = new Crawler(); const packageFiles = packageFilesByLanguage[crawler.language]; packageFiles.forEach((file) => { - const contents = fileContents.get(file); + const contents = fileContents.get(file.path); if (!contents) { return; } - const packages = crawler.parsePackageFile(contents, file); + const packages = crawler.parsePackageFile(file, contents); if (!packagesByLanguage[crawler.language]) { packagesByLanguage[crawler.language] = []; } packagesByLanguage[crawler.language].push(...packages); }); }); - console.log(packagesByLanguage); - // const allPackages = await Promise.all( - // PACKAGE_CRAWLERS.map(async (Crawler) => { - // const crawler = new Crawler(); - // const packageInfos = uniqueFileContents - // .filter(({ path }) => languageToFilePaths[crawler.language].includes(path)) - // .map(({ path, contents }) => crawler.parsePackageFile(contents, path)) - // .flat(); - // return packageInfos; - // }) - // ); - // for (const Crawler of PACKAGE_CRAWLERS) { - // const crawler = new Crawler(); - // const packages = crawler.parsePackageFile() - // languageToFilePaths[crawler.language] = packageFilePaths; - // } + + // Get documentation links for all packages + const docsByLanguage: Record = {}; + await Promise.all( + PACKAGE_CRAWLERS.map(async (Crawler) => { + const crawler = new Crawler(); + const packages = packagesByLanguage[crawler.language]; + docsByLanguage[crawler.language] = await Promise.all( + packages.map(async (packageInfo) => { + try { + const details = await crawler.getPackageDetails(packageInfo); + if (!details.docsLink) { + return { + packageInfo, + error: `No documentation link found for ${packageInfo.name}`, + }; + } + return { + packageInfo, + details: { + ...details, + docsLink: details.docsLink, + }, + }; + } catch (error) { + return { + packageInfo, + error: `Error getting package details for ${name}`, + }; + } + }), + ); + }), + ); + + return docsByLanguage; } +// write me an interface PackageCrawler that contains: +// 1. property `language` to store a given language like "python" or "typescript" +// 2. has a method `getPackageFiles` which takes a list of file names and decides which ones match package/dependency files (e.g. package.json for typescript, requirements.txt for python, etc) +// 3. has a method `parsePackageFile` which returns a list of package name and version from a relevant package file, in a standardized format like semver +// 4. has a method `getDocumentationLink` to check for documentation link for a given package (e.g. GET `https://registry.npmjs.org/` and find docs field for typescript, documentation link in the package metadata for PyPi, etc.) +// Then, write typescript classes to implement this typescript interface for the languages "python" and "typescript" + // I want to present the user with a list of dependencies and allow them to select which ones to index (embed) documentation for. // In order to prevent duplicate file reads, the process will be like this: // 1. take in a list of filepaths called `filepaths` diff --git a/core/indexing/docs/suggestions/packageCrawlers/Python.ts b/core/indexing/docs/suggestions/packageCrawlers/Python.ts index ac0699766..233e44428 100644 --- a/core/indexing/docs/suggestions/packageCrawlers/Python.ts +++ b/core/indexing/docs/suggestions/packageCrawlers/Python.ts @@ -1,33 +1,50 @@ -import { PackageCrawler, PackageDocsResult, PackageInfo } from ".."; +import { PackageCrawler } from ".."; +import { + FilePathAndName, + PackageDetails, + ParsedPackageInfo, +} from "../../../.."; export class PythonPackageCrawler implements PackageCrawler { language = "python"; - getPackageFiles(fileNames: string[]): string[] { + getPackageFiles(files: FilePathAndName[]): FilePathAndName[] { // For Python, we typically look for files like requirements.txt or Pipfile - return fileNames.filter( - (fileName) => fileName === "requirements.txt" || fileName === "Pipfile", + return files.filter( + (file) => file.name === "requirements.txt" || file.name === "Pipfile", ); } - parsePackageFile(fileContent: string, filepath: string): PackageInfo[] { + parsePackageFile( + file: FilePathAndName, + contents: string, + ): ParsedPackageInfo[] { // Assume the fileContent is a string from a requirements.txt formatted file - return fileContent + return contents .split("\n") .map((line) => { const [name, version] = line.split("=="); - return { name, version, foundInFilepath: filepath }; + return { name, version, packageFile: file, language: this.language }; }) .filter((pkg) => pkg.name && pkg.version); } - async getDocumentationLink(packageName: string): Promise { + async getPackageDetails( + packageInfo: ParsedPackageInfo, + ): Promise { // Fetch metadata from PyPI to find the documentation link - const response = await fetch(`https://pypi.org/pypi/${packageName}/json`); + + const response = await fetch( + `https://pypi.org/pypi/${packageInfo.name}/json`, + ); if (!response.ok) { - throw new Error(`Could not fetch data for package ${packageName}`); + throw new Error(`Could not fetch data for package ${packageInfo.name}`); } const data = await response.json(); - return data.info.project_urls?.Documentation; + return { + docsLink: data.info.project_urls?.Documentation as string | undefined, + // title: data.info.name, + // description: data.info.summary as string | undefined, + }; } } diff --git a/core/indexing/docs/suggestions/packageCrawlers/TsJs.ts b/core/indexing/docs/suggestions/packageCrawlers/TsJs.ts index fb073e2a1..107d9ac2a 100644 --- a/core/indexing/docs/suggestions/packageCrawlers/TsJs.ts +++ b/core/indexing/docs/suggestions/packageCrawlers/TsJs.ts @@ -1,33 +1,49 @@ -import { PackageCrawler, PackageDocsResult, PackageInfo } from ".."; +import { PackageCrawler } from ".."; +import { + FilePathAndName, + PackageDetails, + ParsedPackageInfo, +} from "../../../.."; export class TypeScriptPackageCrawler implements PackageCrawler { - language = "typescript"; + language = "js-ts"; - getPackageFiles(fileNames: string[]): string[] { - // For TypeScript, we look for package.json file - return fileNames.filter((fileName) => fileName === "package.json"); + getPackageFiles(files: FilePathAndName[]): FilePathAndName[] { + // For Javascript/TypeScript, we look for package.json file + return files.filter((file) => file.name === "package.json"); } - parsePackageFile(fileContent: string, filepath: string): PackageInfo[] { + parsePackageFile( + file: FilePathAndName, + contents: string, + ): ParsedPackageInfo[] { // Parse the package.json content - const jsonData = JSON.parse(fileContent) as Record; + const jsonData = JSON.parse(contents) as Record; const dependencies = Object.entries(jsonData.dependencies || {}).concat( Object.entries(jsonData.devDependencies || {}), ); return dependencies.map(([name, version]) => ({ name, version, - foundInFilepath: filepath, + packageFile: file, + language: this.language, })); } - async getDocumentationLink(packageName: string): Promise { + async getPackageDetails( + packageInfo: ParsedPackageInfo, + ): Promise { + const { name } = packageInfo; // Fetch metadata from the NPM registry to find the documentation link - const response = await fetch(`https://registry.npmjs.org/${packageName}`); + const response = await fetch(`https://registry.npmjs.org/${name}`); if (!response.ok) { - throw new Error(`Could not fetch data for package ${packageName}`); + throw new Error(`Could not fetch data for package ${name}`); } const data = await response.json(); - return data.homepage; + return { + docsLink: data.homepage as string | undefined, + // title: data.name, + // description: data.description as string | undefined, + }; } }