Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 43 additions & 1 deletion sdk/src/__tests__/apply-patch.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { describe, expect, test } from 'bun:test'
import * as fs from 'node:fs/promises'
import os from 'node:os'
import path from 'node:path'

import { createMockFs } from '@codebuff/common/testing/mocks/filesystem'
import { describe, expect, test } from 'bun:test'

import { applyPatchTool } from '../tools/apply-patch'

Expand Down Expand Up @@ -394,6 +397,45 @@ describe('applyPatchTool', () => {
expect(created).toBe('hello\nworld')
})

test('create_file preserves added lines that resemble diff headers', async () => {
const cwd = await fs.mkdtemp(path.join(os.tmpdir(), 'apply-patch-plus-'))
const content = '++counter\n++ counter\n++other\nconsole.log(counter)'
const addedLines = content.split('\n').map((line) => `+${line}`)

try {
for (const [name, headers] of [
['bare', []],
['unified', ['--- /dev/null', '+++ b/counter.ts', '@@ -0,0 +1,4 @@']],
] as const) {
const file = `${name}.ts`
const result = await applyPatchTool({
parameters: {
operation: {
type: 'create_file',
path: file,
diff: [...headers, ...addedLines].join('\n'),
},
},
cwd,
fs,
})

expect(result).toEqual([
{
type: 'json',
value: {
message: 'Applied 1 patch operation.',
applied: [{ file, action: 'add' }],
},
},
])
expect(await fs.readFile(path.join(cwd, file), 'utf-8')).toBe(content)
}
} finally {
await fs.rm(cwd, { recursive: true, force: true })
}
})

test('create_file errors for non-plus content lines', async () => {
const fs = createMockFs()

Expand Down
12 changes: 6 additions & 6 deletions sdk/src/tools/apply-patch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,13 +108,13 @@ function isWrappedAtHeader(line: string): boolean {

function parseCreateDiff(lines: string[]): string {
// Keep compatibility with unified create payloads by ignoring common diff headers.
const filteredLines = lines.filter(
(line) =>
!line.startsWith('---') &&
!line.startsWith('+++') &&
!line.startsWith('@@') &&
!line.startsWith('***'),
const contentLines = lines.filter(
(line) => !line.startsWith('@@') && !line.startsWith('***'),
)
// Only the leading pair is metadata: an added `++counter` is `+++counter`.
const hasUnifiedHeaders =
contentLines[0]?.startsWith('--- ') && contentLines[1]?.startsWith('+++ ')
const filteredLines = hasUnifiedHeaders ? contentLines.slice(2) : contentLines

const parser: ParserState = {
lines: [...filteredLines, END_PATCH],
Expand Down
Loading