RAG/utils/func_id_generator.py

116 lines
2.8 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""
函数全局唯一ID生成工具类
按用户/仓库/分支/文件/函数生成唯一ID
"""
import os
from typing import Optional, Dict
from config import settings
def generate_func_unique_id(
user_id: str,
repo_id: str,
branch: str,
file_path: str,
class_name: Optional[str],
func_name: str
) -> str:
"""
生成函数全局唯一ID
Args:
user_id: 用户ID
repo_id: 仓库ID
branch: 分支名
file_path: 文件路径
class_name: 类名
func_name: 函数名
Returns:
str: 函数唯一ID
"""
# 类名为None则使用空字符串
class_name = class_name if class_name else "None"
# 直接使用文件路径的绝对路径部分,确保唯一性
# 替换路径分隔符为下划线
file_path = file_path.split(os.sep)[3:]
file_path = "_".join(file_path)
normalized_file_path = file_path.replace(os.sep, "_")
# 生成唯一ID
unique_id = f"{user_id}_{repo_id}_{branch}_{normalized_file_path}_{class_name}_{func_name}"
# 替换特殊字符避免ChromaDB主键冲突
unique_id = unique_id.replace("/", "_").replace("\\", "_").replace(":", "_").replace(" ", "_")
return unique_id
def parse_func_unique_id(func_id: str) -> Dict[str, str]:
"""
解析函数唯一ID
Args:
func_id: 函数唯一ID
Returns:
Dict[str, str]: 解析后的信息
"""
parts = func_id.split("_")
if len(parts) < 6:
raise Exception(f"无效的函数ID格式: {func_id}")
# 解析各部分
user_id = parts[0]
repo_id = parts[1]
branch = parts[2]
# 解析文件路径(可能包含下划线)
# 从第3个部分开始到倒数第2个部分结束
file_path_parts = parts[3:-2]
file_path = "_".join(file_path_parts).replace("_", os.sep)
class_name = parts[-2]
if class_name == "None":
class_name = None
func_name = parts[-1]
return {
"user_id": user_id,
"repo_id": repo_id,
"branch": branch,
"file_path": file_path,
"class_name": class_name,
"func_name": func_name
}
def get_repo_path_from_func_id(func_id: str) -> str:
"""
从函数ID获取仓库路径
Args:
func_id: 函数唯一ID
Returns:
str: 仓库路径
"""
info = parse_func_unique_id(func_id)
return os.path.join(settings.GIT_LOCAL_STORAGE_ROOT, info["user_id"], info["repo_id"])
def get_file_path_from_func_id(func_id: str) -> str:
"""
从函数ID获取文件路径
Args:
func_id: 函数唯一ID
Returns:
str: 文件路径
"""
info = parse_func_unique_id(func_id)
repo_path = get_repo_path_from_func_id(func_id)
return os.path.join(repo_path, info["file_path"])