refactor: 重构解析器架构并添加编码检测和配置管理
简化 parse_input() 为纯调度器,通过遍历 readers 的 supports() 方法识别输入类型,移除 URL 特殊处理和文件检查逻辑。各 reader 的 parse() 方法负责完整验证(文件存在、格式有效性)。 新增功能: - 添加 chardet 编码自动检测,支持多种中文编码回退机制 - 创建统一配置类管理编码、下载超时、日志等级等配置项 - HTML reader 支持本地文件编码检测和 URL 统一处理 安全性改进: - 修复 safe_open_zip() 路径遍历漏洞,使用 pathlib 规范化路径 - 添加边界检查,search_markdown() 检查负数参数 其他改进: - 修复类型注解(argparse.Namespace) - 日志系统仅输出 ERROR 级别,避免干扰 Markdown 输出 - 更新 BaseReader 接口文档,明确 supports() 和 parse() 职责划分 - 同步 delta specs 到主 specs(document-reading、html-reader、configuration、encoding-detection)
This commit is contained in:
@@ -2,6 +2,7 @@
|
||||
|
||||
import re
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
from typing import List, Optional, Tuple
|
||||
|
||||
IMAGE_PATTERN = re.compile(r"!\[[^\]]*\]\([^)]+\)")
|
||||
@@ -75,13 +76,18 @@ def safe_open_zip(zip_file: zipfile.ZipFile, name: str) -> Optional[zipfile.ZipE
|
||||
"""安全地从 ZipFile 中打开文件,防止路径遍历攻击"""
|
||||
if not name:
|
||||
return None
|
||||
if name.startswith("/") or name.startswith(".."):
|
||||
|
||||
try:
|
||||
normalized = Path(name).as_posix()
|
||||
# 检查是否包含父目录引用
|
||||
if ".." in Path(normalized).parts:
|
||||
return None
|
||||
# 检查是否为绝对路径
|
||||
if Path(normalized).is_absolute():
|
||||
return None
|
||||
return zip_file.open(name)
|
||||
except (ValueError, OSError):
|
||||
return None
|
||||
if "/../" in name or name.endswith("/.."):
|
||||
return None
|
||||
if "\\" in name:
|
||||
return None
|
||||
return zip_file.open(name)
|
||||
|
||||
|
||||
def normalize_markdown_whitespace(content: str) -> str:
|
||||
@@ -171,6 +177,13 @@ def search_markdown(
|
||||
content: str, pattern: str, context_lines: int = 0
|
||||
) -> Optional[str]:
|
||||
"""使用正则表达式搜索 markdown 文档,返回匹配结果及其上下文"""
|
||||
# 边界检查
|
||||
if not content:
|
||||
return None
|
||||
|
||||
if context_lines < 0:
|
||||
raise ValueError("context_lines 必须为非负整数")
|
||||
|
||||
try:
|
||||
regex = re.compile(pattern)
|
||||
except re.error:
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"""统一解析调度器,负责根据输入类型选择合适的 reader 进行解析。"""
|
||||
|
||||
import os
|
||||
import argparse
|
||||
import sys
|
||||
from typing import List, Optional, Tuple
|
||||
|
||||
@@ -10,7 +10,6 @@ from core.markdown import (
|
||||
remove_markdown_images,
|
||||
)
|
||||
from readers import BaseReader
|
||||
from utils import detect_file_type, is_html_file, is_url
|
||||
|
||||
|
||||
def parse_input(
|
||||
@@ -18,7 +17,7 @@ def parse_input(
|
||||
readers: List[BaseReader],
|
||||
) -> Tuple[Optional[str], List[str]]:
|
||||
"""
|
||||
统一解析入口函数,根据输入类型自动选择合适的 reader。
|
||||
统一解析入口函数,遍历 readers 选择合适的 reader 进行解析。
|
||||
|
||||
返回: (content, failures)
|
||||
- content: 成功时返回 Markdown 内容,失败时返回 None
|
||||
@@ -27,35 +26,11 @@ def parse_input(
|
||||
if not input_path:
|
||||
raise FileDetectionError("输入路径不能为空")
|
||||
|
||||
# 检测是否为 URL
|
||||
if is_url(input_path):
|
||||
# URL 交给 HTML reader
|
||||
for reader in readers:
|
||||
if hasattr(reader, "download_and_parse"):
|
||||
return reader.download_and_parse(input_path)
|
||||
raise ReaderNotFoundError("未找到支持 URL 下载的 reader")
|
||||
for reader in readers:
|
||||
if reader.supports(input_path):
|
||||
return reader.parse(input_path)
|
||||
|
||||
# 检测文件是否存在
|
||||
if not os.path.exists(input_path):
|
||||
raise FileDetectionError(f"文件不存在: {input_path}")
|
||||
|
||||
# 检测文件类型
|
||||
file_type = detect_file_type(input_path)
|
||||
|
||||
if file_type:
|
||||
# Office/PDF 文件
|
||||
for reader in readers:
|
||||
if reader.supports(input_path):
|
||||
return reader.parse(input_path)
|
||||
raise ReaderNotFoundError(f"未找到支持 {file_type.upper()} 格式的 reader")
|
||||
elif is_html_file(input_path):
|
||||
# HTML 文件
|
||||
for reader in readers:
|
||||
if reader.supports(input_path):
|
||||
return reader.parse(input_path)
|
||||
raise ReaderNotFoundError("未找到支持 HTML 格式的 reader")
|
||||
else:
|
||||
raise FileDetectionError(f"无法识别的文件类型: {input_path}")
|
||||
raise ReaderNotFoundError(f"未找到支持的 reader: {input_path}")
|
||||
|
||||
|
||||
def process_content(content: str) -> str:
|
||||
@@ -67,7 +42,7 @@ def process_content(content: str) -> str:
|
||||
|
||||
def output_result(
|
||||
content: str,
|
||||
args: any,
|
||||
args: argparse.Namespace,
|
||||
) -> None:
|
||||
"""根据命令行参数输出结果"""
|
||||
if args.count:
|
||||
|
||||
Reference in New Issue
Block a user