format.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #! /usr/bin/env python
  2. """
  3. Code formatting tool. Runs uncrustify for constraints that get
  4. enforced automatically, then checks for remaining violations.
  5. """
  6. import argparse
  7. import os
  8. import sys
  9. import glob
  10. SCRIPTDIR = os.path.normpath(os.path.dirname(__file__))
  11. parser = argparse.ArgumentParser(description=__doc__.strip())
  12. parser.add_argument('--check', dest='check', action='store_true',
  13. help='Check the code but do not mutate it')
  14. class bcolors:
  15. HEADER = '\033[95m'
  16. OKBLUE = '\033[94m'
  17. OKGREEN = '\033[92m'
  18. WARNING = '\033[93m'
  19. FAIL = '\033[91m'
  20. ENDC = '\033[0m'
  21. BOLD = '\033[1m'
  22. UNDERLINE = '\033[4m'
  23. def check_format(filename):
  24. infile = open(filename)
  25. lineno = 1
  26. def fail(msg):
  27. print(bcolors.FAIL + msg.format(filename, lineno) + bcolors.ENDC)
  28. bad = False
  29. previous = ''
  30. previous_is_blank = False
  31. for line in infile:
  32. line = line.rstrip('\n')
  33. if len(line) > 100:
  34. fail('{}:{} Line is over 100 chars.')
  35. bad = True
  36. is_blank = len(line) == 0
  37. if previous_is_blank and line.lstrip(' ') == '}':
  38. fail('{}:{} Extra newline before ending brace.')
  39. bad = True
  40. previous_is_blank = is_blank
  41. previous = line
  42. lineno = lineno + 1
  43. return not bad
  44. if __name__ == '__main__':
  45. args = parser.parse_args()
  46. cmd = 'uncrustify -l C -c {}/.uncrustify *.h '.format(SCRIPTDIR)
  47. if os.path.exists('uncrustify'):
  48. cmd = './' + cmd
  49. if args.check:
  50. cmd += '--check'
  51. else:
  52. cmd += '--no-backup'
  53. if os.system(cmd) and args.check:
  54. sys.exit(1)
  55. good = True
  56. for filename in glob.glob('*.h'):
  57. good = check_format(filename) and good
  58. if not good:
  59. print('Illegal formatting detected.')
  60. sys.exit(1)