blob: cf50c8d42a9d78d85bf21a0bda732b40631443b3 [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.
David Horstmann8b5a4492023-01-16 18:28:21 +00003
4This script must be run from the root of a Git work tree containing Mbed TLS.
David Horstmannfa928f12022-11-01 15:46:16 +00005"""
6# Copyright The Mbed TLS Contributors
7# SPDX-License-Identifier: Apache-2.0
8#
9# Licensed under the Apache License, Version 2.0 (the "License"); you may
10# not use this file except in compliance with the License.
11# You may obtain a copy of the License at
12#
13# http://www.apache.org/licenses/LICENSE-2.0
14#
15# Unless required by applicable law or agreed to in writing, software
16# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
17# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18# See the License for the specific language governing permissions and
19# limitations under the License.
20import argparse
David Horstmannfa928f12022-11-01 15:46:16 +000021import os
Gilles Peskine9a3771e2022-12-19 00:48:58 +010022import re
David Horstmannfa928f12022-11-01 15:46:16 +000023import subprocess
24import sys
Gilles Peskine9a3771e2022-12-19 00:48:58 +010025from typing import FrozenSet, List
David Horstmannfa928f12022-11-01 15:46:16 +000026
David Horstmann2cf779c2022-12-08 14:44:36 +000027UNCRUSTIFY_SUPPORTED_VERSION = "0.75.1"
David Horstmannae93a3f2022-12-08 17:03:01 +000028CONFIG_FILE = ".uncrustify.cfg"
David Horstmannfa928f12022-11-01 15:46:16 +000029UNCRUSTIFY_EXE = "uncrustify"
30UNCRUSTIFY_ARGS = ["-c", CONFIG_FILE]
Gilles Peskine9a3771e2022-12-19 00:48:58 +010031CHECK_GENERATED_FILES = "tests/scripts/check-generated-files.sh"
David Horstmannfa928f12022-11-01 15:46:16 +000032
David Horstmannca13c4f2022-12-08 14:33:52 +000033def print_err(*args):
David Horstmann6b3ce302023-01-24 18:36:41 +000034 print("Error: ", *args, file=sys.stderr)
David Horstmannca13c4f2022-12-08 14:33:52 +000035
Pengyu Lvacbeb7f2023-02-06 14:27:30 +080036# Print the file names that will be skipped and the help message
37def print_skip(files_to_skip):
38 print()
39 print(*files_to_skip, sep=", SKIP\n", end=", SKIP\n")
Pengyu Lvc36743f2023-02-15 10:20:40 +080040 print("Warning: The listed files will be skipped because\n"
41 "they are not known to git.")
Pengyu Lvacbeb7f2023-02-06 14:27:30 +080042 print()
43
Gilles Peskine9a3771e2022-12-19 00:48:58 +010044# Match FILENAME(s) in "check SCRIPT (FILENAME...)"
45CHECK_CALL_RE = re.compile(r"\n\s*check\s+[^\s#$&*?;|]+([^\n#$&*?;|]+)",
46 re.ASCII)
47def list_generated_files() -> FrozenSet[str]:
48 """Return the names of generated files.
49
50 We don't reformat generated files, since the result might be different
51 from the output of the generator. Ideally the result of the generator
52 would conform to the code style, but this would be difficult, especially
53 with respect to the placement of line breaks in long logical lines.
54 """
55 # Parse check-generated-files.sh to get an up-to-date list of
56 # generated files. Read the file rather than calling it so that
57 # this script only depends on Git, Python and uncrustify, and not other
58 # tools such as sh or grep which might not be available on Windows.
59 # This introduces a limitation: check-generated-files.sh must have
60 # the expected format and must list the files explicitly, not through
61 # wildcards or command substitution.
62 content = open(CHECK_GENERATED_FILES, encoding="utf-8").read()
63 checks = re.findall(CHECK_CALL_RE, content)
64 return frozenset(word for s in checks for word in s.split())
65
David Horstmannfa928f12022-11-01 15:46:16 +000066def get_src_files() -> List[str]:
67 """
Gilles Peskine22eb82c2023-06-22 19:45:01 +020068 Use git to get a list of the source files.
69
70 Only C files are included, and certain files (generated, or 3rdparty)
71 are excluded.
David Horstmannfa928f12022-11-01 15:46:16 +000072 """
David Horstmannb7dab412022-12-08 13:12:21 +000073 git_ls_files_cmd = ["git", "ls-files",
David Horstmannc6b604e2022-12-08 17:38:27 +000074 "*.[hc]",
75 "tests/suites/*.function",
76 "scripts/data_files/*.fmt"]
Gilles Peskine22eb82c2023-06-22 19:45:01 +020077 output = subprocess.check_output(git_ls_files_cmd,
78 universal_newlines=True)
79 src_files = output.split()
David Horstmannfa928f12022-11-01 15:46:16 +000080
Gilles Peskine22eb82c2023-06-22 19:45:01 +020081 generated_files = list_generated_files()
82 # Don't correct style for third-party files (and, for simplicity,
83 # companion files in the same subtree), or for automatically
84 # generated files (we're correcting the templates instead).
85 src_files = [filename for filename in src_files
86 if not (filename.startswith("3rdparty/") or
87 filename in generated_files)]
88 return src_files
David Horstmannfa928f12022-11-01 15:46:16 +000089
90def get_uncrustify_version() -> str:
91 """
92 Get the version string from Uncrustify
93 """
David Horstmann04bdbe32023-01-25 11:39:04 +000094 result = subprocess.run([UNCRUSTIFY_EXE, "--version"],
95 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
96 check=False)
David Horstmannfa928f12022-11-01 15:46:16 +000097 if result.returncode != 0:
David Horstmannca13c4f2022-12-08 14:33:52 +000098 print_err("Could not get Uncrustify version:", str(result.stderr, "utf-8"))
David Horstmannfa928f12022-11-01 15:46:16 +000099 return ""
100 else:
101 return str(result.stdout, "utf-8")
102
103def check_style_is_correct(src_file_list: List[str]) -> bool:
104 """
David Horstmann9711f4e2022-12-08 14:36:10 +0000105 Check the code style and output a diff for each file whose style is
David Horstmannfa928f12022-11-01 15:46:16 +0000106 incorrect.
107 """
108 style_correct = True
109 for src_file in src_file_list:
110 uncrustify_cmd = [UNCRUSTIFY_EXE] + UNCRUSTIFY_ARGS + [src_file]
David Horstmann04bdbe32023-01-25 11:39:04 +0000111 result = subprocess.run(uncrustify_cmd, stdout=subprocess.PIPE,
112 stderr=subprocess.PIPE, check=False)
David Horstmannc571c5b2023-01-04 18:33:25 +0000113 if result.returncode != 0:
David Horstmann04bdbe32023-01-25 11:39:04 +0000114 print_err("Uncrustify returned " + str(result.returncode) +
115 " correcting file " + src_file)
David Horstmannc571c5b2023-01-04 18:33:25 +0000116 return False
David Horstmannfa928f12022-11-01 15:46:16 +0000117
118 # Uncrustify makes changes to the code and places the result in a new
119 # file with the extension ".uncrustify". To get the changes (if any)
120 # simply diff the 2 files.
David Horstmann0ebc12e2022-12-08 15:04:20 +0000121 diff_cmd = ["diff", "-u", src_file, src_file + ".uncrustify"]
David Horstmannce42cc22023-01-24 18:08:49 +0000122 cp = subprocess.run(diff_cmd, check=False)
123
124 if cp.returncode == 1:
David Horstmann6b3ce302023-01-24 18:36:41 +0000125 print(src_file + " changed - code style is incorrect.")
David Horstmannfa928f12022-11-01 15:46:16 +0000126 style_correct = False
David Horstmannce42cc22023-01-24 18:08:49 +0000127 elif cp.returncode != 0:
128 raise subprocess.CalledProcessError(cp.returncode, cp.args,
129 cp.stdout, cp.stderr)
David Horstmannfa928f12022-11-01 15:46:16 +0000130
131 # Tidy up artifact
David Horstmann0ebc12e2022-12-08 15:04:20 +0000132 os.remove(src_file + ".uncrustify")
David Horstmannfa928f12022-11-01 15:46:16 +0000133
134 return style_correct
135
David Horstmann8d1d6ed2023-01-05 09:59:35 +0000136def fix_style_single_pass(src_file_list: List[str]) -> bool:
David Horstmannfa928f12022-11-01 15:46:16 +0000137 """
138 Run Uncrustify once over the source files.
139 """
140 code_change_args = UNCRUSTIFY_ARGS + ["--no-backup"]
141 for src_file in src_file_list:
142 uncrustify_cmd = [UNCRUSTIFY_EXE] + code_change_args + [src_file]
David Horstmann6b3ce302023-01-24 18:36:41 +0000143 result = subprocess.run(uncrustify_cmd, check=False)
David Horstmannc571c5b2023-01-04 18:33:25 +0000144 if result.returncode != 0:
David Horstmann04bdbe32023-01-25 11:39:04 +0000145 print_err("Uncrustify with file returned: " +
146 str(result.returncode) + " correcting file " +
147 src_file)
David Horstmannc571c5b2023-01-04 18:33:25 +0000148 return False
David Horstmann8d1d6ed2023-01-05 09:59:35 +0000149 return True
David Horstmannfa928f12022-11-01 15:46:16 +0000150
151def fix_style(src_file_list: List[str]) -> int:
152 """
153 Fix the code style. This takes 2 passes of Uncrustify.
154 """
David Horstmann78d566b2023-01-05 10:02:09 +0000155 if not fix_style_single_pass(src_file_list):
David Horstmannc571c5b2023-01-04 18:33:25 +0000156 return 1
David Horstmann78d566b2023-01-05 10:02:09 +0000157 if not fix_style_single_pass(src_file_list):
David Horstmannc571c5b2023-01-04 18:33:25 +0000158 return 1
David Horstmannfa928f12022-11-01 15:46:16 +0000159
160 # Guard against future changes that cause the codebase to require
161 # more passes.
162 if not check_style_is_correct(src_file_list):
David Horstmann28d21572023-01-16 18:32:56 +0000163 print_err("Code style still incorrect after second run of Uncrustify.")
David Horstmannfa928f12022-11-01 15:46:16 +0000164 return 1
165 else:
166 return 0
167
168def main() -> int:
169 """
170 Main with command line arguments.
171 """
David Horstmann2cf779c2022-12-08 14:44:36 +0000172 uncrustify_version = get_uncrustify_version().strip()
173 if UNCRUSTIFY_SUPPORTED_VERSION not in uncrustify_version:
Gilles Peskine9d34cf32022-12-23 18:15:19 +0100174 print("Warning: Using unsupported Uncrustify version '" +
David Horstmann6b3ce302023-01-24 18:36:41 +0000175 uncrustify_version + "'")
Gilles Peskine9d34cf32022-12-23 18:15:19 +0100176 print("Note: The only supported version is " +
David Horstmann6b3ce302023-01-24 18:36:41 +0000177 UNCRUSTIFY_SUPPORTED_VERSION)
David Horstmannfa928f12022-11-01 15:46:16 +0000178
179 parser = argparse.ArgumentParser()
Gilles Peskine59803db2022-12-22 16:34:01 +0100180 parser.add_argument('-f', '--fix', action='store_true',
Gilles Peskine9d34cf32022-12-23 18:15:19 +0100181 help=('modify source files to fix the code style '
182 '(default: print diff, do not modify files)'))
Pengyu Lvc36743f2023-02-15 10:20:40 +0800183 # --subset is almost useless: it only matters if there are no files
184 # ('code_style.py' without arguments checks all files known to Git,
185 # 'code_style.py --subset' does nothing). In particular,
186 # 'code_style.py --fix --subset ...' is intended as a stable ("porcelain")
187 # way to restyle a possibly empty set of files.
Pengyu Lv8c6325c2023-02-06 14:29:02 +0800188 parser.add_argument('--subset', action='store_true',
Pengyu Lvc36743f2023-02-15 10:20:40 +0800189 help='only check the specified files (default with non-option arguments)')
Gilles Peskine59803db2022-12-22 16:34:01 +0100190 parser.add_argument('operands', nargs='*', metavar='FILE',
Pengyu Lvc36743f2023-02-15 10:20:40 +0800191 help='files to check (files MUST be known to git, if none: check all)')
David Horstmannfa928f12022-11-01 15:46:16 +0000192
193 args = parser.parse_args()
194
Pengyu Lve19b51b2023-02-14 10:29:53 +0800195 covered = frozenset(get_src_files())
Pengyu Lvc36743f2023-02-15 10:20:40 +0800196 # We only check files that are known to git
197 if args.subset or args.operands:
Pengyu Lve19b51b2023-02-14 10:29:53 +0800198 src_files = [f for f in args.operands if f in covered]
199 skip_src_files = [f for f in args.operands if f not in covered]
Pengyu Lvacbeb7f2023-02-06 14:27:30 +0800200 if skip_src_files:
201 print_skip(skip_src_files)
Pengyu Lvc36743f2023-02-15 10:20:40 +0800202 else:
Pengyu Lv10f41442023-02-15 16:58:09 +0800203 src_files = list(covered)
Gilles Peskine59803db2022-12-22 16:34:01 +0100204
David Horstmannfa928f12022-11-01 15:46:16 +0000205 if args.fix:
206 # Fix mode
207 return fix_style(src_files)
208 else:
209 # Check mode
210 if check_style_is_correct(src_files):
David Horstmann6b3ce302023-01-24 18:36:41 +0000211 print("Checked {} files, style ok.".format(len(src_files)))
David Horstmannfa928f12022-11-01 15:46:16 +0000212 return 0
213 else:
214 return 1
215
216if __name__ == '__main__':
217 sys.exit(main())