diff --git a/src/app.ts b/src/app.ts index 450ae71..480a636 100644 --- a/src/app.ts +++ b/src/app.ts @@ -1,6 +1,7 @@ import { Octokit } from "@octokit/rest"; import { createNodeMiddleware } from "@octokit/webhooks"; -import { WebhookEventMap } from "@octokit/webhooks-definitions/schema"; + +import { WebhookEventMap } from "@octokit/webhooks-types"; import * as http from "http"; import { App } from "octokit"; import { Review } from "./constants"; diff --git a/src/context/language/python-parser.ts b/src/context/language/python-parser.ts index 845e90b..49517f4 100644 --- a/src/context/language/python-parser.ts +++ b/src/context/language/python-parser.ts @@ -1,15 +1,64 @@ import { AbstractParser, EnclosingContext } from "../../constants"; +import Parser from "tree-sitter"; +import Python from "tree-sitter-python"; + +const parser = new Parser(); +parser.setLanguage(Python); + +function updateLargestContext( + node: Parser.SyntaxNode, + lineStart: number, + lineEnd: number, + currentLargest: { size: number; context: Parser.SyntaxNode | null } +) { + const { startPosition, endPosition } = node; + + if (startPosition.row <= lineStart && lineEnd <= endPosition.row) { + const nodeSize = endPosition.row - startPosition.row; + if (nodeSize > currentLargest.size) { + currentLargest.size = nodeSize; + currentLargest.context = node; + } + } +} + export class PythonParser implements AbstractParser { findEnclosingContext( file: string, lineStart: number, lineEnd: number ): EnclosingContext { - // TODO: Implement this method for Python - return null; + let largestContext = { size: 0, context: null as Parser.SyntaxNode | null }; + + const ast = parser.parse(file); + const rootNode = ast.rootNode; + + function traverseNode(node: Parser.SyntaxNode) { + if (node.type === "function_definition") { + updateLargestContext(node, lineStart, lineEnd, largestContext); + } + + for (let i = 0; i < node.childCount; i++) { + const childNode = node.child(i); + if (childNode?.childCount > 0) { + traverseNode(childNode); + } + } + } + + traverseNode(rootNode); + + return { + enclosingContext: largestContext.context, + } as EnclosingContext; } + dryRun(file: string): { valid: boolean; error: string } { - // TODO: Implement this method for Python - return { valid: false, error: "Not implemented yet" }; + try { + parser.parse(file); + return { valid: true, error: "" }; + } catch (error) { + return { valid: false, error: error.toString() }; + } } } diff --git a/src/context/review.ts b/src/context/review.ts index 7d44aa1..8a5c704 100644 --- a/src/context/review.ts +++ b/src/context/review.ts @@ -1,8 +1,10 @@ import { AbstractParser, + EnclosingContext, PRFile, PatchInfo, getParserForExtension, + isBabelNode, } from "../constants"; import * as diff from "diff"; import { JavascriptParser } from "./language/javascript-parser";