check_py34.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. #!/usr/bin/env python3
  2. """Reject Python syntax the device's Python 3.4 runtime cannot byte-compile.
  3. Why this exists
  4. ---------------
  5. mod-ui is developed on a modern Python but SHIPPED inside a MOD OS image whose
  6. Buildroot toolchain provides Python 3.4. A construct newer than 3.4 does not
  7. fail loudly: the image build's byte-compile step fails for that module, the
  8. cleanup step deletes the .py source anyway, and the device ships with the module
  9. MISSING or stale. The symptom then appears somewhere unrelated.
  10. That happened once already (September 2026): three f-strings in session.py
  11. took mod-ui down on the device, and the cause was first misdiagnosed as an
  12. incremental-build problem.
  13. This checker parses each file with the host interpreter's `ast` module and
  14. rejects node types that do not exist in 3.4. It needs no 3.4 interpreter,
  15. which is what makes it runnable in CI.
  16. Usage
  17. -----
  18. python3 tools/check_py34.py # check everything that ships
  19. python3 tools/check_py34.py path/to/file.py # check specific files
  20. Exit status is 1 if anything is rejected, 0 otherwise.
  21. """
  22. import ast
  23. import os
  24. import subprocess
  25. import sys
  26. # node type -> (minimum Python version, what to write instead)
  27. FORBIDDEN = {
  28. 'JoinedStr': ('3.6', 'f-string', 'use % formatting or .format()'),
  29. 'AnnAssign': ('3.6', 'variable annotation', 'use a plain assignment, or a comment'),
  30. 'NamedExpr': ('3.8', 'walrus operator :=', 'assign on a separate line'),
  31. 'AsyncFunctionDef': ('3.5', 'async def', 'use tornado gen.coroutine'),
  32. 'Await': ('3.5', 'await', 'use tornado yield'),
  33. 'AsyncFor': ('3.5', 'async for', 'use tornado gen.coroutine'),
  34. 'AsyncWith': ('3.5', 'async with', 'use tornado gen.coroutine'),
  35. 'MatMult': ('3.5', 'matrix multiply @', 'not applicable here'),
  36. 'Match': ('3.10', 'match statement', 'use if/elif'),
  37. }
  38. # Directories and files that never reach the device.
  39. EXCLUDE_PREFIXES = ('test/', '.github/', 'mod/old/')
  40. EXCLUDE_FILES = {
  41. 'tools/check_py34.py',
  42. # Python 2 leftovers, broken since the 2015 migration and not shipped as
  43. # working tools. If any is ever revived, delete its line here FIRST.
  44. 'hmi_debug.py',
  45. 'host_debug.py',
  46. 'bluetooth.py',
  47. }
  48. class Scanner(ast.NodeVisitor):
  49. def __init__(self, path):
  50. self.path = path
  51. self.hits = []
  52. def generic_visit(self, node):
  53. name = type(node).__name__
  54. if name in FORBIDDEN:
  55. ver, what, fix = FORBIDDEN[name]
  56. self.hits.append((getattr(node, 'lineno', 0), ver, what, fix))
  57. # starred assignment targets: a, *b = ... is 3.0+, fine.
  58. super().generic_visit(node)
  59. def shipped_files():
  60. out = subprocess.check_output(['git', 'ls-files', '*.py'], text=True)
  61. for f in out.splitlines():
  62. if f.startswith(EXCLUDE_PREFIXES) or f in EXCLUDE_FILES:
  63. continue
  64. yield f
  65. def check(path):
  66. try:
  67. with open(path, 'rb') as fh:
  68. tree = ast.parse(fh.read(), filename=path)
  69. except SyntaxError as e:
  70. # Already unparseable by the HOST python -- worse than a 3.4 problem.
  71. return [(e.lineno or 0, '3.0', 'file does not parse at all', str(e))]
  72. s = Scanner(path)
  73. s.visit(tree)
  74. # One report per line: a single f-string can hold several nested nodes.
  75. seen, unique = set(), []
  76. for hit in s.hits:
  77. key = (hit[0], hit[2])
  78. if key not in seen:
  79. seen.add(key)
  80. unique.append(hit)
  81. return unique
  82. def main(argv):
  83. paths = argv[1:] or sorted(shipped_files())
  84. failures = 0
  85. for p in paths:
  86. for lineno, ver, what, fix in check(p):
  87. failures += 1
  88. print('%s:%d: %s requires Python %s; the device runs 3.4 -- %s'
  89. % (p, lineno, what, ver, fix))
  90. if failures:
  91. print('')
  92. print('%d construct(s) the device cannot byte-compile.' % failures)
  93. print('A failure here is not cosmetic: the image build deletes the .py source')
  94. print('after a failed byte-compile, so the device ships without the module.')
  95. return 1
  96. print('checked %d shipped file(s): all parse under Python 3.4' % len(paths))
  97. return 0
  98. if __name__ == '__main__':
  99. sys.exit(main(sys.argv))