cformat.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. """Format C code according to QMK's style.
  2. """
  3. import subprocess
  4. from shutil import which
  5. from milc import cli
  6. from qmk.path import normpath
  7. from qmk.c_parse import c_source_files
  8. def cformat_run(files, all_files):
  9. """Spawn clang-format subprocess with proper arguments
  10. """
  11. # Determine which version of clang-format to use
  12. clang_format = ['clang-format', '-i']
  13. for clang_version in [10, 9, 8, 7]:
  14. binary = 'clang-format-%d' % clang_version
  15. if which(binary):
  16. clang_format[0] = binary
  17. break
  18. try:
  19. if not files:
  20. cli.log.warn('No changes detected. Use "qmk cformat -a" to format all files')
  21. return False
  22. subprocess.run(clang_format + [file for file in files], check=True)
  23. cli.log.info('Successfully formatted the C code.')
  24. except subprocess.CalledProcessError:
  25. cli.log.error('Error formatting C code!')
  26. return False
  27. @cli.argument('-a', '--all-files', arg_only=True, action='store_true', help='Format all core files.')
  28. @cli.argument('-b', '--base-branch', default='origin/master', help='Branch to compare to diffs to.')
  29. @cli.argument('files', nargs='*', arg_only=True, help='Filename(s) to format.')
  30. @cli.subcommand("Format C code according to QMK's style.", hidden=False if cli.config.user.developer else True)
  31. def cformat(cli):
  32. """Format C code according to QMK's style.
  33. """
  34. # Empty array for files
  35. files = []
  36. # Core directories for formatting
  37. core_dirs = ['drivers', 'quantum', 'tests', 'tmk_core', 'platforms']
  38. ignores = ['tmk_core/protocol/usb_hid', 'quantum/template', 'platforms/chibios']
  39. # Find the list of files to format
  40. if cli.args.files:
  41. files.extend(normpath(file) for file in cli.args.files)
  42. if cli.args.all_files:
  43. cli.log.warning('Filenames passed with -a, only formatting: %s', ','.join(map(str, files)))
  44. # If -a is specified
  45. elif cli.args.all_files:
  46. all_files = c_source_files(core_dirs)
  47. # The following statement checks each file to see if the file path is in the ignored directories.
  48. files.extend(file for file in all_files if not any(i in str(file) for i in ignores))
  49. # No files specified & no -a flag
  50. else:
  51. base_args = ['git', 'diff', '--name-only', cli.args.base_branch]
  52. out = subprocess.run(base_args + core_dirs, check=True, stdout=subprocess.PIPE)
  53. changed_files = filter(None, out.stdout.decode('UTF-8').split('\n'))
  54. filtered_files = [normpath(file) for file in changed_files if not any(i in file for i in ignores)]
  55. files.extend(file for file in filtered_files if file.exists() and file.suffix in ['.c', '.h', '.cpp'])
  56. # Run clang-format on the files we've found
  57. cformat_run(files, cli.args.all_files)