codeformat.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. #!/usr/bin/env python3
  2. #
  3. # This file is part of the MicroPython project, http://micropython.org/
  4. #
  5. # The MIT License (MIT)
  6. #
  7. # Copyright (c) 2020-2023 Damien P. George
  8. # Copyright (c) 2020 Jim Mussared
  9. #
  10. # Permission is hereby granted, free of charge, to any person obtaining a copy
  11. # of this software and associated documentation files (the "Software"), to deal
  12. # in the Software without restriction, including without limitation the rights
  13. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  14. # copies of the Software, and to permit persons to whom the Software is
  15. # furnished to do so, subject to the following conditions:
  16. #
  17. # The above copyright notice and this permission notice shall be included in
  18. # all copies or substantial portions of the Software.
  19. #
  20. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  21. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  22. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  23. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  24. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  25. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  26. # THE SOFTWARE.
  27. import argparse
  28. import glob
  29. import itertools
  30. import os
  31. import re
  32. import subprocess
  33. # Relative to top-level repo dir.
  34. PATHS = [
  35. # C
  36. "src/**/*.[ch]",
  37. "tests/**/*.[ch]",
  38. # Python
  39. "tools/**/*.py",
  40. ]
  41. EXCLUSIONS = []
  42. # Path to repo top-level dir.
  43. TOP = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
  44. UNCRUSTIFY_CFG = os.path.join(TOP, "tools/uncrustify.cfg")
  45. C_EXTS = (
  46. ".c",
  47. ".h",
  48. )
  49. PY_EXTS = (".py",)
  50. def list_files(paths, exclusions=None, prefix=""):
  51. files = set()
  52. for pattern in paths:
  53. files.update(glob.glob(os.path.join(prefix, pattern), recursive=True))
  54. for pattern in exclusions or []:
  55. files.difference_update(glob.fnmatch.filter(files, os.path.join(prefix, pattern)))
  56. return sorted(files)
  57. def fixup_c(filename):
  58. # Read file.
  59. with open(filename) as f:
  60. lines = f.readlines()
  61. # Write out file with fixups.
  62. with open(filename, "w", newline="") as f:
  63. dedent_stack = []
  64. while lines:
  65. # Get next line.
  66. l = lines.pop(0)
  67. # Dedent #'s to match indent of following line (not previous line).
  68. m = re.match(r"( +)#(if |ifdef |ifndef |elif |else|endif)", l)
  69. if m:
  70. indent = len(m.group(1))
  71. directive = m.group(2)
  72. if directive in ("if ", "ifdef ", "ifndef "):
  73. l_next = lines[0]
  74. indent_next = len(re.match(r"( *)", l_next).group(1))
  75. if indent - 4 == indent_next and re.match(r" +(} else |case )", l_next):
  76. # This #-line (and all associated ones) needs dedenting by 4 spaces.
  77. l = l[4:]
  78. dedent_stack.append(indent - 4)
  79. else:
  80. # This #-line does not need dedenting.
  81. dedent_stack.append(-1)
  82. else:
  83. if dedent_stack[-1] >= 0:
  84. # This associated #-line needs dedenting to match the #if.
  85. indent_diff = indent - dedent_stack[-1]
  86. assert indent_diff >= 0
  87. l = l[indent_diff:]
  88. if directive == "endif":
  89. dedent_stack.pop()
  90. # Indent #undef's to match indent of previous line.
  91. m = re.match(r"#undef ", l)
  92. if m:
  93. indent_prev = re.match(r"( *)", l_prev).group(1)
  94. l = indent_prev + l
  95. # Write out line.
  96. f.write(l)
  97. # Remember previous line.
  98. l_prev = l
  99. assert not dedent_stack, filename
  100. def main():
  101. cmd_parser = argparse.ArgumentParser(description="Auto-format C and Python files.")
  102. cmd_parser.add_argument("-c", action="store_true", help="Format C code only")
  103. cmd_parser.add_argument("-p", action="store_true", help="Format Python code only")
  104. cmd_parser.add_argument("-v", action="store_true", help="Enable verbose output")
  105. cmd_parser.add_argument(
  106. "-f",
  107. action="store_true",
  108. help="Filter files provided on the command line against the default list of files to check.",
  109. )
  110. cmd_parser.add_argument("files", nargs="*", help="Run on specific globs")
  111. args = cmd_parser.parse_args()
  112. # Setting only one of -c or -p disables the other. If both or neither are set, then do both.
  113. format_c = args.c or not args.p
  114. format_py = args.p or not args.c
  115. # Expand the globs passed on the command line, or use the default globs above.
  116. files = []
  117. if args.files:
  118. files = list_files(args.files)
  119. if args.f:
  120. # Filter against the default list of files. This is a little fiddly
  121. # because we need to apply both the inclusion globs given in PATHS
  122. # as well as the EXCLUSIONS, and use absolute paths
  123. files = set(os.path.abspath(f) for f in files)
  124. all_files = set(list_files(PATHS, EXCLUSIONS, TOP))
  125. if args.v: # In verbose mode, log any files we're skipping
  126. for f in files - all_files:
  127. print("Not checking: {}".format(f))
  128. files = list(files & all_files)
  129. else:
  130. files = list_files(PATHS, EXCLUSIONS, TOP)
  131. # Extract files matching a specific language.
  132. def lang_files(exts):
  133. for file in files:
  134. if os.path.splitext(file)[1].lower() in exts:
  135. yield file
  136. # Run tool on N files at a time (to avoid making the command line too long).
  137. def batch(cmd, files, N=200):
  138. while True:
  139. file_args = list(itertools.islice(files, N))
  140. if not file_args:
  141. break
  142. subprocess.check_call(cmd + file_args)
  143. # Format C files with uncrustify.
  144. if format_c:
  145. command = ["uncrustify", "-c", UNCRUSTIFY_CFG, "-lC", "--no-backup"]
  146. if not args.v:
  147. command.append("-q")
  148. batch(command, lang_files(C_EXTS))
  149. for file in lang_files(C_EXTS):
  150. fixup_c(file)
  151. # Format Python files with black.
  152. if format_py:
  153. command = ["black", "--fast", "--line-length=99"]
  154. if args.v:
  155. command.append("-v")
  156. else:
  157. command.append("-q")
  158. batch(command, lang_files(PY_EXTS))
  159. if __name__ == "__main__":
  160. main()