cformat.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. """Format C code according to QMK's style.
  2. """
  3. import os
  4. import subprocess
  5. from shutil import which
  6. from milc import cli
  7. @cli.argument('files', nargs='*', arg_only=True, help='Filename(s) to format.')
  8. @cli.subcommand("Format C code according to QMK's style.")
  9. def cformat(cli):
  10. """Format C code according to QMK's style.
  11. """
  12. # Determine which version of clang-format to use
  13. clang_format = ['clang-format', '-i']
  14. for clang_version in [10, 9, 8, 7]:
  15. binary = 'clang-format-%d' % clang_version
  16. if which(binary):
  17. clang_format[0] = binary
  18. break
  19. # Find the list of files to format
  20. if cli.args.files:
  21. cli.args.files = [os.path.join(os.environ['ORIG_CWD'], file) for file in cli.args.files]
  22. else:
  23. for dir in ['drivers', 'quantum', 'tests', 'tmk_core']:
  24. for dirpath, dirnames, filenames in os.walk(dir):
  25. if 'tmk_core/protocol/usb_hid' in dirpath:
  26. continue
  27. for name in filenames:
  28. if name.endswith('.c') or name.endswith('.h') or name.endswith('.cpp'):
  29. cli.args.files.append(os.path.join(dirpath, name))
  30. # Run clang-format on the files we've found
  31. try:
  32. subprocess.run(clang_format + cli.args.files, check=True)
  33. cli.log.info('Successfully formatted the C code.')
  34. except subprocess.CalledProcessError:
  35. cli.log.error('Error formatting C code!')
  36. return False