check-format.py (2176B)
1 # Copyright (c) Microsoft Corporation. 2 # Licensed under the MIT License. 3 4 """Checks the formatting of the codebase and fails if it is not correct.""" 5 6 import os 7 import subprocess 8 import sys 9 import sysconfig 10 11 script_dir = os.path.dirname(os.path.realpath(__file__)) 12 root_dir = os.path.join(script_dir, "..") 13 os.chdir(root_dir) 14 15 user_dir = sysconfig.get_path("scripts",f"{os.name}_user") 16 if os.name == 'nt': 17 clang_format = "{}\clang-format.exe".format(user_dir) 18 cmake_format = "{}\cmake-format.exe".format(user_dir) 19 else: 20 clang_format = "{}/clang-format".format(user_dir) 21 cmake_format = "{}/cmake-format".format(user_dir) 22 23 if not os.path.exists(clang_format): 24 print("clang-format not found at: {}".format(clang_format)) 25 sys.exit(1) 26 27 if not os.path.exists(cmake_format): 28 print("cmake-format not found at: {}".format(cmake_format)) 29 sys.exit(1) 30 31 cmake_filename='CMakeLists.txt' 32 33 # Find all the interesting files in the repository 34 clang_files = [] 35 cmake_files = [] 36 37 all_files = subprocess.check_output('git ls-files', shell=True, text=True).strip('\n').split('\n') 38 39 for file in all_files: 40 if file.endswith('.cpp') or file.endswith('.h'): 41 clang_files.append(file) 42 if file.endswith(cmake_filename): 43 cmake_files.append(file) 44 45 # Run clang and cmake-format on all the interesting files 46 unformatted_files = [] 47 for file in clang_files: 48 # When the file is unformatted, clang-format returns a zero exit code, but a non-empty stderr 49 result = subprocess.check_output("{} {} -n".format(clang_format, file), shell=True, text=True, stderr=subprocess.STDOUT) 50 if len(result) > 0: 51 unformatted_files.append(file) 52 for file in cmake_files: 53 # When the file is unformatted, cmake-format returns a non-zero exit code 54 result = subprocess.run("{} {} --check".format(cmake_format, file), stderr=subprocess.DEVNULL, shell=True) 55 if result.returncode != 0: 56 unformatted_files.append(file) 57 58 unformatted_files.sort() 59 60 if unformatted_files: 61 print("The following files have incorrect formatting:\n") 62 for file in unformatted_files: 63 print(file) 64 sys.exit(1) 65 66 print("All files have correct formatting.")