From e22476e0aacba45980c336ce79fc25adcc7a4b6b Mon Sep 17 00:00:00 2001 From: ydliu2 Date: Sat, 2 May 2026 19:56:30 +0800 Subject: [PATCH] fix: improve code quality across all 8 core scripts - Sort imports alphabetically (isort/Ruff I rule) - Replace broad Exception catches with specific OSError - Use Optional[T] instead of T = None for type hints - Remove debug print statements from plugin_manager.py - Remove internal import (re) already at module level in analyze_project.py - Move json import to top level in generate_toc.py - Fix single-line if statements in analyze_project.py (Ruff E701) - Remove traceback.print_exc() from plugin_manager.py error handler All 8 scripts verified to compile cleanly. Co-Authored-By: Claude Opus 4.7 (1M context) --- scripts/analyze_project.py | 29 ++++++++++++++++------------- scripts/check_quality.py | 8 ++++---- scripts/detect_changes.py | 16 ++++++++-------- scripts/extract_docs.py | 4 ++-- scripts/generate_diagram.py | 4 ++-- scripts/generate_toc.py | 7 +++---- scripts/init_wiki.py | 4 ++-- scripts/plugin_manager.py | 22 +++++++--------------- 8 files changed, 44 insertions(+), 50 deletions(-) diff --git a/scripts/analyze_project.py b/scripts/analyze_project.py index c3990fd..80694f1 100644 --- a/scripts/analyze_project.py +++ b/scripts/analyze_project.py @@ -5,11 +5,12 @@ 输出适配 .mini-wiki 目录结构 """ -import os import json -from pathlib import Path -from typing import Dict, List, Optional, Any, Set +import os +import re from datetime import datetime, timezone +from pathlib import Path +from typing import Any, Dict, List, Optional, Set # 忽略的目录 IGNORE_DIRS = { @@ -79,15 +80,18 @@ def detect_monorepo_tools(root_path: Path) -> List[str]: # workspace configs if (root_path / 'pnpm-workspace.yaml').exists(): tools.append('pnpm-workspaces') - if 'monorepo' not in tools: tools.append('monorepo') - + if 'monorepo' not in tools: + tools.append('monorepo') + if (root_path / 'lerna.json').exists(): tools.append('lerna') - if 'monorepo' not in tools: tools.append('monorepo') - + if 'monorepo' not in tools: + tools.append('monorepo') + if (root_path / 'turbo.json').exists(): tools.append('turborepo') - if 'monorepo' not in tools: tools.append('monorepo') + if 'monorepo' not in tools: + tools.append('monorepo') # check package.json for workspaces pkg_path = root_path / 'package.json' @@ -96,8 +100,9 @@ def detect_monorepo_tools(root_path: Path) -> List[str]: with open(pkg_path, 'r', encoding='utf-8') as f: pkg = json.load(f) if 'workspaces' in pkg: - tools.append('npm-workspaces') # or yarn/bun workspaces, generic term - if 'monorepo' not in tools: tools.append('monorepo') + tools.append('npm-workspaces') + if 'monorepo' not in tools: + tools.append('monorepo') except Exception: pass @@ -162,8 +167,6 @@ def detect_project_types(root_path: Path) -> List[str]: if isinstance(deps, dict): all_deps.update(deps.keys()) if isinstance(deps_std, list): - # Simple parsing for "package>=1.0" - import re for d in deps_std: match = re.match(r'^([a-zA-Z0-9_-]+)', d) if match: @@ -251,7 +254,7 @@ def find_entry_points(root_path: Path, project_types: List[str]) -> List[str]: return entries -def discover_modules(root_path: Path, exclude_dirs: Set[str] = None) -> List[Dict[str, Any]]: +def discover_modules(root_path: Path, exclude_dirs: Optional[Set[str]] = None) -> List[Dict[str, Any]]: """发现项目模块""" if exclude_dirs is None: exclude_dirs = IGNORE_DIRS diff --git a/scripts/check_quality.py b/scripts/check_quality.py index 2dc1248..b84ed68 100644 --- a/scripts/check_quality.py +++ b/scripts/check_quality.py @@ -4,14 +4,14 @@ 检查生成的文档是否符合 v3.0.2 质量标准 """ +import argparse +import json import os import re -import json -import argparse -from pathlib import Path from dataclasses import dataclass, field -from typing import List, Dict, Optional from datetime import datetime +from pathlib import Path +from typing import Dict, List, Optional @dataclass diff --git a/scripts/detect_changes.py b/scripts/detect_changes.py index ea10c07..c19ac83 100644 --- a/scripts/detect_changes.py +++ b/scripts/detect_changes.py @@ -4,12 +4,12 @@ 对比文件校验和,检测项目变更以支持增量更新 """ -import os import json import hashlib -from pathlib import Path -from typing import Dict, List, Set, Tuple, Any +import os from datetime import datetime, timezone +from pathlib import Path +from typing import Any, Dict, Optional, Set # 默认排除规则 DEFAULT_EXCLUDES = { @@ -39,7 +39,7 @@ def calculate_file_hash(file_path: str) -> str: for chunk in iter(lambda: f.read(8192), b''): sha256.update(chunk) return sha256.hexdigest()[:16] # 只取前16位 - except Exception: + except OSError: return "" @@ -58,7 +58,7 @@ def should_include_file(file_path: Path, excludes: Set[str]) -> bool: return file_path.suffix in CODE_EXTENSIONS or file_path.suffix in DOC_EXTENSIONS -def scan_project_files(project_root: str, excludes: Set[str] = None) -> Dict[str, str]: +def scan_project_files(project_root: str, excludes: Optional[Set[str]] = None) -> Dict[str, str]: """ 扫描项目文件并计算校验和 @@ -96,7 +96,7 @@ def save_checksums(wiki_dir: str, checksums: Dict[str, Dict[str, str]]): json.dump(checksums, f, indent=2, ensure_ascii=False) -def detect_changes(project_root: str, excludes: Set[str] = None) -> Dict[str, Any]: +def detect_changes(project_root: str, excludes: Optional[Set[str]] = None) -> Dict[str, Any]: """ 检测项目变更 @@ -159,8 +159,8 @@ def detect_changes(project_root: str, excludes: Set[str] = None) -> Dict[str, An } -def update_checksums_cache(project_root: str, current_checksums: Dict[str, str], - doc_mapping: Dict[str, str] = None): +def update_checksums_cache(project_root: str, current_checksums: Dict[str, str], + doc_mapping: Optional[Dict[str, str]] = None) -> None: """ 更新校验和缓存 diff --git a/scripts/extract_docs.py b/scripts/extract_docs.py index 0fc89bf..7128d63 100644 --- a/scripts/extract_docs.py +++ b/scripts/extract_docs.py @@ -5,9 +5,9 @@ """ import re -from pathlib import Path -from typing import Dict, List, Optional, Any from dataclasses import dataclass +from pathlib import Path +from typing import Any, Dict, List, Optional @dataclass diff --git a/scripts/generate_diagram.py b/scripts/generate_diagram.py index f72e50e..8e0baad 100644 --- a/scripts/generate_diagram.py +++ b/scripts/generate_diagram.py @@ -5,9 +5,9 @@ """ import json -from pathlib import Path -from typing import Dict, List, Any, Optional import re +from pathlib import Path +from typing import Any, Dict, List, Optional def generate_architecture_diagram(structure: Dict[str, Any]) -> str: diff --git a/scripts/generate_toc.py b/scripts/generate_toc.py index c6ad996..aee8bb7 100644 --- a/scripts/generate_toc.py +++ b/scripts/generate_toc.py @@ -4,10 +4,10 @@ 为 wiki 生成导航目录 """ +import json import os from pathlib import Path -from typing import List, Dict, Any -import re +from typing import Any, Dict, List def extract_title_from_markdown(file_path: str) -> str: @@ -20,7 +20,7 @@ def extract_title_from_markdown(file_path: str) -> str: return line[2:].strip() # 如果没有找到标题,使用文件名 return Path(file_path).stem.replace('-', ' ').replace('_', ' ').title() - except Exception: + except OSError: return Path(file_path).stem @@ -117,7 +117,6 @@ def generate_sidebar(wiki_dir: str) -> str: sidebar['/modules/'] = module_items # 生成 JSON 格式 - import json return json.dumps(sidebar, indent=2, ensure_ascii=False) diff --git a/scripts/init_wiki.py b/scripts/init_wiki.py index 8084b23..3aacacd 100644 --- a/scripts/init_wiki.py +++ b/scripts/init_wiki.py @@ -4,11 +4,11 @@ 创建 .mini-wiki 目录结构和默认配置 """ -import os import json +import os import shutil -from pathlib import Path from datetime import datetime, timezone +from pathlib import Path from typing import Optional diff --git a/scripts/plugin_manager.py b/scripts/plugin_manager.py index 5c34243..bd61c12 100644 --- a/scripts/plugin_manager.py +++ b/scripts/plugin_manager.py @@ -6,15 +6,16 @@ """ import os -import sys +import re import shutil +import sys import zipfile -import urllib.request +from datetime import datetime from pathlib import Path -from typing import Dict, List, Optional, Any +from typing import Any, Dict, List, Optional + +import urllib.request import yaml -import re -from datetime import datetime def get_plugins_dir(project_root: str) -> Path: """Get the plugins directory path.""" @@ -229,19 +230,14 @@ def install_plugin(project_root: str, source: str) -> Dict[str, Any]: target_name = re.sub(r'[^a-zA-Z0-9_-]', '-', target_name).lower() target_dir = plugins_dir / target_name - print(f"Installing to: {target_dir}") - print(f"Source path is: {source_path}") - + # Copy plugin if target_dir.exists(): shutil.rmtree(target_dir) shutil.copytree(source_path, target_dir) - - print(f"Directory contents: {list(target_dir.iterdir())}") # Update registry registry = load_registry(project_root) - print(f"Registry loaded, plugins count: {len(registry.get('plugins', []))}") plugins = registry.get('plugins', []) # Remove existing entry if exists @@ -285,9 +281,7 @@ def install_plugin(project_root: str, source: str) -> Dict[str, Any]: }) registry['plugins'] = plugins - print(f"Saving registry with {len(plugins)} plugins...") save_registry(project_root, registry) - print("Registry saved.") # Cleanup temp_zip = plugins_dir / '_temp.zip' @@ -303,8 +297,6 @@ def install_plugin(project_root: str, source: str) -> Dict[str, Any]: except Exception as e: result['message'] = f'Installation failed: {str(e)}' - import traceback - traceback.print_exc() return result