check.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. """Check for specific programs.
  2. """
  3. from enum import Enum
  4. import re
  5. import shutil
  6. from subprocess import DEVNULL, TimeoutExpired
  7. from tempfile import TemporaryDirectory
  8. from pathlib import Path
  9. from milc import cli
  10. from qmk import submodules
  11. class CheckStatus(Enum):
  12. OK = 1
  13. WARNING = 2
  14. ERROR = 3
  15. ESSENTIAL_BINARIES = {
  16. 'dfu-programmer': {},
  17. 'avrdude': {},
  18. 'dfu-util': {},
  19. 'avr-gcc': {
  20. 'version_arg': '-dumpversion'
  21. },
  22. 'arm-none-eabi-gcc': {
  23. 'version_arg': '-dumpversion'
  24. },
  25. }
  26. def _parse_gcc_version(version):
  27. m = re.match(r"(\d+)(?:\.(\d+))?(?:\.(\d+))?", version)
  28. return {
  29. 'major': int(m.group(1)),
  30. 'minor': int(m.group(2)) if m.group(2) else 0,
  31. 'patch': int(m.group(3)) if m.group(3) else 0,
  32. }
  33. def _check_arm_gcc_version():
  34. """Returns True if the arm-none-eabi-gcc version is not known to cause problems.
  35. """
  36. version_number = ESSENTIAL_BINARIES['arm-none-eabi-gcc']['output'].strip()
  37. cli.log.info('Found arm-none-eabi-gcc version %s', version_number)
  38. # Right now all known ARM versions are ok, so check that it can produce binaries
  39. return _check_arm_gcc_installation()
  40. def _check_arm_gcc_installation():
  41. """Returns OK if the arm-none-eabi-gcc is fully installed and can produce binaries.
  42. """
  43. with TemporaryDirectory() as temp_dir:
  44. temp_file = Path(temp_dir) / 'test.elf'
  45. args = ['arm-none-eabi-gcc', '-mcpu=cortex-m0', '-mthumb', '-mno-thumb-interwork', '--specs=nosys.specs', '--specs=nano.specs', '-x', 'c', '-o', str(temp_file), '-']
  46. result = cli.run(args, stdin=None, stdout=None, stderr=None, input='#include <newlib.h>\nint main() { return __NEWLIB__ * __NEWLIB_MINOR__ * __NEWLIB_PATCHLEVEL__; }')
  47. if result.returncode == 0:
  48. cli.log.info('Successfully compiled using arm-none-eabi-gcc')
  49. else:
  50. cli.log.error(f'Failed to compile a simple program with arm-none-eabi-gcc, return code {result.returncode}')
  51. cli.log.error(f'Command: {" ".join(args)}')
  52. return CheckStatus.ERROR
  53. args = ['arm-none-eabi-size', str(temp_file)]
  54. result = cli.run(args, stdin=None, stdout=None, stderr=None)
  55. if result.returncode == 0:
  56. cli.log.info('Successfully tested arm-none-eabi-binutils using arm-none-eabi-size')
  57. else:
  58. cli.log.error(f'Failed to execute arm-none-eabi-size, perhaps corrupt arm-none-eabi-binutils, return code {result.returncode}')
  59. cli.log.error(f'Command: {" ".join(args)}')
  60. return CheckStatus.ERROR
  61. return CheckStatus.OK
  62. def _check_avr_gcc_version():
  63. """Returns True if the avr-gcc version is not known to cause problems.
  64. """
  65. version_number = ESSENTIAL_BINARIES['avr-gcc']['output'].strip()
  66. cli.log.info('Found avr-gcc version %s', version_number)
  67. # Right now all known AVR versions are ok, so check that it can produce binaries
  68. return _check_avr_gcc_installation()
  69. def _check_avr_gcc_installation():
  70. """Returns OK if the avr-gcc is fully installed and can produce binaries.
  71. """
  72. with TemporaryDirectory() as temp_dir:
  73. temp_file = Path(temp_dir) / 'test.elf'
  74. args = ['avr-gcc', '-mmcu=atmega32u4', '-x', 'c', '-o', str(temp_file), '-']
  75. result = cli.run(args, stdin=None, stdout=None, stderr=None, input='int main() { return 0; }')
  76. if result.returncode == 0:
  77. cli.log.info('Successfully compiled using avr-gcc')
  78. else:
  79. cli.log.error(f'Failed to compile a simple program with avr-gcc, return code {result.returncode}')
  80. cli.log.error(f'Command: {" ".join(args)}')
  81. return CheckStatus.ERROR
  82. args = ['avr-size', str(temp_file)]
  83. result = cli.run(args, stdin=None, stdout=None, stderr=None)
  84. if result.returncode == 0:
  85. cli.log.info('Successfully tested avr-binutils using avr-size')
  86. else:
  87. cli.log.error(f'Failed to execute avr-size, perhaps corrupt avr-binutils, return code {result.returncode}')
  88. cli.log.error(f'Command: {" ".join(args)}')
  89. return CheckStatus.ERROR
  90. return CheckStatus.OK
  91. def _check_avrdude_version():
  92. last_line = ESSENTIAL_BINARIES['avrdude']['output'].split('\n')[-2]
  93. version_number = last_line.split()[2][:-1]
  94. cli.log.info('Found avrdude version %s', version_number)
  95. return CheckStatus.OK
  96. def _check_dfu_util_version():
  97. first_line = ESSENTIAL_BINARIES['dfu-util']['output'].split('\n')[0]
  98. version_number = first_line.split()[1]
  99. cli.log.info('Found dfu-util version %s', version_number)
  100. return CheckStatus.OK
  101. def _check_dfu_programmer_version():
  102. first_line = ESSENTIAL_BINARIES['dfu-programmer']['output'].split('\n')[0]
  103. version_number = first_line.split()[1]
  104. cli.log.info('Found dfu-programmer version %s', version_number)
  105. return CheckStatus.OK
  106. def check_binaries():
  107. """Iterates through ESSENTIAL_BINARIES and tests them.
  108. """
  109. ok = CheckStatus.OK
  110. for binary in sorted(ESSENTIAL_BINARIES):
  111. try:
  112. if not is_executable(binary):
  113. ok = CheckStatus.ERROR
  114. except TimeoutExpired:
  115. cli.log.debug('Timeout checking %s', binary)
  116. if ok != CheckStatus.ERROR:
  117. ok = CheckStatus.WARNING
  118. return ok
  119. def check_binary_versions():
  120. """Check the versions of ESSENTIAL_BINARIES
  121. """
  122. checks = {
  123. 'arm-none-eabi-gcc': _check_arm_gcc_version,
  124. 'avr-gcc': _check_avr_gcc_version,
  125. 'avrdude': _check_avrdude_version,
  126. 'dfu-util': _check_dfu_util_version,
  127. 'dfu-programmer': _check_dfu_programmer_version,
  128. }
  129. versions = []
  130. for binary in sorted(ESSENTIAL_BINARIES):
  131. if 'output' not in ESSENTIAL_BINARIES[binary]:
  132. cli.log.warning('Unknown version for %s', binary)
  133. versions.append(CheckStatus.WARNING)
  134. continue
  135. check = checks[binary]
  136. versions.append(check())
  137. return versions
  138. def check_submodules():
  139. """Iterates through all submodules to make sure they're cloned and up to date.
  140. """
  141. for submodule in submodules.status().values():
  142. if submodule['status'] is None:
  143. return CheckStatus.ERROR
  144. elif not submodule['status']:
  145. return CheckStatus.WARNING
  146. return CheckStatus.OK
  147. def is_executable(command):
  148. """Returns True if command exists and can be executed.
  149. """
  150. # Make sure the command is in the path.
  151. res = shutil.which(command)
  152. if res is None:
  153. cli.log.error("{fg_red}Can't find %s in your path.", command)
  154. return False
  155. # Make sure the command can be executed
  156. version_arg = ESSENTIAL_BINARIES[command].get('version_arg', '--version')
  157. check = cli.run([command, version_arg], combined_output=True, stdin=DEVNULL, timeout=5)
  158. ESSENTIAL_BINARIES[command]['output'] = check.stdout
  159. if check.returncode in [0, 1]: # Older versions of dfu-programmer exit 1
  160. cli.log.debug('Found {fg_cyan}%s', command)
  161. return True
  162. cli.log.error("{fg_red}Can't run `%s %s`", command, version_arg)
  163. return False
  164. def release_info(file='/etc/os-release'):
  165. """Parse release info to dict
  166. """
  167. ret = {}
  168. try:
  169. with open(file) as f:
  170. for line in f:
  171. if '=' in line:
  172. key, value = map(str.strip, line.split('=', 1))
  173. if value.startswith('"') and value.endswith('"'):
  174. value = value[1:-1]
  175. ret[key] = value
  176. except (PermissionError, FileNotFoundError):
  177. pass
  178. return ret