-
Notifications
You must be signed in to change notification settings - Fork 519
Expand file tree
/
Copy pathprocess-str-replace.ts
More file actions
216 lines (195 loc) · 5.96 KB
/
process-str-replace.ts
File metadata and controls
216 lines (195 loc) · 5.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
import { logger } from '@codebuff/common/util/logger'
import { createPatch } from 'diff'
import { tryToDoStringReplacementWithExtraIndentation } from './generate-diffs-prompt'
function normalizeLineEndings(str: string): string {
return str.replace(/\r\n/g, '\n')
}
export async function processStrReplace(
path: string,
replacements: { old: string; new: string; allowMultiple: boolean }[],
initialContentPromise: Promise<string | null>,
): Promise<
| {
tool: 'str_replace'
path: string
content: string
patch: string
messages: string[]
}
| { tool: 'str_replace'; path: string; error: string }
> {
logger.debug(
{
path,
replacementsCount: replacements.length,
},
'processStrReplace: Starting to process str_replace',
)
const initialContent = await initialContentPromise
if (initialContent === null) {
logger.warn(
{
path,
},
'processStrReplace: File does not exist',
)
return {
tool: 'str_replace',
path,
error:
'The file does not exist, skipping. Please use the write_file tool to create the file.',
}
}
logger.debug(
{
path,
initialContentLength: initialContent.length,
hasContent: !!initialContent,
},
'processStrReplace: Successfully read initial file content',
)
// Process each old/new string pair
let currentContent = initialContent
let messages: string[] = []
const lineEnding = currentContent.includes('\r\n') ? '\r\n' : '\n'
for (const { old: oldStr, new: newStr, allowMultiple } of replacements) {
// Regular case: require oldStr for replacements
if (!oldStr) {
messages.push(
'The old string was empty, which does not match any content, skipping.',
)
continue
}
const normalizedCurrentContent = normalizeLineEndings(currentContent)
const normalizedOldStr = normalizeLineEndings(oldStr)
const normalizedNewStr = normalizeLineEndings(newStr)
const match = tryMatchOldStr(
normalizedCurrentContent,
normalizedOldStr,
normalizedNewStr,
allowMultiple,
)
let updatedOldStr: string | null
if (match.success) {
updatedOldStr = match.oldStr
} else {
messages.push(match.error)
updatedOldStr = null
}
currentContent =
updatedOldStr === null
? normalizedCurrentContent
: normalizedCurrentContent.replaceAll(updatedOldStr, normalizedNewStr)
}
currentContent = currentContent.replaceAll('\n', lineEnding)
if (initialContent === currentContent) {
logger.debug(
{
path,
initialContent,
},
`processStrReplace: No change to ${path}`,
)
messages.push('No change to the file.')
return {
tool: 'str_replace' as const,
path,
error: messages.join('\n\n'),
}
}
let patch = createPatch(path, initialContent, currentContent)
const lines = patch.split('\n')
const hunkStartIndex = lines.findIndex((line) => line.startsWith('@@'))
if (hunkStartIndex !== -1) {
patch = lines.slice(hunkStartIndex).join('\n')
}
const finalPatch = patch
logger.debug(
{
path,
newContent: currentContent,
patch: finalPatch,
messages,
},
`processStrReplace: Updated file ${path}`,
)
return {
tool: 'str_replace' as const,
path,
content: currentContent!,
patch: finalPatch,
messages,
}
}
const tryMatchOldStr = (
initialContent: string,
oldStr: string,
newStr: string,
allowMultiple: boolean,
): { success: true; oldStr: string } | { success: false; error: string } => {
// count the number of occurrences of oldStr in initialContent
const count = initialContent.split(oldStr).length - 1
if (count === 1) {
return { success: true, oldStr }
}
if (!allowMultiple && count > 1) {
return {
success: false,
error: `Found ${count} occurrences of ${JSON.stringify(oldStr)} in the file. Please try again with a longer (more specified) old string or set allowMultiple to true.`,
}
}
if (allowMultiple && count > 1) {
// For allowMultiple=true with multiple occurrences, use the original oldStr
return { success: true, oldStr }
}
const newChange = tryToDoStringReplacementWithExtraIndentation(
initialContent,
oldStr,
newStr,
)
if (newChange) {
logger.debug('Matched with indentation modification')
return { success: true, oldStr: newChange.searchContent }
} else {
// Try matching without any whitespace as a last resort
const noWhitespaceSearch = oldStr.replace(/\s+/g, '')
const noWhitespaceOld = initialContent.replace(/\s+/g, '')
const noWhitespaceIndex = noWhitespaceOld.indexOf(noWhitespaceSearch)
if (noWhitespaceIndex >= 0) {
// Count non-whitespace characters to find the real position
let realIndex = 0
let nonWhitespaceCount = 0
while (nonWhitespaceCount < noWhitespaceIndex) {
if (initialContent[realIndex].match(/\S/)) {
nonWhitespaceCount++
}
realIndex++
}
// Count non-whitespace characters in search content to find length
let searchLength = 0
let nonWhitespaceSearchCount = 0
while (
nonWhitespaceSearchCount < noWhitespaceSearch.length &&
realIndex + searchLength < initialContent.length
) {
if (initialContent[realIndex + searchLength].match(/\S/)) {
nonWhitespaceSearchCount++
}
searchLength++
}
// Find the actual content with original whitespace
const actualContent = initialContent.slice(
realIndex,
realIndex + searchLength,
)
if (initialContent.includes(actualContent)) {
logger.debug('Matched with whitespace removed')
return { success: true, oldStr: actualContent }
}
}
}
return {
success: false,
error: `The old string ${JSON.stringify(oldStr)} was not found in the file, skipping. Please try again with a different old string that matches the file content exactly.`,
}
}