check-document-python.mjs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. #!/usr/bin/env node
  2. import { readFile, readdir } from "node:fs/promises";
  3. import { extname, join } from "node:path";
  4. import { fileURLToPath } from "node:url";
  5. const root =
  6. process.argv[2] || fileURLToPath(new URL("../apps/zcode-cli/packages", import.meta.url));
  7. const extensions = new Set([".md", ".sh", ".ps1", ".py", ".js", ".mjs", ".ts"]);
  8. const selection = /\$\(command -v zcode-python \|\| command -v python3\)/g;
  9. // 只匹配命令形态;语言名、包名、围栏标签、shebang 和字典键不是调用。
  10. function hasBareCommand(line, extension) {
  11. if (line.startsWith("#!")) return false;
  12. // Markdown 表格里的管道符必须转义,扫描时还原呈现给 Agent 的命令。
  13. const command =
  14. extension === ".md" && line.trimStart().startsWith("|") ? line.replaceAll("\\|", "|") : line;
  15. const text = command.replace(selection, "SELECTED_PYTHON");
  16. return (
  17. /(?<![\w-])(["']?)python3?\b\1[ \t]+(?:-[\w-]|["'$./]|[^\s]+\.py\b|<<)/.test(text) ||
  18. /(?:^|[;|&`])[ \t]*(?:(?:if|then|elif|exec|sudo|!)[ \t]+)*python3?[ \t]+[^\s`(]/.test(text) ||
  19. /\b(?:command -v|which)[ \t]+python3?\b/.test(text) ||
  20. /(?<!-m )\bpip3?[ \t]+install\b/.test(text) ||
  21. /\b(?:spawn|execFile|run|Popen|call)\s*\(\s*\[?\s*["']python3?["']/.test(text) ||
  22. // 直接执行 "$DIR/x.py" 会经 shebang 落到系统 python3;只认带参数的命令位置,模块路径说明不算调用。
  23. /(?:^|[;|&`(])[ \t]*(?:(?:if|then|elif|exec|sudo|!)[ \t]+)*(["']?)(?:\$|\.{1,2}\/|~\/|\/)[^\s"'`]*\.py\1(?=[ \t]+[^\s`])/.test(
  24. text,
  25. )
  26. );
  27. }
  28. async function checkDirectory(directory, failures) {
  29. for (const entry of await readdir(directory, { withFileTypes: true })) {
  30. const path = join(directory, entry.name);
  31. if (entry.isDirectory()) await checkDirectory(path, failures);
  32. else if (entry.isFile() && extensions.has(extname(entry.name))) {
  33. const lines = (await readFile(path, "utf8")).split(/\r?\n/);
  34. for (const [index, line] of lines.entries()) {
  35. if (hasBareCommand(line, extname(entry.name)))
  36. failures.push(`${path}:${index + 1}: use the selected Python interpreter`);
  37. }
  38. }
  39. }
  40. }
  41. try {
  42. const failures = [];
  43. for (const plugin of ["documents", "pdf", "presentations", "spreadsheets"]) {
  44. for (const directory of ["skills", "scripts"]) {
  45. await checkDirectory(join(root, `${plugin}-plugin`, directory), failures);
  46. }
  47. }
  48. if (failures.length) {
  49. process.stderr.write(`${failures.join("\n")}\n`);
  50. process.exitCode = 1;
  51. } else process.stdout.write("Document Python commands use the selected interpreter.\n");
  52. } catch (error) {
  53. process.stderr.write(`${error.message}\n`);
  54. process.exitCode = 1;
  55. }