refactor: Clean up code structure and improve formatting
- Organize imports and remove unused imports - Format code with consistent indentation and line breaks - Remove empty lines and redundant whitespace - Improve function parameter formatting for better readability
This commit is contained in:
parent
021efac1d9
commit
5a0340e8e9
@ -1,13 +1,12 @@
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
|
||||
from typing import List, Dict, Any, Optional, Tuple
|
||||
from typing import Any, Dict, List, Tuple
|
||||
|
||||
from devchat.llm import chat, chat_json
|
||||
|
||||
from lib.chatmark import Step
|
||||
from lib.ide_service import IDEService
|
||||
from lib.chatmark import Step, Form, TextEditor
|
||||
|
||||
|
||||
def get_selected_code():
|
||||
@ -128,9 +127,6 @@ def replace_selected(new_code):
|
||||
file.write(modified_text)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# 定义用于分析代码中缺少定义的符号的提示
|
||||
SYMBOL_ANALYSIS_PROMPT = """
|
||||
角色:你是一个资深的程序工程师,擅长代码分析与代码重构。
|
||||
@ -175,13 +171,15 @@ def fun1():
|
||||
"symbol": "fun2",
|
||||
"line": " fun2(\"hello\")",
|
||||
"value": 0.8,
|
||||
"reason": "不能确定fun2中具体代码逻辑,是否会打印输出参数'hello',如果是,那么重构只需要修改fun1中参数信息"
|
||||
"reason": "不能确定fun2中具体代码逻辑,是否会打印输出参数'hello',\
|
||||
如果是,那么重构只需要修改fun1中参数信息"
|
||||
}},
|
||||
{{
|
||||
"symbol": "fun3",
|
||||
"line": " fun3(",
|
||||
"value": 0.8,
|
||||
"reason": "不能确定fun3中具体代码逻辑,是否会打印输出参数'hello',如果是,那么重构只需要修改fun1中参数信息"
|
||||
"reason": "不能确定fun3中具体代码逻辑,是否会打印输出参数'hello',\
|
||||
如果是,那么重构只需要修改fun1中参数信息"
|
||||
}}
|
||||
]
|
||||
```
|
||||
@ -218,6 +216,7 @@ SYMBOL_USAGE_PROMPT = """
|
||||
请确保返回的JSON格式正确。
|
||||
"""
|
||||
|
||||
|
||||
@chat_json(prompt=SYMBOL_ANALYSIS_PROMPT)
|
||||
def analyze_missing_symbols(code: str, task: str) -> Dict[str, List[Dict[str, Any]]]:
|
||||
"""
|
||||
@ -231,8 +230,11 @@ def analyze_missing_symbols(code: str, task: str) -> Dict[str, List[Dict[str, An
|
||||
"""
|
||||
pass
|
||||
|
||||
|
||||
@chat_json(prompt=SYMBOL_USAGE_PROMPT)
|
||||
def generate_symbol_usage_suggestions(symbol_definitions: str, original_code: str) -> Dict[str, List[Dict[str, Any]]]:
|
||||
def generate_symbol_usage_suggestions(
|
||||
symbol_definitions: str, original_code: str
|
||||
) -> Dict[str, List[Dict[str, Any]]]:
|
||||
"""
|
||||
基于符号定义生成符号使用建议
|
||||
|
||||
@ -245,7 +247,15 @@ def generate_symbol_usage_suggestions(symbol_definitions: str, original_code: st
|
||||
"""
|
||||
pass
|
||||
|
||||
def get_symbol_definition(abspath: str, line: int, character: int, symbol_name: str, symbol_type: str, project_root_path: str) -> List[Tuple]:
|
||||
|
||||
def get_symbol_definition(
|
||||
abspath: str,
|
||||
line: int,
|
||||
character: int,
|
||||
symbol_name: str,
|
||||
symbol_type: str,
|
||||
project_root_path: str,
|
||||
) -> List[Tuple]:
|
||||
"""
|
||||
获取符号定义的代码
|
||||
|
||||
@ -265,7 +275,9 @@ def get_symbol_definition(abspath: str, line: int, character: int, symbol_name:
|
||||
# 根据符号类型选择合适的查找方法
|
||||
locations1 = ide_service.find_type_def_locations(abspath, line, character)
|
||||
locations2 = ide_service.find_def_locations(abspath, line, character)
|
||||
locations3 = ide_service.find_type_def_locations(abspath, line, character + len(symbol_name) - 1)
|
||||
locations3 = ide_service.find_type_def_locations(
|
||||
abspath, line, character + len(symbol_name) - 1
|
||||
)
|
||||
locations4 = ide_service.find_def_locations(abspath, line, character + len(symbol_name) - 1)
|
||||
for location in locations1 + locations2 + locations3 + locations4:
|
||||
if not location.abspath.startswith(project_root_path):
|
||||
@ -302,7 +314,7 @@ def format_symbol_results(symbols: List[Dict[str, Any]], definitions: Dict[str,
|
||||
result += f"- 位置: 第{symbol['line'] + 1}行,第{symbol['character'] + 1}列\n"
|
||||
result += f"- 原因: {symbol['reason']}\n\n"
|
||||
|
||||
if symbol['name'] in definitions and definitions[symbol['name']]:
|
||||
if symbol["name"] in definitions and definitions[symbol["name"]]:
|
||||
result += "#### 找到的定义:\n\n"
|
||||
result += f"{definitions[symbol['name']]}\n\n"
|
||||
else:
|
||||
@ -311,6 +323,7 @@ def format_symbol_results(symbols: List[Dict[str, Any]], definitions: Dict[str,
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def format_usage_suggestions(suggestions: List[Dict[str, Any]]) -> str:
|
||||
"""
|
||||
格式化符号使用建议为Markdown格式
|
||||
@ -330,14 +343,14 @@ def format_usage_suggestions(suggestions: List[Dict[str, Any]]) -> str:
|
||||
result += f"### {i+1}. {suggestion['symbol']}\n\n"
|
||||
result += f"**正确使用方法**:\n{suggestion['explanation']}\n\n"
|
||||
|
||||
if suggestion.get('errors'):
|
||||
if suggestion.get("errors"):
|
||||
result += f"**可能存在的错误**:\n{suggestion['errors']}\n\n"
|
||||
|
||||
if suggestion.get('fix'):
|
||||
if suggestion.get("fix"):
|
||||
result += f"**修复建议**:\n{suggestion['fix']}\n\n"
|
||||
|
||||
if suggestion.get('example'):
|
||||
result += "**示例代码**:\n```python\n" + suggestion['example'] + "\n```\n\n"
|
||||
if suggestion.get("example"):
|
||||
result += "**示例代码**:\n```python\n" + suggestion["example"] + "\n```\n\n"
|
||||
|
||||
return result
|
||||
|
||||
@ -360,10 +373,11 @@ def find_project_root(file_path: str) -> str:
|
||||
current_dir = os.path.dirname(file_path)
|
||||
|
||||
# 向上遍历目录,直到找到包含 .git 或 .svn 的目录,或者到达根目录
|
||||
while current_dir and current_dir != '/':
|
||||
while current_dir and current_dir != "/":
|
||||
# 检查当前目录是否包含 .git 或 .svn
|
||||
if os.path.exists(os.path.join(current_dir, '.git')) or \
|
||||
os.path.exists(os.path.join(current_dir, '.svn')):
|
||||
if os.path.exists(os.path.join(current_dir, ".git")) or os.path.exists(
|
||||
os.path.join(current_dir, ".svn")
|
||||
):
|
||||
return current_dir
|
||||
|
||||
# 向上移动一级目录
|
||||
@ -382,7 +396,6 @@ def main():
|
||||
rafact_task = sys.argv[1]
|
||||
# prepare code
|
||||
|
||||
|
||||
# 步骤1: 获取用户选中的代码片段
|
||||
with Step("获取选中的代码片段..."):
|
||||
selected_code = ide_service.get_selected_range()
|
||||
@ -395,7 +408,6 @@ def main():
|
||||
project_root_path = find_project_root(selected_code.abspath)
|
||||
print(f"项目根目录: {project_root_path}\n\n")
|
||||
|
||||
|
||||
# 步骤2: 分析代码片段中缺少定义的符号
|
||||
with Step("分析代码中缺少定义的符号..."):
|
||||
try:
|
||||
@ -412,9 +424,7 @@ def main():
|
||||
print(f"分析代码时出错: {str(e)}")
|
||||
return
|
||||
|
||||
current_filepath = selected_code.abspath
|
||||
base_line = selected_code.range.start.line
|
||||
# range = "abspath='/Users/boboyang/.chat/scripts/merico/symbol_resolver/command.py' range=line=248 character=0 - line=248 character=24 text=' print(selected_code)'"
|
||||
|
||||
# 步骤3: 将分析结果转换为可处理的结构
|
||||
with Step("处理符号信息..."):
|
||||
@ -448,7 +458,7 @@ def main():
|
||||
"line": base_line + line_index,
|
||||
"character": char_index,
|
||||
"type": "unknown", # 默认类型
|
||||
"reason": symbol_info.get("reason", "未知原因")
|
||||
"reason": symbol_info.get("reason", "未知原因"),
|
||||
}
|
||||
|
||||
symbols.append(symbol)
|
||||
@ -469,7 +479,7 @@ def main():
|
||||
symbol_char,
|
||||
symbol_name,
|
||||
symbol_type,
|
||||
project_root_path
|
||||
project_root_path,
|
||||
)
|
||||
|
||||
symbol_definitions[symbol_name] = definitions
|
||||
|
Loading…
x
Reference in New Issue
Block a user