Skip to content

Commit f51fc39

Browse files
committed
initial refactor using diffUtils
1 parent 6aafc4d commit f51fc39

File tree

6 files changed

+28
-69
lines changed

6 files changed

+28
-69
lines changed

packages/amazonq/.vscode/launch.json

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,9 @@
1313
"args": ["--extensionDevelopmentPath=${workspaceFolder}", "--disable-extensions"],
1414
"env": {
1515
"SSMDOCUMENT_LANGUAGESERVER_PORT": "6010",
16-
"WEBPACK_DEVELOPER_SERVER": "http://localhost:8080",
17-
"__AMAZONQLSP_PATH": "${workspaceFolder}/../../../language-servers/app/aws-lsp-codewhisperer-runtimes/out/token-standalone.js",
18-
"__AMAZONQLSP_UI": "${workspaceFolder}/../../../language-servers/chat-client/build/amazonq-ui.js"
16+
"WEBPACK_DEVELOPER_SERVER": "http://localhost:8080"
17+
// "__AMAZONQLSP_PATH": "${workspaceFolder}/../../../language-servers/app/aws-lsp-codewhisperer-runtimes/out/token-standalone.js",
18+
// "__AMAZONQLSP_UI": "${workspaceFolder}/../../../language-servers/chat-client/build/amazonq-ui.js"
1919
},
2020
"envFile": "${workspaceFolder}/.local.env",
2121
"outFiles": ["${workspaceFolder}/dist/**/*.js", "${workspaceFolder}/../core/dist/**/*.js"],

packages/amazonq/src/app/inline/EditRendering/diffUtils.ts

Lines changed: 5 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
33
* SPDX-License-Identifier: Apache-2.0
44
*/
5+
// TODO: deprecate this file in favor of core/shared/utils/diffUtils
56
import { applyPatch } from 'diff'
67

78
export type LineDiff =
@@ -18,15 +19,15 @@ export type LineDiff =
1819
export function applyUnifiedDiff(
1920
docText: string,
2021
unifiedDiff: string
21-
): { newCode: string; addedCharacterCount: number; deletedCharacterCount: number } {
22+
): { appliedCode: string; addedCharacterCount: number; deletedCharacterCount: number } {
2223
try {
2324
const { addedCharacterCount, deletedCharacterCount } = getAddedAndDeletedCharCount(unifiedDiff)
2425
// First try the standard diff package
2526
try {
2627
const result = applyPatch(docText, unifiedDiff)
2728
if (result !== false) {
2829
return {
29-
newCode: result,
30+
appliedCode: result,
3031
addedCharacterCount: addedCharacterCount,
3132
deletedCharacterCount: deletedCharacterCount,
3233
}
@@ -94,56 +95,19 @@ export function applyUnifiedDiff(
9495
result = result.replace(textToReplace, newText)
9596
}
9697
return {
97-
newCode: result,
98+
appliedCode: result,
9899
addedCharacterCount: addedCharacterCount,
99100
deletedCharacterCount: deletedCharacterCount,
100101
}
101102
} catch (error) {
102103
return {
103-
newCode: docText, // Return original text if all methods fail
104+
appliedCode: docText, // Return original text if all methods fail
104105
addedCharacterCount: 0,
105106
deletedCharacterCount: 0,
106107
}
107108
}
108109
}
109110

110-
export function parseUnifiedDiff(diff: string): LineDiff[] {
111-
const lines = diff.split('\n')
112-
const result: LineDiff[] = []
113-
let i = 0
114-
while (i < lines.length) {
115-
const line = lines[i]
116-
117-
if (line.startsWith('-')) {
118-
const removedLine = line.slice(1)
119-
const next = lines[i + 1]
120-
121-
if (next && next.startsWith('+')) {
122-
const addedLine = next.slice(1)
123-
// const similarity = jaroWinkler(removedLine, addedLine)
124-
const similarity = 0
125-
126-
if (similarity > 0.5) {
127-
result.push({ type: 'modified', before: removedLine, after: addedLine })
128-
i += 2
129-
continue
130-
}
131-
}
132-
133-
result.push({ type: 'removed', content: removedLine })
134-
i++
135-
} else if (line.startsWith('+')) {
136-
result.push({ type: 'added', content: line.slice(1) })
137-
i++
138-
} else {
139-
// Ignore context lines and hunk headers
140-
i++
141-
}
142-
}
143-
144-
return result
145-
}
146-
147111
export function getAddedAndDeletedCharCount(diff: string): {
148112
addedCharacterCount: number
149113
deletedCharacterCount: number

packages/amazonq/src/app/inline/EditRendering/imageRenderer.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,10 +22,10 @@ export async function showEdits(
2222
}
2323
try {
2424
const svgGenerationService = new SvgGenerationService()
25-
// Generate your SVG image with the file contents ?
26-
const originalCode = editor.document.getText()
25+
// Generate your SVG image with the file contents
26+
const currentFile = editor.document.uri.fsPath
2727
const { svgImage, startLine, newCode, addedCharacterCount, deletedCharacterCount } =
28-
await svgGenerationService.generateDiffSvg(originalCode, item.insertText as string)
28+
await svgGenerationService.generateDiffSvg(currentFile, item.insertText as string)
2929

3030
if (svgImage) {
3131
// display the SVG image

packages/amazonq/src/app/inline/EditRendering/svgGenerator.ts

Lines changed: 12 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import { diffLines } from 'diff'
77
import * as vscode from 'vscode'
88
import { applyUnifiedDiff } from './diffUtils'
99
import { getLogger, isWeb } from 'aws-core-vscode/shared'
10+
import { diffUtilities } from 'aws-core-vscode/shared'
1011

1112
const logger = getLogger('nextEditPrediction')
1213

@@ -19,7 +20,7 @@ export class SvgGenerationService {
1920
* @param offSet The margin to add to the left of the image
2021
*/
2122
public async generateDiffSvg(
22-
originalCode: string,
23+
filePath: string,
2324
udiff: string
2425
): Promise<{
2526
svgImage: vscode.Uri
@@ -28,12 +29,15 @@ export class SvgGenerationService {
2829
addedCharacterCount: number
2930
deletedCharacterCount: number
3031
}> {
31-
const { newCode, addedCharacterCount, deletedCharacterCount } = applyUnifiedDiff(originalCode, udiff)
32+
const textDoc = await vscode.workspace.openTextDocument(filePath)
33+
const originalCode = textDoc.getText()
34+
const { appliedCode, addedCharacterCount, deletedCharacterCount } = applyUnifiedDiff(originalCode, udiff)
35+
const newCode = await diffUtilities.getPatchedCode(filePath, udiff)
36+
logger.info(`testing patch udiff: ${newCode}`)
37+
logger.info(`old patch udiff: ${appliedCode}`)
3238

33-
// Abort SVG generation if we're in web mode
3439
if (isWeb() || !process.versions?.node) {
3540
logger.info('Skipping SVG generation in web mode')
36-
// Return a placeholder URI and the new code
3741
return {
3842
svgImage: vscode.Uri.parse(
3943
'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMCIgaGVpZ2h0PSIxMCI+PC9zdmc+'
@@ -44,21 +48,11 @@ export class SvgGenerationService {
4448
deletedCharacterCount: 0,
4549
}
4650
}
47-
// Import required libraries - make sure we load svgdom before svg.js
48-
// These need to be imported in sequence, not in parallel, to avoid initialization issues
4951
const { createSVGWindow } = await import('svgdom')
5052

51-
// Only import svg.js after svgdom is fully initialized
52-
let svgjs
53-
let SVG, registerWindow
54-
try {
55-
svgjs = await import('@svgdotjs/svg.js')
56-
SVG = svgjs.SVG
57-
registerWindow = svgjs.registerWindow
58-
} catch (error) {
59-
logger.error(`Failed to import @svgdotjs/svg.js: ${error}`)
60-
throw error
61-
}
53+
const svgjs = await import('@svgdotjs/svg.js')
54+
const SVG = svgjs.SVG
55+
const registerWindow = svgjs.registerWindow
6256

6357
// Get editor theme info
6458
const currentTheme = this.getEditorTheme()
@@ -93,9 +87,9 @@ export class SvgGenerationService {
9387
const foreignObject = draw.foreignObject(width + offset, height)
9488
foreignObject.node.innerHTML = htmlContent.trim()
9589

96-
// Convert SVG to data URI
9790
const svgData = draw.svg()
9891
const svgResult = `data:image/svg+xml;base64,${Buffer.from(svgData).toString('base64')}`
92+
// const adjustedStartLine = editStartLine > 0 ? editStartLine - 1 : editStartLine
9993

10094
return {
10195
svgImage: vscode.Uri.parse(svgResult),

packages/amazonq/test/unit/app/inline/EditRendering/diffUtils.test.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -27,10 +27,10 @@ describe('diffUtils', function () {
2727
const expectedResult = 'function add(a, b) {\n // Add two numbers\n return a + b; // Return the sum\n}'
2828

2929
// Apply the diff
30-
const { newCode } = applyUnifiedDiff(originalCode, unifiedDiff)
30+
const { appliedCode } = applyUnifiedDiff(originalCode, unifiedDiff)
3131

3232
// Verify the result
33-
assert.strictEqual(newCode, expectedResult)
33+
assert.strictEqual(appliedCode, expectedResult)
3434
})
3535
})
3636

@@ -96,10 +96,10 @@ describe('diffUtils', function () {
9696
'}'
9797

9898
// Apply the diff
99-
const { newCode } = applyUnifiedDiff(originalCode, unifiedDiff)
99+
const { appliedCode } = applyUnifiedDiff(originalCode, unifiedDiff)
100100

101101
// Verify the result
102-
assert.strictEqual(newCode, expectedResult)
102+
assert.strictEqual(appliedCode, expectedResult)
103103
})
104104
})
105105
})

packages/core/src/shared/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ export * from './utilities/pathUtils'
5151
export * from './utilities/zipStream'
5252
export * as editorUtilities from './utilities/editorUtilities'
5353
export * as functionUtilities from './utilities/functionUtils'
54+
export * as diffUtilities from './utilities/diffUtils'
5455
export * as vscodeUtilities from './utilities/vsCodeUtils'
5556
export * from './errors'
5657
export * as messages from './utilities/messages'

0 commit comments

Comments
 (0)