blob: 7923db451e61ea38456e211b7d988bf365d8d437 [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
31def get_src_files() -> List[str]:
32 """
33 Use git ls-files to get a list of the source files
34 """
35 git_ls_files_cmd = ["git", "ls-files", \
36 "*.[hc]", \
37 "tests/suites/*.function", \
38 "scripts/data_files/*.fmt"]
39
40 result = subprocess.run(git_ls_files_cmd, stdout=subprocess.PIPE, \
41 stderr=STDERR_UTF8, check=False)
42
43 if result.returncode != 0:
44 print("Error: git ls-files returned: "+str(result.returncode), \
45 file=STDERR_UTF8)
46 return []
47 else:
48 src_files = str(result.stdout, "utf-8").split()
49 # Don't correct style for files in 3rdparty/
50 src_files = list(filter( \
51 lambda filename: not filename.startswith("3rdparty/"), \
52 src_files))
53 return src_files
54
55def get_uncrustify_version() -> str:
56 """
57 Get the version string from Uncrustify
58 """
59 version_args = ["--version"]
60 result = subprocess.run([UNCRUSTIFY_EXE] + version_args, \
61 stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False)
62 if result.returncode != 0:
63 print("Error getting version: "+str(result.stderr, "utf-8"), \
64 file=STDERR_UTF8)
65 return ""
66 else:
67 return str(result.stdout, "utf-8")
68
69def check_style_is_correct(src_file_list: List[str]) -> bool:
70 """
71 Check the code style and output a diff foir each file whose style is
72 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):
119 print("Error: Code style still incorrect after second run of Uncrustify.", \
120 file=STDERR_UTF8)
121 return 1
122 else:
123 return 0
124
125def main() -> int:
126 """
127 Main with command line arguments.
128 """
129 uncrustify_version = get_uncrustify_version()
130 if "0.75.1" not in uncrustify_version:
131 print("Warning: Using unsupported Uncrustify version '" \
132 + uncrustify_version + "'", file=STDOUT_UTF8)
133
134 src_files = get_src_files()
135
136 parser = argparse.ArgumentParser()
137 parser.add_argument('-f', '--fix', action='store_true', \
138 help='modify source files to fix the code style')
139
140 args = parser.parse_args()
141
142 if args.fix:
143 # Fix mode
144 return fix_style(src_files)
145 else:
146 # Check mode
147 if check_style_is_correct(src_files):
148 return 0
149 else:
150 return 1
151
152if __name__ == '__main__':
153 sys.exit(main())