__init__.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. """QMK CLI Subcommands
  2. We list each subcommand here explicitly because all the reliable ways of searching for modules are slow and delay startup.
  3. """
  4. import os
  5. import shlex
  6. import sys
  7. from importlib.util import find_spec
  8. from pathlib import Path
  9. from subprocess import run
  10. from milc import cli, __VERSION__
  11. from milc.questions import yesno
  12. import_names = {
  13. # A mapping of package name to importable name
  14. 'pep8-naming': 'pep8ext_naming',
  15. 'pyserial': 'serial',
  16. 'pyusb': 'usb.core',
  17. 'qmk-dotty-dict': 'dotty_dict',
  18. 'pillow': 'PIL'
  19. }
  20. safe_commands = [
  21. # A list of subcommands we always run, even when the module imports fail
  22. 'clone',
  23. 'config',
  24. 'doctor',
  25. 'env',
  26. 'setup',
  27. ]
  28. subcommands = [
  29. 'qmk.cli.bux',
  30. 'qmk.cli.c2json',
  31. 'qmk.cli.cd',
  32. 'qmk.cli.cformat',
  33. 'qmk.cli.chibios.confmigrate',
  34. 'qmk.cli.clean',
  35. 'qmk.cli.compile',
  36. 'qmk.cli.docs',
  37. 'qmk.cli.doctor',
  38. 'qmk.cli.fileformat',
  39. 'qmk.cli.flash',
  40. 'qmk.cli.format.c',
  41. 'qmk.cli.format.json',
  42. 'qmk.cli.format.python',
  43. 'qmk.cli.format.text',
  44. 'qmk.cli.generate.api',
  45. 'qmk.cli.generate.autocorrect_data',
  46. 'qmk.cli.generate.compilation_database',
  47. 'qmk.cli.generate.config_h',
  48. 'qmk.cli.generate.develop_pr_list',
  49. 'qmk.cli.generate.dfu_header',
  50. 'qmk.cli.generate.docs',
  51. 'qmk.cli.generate.info_json',
  52. 'qmk.cli.generate.keyboard_c',
  53. 'qmk.cli.generate.keyboard_h',
  54. 'qmk.cli.generate.layouts',
  55. 'qmk.cli.generate.rgb_breathe_table',
  56. 'qmk.cli.generate.rules_mk',
  57. 'qmk.cli.generate.version_h',
  58. 'qmk.cli.hello',
  59. 'qmk.cli.import.kbfirmware',
  60. 'qmk.cli.import.keyboard',
  61. 'qmk.cli.import.keymap',
  62. 'qmk.cli.info',
  63. 'qmk.cli.json2c',
  64. 'qmk.cli.lint',
  65. 'qmk.cli.list.keyboards',
  66. 'qmk.cli.list.keymaps',
  67. 'qmk.cli.list.layouts',
  68. 'qmk.cli.kle2json',
  69. 'qmk.cli.multibuild',
  70. 'qmk.cli.new.keyboard',
  71. 'qmk.cli.new.keymap',
  72. 'qmk.cli.painter',
  73. 'qmk.cli.pyformat',
  74. 'qmk.cli.pytest',
  75. 'qmk.cli.via2json',
  76. ]
  77. def _install_deps(requirements):
  78. """Perform the installation of missing requirements.
  79. If we detect that we are running in a virtualenv we can't write into we'll use sudo to perform the pip install.
  80. """
  81. command = [sys.executable, '-m', 'pip', 'install']
  82. if sys.prefix != sys.base_prefix:
  83. # We are in a virtualenv, check to see if we need to use sudo to write to it
  84. if not os.access(sys.prefix, os.W_OK):
  85. print('Notice: Using sudo to install modules to location owned by root:', sys.prefix)
  86. command.insert(0, 'sudo')
  87. elif not os.access(sys.prefix, os.W_OK):
  88. # We can't write to sys.prefix, attempt to install locally
  89. command.append('--user')
  90. return _run_cmd(*command, '-r', requirements)
  91. def _run_cmd(*command):
  92. """Run a command in a subshell.
  93. """
  94. if 'windows' in cli.platform.lower():
  95. safecmd = map(shlex.quote, command)
  96. safecmd = ' '.join(safecmd)
  97. command = [os.environ['SHELL'], '-c', safecmd]
  98. return run(command)
  99. def _find_broken_requirements(requirements):
  100. """ Check if the modules in the given requirements.txt are available.
  101. Args:
  102. requirements
  103. The path to a requirements.txt file
  104. Returns a list of modules that couldn't be imported
  105. """
  106. with Path(requirements).open() as fd:
  107. broken_modules = []
  108. for line in fd.readlines():
  109. line = line.strip().replace('<', '=').replace('>', '=')
  110. if len(line) == 0 or line[0] == '#' or line.startswith('-r'):
  111. continue
  112. if '#' in line:
  113. line = line.split('#')[0]
  114. module_name = line.split('=')[0] if '=' in line else line
  115. module_import = module_name.replace('-', '_')
  116. # Not every module is importable by its own name.
  117. if module_name in import_names:
  118. module_import = import_names[module_name]
  119. if not find_spec(module_import):
  120. broken_modules.append(module_name)
  121. return broken_modules
  122. def _broken_module_imports(requirements):
  123. """Make sure we can import all the python modules.
  124. """
  125. broken_modules = _find_broken_requirements(requirements)
  126. for module in broken_modules:
  127. print('Could not find module %s!' % module)
  128. if broken_modules:
  129. return True
  130. return False
  131. def _yesno(*args):
  132. """Wrapper to only prompt if interactive
  133. """
  134. return sys.stdout.isatty() and yesno(*args)
  135. def _eprint(errmsg):
  136. """Wrapper to print to stderr
  137. """
  138. print(errmsg, file=sys.stderr)
  139. # Make sure our python is new enough
  140. #
  141. # Supported version information
  142. #
  143. # Based on the OSes we support these are the minimum python version available by default.
  144. # Last update: 2021 Jan 02
  145. #
  146. # Arch: 3.9
  147. # Debian: 3.7
  148. # Fedora 31: 3.7
  149. # Fedora 32: 3.8
  150. # Fedora 33: 3.9
  151. # FreeBSD: 3.7
  152. # Gentoo: 3.7
  153. # macOS: 3.9 (from homebrew)
  154. # msys2: 3.8
  155. # Slackware: 3.7
  156. # solus: 3.7
  157. # void: 3.9
  158. if sys.version_info[0] != 3 or sys.version_info[1] < 7:
  159. _eprint('Error: Your Python is too old! Please upgrade to Python 3.7 or later.')
  160. exit(127)
  161. milc_version = __VERSION__.split('.')
  162. if int(milc_version[0]) < 2 and int(milc_version[1]) < 4:
  163. requirements = Path('requirements.txt').resolve()
  164. _eprint(f'Your MILC library is too old! Please upgrade: python3 -m pip install -U -r {str(requirements)}')
  165. exit(127)
  166. # Make sure we can run binaries in the same directory as our Python interpreter
  167. python_dir = os.path.dirname(sys.executable)
  168. if python_dir not in os.environ['PATH'].split(':'):
  169. os.environ['PATH'] = ":".join((python_dir, os.environ['PATH']))
  170. # Check to make sure we have all our dependencies
  171. msg_install = f'\nPlease run `{sys.executable} -m pip install -r %s` to install required python dependencies.'
  172. args = sys.argv[1:]
  173. while args and args[0][0] == '-':
  174. del args[0]
  175. safe_command = args and args[0] in safe_commands
  176. if not safe_command:
  177. if _broken_module_imports('requirements.txt'):
  178. if _yesno('Would you like to install the required Python modules?'):
  179. _install_deps('requirements.txt')
  180. else:
  181. _eprint(msg_install % (str(Path('requirements.txt').resolve()),))
  182. exit(1)
  183. if cli.config.user.developer and _broken_module_imports('requirements-dev.txt'):
  184. if _yesno('Would you like to install the required developer Python modules?'):
  185. _install_deps('requirements-dev.txt')
  186. elif _yesno('Would you like to disable developer mode?'):
  187. _run_cmd(sys.argv[0], 'config', 'user.developer=None')
  188. else:
  189. _eprint(msg_install % (str(Path('requirements-dev.txt').resolve()),))
  190. _eprint('You can also turn off developer mode: qmk config user.developer=None')
  191. exit(1)
  192. # Import our subcommands
  193. for subcommand in subcommands:
  194. try:
  195. __import__(subcommand)
  196. except (ImportError, ModuleNotFoundError) as e:
  197. if safe_command:
  198. _eprint(f'Warning: Could not import {subcommand}: {e.__class__.__name__}, {e}')
  199. else:
  200. raise