蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

离线校验 AST 安全移动与删除拦截、全局正则搜索、文件模板渲染与本地历史回滚

PYTHONWindows x64、CPython 3.12.14 离线 PyCharm 工程语义与配置验证器(未启动桌面端 PyCharm IDE)。explore-file.py
explore-file.py201 行
"""Offline Python verification lab for PyCharm Chapter 08 (file)."""
import ast
import difflib
import json
import re
import tempfile
from pathlib import Path

VERSION = "CPython 3.12.14 offline PyCharm workflow verifier (desktop IDE not launched)"


def case_safe_rename_move_and_delete():
    with tempfile.TemporaryDirectory() as tmp:
        root = Path(tmp)
        (root / "utils").mkdir()
        (root / "core").mkdir()
        (root / "utils" / "helper.py").write_text("def greet():\n    return 'ok'\n", encoding="utf-8")
        app = root / "app.py"
        app.write_text("from utils.helper import greet\n\nresult = greet()\n", encoding="utf-8")

        tree = ast.parse(app.read_text(encoding="utf-8"))
        refs_before = [
            f"{node.module}.{alias.name}"
            for node in ast.walk(tree)
            if isinstance(node, ast.ImportFrom) and node.module == "utils.helper"
            for alias in node.names
        ]
        safe_delete_blocked = len(refs_before) > 0

        # Simulate safe move: utils/helper.py -> core/helper.py and rewrite imports
        (root / "utils" / "helper.py").rename(root / "core" / "helper.py")
        rewritten = app.read_text(encoding="utf-8").replace("from utils.helper import", "from core.helper import")
        app.write_text(rewritten, encoding="utf-8")

        new_tree = ast.parse(app.read_text(encoding="utf-8"))
        refs_after = [
            node.module
            for node in ast.walk(new_tree)
            if isinstance(node, ast.ImportFrom)
        ]

        # Batch rename pattern test_*.py -> spec_*.py
        samples = ["test_auth.py", "test_order.py", "main.py"]
        batch_renamed = [re.sub(r"^test_(.+\.py)$", r"spec_\1", name) for name in samples]

        expected = {
            "refs_before": ["utils.helper.greet"],
            "safe_delete_blocked": True,
            "moved_exists": True,
            "refs_after": ["core.helper"],
            "batch_renamed": ["spec_auth.py", "spec_order.py", "main.py"],
        }
        actual = {
            "refs_before": refs_before,
            "safe_delete_blocked": safe_delete_blocked,
            "moved_exists": (root / "core" / "helper.py").is_file(),
            "refs_after": refs_after,
            "batch_renamed": batch_renamed,
        }
    return {
        "name": "safe_rename_move_and_delete",
        "summary": "基于 AST 引用分析验证安全移动(导入路径自动更新)、安全删除拦截与批量模式重命名",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_navigation_search_and_diff():
    files = {
        "models/user.py": "class User:\n    def get_name(self):\n        return 'alice'\n",
        "services/auth.py": "def verify_token(token):\n    return token.startswith('bs_')\n",
    }
    file_hits = [p for p in files if "user" in p]
    class_hits = []
    symbol_hits = []
    for path, src in files.items():
        tree = ast.parse(src)
        for node in ast.walk(tree):
            if isinstance(node, ast.ClassDef):
                class_hits.append(node.name)
            elif isinstance(node, ast.FunctionDef):
                symbol_hits.append(node.name)

    regex_matches = [p for p, src in files.items() if re.search(r"def\s+verify_\w+", src)]
    diff_lines = list(
        difflib.unified_diff(
            ["mode = 'dev'\n", "port = 8000\n"],
            ["mode = 'prod'\n", "port = 8000\n"],
            fromfile="old.py",
            tofile="new.py",
            n=1,
        )
    )
    expected = {
        "file_hits": ["models/user.py"],
        "class_hits": ["User"],
        "symbol_hits": ["get_name", "verify_token"],
        "regex_matches": ["services/auth.py"],
        "diff_changed": True,
    }
    actual = {
        "file_hits": file_hits,
        "class_hits": class_hits,
        "symbol_hits": symbol_hits,
        "regex_matches": regex_matches,
        "diff_changed": any(ln.startswith("-mode = 'dev'") for ln in diff_lines) and any(ln.startswith("+mode = 'prod'") for ln in diff_lines),
    }
    return {
        "name": "navigation_search_and_diff",
        "summary": "验证按文件/类/符号快速导航、正则全局搜索与 difflib 文件差异对比",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_file_template_rendering():
    template = (
        "#!/usr/bin/env python\n"
        "# -*- coding: utf-8 -*-\n\n"
        '"""\n'
        "@Author: ${USER}\n"
        "@Date: ${DATE}\n"
        "@Description: demo module\n"
        '"""\n\n'
        "def main():\n"
        "    pass\n\n"
        "if __name__ == '__main__':\n"
        "    main()\n"
    )
    rendered = template.replace("${USER}", "developer").replace("${DATE}", "2026-12-01")
    tree = ast.parse(rendered)
    funcs = [n.name for n in tree.body if isinstance(n, ast.FunctionDef)]
    expected = {
        "ast_valid": True,
        "docstring_has_author": True,
        "functions": ["main"],
        "has_main_guard": True,
    }
    actual = {
        "ast_valid": True,
        "docstring_has_author": "@Author: developer" in (ast.get_docstring(tree) or ""),
        "functions": funcs,
        "has_main_guard": "if __name__ == '__main__':" in rendered,
    }
    return {
        "name": "file_template_rendering",
        "summary": "渲染 Python Script 文件模板占位符(${USER}/${DATE})并验证生成脚本语法合法",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_local_history_bookmarks_and_exclude():
    snapshots = [
        {"rev": 1, "content": "x = 1\n"},
        {"rev": 2, "content": "x = 2\n"},
        {"rev": 3, "deleted": True},
    ]
    restored = next(s["content"] for s in reversed(snapshots) if not s.get("deleted"))
    bookmarks = {
        "anonymous": [("app.py", 12)],
        "mnemonic": {"1": ("app.py", 28)},
    }
    ignore_rules = [".idea/", "build/", "__pycache__/"]
    expected = {
        "restored_content": "x = 2\n",
        "bookmark_total": 2,
        "mnemonic_1_line": 28,
        "idea_excluded": True,
    }
    actual = {
        "restored_content": restored,
        "bookmark_total": len(bookmarks["anonymous"]) + len(bookmarks["mnemonic"]),
        "mnemonic_1_line": bookmarks["mnemonic"]["1"][1],
        "idea_excluded": ".idea/" in ignore_rules,
    }
    return {
        "name": "local_history_bookmarks_and_exclude",
        "summary": "模拟本地历史误删恢复、匿名/编号书签索引与 Excluded 目录过滤规则",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_safe_rename_move_and_delete(),
        case_navigation_search_and_diff(),
        case_file_template_rendering(),
        case_local_history_bookmarks_and_exclude(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14 离线 PyCharm 工程语义与配置验证器(未启动桌面端 PyCharm IDE)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14 离线 PyCharm 工程语义与配置验证器(未启动桌面端 PyCharm IDE)。

入口文件:projects/pycharm-file-lab/explore-file.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-file.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14 离线 PyCharm 工程语义与配置验证器(未启动桌面端 PyCharm IDE)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:PyCharm

课程关联工程包(登记关联17章) · 含当前章节或实例 · mbskycom202612a2240.zip

下载课程关联工程包:PyCharm

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2244.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习