bootstrap.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. #!/usr/bin/env python3
  2. #
  3. # Bootstrap Script
  4. #
  5. # This script
  6. # 1) records the recommended versions of dependencies, and
  7. # 2) when run, checks that all of them are present and downloads
  8. # them if they are not.
  9. #
  10. # pylint: disable=line-too-long
  11. import json
  12. import os
  13. import platform
  14. import shutil
  15. import stat
  16. import subprocess
  17. import sys
  18. import tarfile
  19. import zipfile
  20. from argparse import ArgumentParser
  21. from pathlib import Path
  22. from urllib.request import urlretrieve
  23. project_root_dir = Path(__file__).resolve().parent.parent
  24. dependencies_dir = project_root_dir / '.dependencies'
  25. # All dependencies of this project.
  26. #
  27. # yapf: disable
  28. dependencies = {
  29. 'ninja': {
  30. 'version': '1.10.2',
  31. 'url': {
  32. 'Linux': 'https://github.com/ninja-build/ninja/releases/download/v1.10.2/ninja-linux.zip',
  33. 'Windows': 'https://github.com/ninja-build/ninja/releases/download/v1.10.2/ninja-win.zip',
  34. 'Darwin': 'https://github.com/ninja-build/ninja/releases/download/v1.10.2/ninja-mac.zip',
  35. },
  36. },
  37. 'cmake': {
  38. 'version': '3.22.5',
  39. 'url': {
  40. 'Linux': 'https://github.com/Kitware/CMake/releases/download/v3.22.5/cmake-3.22.5-linux-x86_64.tar.gz',
  41. 'Windows': 'https://github.com/Kitware/CMake/releases/download/v3.22.5/cmake-3.22.5-windows-x86_64.zip',
  42. 'Darwin': 'https://github.com/Kitware/CMake/releases/download/v3.22.5/cmake-3.22.5-macos-universal.tar.gz',
  43. },
  44. },
  45. 'avr-gcc': {
  46. 'version': '7.3.0',
  47. 'url': {
  48. 'Linux': 'https://ww1.microchip.com/downloads/aemDocuments/documents/DEV/ProductDocuments/SoftwareTools/avr8-gnu-toolchain-3.7.0.1796-linux.any.x86_64.tar.gz',
  49. 'Windows': 'https://ww1.microchip.com/downloads/aemDocuments/documents/DEV/ProductDocuments/SoftwareTools/avr8-gnu-toolchain-3.7.0.1796-win32.any.x86_64.zip',
  50. 'Darwin': 'https://ww1.microchip.com/downloads/aemDocuments/documents/DEV/ProductDocuments/SoftwareTools/avr8-gnu-toolchain-osx-3.7.0.518-darwin.any.x86_64.tar.gz',
  51. },
  52. },
  53. 'prusa3dboards': {
  54. 'version': '1.0.6',
  55. 'url': {
  56. 'Linux': 'https://raw.githubusercontent.com/prusa3d/Arduino_Boards/master/IDE_Board_Manager/prusa3dboards-1.0.6.tar.bz2',
  57. 'Windows': 'https://raw.githubusercontent.com/prusa3d/Arduino_Boards/master/IDE_Board_Manager/prusa3dboards-1.0.6.tar.bz2',
  58. 'Darwin': 'https://raw.githubusercontent.com/prusa3d/Arduino_Boards/master/IDE_Board_Manager/prusa3dboards-1.0.6.tar.bz2',
  59. }
  60. },
  61. }
  62. pip_dependencies = ["pyelftools","polib","regex"]
  63. # yapf: enable
  64. def directory_for_dependency(dependency, version):
  65. return dependencies_dir / (dependency + '-' + version)
  66. def find_single_subdir(path: Path):
  67. members = list(path.iterdir())
  68. if path.is_dir() and len(members) > 1:
  69. return path
  70. elif path.is_dir() and len(members) == 1:
  71. return find_single_subdir(members[0]) if members[0].is_dir() else path
  72. else:
  73. raise RuntimeError
  74. def download_and_unzip(url: str, directory: Path):
  75. """Download a compressed file and extract it at `directory`."""
  76. extract_dir = directory.with_suffix('.temp')
  77. shutil.rmtree(directory, ignore_errors=True)
  78. shutil.rmtree(extract_dir, ignore_errors=True)
  79. print('Downloading ' + directory.name)
  80. f, _ = urlretrieve(url, filename=None)
  81. print('Extracting ' + directory.name)
  82. if '.tar.bz2' in url or '.tar.gz' in url or '.tar.xz' in url:
  83. obj = tarfile.open(f)
  84. else:
  85. obj = zipfile.ZipFile(f, 'r')
  86. obj.extractall(path=str(extract_dir))
  87. subdir = find_single_subdir(extract_dir)
  88. shutil.move(str(subdir), str(directory))
  89. shutil.rmtree(extract_dir, ignore_errors=True)
  90. def run(*cmd):
  91. process = subprocess.run([str(a) for a in cmd],
  92. stdout=subprocess.PIPE,
  93. check=True,
  94. encoding='utf-8')
  95. return process.stdout.strip()
  96. def fix_executable_permissions(dependency, installation_directory):
  97. to_fix = ('ninja', 'clang-format')
  98. if dependency not in to_fix:
  99. return
  100. for fpath in installation_directory.iterdir():
  101. if fpath.is_file and fpath.with_suffix('').name in to_fix:
  102. st = os.stat(fpath)
  103. os.chmod(fpath, st.st_mode | stat.S_IEXEC)
  104. def recommended_version_is_available(dependency):
  105. version = dependencies[dependency]['version']
  106. directory = directory_for_dependency(dependency, version)
  107. return directory.exists() and directory.is_dir()
  108. def get_installed_pip_packages():
  109. result = run(sys.executable, '-m', 'pip', 'list',
  110. '--disable-pip-version-check', '--format', 'json')
  111. data = json.loads(result)
  112. return [(pkg['name'].lower(), pkg['version']) for pkg in data]
  113. def install_dependency(dependency):
  114. specs = dependencies[dependency]
  115. installation_directory = directory_for_dependency(dependency,
  116. specs['version'])
  117. url = specs['url']
  118. if isinstance(url, dict):
  119. url = url[platform.system()]
  120. download_and_unzip(url=url, directory=installation_directory)
  121. fix_executable_permissions(dependency, installation_directory)
  122. def get_dependency_version(dependency):
  123. return dependencies[dependency]['version']
  124. def get_dependency_directory(dependency) -> Path:
  125. version = dependencies[dependency]['version']
  126. return Path(directory_for_dependency(dependency, version))
  127. def main() -> int:
  128. parser = ArgumentParser()
  129. # yapf: disable
  130. parser.add_argument(
  131. '--print-dependency-version', type=str,
  132. help='Prints recommended version of given dependency and exits.')
  133. parser.add_argument(
  134. '--print-dependency-directory', type=str,
  135. help='Prints installation directory of given dependency and exits.')
  136. args = parser.parse_args(sys.argv[1:])
  137. # yapf: enable
  138. if args.print_dependency_version:
  139. try:
  140. print(get_dependency_version(args.print_dependency_version))
  141. return 0
  142. except KeyError:
  143. print('Unknown dependency "%s"' % args.print_dependency_version)
  144. return 1
  145. if args.print_dependency_directory:
  146. try:
  147. print(get_dependency_directory(args.print_dependency_directory))
  148. return 0
  149. except KeyError:
  150. print('Unknown dependency "%s"' % args.print_dependency_directory)
  151. return 1
  152. # if no argument present, check and install dependencies
  153. for dependency in dependencies:
  154. if recommended_version_is_available(dependency):
  155. continue
  156. install_dependency(dependency)
  157. # also, install pip packages
  158. installed_pip_packages = get_installed_pip_packages()
  159. for package in pip_dependencies:
  160. is_installed = any(installed[0] == package
  161. for installed in installed_pip_packages)
  162. if is_installed:
  163. continue
  164. print('Installing Python package %s' % package)
  165. run(sys.executable, '-m', 'pip', 'install', package,
  166. '--disable-pip-version-check')
  167. return 0
  168. if __name__ == "__main__":
  169. sys.exit(main())