Source code for langchain_community.tools.file_management.utils

import sys
from pathlib import Path
from typing import Optional

from langchain_core.pydantic_v1 import BaseModel


[docs]def is_relative_to(path: Path, root: Path) -> bool: """检查路径是否相对于根目录。""" if sys.version_info >= (3, 9): # No need for a try/except block in Python 3.8+. return path.is_relative_to(root) try: path.relative_to(root) return True except ValueError: return False
INVALID_PATH_TEMPLATE = ( "Error: Access denied to {arg_name}: {value}." " Permission granted exclusively to the current working directory" )
[docs]class FileValidationError(ValueError): """根目录之外的路径错误。"""
[docs]class BaseFileToolMixin(BaseModel): """文件系统工具的Mixin。""" root_dir: Optional[str] = None """如果指定了root_dir,则将选择相对于root_dir的最终路径。"""
[docs] def get_relative_path(self, file_path: str) -> Path: """获取相对路径,如果不支持则返回错误。""" if self.root_dir is None: return Path(file_path) return get_validated_relative_path(Path(self.root_dir), file_path)
[docs]def get_validated_relative_path(root: Path, user_path: str) -> Path: """解析相对路径,如果不在根目录内则引发错误。""" # Note, this still permits symlinks from outside that point within the root. # Further validation would be needed if those are to be disallowed. root = root.resolve() full_path = (root / user_path).resolve() if not is_relative_to(full_path, root): raise FileValidationError( f"Path {user_path} is outside of the allowed directory {root}" ) return full_path