commands.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. """Helper functions for commands.
  2. """
  3. import json
  4. import os
  5. import shutil
  6. from pathlib import Path
  7. from subprocess import DEVNULL
  8. from time import strftime
  9. from milc import cli
  10. import qmk.keymap
  11. from qmk.constants import KEYBOARD_OUTPUT_PREFIX
  12. from qmk.json_schema import json_load
  13. time_fmt = '%Y-%m-%d-%H:%M:%S'
  14. def _find_make():
  15. """Returns the correct make command for this environment.
  16. """
  17. make_cmd = os.environ.get('MAKE')
  18. if not make_cmd:
  19. make_cmd = 'gmake' if shutil.which('gmake') else 'make'
  20. return make_cmd
  21. def create_make_target(target, parallel=1, **env_vars):
  22. """Create a make command
  23. Args:
  24. target
  25. Usually a make rule, such as 'clean' or 'all'.
  26. parallel
  27. The number of make jobs to run in parallel
  28. **env_vars
  29. Environment variables to be passed to make.
  30. Returns:
  31. A command that can be run to make the specified keyboard and keymap
  32. """
  33. env = []
  34. make_cmd = _find_make()
  35. for key, value in env_vars.items():
  36. env.append(f'{key}={value}')
  37. return [make_cmd, '-j', str(parallel), *env, target]
  38. def create_make_command(keyboard, keymap, target=None, parallel=1, **env_vars):
  39. """Create a make compile command
  40. Args:
  41. keyboard
  42. The path of the keyboard, for example 'plank'
  43. keymap
  44. The name of the keymap, for example 'algernon'
  45. target
  46. Usually a bootloader.
  47. parallel
  48. The number of make jobs to run in parallel
  49. **env_vars
  50. Environment variables to be passed to make.
  51. Returns:
  52. A command that can be run to make the specified keyboard and keymap
  53. """
  54. make_args = [keyboard, keymap]
  55. if target:
  56. make_args.append(target)
  57. return create_make_target(':'.join(make_args), parallel, **env_vars)
  58. def get_git_version(repo_dir='.', check_dir='.'):
  59. """Returns the current git version for a repo, or the current time.
  60. """
  61. git_describe_cmd = ['git', 'describe', '--abbrev=6', '--dirty', '--always', '--tags']
  62. if Path(check_dir).exists():
  63. git_describe = cli.run(git_describe_cmd, stdin=DEVNULL, cwd=repo_dir)
  64. if git_describe.returncode == 0:
  65. return git_describe.stdout.strip()
  66. else:
  67. cli.log.warn(f'"{" ".join(git_describe_cmd)}" returned error code {git_describe.returncode}')
  68. print(git_describe.stderr)
  69. return strftime(time_fmt)
  70. return strftime(time_fmt)
  71. def write_version_h(git_version, build_date, chibios_version, chibios_contrib_version):
  72. """Generate and write quantum/version.h
  73. """
  74. version_h = [
  75. f'#define QMK_VERSION "{git_version}"',
  76. f'#define QMK_BUILDDATE "{build_date}"',
  77. f'#define CHIBIOS_VERSION "{chibios_version}"',
  78. f'#define CHIBIOS_CONTRIB_VERSION "{chibios_contrib_version}"',
  79. ]
  80. version_h_file = Path('quantum/version.h')
  81. version_h_file.write_text('\n'.join(version_h))
  82. def compile_configurator_json(user_keymap, bootloader=None, parallel=1, **env_vars):
  83. """Convert a configurator export JSON file into a C file and then compile it.
  84. Args:
  85. user_keymap
  86. A deserialized keymap export
  87. bootloader
  88. A bootloader to flash
  89. parallel
  90. The number of make jobs to run in parallel
  91. Returns:
  92. A command to run to compile and flash the C file.
  93. """
  94. # Write the keymap.c file
  95. keyboard_filesafe = user_keymap['keyboard'].replace('/', '_')
  96. target = f'{keyboard_filesafe}_{user_keymap["keymap"]}'
  97. keyboard_output = Path(f'{KEYBOARD_OUTPUT_PREFIX}{keyboard_filesafe}')
  98. keymap_output = Path(f'{keyboard_output}_{user_keymap["keymap"]}')
  99. c_text = qmk.keymap.generate_c(user_keymap['keyboard'], user_keymap['layout'], user_keymap['layers'])
  100. keymap_dir = keymap_output / 'src'
  101. keymap_c = keymap_dir / 'keymap.c'
  102. keymap_dir.mkdir(exist_ok=True, parents=True)
  103. keymap_c.write_text(c_text)
  104. # Write the version.h file
  105. git_version = get_git_version()
  106. build_date = strftime('%Y-%m-%d-%H:%M:%S')
  107. chibios_version = get_git_version("lib/chibios", "lib/chibios/os")
  108. chibios_contrib_version = get_git_version("lib/chibios-contrib", "lib/chibios-contrib/os")
  109. write_version_h(git_version, build_date, chibios_version, chibios_contrib_version)
  110. # Return a command that can be run to make the keymap and flash if given
  111. verbose = 'true' if cli.config.general.verbose else 'false'
  112. color = 'true' if cli.config.general.color else 'false'
  113. make_command = [_find_make()]
  114. if not cli.config.general.verbose:
  115. make_command.append('-s')
  116. make_command.extend([
  117. '-j',
  118. str(parallel),
  119. '-r',
  120. '-R',
  121. '-f',
  122. 'build_keyboard.mk',
  123. ])
  124. if bootloader:
  125. make_command.append(bootloader)
  126. for key, value in env_vars.items():
  127. make_command.append(f'{key}={value}')
  128. make_command.extend([
  129. f'GIT_VERSION={git_version}',
  130. f'BUILD_DATE={build_date}',
  131. f'CHIBIOS_VERSION={chibios_version}',
  132. f'CHIBIOS_CONTRIB_VERSION={chibios_contrib_version}',
  133. f'KEYBOARD={user_keymap["keyboard"]}',
  134. f'KEYMAP={user_keymap["keymap"]}',
  135. f'KEYBOARD_FILESAFE={keyboard_filesafe}',
  136. f'TARGET={target}',
  137. f'KEYBOARD_OUTPUT={keyboard_output}',
  138. f'KEYMAP_OUTPUT={keymap_output}',
  139. f'MAIN_KEYMAP_PATH_1={keymap_output}',
  140. f'MAIN_KEYMAP_PATH_2={keymap_output}',
  141. f'MAIN_KEYMAP_PATH_3={keymap_output}',
  142. f'MAIN_KEYMAP_PATH_4={keymap_output}',
  143. f'MAIN_KEYMAP_PATH_5={keymap_output}',
  144. f'KEYMAP_C={keymap_c}',
  145. f'KEYMAP_PATH={keymap_dir}',
  146. f'VERBOSE={verbose}',
  147. f'COLOR={color}',
  148. 'SILENT=false',
  149. ])
  150. return make_command
  151. def parse_configurator_json(configurator_file):
  152. """Open and parse a configurator json export
  153. """
  154. # FIXME(skullydazed/anyone): Add validation here
  155. user_keymap = json.load(configurator_file)
  156. orig_keyboard = user_keymap['keyboard']
  157. aliases = json_load(Path('data/mappings/keyboard_aliases.json'))
  158. if orig_keyboard in aliases:
  159. if 'target' in aliases[orig_keyboard]:
  160. user_keymap['keyboard'] = aliases[orig_keyboard]['target']
  161. if 'layouts' in aliases[orig_keyboard] and user_keymap['layout'] in aliases[orig_keyboard]['layouts']:
  162. user_keymap['layout'] = aliases[orig_keyboard]['layouts'][user_keymap['layout']]
  163. return user_keymap