cformat.py 2.7 KB

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