"""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())
本例需在 Windows、Python 3.12。各实验所需工具和版本见下载包 README。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows、Python 3.12。各实验所需工具和版本见下载包 README。
入口文件:projects/skills-review/review.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
review.py,或下载右侧课程工程包。 - 确认本地已准备 Windows、Python 3.12。各实验所需工具和版本见下载包 README。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a351.zip
课程关联工程包(登记关联39章) · 含当前章节或实例 · mbskycom202612a331.zip