蓝色天空网mbsky.com · 知识 · 实践 · 创造Skills(技能) · 本地阅读预览
教程 / AI / 智能开发 / Skills(技能)

Skill 实战:自动代码审查

组合独立的语法、风格、复杂度和类型检查,交付可定位的报告。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

文件是审查输入,工具由工程固定

按后缀选择 Python、JavaScript 或 TypeScript 检查。把样本复制到临时位置,由熟悉的工具静态读取。py_compile 生成临时字节码,不导入或运行待审模块。语法失败时先报告原文件行列。

项目清单声明环境和版本。历史示例自动安装缺失工具,可能改变运行环境。本站事先准备依赖,缺工具时报告覆盖缺口。样本按 README 操作,可在隔离目录重现。

区分风格、复杂度与类型诊断

用 flake8 读取行号、列、诊断码与说明。F 类提示通常来自 PyFlakes,E 或 W 由配置和检查器决定。复杂度本例使用 flake8 的 McCabe 插件与明确阈值,Radon 的计算与等级输出需以其规则另外核对。

JS 和 TS 例子用 TypeScript 编译器,以 --noEmit 做静态检查。JS 显式开启 --allowJs 与 --checkJs。ESLint 关注的规则可与类型检查并用,需配置本地版本与适用规则,验证样本未执行。

让报告能区分没有问题与覆盖不足

结果表列出诊断编号、位置和实际检查器,优先展示需要先修复的三项,同时保留全量诊断。本例优先语法、潜在错误和类型,再给出复杂度与格式。评级只是工程演练的输出规则。

检查工具不存在、输出格式不对或执行故障应记跳过或工具失败。单独验证干净样本与有意留下错误的样本,核对语法失败后可以定位,补齐测试再判断质量。

审查任务、语言与观察

条目用途与条件
Python运行 py_compile,审查输入代码不被执行。
Python实际运行 flake8,读取行列及诊断号。
Python运行 McCabe C901 作为本例阈值。Radon 等级需独立核验。
JS/TS本站用 tsc 无产物类型检查,ESLint 规则另核。
各输入语言聚合工具、覆盖范围及 Top 3 优先项。

审查实际 Python、JS 与 TS 样本

python · 阅读源码
"""Review selected code files as data and aggregate real tool diagnostics."""
import argparse
from importlib.metadata import PackageNotFoundError,version
import json
from pathlib import Path
import py_compile
import re
from shutil import which
import subprocess
import sys
from tempfile import TemporaryDirectory

TS_MESSAGE=re.compile(r"^(?:.+\((\d+),(\d+)\): )?error (TS\d+): (.+)$")


def issue(tool,code,line,column,text):
    return {"tool":tool,"code":code,"line":line,"column":column,"message":text}


def call(arguments,work):
    return subprocess.run(arguments,cwd=work,capture_output=True,encoding="utf-8",errors="replace",timeout=15)


def python_review(source,work):
    try:
        py_compile.compile(str(source),cfile=str(work/"compiled.pyc"),doraise=True)
    except py_compile.PyCompileError as error:
        failure=error.exc_value
        return False,[issue("py_compile","SYNTAX",failure.lineno,failure.offset,failure.msg)],[]

    try:
        installed=version("flake8")
    except PackageNotFoundError:
        return True,[],["flake8"]
    result=call([sys.executable,"-B","-s","-m","flake8","--isolated","--jobs=1","--max-complexity=3",
                 "--max-line-length=88","--format=%(row)d:%(col)d:%(code)s:%(text)s",str(source)],work)
    findings=[]
    try:
        for raw in result.stdout.splitlines():
            line,column,code,text=raw.split(":",3)
            findings.append(issue("flake8-"+installed,code,int(line),int(column),text))
    except ValueError:
        return True,[],["flake8_output"]
    if result.returncode not in (0,1) or (result.returncode==1 and not findings) or result.stderr:
        return True,findings,["flake8_tool_failure"]
    return True,findings,[]


def javascript_review(source,compiler,work):
    node=which("node")
    if not node or compiler is None or not compiler.is_file():
        return None,[],["typescript"]
    options=["--pretty","false","--noEmit","--strict","--skipLibCheck"]
    if source.suffix==".js":
        options.extend(("--allowJs","--checkJs"))
    result=call([node,str(compiler.resolve()),*options,str(source)],work)
    findings=[]
    for raw in result.stdout.splitlines():
        match=TS_MESSAGE.fullmatch(raw)
        if match:
            line,column,code,text=match.groups()
            findings.append(issue("tsc",code,int(line or 0),int(column or 0),text))
    if result.stderr or (result.returncode and not findings):
        return None,findings,["typescript_tool_failure"]
    return None,findings,[]


def review(source,compiler=None):
    suffix=source.suffix.lower()
    if suffix not in (".py",".js",".ts"):
        return {"status":"input_error","code":"FORMAT"}
    if not source.is_file():
        return {"status":"input_error","code":"MISSING"}
    if source.stat().st_size>512000:
        return {"status":"input_error","code":"SIZE"}
    raw=source.read_bytes()
    with TemporaryDirectory(prefix="review-input-") as stage:
        work=Path(stage)
        staged=work/("submission"+suffix)
        staged.write_bytes(raw)
        if suffix==".py":
            syntax,findings,unavailable=python_review(staged,work)
        else:
            syntax,findings,unavailable=javascript_review(staged,compiler,work)
    def priority(item):
        code=item["code"]
        return 0 if code=="SYNTAX" else 1 if code.startswith(("F","TS")) else 2 if code=="C901" else 3
    findings.sort(key=lambda row:(priority(row),row["line"] or 0,row["column"] or 0,row["code"]))
    outcome="partial" if unavailable else "complete"
    grade=None if unavailable else "F" if syntax is False else "B" if findings else "A"
    return {"file":source.name,"status":outcome,"grade":grade,"syntax_ok":syntax,
            "issues":findings,"top":findings[:3],"skipped":unavailable,
            "counts":{"syntax":sum(row["code"]=="SYNTAX" for row in findings),
                      "style_or_bug":sum(row["code"].startswith(("E","W","F")) for row in findings),
                      "complexity":sum(row["code"]=="C901" for row in findings),
                      "tsc":sum(row["code"].startswith("TS") for row in findings)}}


def main():
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument("source",type=Path)
    parser.add_argument("--typescript",type=Path)
    args=parser.parse_args()
    try:
        outcome=review(args.source,args.typescript)
    except (subprocess.SubprocessError,OSError) as error:
        outcome={"status":"tool_error","code":type(error).__name__}
    print(json.dumps(outcome,ensure_ascii=False))
    return 0 if outcome["status"] in ("complete","partial") else 2


if __name__=="__main__":
    raise SystemExit(main())
预期结果 · 待实际运行核验
  • 对提交文件只做编译或静态分析。实测 Python 语法错误、风格、未使用变量与复杂度,以及 JS 和 TS 类型不匹配,并按位置汇总。
审查实际 Python、JS 与 TS 样本

所需环境:Windows、Python 3.12。各实验所需工具和版本见下载包 README。

当前源码 SHA256:88a48f3f28b3b785d26ba3f600bb7871800cc628cf6061a42b2dbc849a634421

下载本站示例源码

运行本地实验

解压后按 README 运行当前章节对应的脚本,并查看真实输出。

下载 Skills 基础实验

所需环境:Windows、Python 3.12。各实验所需工具和版本见下载包 README。

ZIP SHA256:029a845724912c8cbe74d06765bb66a655aa5bb49b228422a5ebdd26b3ba67b1

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

为什么不能把某次未加载 linter 的报告评成 A?

展开参考解答

工具缺失时结果范围不完整。另记跳过项,先核对工具实际运行和诊断,再解释全部覆盖情况。

规范与官方依据