blob: 7de223a1665f6f5492ab9e8cc7703f1e098ed288 [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 """
David Horstmann27b37042022-12-08 13:12:21 +000035 git_ls_files_cmd = ["git", "ls-files",
36 "*.[hc]",
37 "tests/suites/*.function",
David Horstmann20d6bfa2022-11-01 15:46:16 +000038 "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 """
David Horstmann27b37042022-12-08 13:12:21 +000059 result = subprocess.run([UNCRUSTIFY_EXE, "--version"], \
David Horstmann20d6bfa2022-11-01 15:46:16 +000060 stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False)
61 if result.returncode != 0:
62 print("Error getting version: "+str(result.stderr, "utf-8"), \
63 file=STDERR_UTF8)
64 return ""
65 else:
66 return str(result.stdout, "utf-8")
67
68def check_style_is_correct(src_file_list: List[str]) -> bool:
69 """
70 Check the code style and output a diff foir each file whose style is
71 incorrect.
72 """
73 style_correct = True
74 for src_file in src_file_list:
75 uncrustify_cmd = [UNCRUSTIFY_EXE] + UNCRUSTIFY_ARGS + [src_file]
76 subprocess.run(uncrustify_cmd, stdout=subprocess.PIPE, \
77 stderr=subprocess.PIPE, check=False)
78
79 # Uncrustify makes changes to the code and places the result in a new
80 # file with the extension ".uncrustify". To get the changes (if any)
81 # simply diff the 2 files.
82 diff_cmd = ["diff", "-u", src_file, src_file+".uncrustify"]
83 result = subprocess.run(diff_cmd, stdout=subprocess.PIPE, \
84 stderr=STDERR_UTF8, check=False)
85 if len(result.stdout) > 0:
86 print(src_file+" - Incorrect code style.", file=STDOUT_UTF8)
87 print("File changed - diff:", file=STDOUT_UTF8)
88 print(str(result.stdout, "utf-8"), file=STDOUT_UTF8)
89 style_correct = False
90 else:
91 print(src_file+" - OK.", file=STDOUT_UTF8)
92
93 # Tidy up artifact
94 os.remove(src_file+".uncrustify")
95
96 return style_correct
97
98def fix_style_single_pass(src_file_list: List[str]) -> None:
99 """
100 Run Uncrustify once over the source files.
101 """
102 code_change_args = UNCRUSTIFY_ARGS + ["--no-backup"]
103 for src_file in src_file_list:
104 uncrustify_cmd = [UNCRUSTIFY_EXE] + code_change_args + [src_file]
105 subprocess.run(uncrustify_cmd, check=False, stdout=STDOUT_UTF8, \
106 stderr=STDERR_UTF8)
107
108def fix_style(src_file_list: List[str]) -> int:
109 """
110 Fix the code style. This takes 2 passes of Uncrustify.
111 """
112 fix_style_single_pass(src_file_list)
113 fix_style_single_pass(src_file_list)
114
115 # Guard against future changes that cause the codebase to require
116 # more passes.
117 if not check_style_is_correct(src_file_list):
118 print("Error: Code style still incorrect after second run of Uncrustify.", \
119 file=STDERR_UTF8)
120 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())