jarvis-ai-assistant 0.1.162__py3-none-any.whl → 0.1.163__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of jarvis-ai-assistant might be problematic. Click here for more details.
- jarvis/__init__.py +1 -1
- jarvis/jarvis_agent/__init__.py +23 -4
- jarvis/jarvis_code_agent/code_agent.py +123 -160
- jarvis/jarvis_dev/main.py +6 -0
- jarvis/jarvis_git_details/main.py +2 -1
- jarvis/jarvis_multi_agent/__init__.py +2 -3
- jarvis/jarvis_platform/base.py +0 -2
- jarvis/jarvis_platform/yuanbao.py +1 -0
- jarvis/jarvis_tools/edit_file.py +236 -526
- jarvis/jarvis_tools/file_operation.py +0 -2
- jarvis/jarvis_tools/read_code.py +0 -2
- jarvis/jarvis_tools/rewrite_file.py +183 -0
- jarvis/jarvis_utils/git_utils.py +144 -0
- jarvis/jarvis_utils/globals.py +0 -29
- jarvis/jarvis_utils/methodology.py +15 -9
- {jarvis_ai_assistant-0.1.162.dist-info → jarvis_ai_assistant-0.1.163.dist-info}/METADATA +3 -1
- {jarvis_ai_assistant-0.1.162.dist-info → jarvis_ai_assistant-0.1.163.dist-info}/RECORD +21 -20
- {jarvis_ai_assistant-0.1.162.dist-info → jarvis_ai_assistant-0.1.163.dist-info}/WHEEL +1 -1
- {jarvis_ai_assistant-0.1.162.dist-info → jarvis_ai_assistant-0.1.163.dist-info}/entry_points.txt +0 -0
- {jarvis_ai_assistant-0.1.162.dist-info → jarvis_ai_assistant-0.1.163.dist-info}/licenses/LICENSE +0 -0
- {jarvis_ai_assistant-0.1.162.dist-info → jarvis_ai_assistant-0.1.163.dist-info}/top_level.txt +0 -0
jarvis/jarvis_tools/edit_file.py
CHANGED
|
@@ -1,37 +1,39 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
from
|
|
17
|
-
from jarvis.jarvis_utils.globals import add_read_file_record, has_read_file
|
|
18
|
-
from jarvis.jarvis_utils.input import get_multiline_input
|
|
19
|
-
from jarvis.jarvis_utils.output import OutputType, PrettyOutput
|
|
20
|
-
from jarvis.jarvis_utils.utils import is_context_overflow, get_file_line_count, user_confirm
|
|
21
|
-
from jarvis.jarvis_utils.tag import ot, ct
|
|
22
|
-
|
|
1
|
+
"""
|
|
2
|
+
文件搜索替换工具类
|
|
3
|
+
|
|
4
|
+
功能概述:
|
|
5
|
+
1. 提供精确的文件内容搜索和替换功能
|
|
6
|
+
2. 支持单个文件的编辑操作,包括创建新文件
|
|
7
|
+
3. 实现原子操作:所有修改要么全部成功,要么全部回滚
|
|
8
|
+
4. 严格匹配控制:每个搜索文本必须且只能匹配一次
|
|
9
|
+
|
|
10
|
+
核心特性:
|
|
11
|
+
- 支持不存在的文件和空文件处理
|
|
12
|
+
- 自动创建所需目录结构
|
|
13
|
+
- 完善的错误处理和回滚机制
|
|
14
|
+
- 严格的格式保持要求
|
|
15
|
+
"""
|
|
16
|
+
from typing import Any, Dict
|
|
23
17
|
|
|
24
|
-
class PatchOutputHandler:
|
|
25
18
|
|
|
19
|
+
class FileSearchReplaceTool:
|
|
26
20
|
name = "edit_file"
|
|
27
|
-
description = """
|
|
21
|
+
description = """代码编辑工具,用于编辑单个文件
|
|
22
|
+
|
|
28
23
|
# 代码编辑规范
|
|
29
24
|
|
|
30
25
|
## 重要提示
|
|
31
|
-
|
|
26
|
+
此工具可以查看和修改单个文件的代码,只需提供要修改的代码片段即可。应尽量精简内容,只包含必要的上下文和修改部分。特别注意:不要提供完整文件内容,只提供需要修改的部分!
|
|
27
|
+
|
|
28
|
+
## 基本使用
|
|
29
|
+
1. 指定需要修改的文件路径
|
|
30
|
+
2. 提供一组或多组"搜索文本"和"替换文本"对
|
|
31
|
+
3. 每个搜索文本需在目标文件中有且仅有一次精确匹配
|
|
32
|
+
4. 创建新文件时,使用空字符串("")作为搜索文本,替换文本作为完整文件内容
|
|
33
|
+
5. 所有修改要么全部成功,要么全部失败并回滚
|
|
32
34
|
|
|
33
35
|
## 核心原则
|
|
34
|
-
1.
|
|
36
|
+
1. **精准修改**:只提供需要修改的代码部分,不需要展示整个文件内容
|
|
35
37
|
2. **最小补丁原则**:始终生成最小范围的补丁,只包含必要的上下文和实际修改
|
|
36
38
|
3. **格式严格保持**:
|
|
37
39
|
- 严格保持原始代码的缩进方式(空格或制表符)
|
|
@@ -41,529 +43,237 @@ class PatchOutputHandler:
|
|
|
41
43
|
4. **新旧区分**:
|
|
42
44
|
- 对于新文件:提供完整的代码内容
|
|
43
45
|
- 对于现有文件:只提供修改部分,不要提供整个文件
|
|
44
|
-
5. **理由说明**:每个补丁必须包含清晰的修改理由,解释为什么需要此更改
|
|
45
46
|
|
|
46
47
|
## 格式兼容性要求
|
|
47
48
|
1. **缩进一致性**:
|
|
48
|
-
- 如果原代码使用4
|
|
49
|
-
-
|
|
49
|
+
- 如果原代码使用4个空格缩进,替换文本也必须使用4个空格缩进
|
|
50
|
+
- 如果原代码使用制表符缩进,替换文本也必须使用制表符
|
|
50
51
|
2. **空行保留**:
|
|
51
|
-
-
|
|
52
|
-
-
|
|
52
|
+
- 如果原代码在函数之间有两个空行,替换文本也必须保留这两个空行
|
|
53
|
+
- 如果原代码在类方法之间有一个空行,替换文本也必须保留这一个空行
|
|
53
54
|
3. **行尾处理**:
|
|
54
|
-
-
|
|
55
|
-
-
|
|
55
|
+
- 不要改变原代码的行尾空格或换行符风格
|
|
56
|
+
- 保持原有的换行符类型(CR、LF或CRLF)
|
|
56
57
|
|
|
57
58
|
## 最佳实践
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
- 绝不提供完整文件内容,除非是新建文件
|
|
64
|
-
- 每个文件的修改是独立的,不能出现“参照xxx文件的修改”这样的描述
|
|
65
|
-
- 不要出现未实现的代码,如:TODO
|
|
66
|
-
- 如果要修改的内容较多,请分多次修改
|
|
67
|
-
"""
|
|
59
|
+
1. 每个修改应专注于单一职责,避免包含过多无关代码
|
|
60
|
+
2. 设计唯一的搜索文本,避免多处匹配的风险
|
|
61
|
+
3. 创建新文件时提供完整、格式良好的内容
|
|
62
|
+
4. 不要出现未实现的代码,如:TODO
|
|
63
|
+
"""
|
|
68
64
|
parameters = {
|
|
69
65
|
"type": "object",
|
|
70
66
|
"properties": {
|
|
71
|
-
"file": {
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
67
|
+
"file": {
|
|
68
|
+
"type": "string",
|
|
69
|
+
"description": "需要修改的文件路径"
|
|
70
|
+
},
|
|
71
|
+
"changes": {
|
|
72
|
+
"type": "array",
|
|
73
|
+
"description": "一组或多组搜索替换对",
|
|
74
|
+
"items": {
|
|
75
|
+
"type": "object",
|
|
76
|
+
"properties": {
|
|
77
|
+
"search": {
|
|
78
|
+
"type": "string",
|
|
79
|
+
"description": "需要被替换的文本,必须在文件中唯一匹配,新文件用空字符串"
|
|
80
|
+
},
|
|
81
|
+
"replace": {
|
|
82
|
+
"type": "string",
|
|
83
|
+
"description": "替换的目标文本,需保持与原代码相同的缩进和格式风格"
|
|
84
|
+
}
|
|
85
|
+
},
|
|
86
|
+
"required": ["search", "replace"]
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
},
|
|
90
|
+
"required": ["file", "changes"]
|
|
75
91
|
}
|
|
76
92
|
|
|
77
|
-
|
|
93
|
+
def __init__(self):
|
|
94
|
+
"""初始化文件搜索替换工具"""
|
|
95
|
+
pass
|
|
78
96
|
|
|
79
97
|
def execute(self, args: Dict) -> Dict[str, Any]:
|
|
80
|
-
"""
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
if not_read_file:
|
|
96
|
-
spinner.text=f"以下文件未读取: {filepath},应用补丁存在风险,将先读取文件后再生成补丁"
|
|
97
|
-
spinner.fail("❌")
|
|
98
|
-
return {
|
|
99
|
-
"success": False,
|
|
100
|
-
"stdout": f"以下文件未读取: {filepath},应用补丁存在风险,请先读取文件后再生成补丁",
|
|
101
|
-
"stderr": ""
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
# 检查是否有文件在Git仓库外
|
|
105
|
-
in_git_repo = _is_file_in_git_repo(filepath)
|
|
106
|
-
|
|
107
|
-
try:
|
|
108
|
-
spinner.text = f"正在处理文件: {filepath}"
|
|
109
|
-
if not os.path.exists(filepath):
|
|
110
|
-
# 新建文件
|
|
111
|
-
spinner.text = "文件不存在,正在创建文件..."
|
|
112
|
-
os.makedirs(os.path.dirname(filepath), exist_ok=True)
|
|
113
|
-
open(filepath, 'w', encoding='utf-8').close()
|
|
114
|
-
spinner.write("✅ 文件创建完成")
|
|
115
|
-
add_read_file_record(filepath)
|
|
116
|
-
with spinner.hidden():
|
|
117
|
-
while not handle_code_operation(filepath, patch_content):
|
|
118
|
-
if user_confirm("补丁应用失败,是否重试?", default=True):
|
|
119
|
-
pass
|
|
120
|
-
else:
|
|
121
|
-
raise Exception("补丁应用失败")
|
|
122
|
-
spinner.write(f"✅ 文件 {filepath} 处理完成")
|
|
123
|
-
except Exception as e:
|
|
124
|
-
spinner.text = f"文件 {filepath} 处理失败: {str(e)}, 回滚文件"
|
|
125
|
-
revert_file(filepath) # 回滚单个文件
|
|
126
|
-
spinner.write(f"✅ 文件 {filepath} 回滚完成")
|
|
127
|
-
|
|
128
|
-
final_ret = ""
|
|
129
|
-
if in_git_repo:
|
|
130
|
-
diff = get_diff()
|
|
131
|
-
if diff:
|
|
132
|
-
PrettyOutput.print(diff, OutputType.CODE, lang="diff")
|
|
133
|
-
with spinner.hidden():
|
|
134
|
-
commited = handle_commit_workflow()
|
|
135
|
-
if commited:
|
|
136
|
-
# 获取提交信息
|
|
137
|
-
end_hash = get_latest_commit_hash()
|
|
138
|
-
commits = get_commits_between(start_hash, end_hash)
|
|
139
|
-
|
|
140
|
-
# 添加提交信息到final_ret
|
|
141
|
-
if commits:
|
|
142
|
-
final_ret += "✅ 补丁已应用\n"
|
|
143
|
-
final_ret += "# 提交信息:\n"
|
|
144
|
-
for commit_hash, commit_message in commits:
|
|
145
|
-
final_ret += f"- {commit_hash[:7]}: {commit_message}\n"
|
|
146
|
-
|
|
147
|
-
final_ret += f"# 应用补丁:\n```diff\n{diff}\n```"
|
|
148
|
-
|
|
149
|
-
# 修改后的提示逻辑
|
|
150
|
-
addon_prompt = f"如果用户的需求未完成,请继续生成补丁,如果已经完成,请终止,不要输出新的PATCH,不要实现任何超出用户需求外的内容\n"
|
|
151
|
-
addon_prompt += "如果有任何信息不明确,调用工具获取信息\n"
|
|
152
|
-
addon_prompt += "每次响应必须且只能包含一个操作\n"
|
|
153
|
-
|
|
154
|
-
agent.set_addon_prompt(addon_prompt)
|
|
155
|
-
|
|
156
|
-
else:
|
|
157
|
-
final_ret += "✅ 补丁已应用(没有新的提交)"
|
|
158
|
-
else:
|
|
159
|
-
final_ret += "❌ 补丁应用被拒绝\n"
|
|
160
|
-
final_ret += f"# 补丁预览:\n```diff\n{diff}\n```"
|
|
161
|
-
else:
|
|
162
|
-
commited = False
|
|
163
|
-
final_ret += "❌ 没有要提交的更改\n"
|
|
164
|
-
else:
|
|
165
|
-
# 对于Git仓库外的文件,直接返回成功
|
|
166
|
-
final_ret += "✅ 补丁已应用(文件不在Git仓库中)"
|
|
167
|
-
commited = True
|
|
168
|
-
# 用户确认最终结果
|
|
169
|
-
with spinner.hidden():
|
|
170
|
-
if commited:
|
|
171
|
-
return {
|
|
172
|
-
"success": True,
|
|
173
|
-
"stdout": final_ret,
|
|
174
|
-
"stderr": ""
|
|
175
|
-
}
|
|
176
|
-
PrettyOutput.print(final_ret, OutputType.USER, lang="markdown")
|
|
177
|
-
if not is_confirm_before_apply_patch() or user_confirm("是否使用此回复?", default=True):
|
|
178
|
-
return {
|
|
179
|
-
"success": True,
|
|
180
|
-
"stdout": final_ret,
|
|
181
|
-
"stderr": ""
|
|
182
|
-
}
|
|
183
|
-
custom_reply = get_multiline_input("请输入自定义回复")
|
|
184
|
-
if not custom_reply.strip(): # 如果自定义回复为空,返回空字符串
|
|
185
|
-
return {
|
|
186
|
-
"success": True,
|
|
187
|
-
"stdout": final_ret,
|
|
188
|
-
"stderr": ""
|
|
189
|
-
}
|
|
190
|
-
agent.set_addon_prompt(custom_reply)
|
|
191
|
-
return {
|
|
192
|
-
"success": True,
|
|
193
|
-
"stdout": final_ret,
|
|
194
|
-
"stderr": ""
|
|
98
|
+
"""
|
|
99
|
+
执行文件搜索替换操作,每个搜索文本只允许有且只有一次匹配,否则失败
|
|
100
|
+
特殊支持不存在的文件和空文件处理
|
|
101
|
+
|
|
102
|
+
参数:
|
|
103
|
+
file (str): 文件路径
|
|
104
|
+
changes (list): 一组或多组搜索替换对,格式如下:
|
|
105
|
+
[
|
|
106
|
+
{
|
|
107
|
+
"search": "搜索文本1",
|
|
108
|
+
"replace": "替换文本1"
|
|
109
|
+
},
|
|
110
|
+
{
|
|
111
|
+
"search": "搜索文本2",
|
|
112
|
+
"replace": "替换文本2"
|
|
195
113
|
}
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
# 检查文件路径是否在仓库根目录下
|
|
209
|
-
return os.path.abspath(filepath).startswith(os.path.abspath(repo_root))
|
|
210
|
-
except:
|
|
211
|
-
return False
|
|
212
|
-
|
|
213
|
-
def revert_file(filepath: str):
|
|
214
|
-
"""增强版git恢复,处理新文件"""
|
|
215
|
-
import subprocess
|
|
216
|
-
try:
|
|
217
|
-
# 检查文件是否在版本控制中
|
|
218
|
-
result = subprocess.run(
|
|
219
|
-
['git', 'ls-files', '--error-unmatch', filepath],
|
|
220
|
-
stderr=subprocess.PIPE,
|
|
221
|
-
text=False # 禁用自动文本解码
|
|
222
|
-
)
|
|
223
|
-
if result.returncode == 0:
|
|
224
|
-
subprocess.run(['git', 'checkout', 'HEAD',
|
|
225
|
-
'--', filepath], check=True)
|
|
226
|
-
else:
|
|
227
|
-
if os.path.exists(filepath):
|
|
228
|
-
os.remove(filepath)
|
|
229
|
-
subprocess.run(['git', 'clean', '-f', '--', filepath], check=True)
|
|
230
|
-
except subprocess.CalledProcessError as e:
|
|
231
|
-
error_msg = e.stderr.decode('utf-8', errors='replace') if e.stderr else str(e)
|
|
232
|
-
PrettyOutput.print(f"恢复文件失败: {error_msg}", OutputType.ERROR)
|
|
233
|
-
# 修改后的恢复函数
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
def revert_change():
|
|
237
|
-
"""恢复所有未提交的修改到HEAD状态"""
|
|
238
|
-
import subprocess
|
|
239
|
-
try:
|
|
240
|
-
# 检查是否为空仓库
|
|
241
|
-
head_check = subprocess.run(
|
|
242
|
-
['git', 'rev-parse', '--verify', 'HEAD'],
|
|
243
|
-
stderr=subprocess.PIPE,
|
|
244
|
-
stdout=subprocess.PIPE
|
|
245
|
-
)
|
|
246
|
-
if head_check.returncode == 0:
|
|
247
|
-
subprocess.run(['git', 'reset', '--hard', 'HEAD'], check=True)
|
|
248
|
-
subprocess.run(['git', 'clean', '-fd'], check=True)
|
|
249
|
-
except subprocess.CalledProcessError as e:
|
|
250
|
-
return f"恢复更改失败: {str(e)}"
|
|
251
|
-
# 修改后的获取差异函数
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
def get_diff() -> str:
|
|
255
|
-
"""使用git获取暂存区差异"""
|
|
256
|
-
import subprocess
|
|
257
|
-
|
|
258
|
-
# 初始化状态
|
|
259
|
-
need_reset = False
|
|
260
|
-
|
|
261
|
-
try:
|
|
262
|
-
# 暂存所有修改
|
|
263
|
-
subprocess.run(['git', 'add', '.'], check=True)
|
|
264
|
-
need_reset = True
|
|
265
|
-
|
|
266
|
-
# 获取差异
|
|
267
|
-
result = subprocess.run(
|
|
268
|
-
['git', 'diff', '--cached'],
|
|
269
|
-
capture_output=True,
|
|
270
|
-
text=False,
|
|
271
|
-
check=True
|
|
272
|
-
)
|
|
273
|
-
|
|
274
|
-
# 解码输出
|
|
275
|
-
try:
|
|
276
|
-
ret = result.stdout.decode('utf-8')
|
|
277
|
-
except UnicodeDecodeError:
|
|
278
|
-
ret = result.stdout.decode('utf-8', errors='replace')
|
|
114
|
+
]
|
|
115
|
+
|
|
116
|
+
返回:
|
|
117
|
+
dict: 包含执行结果的字典
|
|
118
|
+
{
|
|
119
|
+
"success": bool, # 是否成功完成所有替换
|
|
120
|
+
"stdout": str, # 标准输出信息
|
|
121
|
+
"stderr": str # 错误信息
|
|
122
|
+
}
|
|
123
|
+
"""
|
|
124
|
+
import os
|
|
125
|
+
from jarvis.jarvis_utils.output import PrettyOutput, OutputType
|
|
279
126
|
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
127
|
+
stdout_messages = []
|
|
128
|
+
stderr_messages = []
|
|
129
|
+
success = True
|
|
283
130
|
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
subprocess.run(['git', "reset", "--mixed"], check=False)
|
|
287
|
-
return f"获取差异失败: {str(e)}"
|
|
288
|
-
except Exception as e:
|
|
289
|
-
if need_reset:
|
|
290
|
-
subprocess.run(['git', "reset", "--mixed"], check=False)
|
|
291
|
-
return f"发生意外错误: {str(e)}"
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
def handle_commit_workflow() -> bool:
|
|
295
|
-
"""Handle the git commit workflow and return the commit details.
|
|
296
|
-
|
|
297
|
-
Returns:
|
|
298
|
-
bool: 提交是否成功
|
|
299
|
-
"""
|
|
300
|
-
if is_confirm_before_apply_patch() and not user_confirm("是否要提交代码?", default=True):
|
|
301
|
-
revert_change()
|
|
302
|
-
return False
|
|
303
|
-
|
|
304
|
-
import subprocess
|
|
305
|
-
try:
|
|
306
|
-
# 获取当前分支的提交总数
|
|
307
|
-
commit_count = subprocess.run(
|
|
308
|
-
['git', 'rev-list', '--count', 'HEAD'],
|
|
309
|
-
capture_output=True,
|
|
310
|
-
text=True
|
|
311
|
-
)
|
|
312
|
-
if commit_count.returncode != 0:
|
|
313
|
-
return False
|
|
314
|
-
|
|
315
|
-
commit_count = int(commit_count.stdout.strip())
|
|
131
|
+
file_path = args["file"]
|
|
132
|
+
changes = args["changes"]
|
|
316
133
|
|
|
317
|
-
#
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
# 提交变更
|
|
321
|
-
subprocess.run(
|
|
322
|
-
['git', 'commit', '-m', f'CheckPoint #{commit_count + 1}'],
|
|
323
|
-
check=True
|
|
324
|
-
)
|
|
325
|
-
return True
|
|
326
|
-
except subprocess.CalledProcessError as e:
|
|
327
|
-
return False
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
def handle_code_operation(filepath: str, patch_content: str) -> bool:
|
|
331
|
-
"""处理代码操作"""
|
|
332
|
-
if get_file_line_count(filepath) < 5:
|
|
333
|
-
return handle_small_code_operation(filepath, patch_content)
|
|
334
|
-
else:
|
|
335
|
-
retry_count = 5
|
|
336
|
-
while retry_count > 0:
|
|
337
|
-
retry_count -= 1
|
|
338
|
-
if handle_large_code_operation(filepath, patch_content, PlatformRegistry().get_normal_platform() if retry_count > 2 else PlatformRegistry().get_thinking_platform()):
|
|
339
|
-
return True
|
|
340
|
-
return handle_small_code_operation(filepath, patch_content)
|
|
134
|
+
# 创建已处理文件变量,用于失败时回滚
|
|
135
|
+
original_content = None
|
|
136
|
+
processed = False
|
|
341
137
|
|
|
342
|
-
|
|
343
|
-
def handle_small_code_operation(filepath: str, patch_content: str) -> bool:
|
|
344
|
-
"""处理基于上下文的代码片段"""
|
|
345
|
-
with yaspin(text=f"正在修改文件 {filepath}...", color="cyan") as spinner:
|
|
346
138
|
try:
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
model.set_suppress_output(False)
|
|
351
|
-
|
|
352
|
-
prompt = f"""
|
|
353
|
-
# 代码合并专家指南
|
|
354
|
-
|
|
355
|
-
## 任务描述
|
|
356
|
-
你是一位精确的代码审查与合并专家,需要将补丁内容与原始代码智能合并。
|
|
357
|
-
|
|
358
|
-
### 补丁内容
|
|
359
|
-
```
|
|
360
|
-
{patch_content}
|
|
361
|
-
```
|
|
362
|
-
|
|
363
|
-
## 合并要求
|
|
364
|
-
1. **精确性**:严格按照补丁的意图修改代码
|
|
365
|
-
2. **完整性**:确保所有需要的更改都被应用
|
|
366
|
-
3. **一致性**:严格保留原始代码的格式、空行和缩进风格
|
|
367
|
-
4. **上下文保留**:保持未修改部分的代码完全不变
|
|
368
|
-
|
|
369
|
-
## 输出格式规范
|
|
370
|
-
- 仅在{ot("MERGED_CODE")}标签内输出合并后的完整代码
|
|
371
|
-
- 每次最多输出300行代码
|
|
372
|
-
- 不要使用markdown代码块(```)或反引号,除非修改的是markdown文件
|
|
373
|
-
- 除了合并后的代码,不要输出任何其他文本
|
|
374
|
-
- 所有代码输出完成后,输出{ot("!!!FINISHED!!!")}标记
|
|
375
|
-
|
|
376
|
-
## 输出模板
|
|
377
|
-
{ot("MERGED_CODE")}
|
|
378
|
-
[合并后的完整代码,包括所有空行和缩进]
|
|
379
|
-
{ct("MERGED_CODE")}
|
|
380
|
-
|
|
381
|
-
# 原始代码
|
|
382
|
-
{file_content}
|
|
383
|
-
"""
|
|
384
|
-
|
|
385
|
-
count = 30
|
|
386
|
-
start_line = -1
|
|
387
|
-
end_line = -1
|
|
388
|
-
code = []
|
|
389
|
-
finished = False
|
|
390
|
-
while count > 0:
|
|
391
|
-
count -= 1
|
|
392
|
-
with spinner.hidden():
|
|
393
|
-
response = model.chat_until_success(prompt).splitlines()
|
|
394
|
-
try:
|
|
395
|
-
start_line = response.index(ot("MERGED_CODE")) + 1
|
|
396
|
-
try:
|
|
397
|
-
end_line = response.index(ct("MERGED_CODE"))
|
|
398
|
-
code = response[start_line:end_line]
|
|
399
|
-
except:
|
|
400
|
-
pass
|
|
401
|
-
except:
|
|
402
|
-
pass
|
|
403
|
-
|
|
404
|
-
try:
|
|
405
|
-
response.index(ot("!!!FINISHED!!!"))
|
|
406
|
-
finished = True
|
|
407
|
-
break
|
|
408
|
-
except:
|
|
409
|
-
prompt += f"""
|
|
410
|
-
# 继续输出
|
|
411
|
-
|
|
412
|
-
## 说明
|
|
413
|
-
请继续输出接下来的300行代码
|
|
414
|
-
|
|
415
|
-
## 要求
|
|
416
|
-
- 严格保留原始代码的格式、空行和缩进
|
|
417
|
-
- 仅在{ot("MERGED_CODE")}块中包含实际代码内容
|
|
418
|
-
- 不要使用markdown代码块(```)或反引号
|
|
419
|
-
- 除了合并后的代码,不要输出任何其他文本
|
|
420
|
-
- 所有代码输出完成后,输出{ot("!!!FINISHED!!!")}标记
|
|
421
|
-
"""
|
|
422
|
-
pass
|
|
423
|
-
if not finished:
|
|
424
|
-
spinner.text = "生成代码失败"
|
|
425
|
-
spinner.fail("❌")
|
|
426
|
-
return False
|
|
427
|
-
# 写入合并后的代码
|
|
428
|
-
spinner.text = "写入合并后的代码..."
|
|
429
|
-
with open(filepath, 'w', encoding='utf-8', errors="ignore") as f:
|
|
430
|
-
f.write("\n".join(code)+"\n")
|
|
431
|
-
spinner.write("✅ 合并后的代码写入完成")
|
|
432
|
-
spinner.text = "代码修改完成"
|
|
433
|
-
spinner.ok("✅")
|
|
434
|
-
return True
|
|
435
|
-
except Exception as e:
|
|
436
|
-
spinner.text = "代码修改失败"
|
|
437
|
-
spinner.fail("❌")
|
|
438
|
-
return False
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
def handle_large_code_operation(filepath: str, patch_content: str, model: BasePlatform) -> bool:
|
|
443
|
-
"""处理大型代码文件的补丁操作,使用差异化补丁格式"""
|
|
444
|
-
with yaspin(text=f"正在处理文件 {filepath}...", color="cyan") as spinner:
|
|
445
|
-
try:
|
|
446
|
-
file_content = FileOperationTool().execute({"operation":"read", "files":[{"path":filepath}]})["stdout"]
|
|
447
|
-
need_upload_file = is_context_overflow(file_content)
|
|
448
|
-
upload_success = False
|
|
449
|
-
# 读取原始文件内容
|
|
450
|
-
with spinner.hidden():
|
|
451
|
-
if need_upload_file and model.upload_files([filepath]):
|
|
452
|
-
upload_success = True
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
model.set_suppress_output(False)
|
|
456
|
-
|
|
457
|
-
main_prompt = f"""
|
|
458
|
-
# 代码补丁生成专家指南
|
|
459
|
-
|
|
460
|
-
## 任务描述
|
|
461
|
-
你是一位精确的代码补丁生成专家,需要根据补丁描述生成精确的代码差异。
|
|
462
|
-
|
|
463
|
-
### 补丁内容
|
|
464
|
-
```
|
|
465
|
-
{patch_content}
|
|
466
|
-
```
|
|
467
|
-
|
|
468
|
-
## 补丁生成要求
|
|
469
|
-
1. **精确性**:严格按照补丁的意图修改代码
|
|
470
|
-
2. **格式一致性**:严格保持原始代码的格式风格
|
|
471
|
-
- 缩进方式(空格或制表符)必须与原代码保持一致
|
|
472
|
-
- 空行数量和位置必须与原代码风格匹配
|
|
473
|
-
- 行尾空格处理必须与原代码一致
|
|
474
|
-
3. **最小化修改**:只修改必要的代码部分,保持其他部分不变
|
|
475
|
-
4. **上下文完整性**:提供足够的上下文,确保补丁能准确应用
|
|
476
|
-
|
|
477
|
-
## 输出格式规范
|
|
478
|
-
- 使用{ot("DIFF")}块包围每个需要修改的代码段
|
|
479
|
-
- 每个{ot("DIFF")}块必须包含SEARCH部分和REPLACE部分
|
|
480
|
-
- SEARCH部分是需要查找的原始代码
|
|
481
|
-
- REPLACE部分是替换后的新代码
|
|
482
|
-
- 确保SEARCH部分能在原文件中**唯一匹配**
|
|
483
|
-
- 如果修改较大,可以使用多个{ot("DIFF")}块
|
|
484
|
-
|
|
485
|
-
## 输出模板
|
|
486
|
-
{ot("DIFF")}
|
|
487
|
-
{">" * 5} SEARCH
|
|
488
|
-
[需要查找的原始代码,包含足够上下文,避免出现可匹配多处的情况]
|
|
489
|
-
{'='*5}
|
|
490
|
-
[替换后的新代码]
|
|
491
|
-
{"<" * 5} REPLACE
|
|
492
|
-
{ct("DIFF")}
|
|
493
|
-
|
|
494
|
-
{ot("DIFF")}
|
|
495
|
-
{">" * 5} SEARCH
|
|
496
|
-
[另一处需要查找的原始代码,包含足够上下文,避免出现可匹配多处的情况]
|
|
497
|
-
{'='*5}
|
|
498
|
-
[另一处替换后的新代码]
|
|
499
|
-
{"<" * 5} REPLACE
|
|
500
|
-
{ct("DIFF")}
|
|
501
|
-
"""
|
|
139
|
+
file_exists = os.path.exists(file_path)
|
|
140
|
+
content = ""
|
|
502
141
|
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
if
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
142
|
+
try:
|
|
143
|
+
# 如果文件存在,则读取内容
|
|
144
|
+
if file_exists:
|
|
145
|
+
with open(file_path, 'r', encoding='utf-8') as f:
|
|
146
|
+
content = f.read()
|
|
147
|
+
original_content = content
|
|
148
|
+
|
|
149
|
+
# 创建一个临时内容副本进行操作
|
|
150
|
+
temp_content = content
|
|
151
|
+
replaced_count = 0
|
|
152
|
+
|
|
153
|
+
# 处理所有搜索替换对
|
|
154
|
+
for change in changes:
|
|
155
|
+
search_text = change["search"]
|
|
156
|
+
replace_text = change["replace"]
|
|
157
|
+
|
|
158
|
+
# 特殊处理不存在的文件或空文件
|
|
159
|
+
if not file_exists or content == "":
|
|
160
|
+
if search_text == "":
|
|
161
|
+
# 对于不存在的文件或空文件,如果搜索文本为空,则直接使用替换文本作为内容
|
|
162
|
+
temp_content = replace_text
|
|
163
|
+
replaced_count += 1
|
|
164
|
+
# 只允许有一个空字符串搜索
|
|
165
|
+
break
|
|
166
|
+
else:
|
|
167
|
+
stderr_message = f"文件 {file_path} {'不存在' if not file_exists else '为空'},但搜索文本非空: '{search_text}'"
|
|
168
|
+
stderr_messages.append(stderr_message)
|
|
169
|
+
PrettyOutput.print(stderr_message, OutputType.ERROR)
|
|
170
|
+
success = False
|
|
171
|
+
break
|
|
516
172
|
else:
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
# 读取原始文件内容
|
|
525
|
-
with open(filepath, 'r', encoding='utf-8', errors="ignore") as f:
|
|
526
|
-
file_content = f.read()
|
|
527
|
-
|
|
528
|
-
# 应用所有差异化补丁
|
|
529
|
-
modified_content = file_content
|
|
530
|
-
patch_count = 0
|
|
531
|
-
success = True
|
|
532
|
-
for match in diff_blocks:
|
|
533
|
-
search_text = match.group(1).strip()
|
|
534
|
-
replace_text = match.group(2).strip()
|
|
535
|
-
patch_count += 1
|
|
536
|
-
# 检查搜索文本是否存在于文件中
|
|
537
|
-
if search_text in modified_content:
|
|
538
|
-
# 如果有多处,报错
|
|
539
|
-
if modified_content.count(search_text) > 1:
|
|
540
|
-
spinner.write(f"❌ 补丁 #{patch_count} 应用失败:找到多个匹配的代码段")
|
|
173
|
+
# 正常文件处理 - 检查匹配次数
|
|
174
|
+
match_count = temp_content.count(search_text)
|
|
175
|
+
|
|
176
|
+
if match_count == 0:
|
|
177
|
+
stderr_message = f"文件 {file_path} 中未找到匹配文本: '{search_text}'"
|
|
178
|
+
stderr_messages.append(stderr_message)
|
|
179
|
+
PrettyOutput.print(stderr_message, OutputType.ERROR)
|
|
541
180
|
success = False
|
|
542
181
|
break
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
182
|
+
elif match_count > 1:
|
|
183
|
+
stderr_message = f"文件 {file_path} 中匹配到多个 ({match_count}) '{search_text}',搜索文本只允许一次匹配"
|
|
184
|
+
stderr_messages.append(stderr_message)
|
|
185
|
+
PrettyOutput.print(stderr_message, OutputType.ERROR)
|
|
186
|
+
success = False
|
|
187
|
+
break
|
|
188
|
+
else:
|
|
189
|
+
# 只有一个匹配,执行替换
|
|
190
|
+
temp_content = temp_content.replace(search_text, replace_text, 1)
|
|
191
|
+
replaced_count += 1
|
|
192
|
+
|
|
193
|
+
# 只有当所有替换操作都成功时,才写回文件
|
|
194
|
+
if success and (temp_content != original_content or not file_exists):
|
|
195
|
+
# 确保目录存在
|
|
196
|
+
os.makedirs(os.path.dirname(os.path.abspath(file_path)), exist_ok=True)
|
|
197
|
+
|
|
198
|
+
with open(file_path, 'w', encoding='utf-8') as f:
|
|
199
|
+
f.write(temp_content)
|
|
200
|
+
|
|
201
|
+
processed = True
|
|
202
|
+
|
|
203
|
+
action = "创建并写入" if not file_exists else "成功替换"
|
|
204
|
+
stdout_message = f"文件 {file_path} {action} {replaced_count} 处"
|
|
205
|
+
stdout_messages.append(stdout_message)
|
|
206
|
+
PrettyOutput.print(stdout_message, OutputType.SUCCESS)
|
|
207
|
+
elif success:
|
|
208
|
+
stdout_message = f"文件 {file_path} 没有找到需要替换的内容"
|
|
209
|
+
stdout_messages.append(stdout_message)
|
|
210
|
+
PrettyOutput.print(stdout_message, OutputType.INFO)
|
|
211
|
+
|
|
212
|
+
except Exception as e:
|
|
213
|
+
stderr_message = f"处理文件 {file_path} 时出错: {str(e)}"
|
|
214
|
+
stderr_messages.append(stderr_message)
|
|
215
|
+
PrettyOutput.print(stderr_message, OutputType.ERROR)
|
|
216
|
+
success = False
|
|
217
|
+
|
|
218
|
+
# 如果操作失败,回滚已修改的文件
|
|
219
|
+
if not success and processed:
|
|
220
|
+
rollback_message = "操作失败,正在回滚修改..."
|
|
221
|
+
stderr_messages.append(rollback_message)
|
|
222
|
+
PrettyOutput.print(rollback_message, OutputType.WARNING)
|
|
223
|
+
|
|
224
|
+
try:
|
|
225
|
+
if original_content is None:
|
|
226
|
+
# 如果是新创建的文件,则删除
|
|
227
|
+
if os.path.exists(file_path):
|
|
228
|
+
os.remove(file_path)
|
|
229
|
+
rollback_file_message = f"已删除新创建的文件: {file_path}"
|
|
547
230
|
else:
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
231
|
+
# 如果是修改的文件,则恢复原内容
|
|
232
|
+
with open(file_path, 'w', encoding='utf-8') as f:
|
|
233
|
+
f.write(original_content)
|
|
234
|
+
rollback_file_message = f"已回滚文件: {file_path}"
|
|
235
|
+
|
|
236
|
+
stderr_messages.append(rollback_file_message)
|
|
237
|
+
PrettyOutput.print(rollback_file_message, OutputType.INFO)
|
|
238
|
+
except Exception as e:
|
|
239
|
+
rollback_error = f"回滚文件 {file_path} 失败: {str(e)}"
|
|
240
|
+
stderr_messages.append(rollback_error)
|
|
241
|
+
PrettyOutput.print(rollback_error, OutputType.ERROR)
|
|
242
|
+
|
|
243
|
+
return {
|
|
244
|
+
"success": success,
|
|
245
|
+
"stdout": "\n".join(stdout_messages),
|
|
246
|
+
"stderr": "\n".join(stderr_messages)
|
|
247
|
+
}
|
|
248
|
+
|
|
566
249
|
except Exception as e:
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
250
|
+
error_msg = f"文件搜索替换操作失败: {str(e)}"
|
|
251
|
+
PrettyOutput.print(error_msg, OutputType.ERROR)
|
|
252
|
+
|
|
253
|
+
# 如果有已修改的文件,尝试回滚
|
|
254
|
+
if processed:
|
|
255
|
+
rollback_message = "操作失败,正在回滚修改..."
|
|
256
|
+
stderr_messages.append(rollback_message)
|
|
257
|
+
PrettyOutput.print(rollback_message, OutputType.WARNING)
|
|
258
|
+
|
|
259
|
+
try:
|
|
260
|
+
if original_content is None:
|
|
261
|
+
# 如果是新创建的文件,则删除
|
|
262
|
+
if os.path.exists(file_path):
|
|
263
|
+
os.remove(file_path)
|
|
264
|
+
stderr_messages.append(f"已删除新创建的文件: {file_path}")
|
|
265
|
+
else:
|
|
266
|
+
# 如果是修改的文件,则恢复原内容
|
|
267
|
+
with open(file_path, 'w', encoding='utf-8') as f:
|
|
268
|
+
f.write(original_content)
|
|
269
|
+
stderr_messages.append(f"已回滚文件: {file_path}")
|
|
270
|
+
except:
|
|
271
|
+
stderr_messages.append(f"回滚文件失败: {file_path}")
|
|
272
|
+
|
|
273
|
+
return {
|
|
274
|
+
"success": False,
|
|
275
|
+
"stdout": "",
|
|
276
|
+
"stderr": error_msg + "\n" + "\n".join(stderr_messages)
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
|