__init__.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  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. 'pyusb': 'usb.core',
  16. }
  17. safe_commands = [
  18. # A list of subcommands we always run, even when the module imports fail
  19. 'clone',
  20. 'config',
  21. 'env',
  22. 'setup',
  23. ]
  24. subcommands = [
  25. 'qmk.cli.bux',
  26. 'qmk.cli.c2json',
  27. 'qmk.cli.cformat',
  28. 'qmk.cli.chibios.confmigrate',
  29. 'qmk.cli.clean',
  30. 'qmk.cli.compile',
  31. 'qmk.cli.console',
  32. 'qmk.cli.docs',
  33. 'qmk.cli.doctor',
  34. 'qmk.cli.fileformat',
  35. 'qmk.cli.flash',
  36. 'qmk.cli.format.json',
  37. 'qmk.cli.generate.api',
  38. 'qmk.cli.generate.config_h',
  39. 'qmk.cli.generate.dfu_header',
  40. 'qmk.cli.generate.docs',
  41. 'qmk.cli.generate.info_json',
  42. 'qmk.cli.generate.keyboard_h',
  43. 'qmk.cli.generate.layouts',
  44. 'qmk.cli.generate.rgb_breathe_table',
  45. 'qmk.cli.generate.rules_mk',
  46. 'qmk.cli.hello',
  47. 'qmk.cli.info',
  48. 'qmk.cli.json2c',
  49. 'qmk.cli.lint',
  50. 'qmk.cli.list.keyboards',
  51. 'qmk.cli.list.keymaps',
  52. 'qmk.cli.kle2json',
  53. 'qmk.cli.multibuild',
  54. 'qmk.cli.new.keyboard',
  55. 'qmk.cli.new.keymap',
  56. 'qmk.cli.pyformat',
  57. 'qmk.cli.pytest',
  58. ]
  59. def _run_cmd(*command):
  60. """Run a command in a subshell.
  61. """
  62. if 'windows' in cli.platform.lower():
  63. safecmd = map(shlex.quote, command)
  64. safecmd = ' '.join(safecmd)
  65. command = [os.environ['SHELL'], '-c', safecmd]
  66. return run(command)
  67. def _find_broken_requirements(requirements):
  68. """ Check if the modules in the given requirements.txt are available.
  69. Args:
  70. requirements
  71. The path to a requirements.txt file
  72. Returns a list of modules that couldn't be imported
  73. """
  74. with Path(requirements).open() as fd:
  75. broken_modules = []
  76. for line in fd.readlines():
  77. line = line.strip().replace('<', '=').replace('>', '=')
  78. if len(line) == 0 or line[0] == '#' or line.startswith('-r'):
  79. continue
  80. if '#' in line:
  81. line = line.split('#')[0]
  82. module_name = line.split('=')[0] if '=' in line else line
  83. module_import = module_name.replace('-', '_')
  84. # Not every module is importable by its own name.
  85. if module_name in import_names:
  86. module_import = import_names[module_name]
  87. if not find_spec(module_import):
  88. broken_modules.append(module_name)
  89. return broken_modules
  90. def _broken_module_imports(requirements):
  91. """Make sure we can import all the python modules.
  92. """
  93. broken_modules = _find_broken_requirements(requirements)
  94. for module in broken_modules:
  95. print('Could not find module %s!' % module)
  96. if broken_modules:
  97. return True
  98. return False
  99. # Make sure our python is new enough
  100. #
  101. # Supported version information
  102. #
  103. # Based on the OSes we support these are the minimum python version available by default.
  104. # Last update: 2021 Jan 02
  105. #
  106. # Arch: 3.9
  107. # Debian: 3.7
  108. # Fedora 31: 3.7
  109. # Fedora 32: 3.8
  110. # Fedora 33: 3.9
  111. # FreeBSD: 3.7
  112. # Gentoo: 3.7
  113. # macOS: 3.9 (from homebrew)
  114. # msys2: 3.8
  115. # Slackware: 3.7
  116. # solus: 3.7
  117. # void: 3.9
  118. if sys.version_info[0] != 3 or sys.version_info[1] < 7:
  119. print('Error: Your Python is too old! Please upgrade to Python 3.7 or later.')
  120. exit(127)
  121. milc_version = __VERSION__.split('.')
  122. if int(milc_version[0]) < 2 and int(milc_version[1]) < 4:
  123. requirements = Path('requirements.txt').resolve()
  124. print(f'Your MILC library is too old! Please upgrade: python3 -m pip install -U -r {str(requirements)}')
  125. exit(127)
  126. # Check to make sure we have all our dependencies
  127. msg_install = 'Please run `python3 -m pip install -r %s` to install required python dependencies.'
  128. args = sys.argv[1:]
  129. while args and args[0][0] == '-':
  130. del args[0]
  131. safe_command = args and args[0] in safe_commands
  132. if not safe_command:
  133. if _broken_module_imports('requirements.txt'):
  134. if yesno('Would you like to install the required Python modules?'):
  135. _run_cmd(sys.executable, '-m', 'pip', 'install', '-r', 'requirements.txt')
  136. else:
  137. print()
  138. print(msg_install % (str(Path('requirements.txt').resolve()),))
  139. print()
  140. exit(1)
  141. if cli.config.user.developer and _broken_module_imports('requirements-dev.txt'):
  142. if yesno('Would you like to install the required developer Python modules?'):
  143. _run_cmd(sys.executable, '-m', 'pip', 'install', '-r', 'requirements-dev.txt')
  144. elif yesno('Would you like to disable developer mode?'):
  145. _run_cmd(sys.argv[0], 'config', 'user.developer=None')
  146. else:
  147. print()
  148. print(msg_install % (str(Path('requirements-dev.txt').resolve()),))
  149. print('You can also turn off developer mode: qmk config user.developer=None')
  150. print()
  151. exit(1)
  152. # Import our subcommands
  153. for subcommand in subcommands:
  154. try:
  155. __import__(subcommand)
  156. except ModuleNotFoundError as e:
  157. if safe_command:
  158. print(f'Warning: Could not import {subcommand}: {e.__class__.__name__}, {e}')
  159. else:
  160. raise