blob: be333f093f62ea810e9e14380055d04eb3e5f721 [file] [log] [blame]
David Horstmann20d6bfa2022-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
25CONFIG_FILE = "codestyle.cfg"
26UNCRUSTIFY_EXE = "uncrustify"
27UNCRUSTIFY_ARGS = ["-c", CONFIG_FILE]
28STDOUT_UTF8 = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
29STDERR_UTF8 = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')
30
David Horstmann448cfec2022-12-08 14:33:52 +000031def print_err(*args):
32 print("Error: ", *args, file=STDERR_UTF8)
33
David Horstmann20d6bfa2022-11-01 15:46:16 +000034def get_src_files() -> List[str]:
35 """
36 Use git ls-files to get a list of the source files
37 """
David Horstmann27b37042022-12-08 13:12:21 +000038 git_ls_files_cmd = ["git", "ls-files",
39 "*.[hc]",
40 "tests/suites/*.function",
David Horstmann20d6bfa2022-11-01 15:46:16 +000041 "scripts/data_files/*.fmt"]
42
43 result = subprocess.run(git_ls_files_cmd, stdout=subprocess.PIPE, \
44 stderr=STDERR_UTF8, check=False)
45
46 if result.returncode != 0:
David Horstmann448cfec2022-12-08 14:33:52 +000047 print_err("git ls-files returned: "+str(result.returncode))
David Horstmann20d6bfa2022-11-01 15:46:16 +000048 return []
49 else:
50 src_files = str(result.stdout, "utf-8").split()
51 # Don't correct style for files in 3rdparty/
52 src_files = list(filter( \
53 lambda filename: not filename.startswith("3rdparty/"), \
54 src_files))
55 return src_files
56
57def get_uncrustify_version() -> str:
58 """
59 Get the version string from Uncrustify
60 """
David Horstmann27b37042022-12-08 13:12:21 +000061 result = subprocess.run([UNCRUSTIFY_EXE, "--version"], \
David Horstmann20d6bfa2022-11-01 15:46:16 +000062 stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False)
63 if result.returncode != 0:
David Horstmann448cfec2022-12-08 14:33:52 +000064 print_err("Could not get Uncrustify version:", str(result.stderr, "utf-8"))
David Horstmann20d6bfa2022-11-01 15:46:16 +000065 return ""
66 else:
67 return str(result.stdout, "utf-8")
68
69def check_style_is_correct(src_file_list: List[str]) -> bool:
70 """
David Horstmann99a669a2022-12-08 14:36:10 +000071 Check the code style and output a diff for each file whose style is
David Horstmann20d6bfa2022-11-01 15:46:16 +000072 incorrect.
73 """
74 style_correct = True
75 for src_file in src_file_list:
76 uncrustify_cmd = [UNCRUSTIFY_EXE] + UNCRUSTIFY_ARGS + [src_file]
77 subprocess.run(uncrustify_cmd, stdout=subprocess.PIPE, \
78 stderr=subprocess.PIPE, check=False)
79
80 # Uncrustify makes changes to the code and places the result in a new
81 # file with the extension ".uncrustify". To get the changes (if any)
82 # simply diff the 2 files.
83 diff_cmd = ["diff", "-u", src_file, src_file+".uncrustify"]
84 result = subprocess.run(diff_cmd, stdout=subprocess.PIPE, \
85 stderr=STDERR_UTF8, check=False)
86 if len(result.stdout) > 0:
87 print(src_file+" - Incorrect code style.", file=STDOUT_UTF8)
88 print("File changed - diff:", file=STDOUT_UTF8)
89 print(str(result.stdout, "utf-8"), file=STDOUT_UTF8)
90 style_correct = False
91 else:
92 print(src_file+" - OK.", file=STDOUT_UTF8)
93
94 # Tidy up artifact
95 os.remove(src_file+".uncrustify")
96
97 return style_correct
98
99def fix_style_single_pass(src_file_list: List[str]) -> None:
100 """
101 Run Uncrustify once over the source files.
102 """
103 code_change_args = UNCRUSTIFY_ARGS + ["--no-backup"]
104 for src_file in src_file_list:
105 uncrustify_cmd = [UNCRUSTIFY_EXE] + code_change_args + [src_file]
106 subprocess.run(uncrustify_cmd, check=False, stdout=STDOUT_UTF8, \
107 stderr=STDERR_UTF8)
108
109def fix_style(src_file_list: List[str]) -> int:
110 """
111 Fix the code style. This takes 2 passes of Uncrustify.
112 """
113 fix_style_single_pass(src_file_list)
114 fix_style_single_pass(src_file_list)
115
116 # Guard against future changes that cause the codebase to require
117 # more passes.
118 if not check_style_is_correct(src_file_list):
David Horstmann448cfec2022-12-08 14:33:52 +0000119 print("Code style still incorrect after second run of Uncrustify.")
David Horstmann20d6bfa2022-11-01 15:46:16 +0000120 return 1
121 else:
122 return 0
123
124def main() -> int:
125 """
126 Main with command line arguments.
127 """
128 uncrustify_version = get_uncrustify_version()
129 if "0.75.1" not in uncrustify_version:
130 print("Warning: Using unsupported Uncrustify version '" \
131 + uncrustify_version + "'", file=STDOUT_UTF8)
132
133 src_files = get_src_files()
134
135 parser = argparse.ArgumentParser()
136 parser.add_argument('-f', '--fix', action='store_true', \
137 help='modify source files to fix the code style')
138
139 args = parser.parse_args()
140
141 if args.fix:
142 # Fix mode
143 return fix_style(src_files)
144 else:
145 # Check mode
146 if check_style_is_correct(src_files):
147 return 0
148 else:
149 return 1
150
151if __name__ == '__main__':
152 sys.exit(main())