| 1 | import { DiffLine, ILLM } from "../.."; |
| 2 | import { generateLines } from "../../diff/util"; |
| 3 | import { supportedLanguages } from "../../util/treeSitter"; |
| 4 | import { getUriFileExtension } from "../../util/uri"; |
| 5 | import { deterministicApplyLazyEdit } from "./deterministic"; |
| 6 | import { streamLazyApply } from "./streamLazyApply"; |
| 7 | import { applyUnifiedDiff, isUnifiedDiffFormat } from "./unifiedDiffApply"; |
| 8 | |
| 9 | function canUseInstantApply(filename: string) { |
| 10 | const fileExtension = getUriFileExtension(filename); |
| 11 | return supportedLanguages[fileExtension] !== undefined; |
| 12 | } |
| 13 | |
| 14 | export async function applyCodeBlock( |
| 15 | oldFile: string, |
| 16 | newLazyFile: string, |
| 17 | filename: string, |
| 18 | llm: ILLM, |
| 19 | ): Promise<{ |
| 20 | isInstantApply: boolean; |
| 21 | diffLinesGenerator: AsyncGenerator<DiffLine>; |
| 22 | }> { |
| 23 | if (canUseInstantApply(filename)) { |
| 24 | const diffLines = await deterministicApplyLazyEdit({ |
| 25 | oldFile, |
| 26 | newLazyFile, |
| 27 | filename, |
| 28 | onlyFullFileRewrite: true, |
| 29 | }); |
| 30 | |
| 31 | if (diffLines !== undefined) { |
| 32 | return { |
| 33 | isInstantApply: true, |
| 34 | diffLinesGenerator: generateLines(diffLines!), |
| 35 | }; |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | // If the code block is a diff |
| 40 | if (isUnifiedDiffFormat(newLazyFile)) { |
| 41 | try { |
| 42 | const diffLines = applyUnifiedDiff(oldFile, newLazyFile); |
| 43 | return { |
| 44 | isInstantApply: true, |
| 45 | diffLinesGenerator: generateLines(diffLines!), |
| 46 | }; |
| 47 | } catch (e) { |
| 48 | console.error("Failed to apply unified diff", e); |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | return { |
| 53 | isInstantApply: false, |
| 54 | diffLinesGenerator: streamLazyApply(oldFile, filename, newLazyFile, llm), |
| 55 | }; |
| 56 | } |