cformat.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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. ignores = ['tmk_core/protocol/usb_hid', 'quantum/template']
  24. for dir in ['drivers', 'quantum', 'tests', 'tmk_core']:
  25. for dirpath, dirnames, filenames in os.walk(dir):
  26. if any(i in dirpath for i in ignores):
  27. dirnames.clear()
  28. continue
  29. for name in filenames:
  30. if name.endswith(('.c', '.h', '.cpp')):
  31. cli.args.files.append(os.path.join(dirpath, name))
  32. # Run clang-format on the files we've found
  33. try:
  34. subprocess.run(clang_format + cli.args.files, check=True)
  35. cli.log.info('Successfully formatted the C code.')
  36. except subprocess.CalledProcessError:
  37. cli.log.error('Error formatting C code!')
  38. return False