logo

qmk_firmware

custom branch of QMK firmware git clone https://anongit.hacktivis.me/git/qmk_firmware.git

check.py (7847B)


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