blob: 4aa9a40a0fb5268cbde4d103578ba43a29d5c75f [file] [log] [blame]
David Horstmannfa928f12022-11-01 15:46:16 +00001#!/usr/bin/env python3
2"""Check or fix the code style by running Uncrustify.
3"""
4# Copyright The Mbed TLS Contributors
5# SPDX-License-Identifier: Apache-2.0
6#
7# Licensed under the Apache License, Version 2.0 (the "License"); you may
8# not use this file except in compliance with the License.
9# You may obtain a copy of the License at
10#
11# http://www.apache.org/licenses/LICENSE-2.0
12#
13# Unless required by applicable law or agreed to in writing, software
14# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16# See the License for the specific language governing permissions and
17# limitations under the License.
18import argparse
19import io
20import os
21import subprocess
22import sys
23from typing import List
24
David Horstmann2cf779c2022-12-08 14:44:36 +000025UNCRUSTIFY_SUPPORTED_VERSION = "0.75.1"
David Horstmannfa928f12022-11-01 15:46:16 +000026CONFIG_FILE = "codestyle.cfg"
27UNCRUSTIFY_EXE = "uncrustify"
28UNCRUSTIFY_ARGS = ["-c", CONFIG_FILE]
29STDOUT_UTF8 = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
30STDERR_UTF8 = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')
31
David Horstmannca13c4f2022-12-08 14:33:52 +000032def print_err(*args):
33 print("Error: ", *args, file=STDERR_UTF8)
34
David Horstmannfa928f12022-11-01 15:46:16 +000035def get_src_files() -> List[str]:
36 """
37 Use git ls-files to get a list of the source files
38 """
David Horstmannb7dab412022-12-08 13:12:21 +000039 git_ls_files_cmd = ["git", "ls-files",
40 "*.[hc]",
41 "tests/suites/*.function",
David Horstmannfa928f12022-11-01 15:46:16 +000042 "scripts/data_files/*.fmt"]
43
44 result = subprocess.run(git_ls_files_cmd, stdout=subprocess.PIPE, \
45 stderr=STDERR_UTF8, check=False)
46
47 if result.returncode != 0:
David Horstmannca13c4f2022-12-08 14:33:52 +000048 print_err("git ls-files returned: "+str(result.returncode))
David Horstmannfa928f12022-11-01 15:46:16 +000049 return []
50 else:
51 src_files = str(result.stdout, "utf-8").split()
52 # Don't correct style for files in 3rdparty/
53 src_files = list(filter( \
54 lambda filename: not filename.startswith("3rdparty/"), \
55 src_files))
56 return src_files
57
58def get_uncrustify_version() -> str:
59 """
60 Get the version string from Uncrustify
61 """
David Horstmannb7dab412022-12-08 13:12:21 +000062 result = subprocess.run([UNCRUSTIFY_EXE, "--version"], \
David Horstmannfa928f12022-11-01 15:46:16 +000063 stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False)
64 if result.returncode != 0:
David Horstmannca13c4f2022-12-08 14:33:52 +000065 print_err("Could not get Uncrustify version:", str(result.stderr, "utf-8"))
David Horstmannfa928f12022-11-01 15:46:16 +000066 return ""
67 else:
68 return str(result.stdout, "utf-8")
69
70def check_style_is_correct(src_file_list: List[str]) -> bool:
71 """
David Horstmann9711f4e2022-12-08 14:36:10 +000072 Check the code style and output a diff for each file whose style is
David Horstmannfa928f12022-11-01 15:46:16 +000073 incorrect.
74 """
75 style_correct = True
76 for src_file in src_file_list:
77 uncrustify_cmd = [UNCRUSTIFY_EXE] + UNCRUSTIFY_ARGS + [src_file]
78 subprocess.run(uncrustify_cmd, stdout=subprocess.PIPE, \
79 stderr=subprocess.PIPE, check=False)
80
81 # Uncrustify makes changes to the code and places the result in a new
82 # file with the extension ".uncrustify". To get the changes (if any)
83 # simply diff the 2 files.
84 diff_cmd = ["diff", "-u", src_file, src_file+".uncrustify"]
85 result = subprocess.run(diff_cmd, stdout=subprocess.PIPE, \
86 stderr=STDERR_UTF8, check=False)
87 if len(result.stdout) > 0:
88 print(src_file+" - Incorrect code style.", file=STDOUT_UTF8)
89 print("File changed - diff:", file=STDOUT_UTF8)
90 print(str(result.stdout, "utf-8"), file=STDOUT_UTF8)
91 style_correct = False
92 else:
93 print(src_file+" - OK.", file=STDOUT_UTF8)
94
95 # Tidy up artifact
96 os.remove(src_file+".uncrustify")
97
98 return style_correct
99
100def fix_style_single_pass(src_file_list: List[str]) -> None:
101 """
102 Run Uncrustify once over the source files.
103 """
104 code_change_args = UNCRUSTIFY_ARGS + ["--no-backup"]
105 for src_file in src_file_list:
106 uncrustify_cmd = [UNCRUSTIFY_EXE] + code_change_args + [src_file]
107 subprocess.run(uncrustify_cmd, check=False, stdout=STDOUT_UTF8, \
108 stderr=STDERR_UTF8)
109
110def fix_style(src_file_list: List[str]) -> int:
111 """
112 Fix the code style. This takes 2 passes of Uncrustify.
113 """
114 fix_style_single_pass(src_file_list)
115 fix_style_single_pass(src_file_list)
116
117 # Guard against future changes that cause the codebase to require
118 # more passes.
119 if not check_style_is_correct(src_file_list):
David Horstmannca13c4f2022-12-08 14:33:52 +0000120 print("Code style still incorrect after second run of Uncrustify.")
David Horstmannfa928f12022-11-01 15:46:16 +0000121 return 1
122 else:
123 return 0
124
125def main() -> int:
126 """
127 Main with command line arguments.
128 """
David Horstmann2cf779c2022-12-08 14:44:36 +0000129 uncrustify_version = get_uncrustify_version().strip()
130 if UNCRUSTIFY_SUPPORTED_VERSION not in uncrustify_version:
David Horstmannfa928f12022-11-01 15:46:16 +0000131 print("Warning: Using unsupported Uncrustify version '" \
David Horstmann2cf779c2022-12-08 14:44:36 +0000132 + uncrustify_version + "' (Note: The only supported version" \
133 "is " + UNCRUSTIFY_SUPPORTED_VERSION + ")", file=STDOUT_UTF8)
David Horstmannfa928f12022-11-01 15:46:16 +0000134
135 src_files = get_src_files()
136
137 parser = argparse.ArgumentParser()
138 parser.add_argument('-f', '--fix', action='store_true', \
139 help='modify source files to fix the code style')
140
141 args = parser.parse_args()
142
143 if args.fix:
144 # Fix mode
145 return fix_style(src_files)
146 else:
147 # Check mode
148 if check_style_is_correct(src_files):
149 return 0
150 else:
151 return 1
152
153if __name__ == '__main__':
154 sys.exit(main())