9"""Check and apply the ns-3 coding style recursively to all files in the PATH arguments.
11The coding style is defined with the clang-format tool, whose definitions are in
12the ".clang-format" file. This script performs the following checks / fixes:
13- Check / apply clang-format. Respects clang-format guards.
14- Check / fix local #include headers with "ns3/" prefix. Respects clang-format guards.
15- Check / fix ns-3 #include headers using angle brackets <> rather than quotes "". Respects clang-format guards.
16- Check / fix Doxygen tags using @ rather than \\. Respects clang-format guards.
17- Check / fix SPDX licenses rather than GPL text. Respects clang-format guards.
18- Check / fix emacs file style comments. Respects clang-format guards.
19- Check / trim trailing whitespace. Always checked.
20- Check / replace tabs with spaces. Respects clang-format guards.
21- Check file encoding. Always checked.
23This script can be applied to all text files in a given path or to individual files.
25NOTE: The formatting check requires clang-format to be found on the path (see the supported versions below).
26The remaining checks do not depend on clang-format and can be executed by disabling clang-format
27checking with the "--no-formatting" option.
31import concurrent.futures
38from typing
import Callable, Dict, List, Tuple
43CLANG_FORMAT_MAX_VERSION = 22
44CLANG_FORMAT_MIN_VERSION = 20
52 "// clang-format off",
53 "# cmake-format: off",
57DIRECTORIES_TO_SKIP = [
89FILES_TO_CHECK: Dict[str, List[str]] = {c: []
for c
in CHECKS}
90FILES_TO_CHECK[
"tabs"] = [
95 "codespell-ignored-lines",
96 "codespell-ignored-words",
99FILES_TO_CHECK[
"whitespace"] = FILES_TO_CHECK[
"tabs"] + [
104FILE_EXTENSIONS_TO_CHECK: Dict[str, List[str]] = {c: []
for c
in CHECKS}
105FILE_EXTENSIONS_TO_CHECK[
"formatting"] = [
110FILE_EXTENSIONS_TO_CHECK[
"include_prefixes"] = FILE_EXTENSIONS_TO_CHECK[
"formatting"]
111FILE_EXTENSIONS_TO_CHECK[
"include_quotes"] = FILE_EXTENSIONS_TO_CHECK[
"formatting"]
112FILE_EXTENSIONS_TO_CHECK[
"encoding"] = FILE_EXTENSIONS_TO_CHECK[
"formatting"]
113FILE_EXTENSIONS_TO_CHECK[
"doxygen_tags"] = FILE_EXTENSIONS_TO_CHECK[
"formatting"] + [
116FILE_EXTENSIONS_TO_CHECK[
"license"] = [
123FILE_EXTENSIONS_TO_CHECK[
"emacs"] = [
130FILE_EXTENSIONS_TO_CHECK[
"tabs"] = [
148FILE_EXTENSIONS_TO_CHECK[
"whitespace"] = FILE_EXTENSIONS_TO_CHECK[
"tabs"] + [
166FILE_ENCODING =
"UTF-8"
173 """Check whether a directory should be analyzed.
176 dirpath: Directory path.
179 Whether the directory should be analyzed.
182 _, directory = os.path.split(dirpath)
183 return directory
not in DIRECTORIES_TO_SKIP
188 files_to_check: List[str],
189 file_extensions_to_check: List[str],
191 """Check whether a file should be analyzed.
194 path: Path to the file.
195 files_to_check: List of files that shall be checked.
196 file_extensions_to_check: List of file extensions that shall be checked.
199 Whether the file should be analyzed.
202 filename = os.path.split(path)[1]
203 extension = os.path.splitext(filename)[1]
205 if filename
in FILES_TO_SKIP:
208 return filename
in files_to_check
or extension
in file_extensions_to_check
213) -> Dict[str, List[str]]:
214 """Find all files to be checked in a given list of paths.
217 paths: List of paths to the files to check.
220 Dictionary of checks and corresponding list of files to check.
222 "formatting": list_of_files_to_check_formatting,
228 files_found: List[str] = []
231 abs_path = os.path.abspath(os.path.expanduser(path))
233 if os.path.isfile(abs_path):
234 files_found.append(path)
235 elif os.path.isdir(abs_path):
236 for dirpath, dirnames, filenames
in os.walk(path, topdown=
True):
242 files_found.extend([os.path.join(dirpath, f)
for f
in filenames])
244 raise ValueError(f
"{path} is not a valid file nor a directory")
249 files_to_check: Dict[str, List[str]] = {c: []
for c
in CHECKS}
251 for f
in files_found:
254 files_to_check[check].append(f)
256 return files_to_check
260 """Find the path to one of the supported versions of clang-format.
263 Path to clang-format.
266 RuntimeError: If no supported version of clang-format is found.
270 for version
in range(CLANG_FORMAT_MAX_VERSION, CLANG_FORMAT_MIN_VERSION - 1, -1):
271 clang_format_path = shutil.which(f
"clang-format-{version}")
272 if clang_format_path:
273 return clang_format_path
276 clang_format_path = shutil.which(
"clang-format")
279 if clang_format_path:
280 process = subprocess.run(
281 [clang_format_path,
"--version"],
286 clang_format_version = process.stdout.strip()
287 version_regex = re.findall(
r"\b(\d+)(\.\d+){0,2}\b", clang_format_version)
289 major_version = int(version_regex[0][0])
290 if CLANG_FORMAT_MIN_VERSION <= major_version <= CLANG_FORMAT_MAX_VERSION:
291 return clang_format_path
295 f
"Could not find any supported version of clang-format installed on this system. "
296 f
"List of supported versions: [{CLANG_FORMAT_MAX_VERSION}-{CLANG_FORMAT_MIN_VERSION}]. "
297 + (f
"Found clang-format {major_version}." if major_version
else "")
306 checks_enabled: Dict[str, bool],
311 """Check / fix the coding style of a list of files.
314 paths: List of paths to the files to check.
315 checks_enabled: Dictionary of checks indicating whether to enable each of them.
316 fix: Whether to fix (True) or just check (False) the file.
317 verbose: Show the lines that are not compliant with the style.
318 n_jobs: Number of parallel jobs.
321 Whether all files are compliant with all enabled style checks.
325 checks_successful = {c:
True for c
in CHECKS}
328 "include_prefixes":
'#include headers from the same module with the "ns3/" prefix',
329 "include_quotes":
'ns-3 #include headers using angle brackets <> rather than quotes ""',
330 "doxygen_tags":
"Doxygen tags using \\ rather than @",
331 "license":
"GPL license text instead of SPDX license",
332 "emacs":
"emacs file style comments",
333 "whitespace":
"trailing whitespace",
335 "formatting":
"bad code formatting",
336 "encoding": f
"bad file encoding ({FILE_ENCODING})",
339 check_style_file_functions_kwargs = {
340 "include_prefixes": {
341 "function": check_manually_file,
343 "respect_clang_format_guards":
True,
344 "check_style_line_function": check_include_prefixes_line,
348 "function": check_manually_file,
350 "respect_clang_format_guards":
True,
351 "check_style_line_function": check_include_quotes_line,
355 "function": check_manually_file,
357 "respect_clang_format_guards":
True,
358 "check_style_line_function": check_doxygen_tags_line,
362 "function": check_manually_file,
364 "respect_clang_format_guards":
True,
365 "check_style_line_function": check_licenses_line,
369 "function": check_manually_file,
371 "respect_clang_format_guards":
True,
372 "check_style_line_function": check_emacs_line,
376 "function": check_manually_file,
378 "respect_clang_format_guards":
False,
379 "check_style_line_function": check_whitespace_line,
383 "function": check_manually_file,
385 "respect_clang_format_guards":
True,
386 "check_style_line_function": check_tabs_line,
390 "function": check_formatting_file,
394 "function": check_encoding_file,
399 if checks_enabled[
"formatting"]:
400 check_style_file_functions_kwargs[
"formatting"][
"kwargs"] = {
404 n_checks_enabled = sum(checks_enabled.values())
408 if checks_enabled[check]:
410 style_check_strs[check],
411 check_style_file_functions_kwargs[check][
"function"],
412 files_to_check[check],
416 **check_style_file_functions_kwargs[check][
"kwargs"],
420 if n_check < n_checks_enabled:
423 return all(checks_successful.values())
427 style_check_str: str,
428 check_style_file_function: Callable[..., Tuple[str, bool, List[str]]],
429 filenames: List[str],
435 """Check / fix style of a list of files.
438 style_check_str: Description of the check to be performed.
439 check_style_file_function: Function used to check the file.
440 filenames: List of names of the files to be checked.
441 fix: Whether to fix (True) or just check (False) the file (True).
442 verbose: Show the lines that are not compliant with the style.
443 n_jobs: Number of parallel jobs.
444 kwargs: Additional keyword arguments to the check_style_file_function.
447 Whether all files are compliant with the style.
451 non_compliant_files: List[str] = []
452 files_verbose_infos: Dict[str, List[str]] = {}
454 with concurrent.futures.ProcessPoolExecutor(n_jobs)
as executor:
455 non_compliant_files_results = executor.map(
456 check_style_file_function,
458 itertools.repeat(fix),
459 itertools.repeat(verbose),
460 *[arg
if isinstance(arg, list)
else itertools.repeat(arg)
for arg
in kwargs.values()],
463 for filename, is_file_compliant, verbose_infos
in non_compliant_files_results:
464 if not is_file_compliant:
465 non_compliant_files.append(filename)
468 files_verbose_infos[filename] = verbose_infos
471 if not non_compliant_files:
472 print(f
"- No files detected with {style_check_str}")
475 n_non_compliant_files = len(non_compliant_files)
478 print(f
"- Fixed {style_check_str} in the files ({n_non_compliant_files}):")
480 print(f
"- Detected {style_check_str} in the files ({n_non_compliant_files}):")
482 for f
in non_compliant_files:
484 print(*[f
" {l}" for l
in files_verbose_infos[f]], sep=
"\n")
499 clang_format_path: str,
500) -> Tuple[str, bool, List[str]]:
501 """Check / fix the coding style of a file with clang-format.
504 filename: Name of the file to be checked.
505 fix: Whether to fix (True) or just check (False) the style of the file.
506 verbose: Show the lines that are not compliant with the style.
507 clang_format_path: Path to clang-format.
511 Whether the file is compliant with the style (before the check),
515 verbose_infos: List[str] = []
518 process = subprocess.run(
526 f
"--ferror-limit={0 if verbose else 1}",
532 is_file_compliant = process.returncode == 0
534 verbose_infos = process.stderr.splitlines()
537 if fix
and not is_file_compliant:
538 process = subprocess.run(
546 stdout=subprocess.DEVNULL,
547 stderr=subprocess.DEVNULL,
550 return (filename, is_file_compliant, verbose_infos)
557) -> Tuple[str, bool, List[str]]:
558 """Check / fix the encoding of a file.
561 filename: Name of the file to be checked.
562 fix: Whether to fix (True) or just check (False) the encoding of the file.
563 verbose: Show the lines that are not compliant with the style.
567 Whether the file is compliant with the style (before the check),
571 verbose_infos: List[str] = []
572 is_file_compliant =
True
574 with open(filename,
"rb")
as f:
576 file_lines = file_data.decode(FILE_ENCODING, errors=
"replace").splitlines(keepends=
True)
580 file_data.decode(FILE_ENCODING)
581 except UnicodeDecodeError
as e:
582 is_file_compliant =
False
586 bad_char_start_index = e.start
587 n_chars_file_read = 0
589 for line_number, line
in enumerate(file_lines):
590 n_chars_line = len(line)
592 if bad_char_start_index < n_chars_file_read + n_chars_line:
593 bad_char_column = bad_char_start_index - n_chars_file_read
594 verbose_infos.extend(
596 f
"{filename}:{line_number + 1}:{bad_char_column + 1}: error: bad {FILE_ENCODING} encoding",
598 f
" {'':>{bad_char_column}}^",
603 n_chars_file_read += n_chars_line
606 if fix
and not is_file_compliant:
607 with open(filename,
"w", encoding=FILE_ENCODING)
as f:
608 f.writelines(file_lines)
610 return (filename, is_file_compliant, verbose_infos)
617 respect_clang_format_guards: bool,
618 check_style_line_function: Callable[[str, str, int], Tuple[bool, str, List[str]]],
619) -> Tuple[str, bool, List[str]]:
620 """Check / fix a file manually using a function to check / fix each line.
623 filename: Name of the file to be checked.
624 fix: Whether to fix (True) or just check (False) the style of the file.
625 verbose: Show the lines that are not compliant with the style.
626 respect_clang_format_guards: Whether to respect clang-format guards.
627 check_style_line_function: Function used to check each line.
631 Whether the file is compliant with the style (before the check),
635 is_file_compliant =
True
636 verbose_infos: List[str] = []
637 clang_format_enabled =
True
639 with open(filename,
"r", encoding=FILE_ENCODING)
as f:
640 file_lines = f.readlines()
642 for i, line
in enumerate(file_lines):
644 if respect_clang_format_guards:
645 line_stripped = line.strip()
647 if line_stripped
in FORMAT_GUARD_ON:
648 clang_format_enabled =
True
649 elif line_stripped
in FORMAT_GUARD_OFF:
650 clang_format_enabled =
False
652 if not clang_format_enabled
and line_stripped
not in (
653 FORMAT_GUARD_ON + FORMAT_GUARD_OFF
658 is_line_compliant, line_fixed, line_verbose_infos = check_style_line_function(
662 if not is_line_compliant:
663 is_file_compliant =
False
664 file_lines[i] = line_fixed
665 verbose_infos.extend(line_verbose_infos)
668 if not fix
and not verbose:
672 if fix
and not is_file_compliant:
673 with open(filename,
"w", encoding=FILE_ENCODING)
as f:
674 f.writelines(file_lines)
676 return (filename, is_file_compliant, verbose_infos)
683) -> Tuple[bool, str, List[str]]:
684 """Check / fix #include headers from the same module with the "ns3/" prefix in a line.
687 line: The line to check.
688 filename: Name of the file to be checked.
689 line_number: The number of the line checked.
693 Whether the line is compliant with the style (before the check),
697 is_line_compliant =
True
699 verbose_infos: List[str] = []
702 line_stripped = line.strip()
703 header_file = re.findall(
r'^#include ["<]ns3/(.*\.h)[">]', line_stripped)
707 header_file = header_file[0]
708 parent_path = os.path.split(filename)[0]
710 if os.path.exists(os.path.join(parent_path, header_file)):
711 is_line_compliant =
False
713 line_stripped.replace(f
"ns3/{header_file}", header_file)
718 header_index = len(
'#include "')
719 verbose_infos.extend(
721 f
'{filename}:{line_number + 1}:{header_index + 1}: error: #include headers from the same module with the "ns3/" prefix detected',
723 f
" {'':>{header_index}}^",
727 return (is_line_compliant, line_fixed, verbose_infos)
734) -> Tuple[bool, str, List[str]]:
735 """Check / fix ns-3 #include headers using angle brackets <> rather than quotes "" in a line.
738 line: The line to check.
739 filename: Name of the file to be checked.
740 line_number: The number of the line checked.
743 Tuple (Whether the line is compliant with the style (before the check),
748 is_line_compliant =
True
750 verbose_infos: List[str] = []
753 header_file = re.findall(
r"^#include <ns3/.*\.h>", line)
756 is_line_compliant =
False
757 line_fixed = line.replace(
"<",
'"').replace(
">",
'"')
758 header_index = len(
"#include ")
760 f
"{filename}:{line_number + 1}:{header_index + 1}: error: ns-3 #include headers with angle brackets detected",
762 f
" {'':{header_index}}^",
765 return (is_line_compliant, line_fixed, verbose_infos)
772) -> Tuple[bool, str, List[str]]:
773 """Check / fix Doxygen tags using \\ rather than @ in a line.
776 line: The line to check.
777 filename: Name of the file to be checked.
778 line_number: The number of the line checked.
781 Tuple (Whether the line is compliant with the style (before the check),
792 is_line_compliant =
True
794 verbose_infos: List[str] = []
797 line_stripped = line.rstrip()
798 regex_findings = re.findall(
r"^\s*(?:\*|\/\*\*|\/\/\/)\s*(\\\w{3,})(?=(?:\s|$))", line_stripped)
801 doxygen_tag = regex_findings[0]
803 if doxygen_tag
not in IGNORED_WORDS:
804 is_line_compliant =
False
805 doxygen_tag_index = line_fixed.find(doxygen_tag)
806 line_fixed = line.replace(doxygen_tag, f
"@{doxygen_tag[1:]}")
807 verbose_infos.extend(
809 f
"{filename}:{line_number + 1}:{doxygen_tag_index + 1}: error: detected Doxygen tags using \\ rather than @",
811 f
" {'':{doxygen_tag_index}}^",
815 return (is_line_compliant, line_fixed, verbose_infos)
822) -> Tuple[bool, str, List[str]]:
823 """Check / fix SPDX licenses rather than GPL text in a line.
826 line: The line to check.
827 filename: Name of the file to be checked.
828 line_number: The number of the line checked.
831 Tuple (Whether the line is compliant with the style (before the check),
837 GPL_LICENSE_LINES = [
838 "This program is free software; you can redistribute it and/or modify",
839 "it under the terms of the GNU General Public License version 2 as",
840 "published by the Free Software Foundation;",
841 "This program is distributed in the hope that it will be useful,",
842 "but WITHOUT ANY WARRANTY; without even the implied warranty of",
843 "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the",
844 "GNU General Public License for more details.",
845 "You should have received a copy of the GNU General Public License",
846 "along with this program; if not, write to the Free Software",
847 "Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA",
852 SPDX_LICENSE =
"SPDX-License-Identifier: GPL-2.0-only"
855 is_line_compliant =
True
857 verbose_infos: List[str] = []
860 line_stripped = line.strip()
861 line_stripped_no_leading_comments = line_stripped.strip(
"*#/").strip()
863 if line_stripped_no_leading_comments
in GPL_LICENSE_LINES:
864 is_line_compliant =
False
870 if line_stripped_no_leading_comments == GPL_LICENSE_LINES[0]:
871 line_fixed = line.replace(line_stripped_no_leading_comments, SPDX_LICENSE)
875 verbose_infos.extend(
877 f
"{filename}:{line_number + 1}:{col_index}: error: GPL license text detected instead of SPDX license",
879 f
" {'':>{col_index}}^",
883 return (is_line_compliant, line_fixed, verbose_infos)
890) -> Tuple[bool, str, List[str]]:
891 """Check / fix emacs file style comment in a line.
894 line: The line to check.
895 filename: Name of the file to be checked.
896 line_number: The number of the line checked.
899 Tuple (Whether the line is compliant with the style (before the check),
904 is_line_compliant =
True
906 verbose_infos: List[str] = []
909 line_stripped = line.strip()
911 emacs_line = re.search(
r"c-file-style:|py-indent-offset:", line_stripped)
915 is_line_compliant =
False
917 col_index = emacs_line.start()
919 f
"{filename}:{line_number + 1}:{col_index}: error: emacs file style comment detected",
921 f
" {'':{col_index}}^",
924 return (is_line_compliant, line_fixed, verbose_infos)
931) -> Tuple[bool, str, List[str]]:
932 """Check / fix whitespace in a line.
935 line: The line to check.
936 filename: Name of the file to be checked.
937 line_number: The number of the line checked.
940 Tuple (Whether the line is compliant with the style (before the check),
945 is_line_compliant =
True
946 line_fixed = line.rstrip() +
"\n"
947 verbose_infos: List[str] = []
949 if line_fixed != line:
950 is_line_compliant =
False
951 line_fixed_stripped_expanded = line_fixed.rstrip().expandtabs(TAB_SIZE)
953 f
"{filename}:{line_number + 1}:{len(line_fixed_stripped_expanded) + 1}: error: Trailing whitespace detected",
954 f
" {line_fixed_stripped_expanded}",
955 f
" {'':>{len(line_fixed_stripped_expanded)}}^",
958 return (is_line_compliant, line_fixed, verbose_infos)
965) -> Tuple[bool, str, List[str]]:
966 """Check / fix tabs in a line.
969 line: The line to check.
970 filename: Name of the file to be checked.
971 line_number: The number of the line checked.
974 Tuple (Whether the line is compliant with the style (before the check),
979 is_line_compliant =
True
981 verbose_infos: List[str] = []
983 tab_index = line.find(
"\t")
986 is_line_compliant =
False
987 line_fixed = line.expandtabs(TAB_SIZE)
989 f
"{filename}:{line_number + 1}:{tab_index + 1}: error: Tab detected",
991 f
" {'':>{tab_index}}^",
994 return (is_line_compliant, line_fixed, verbose_infos)
1000if __name__ ==
"__main__":
1001 parser = argparse.ArgumentParser(
1002 description=
"Check and apply the ns-3 coding style recursively to all files in the given PATHs. "
1003 "The script checks the formatting of the files using clang-format and"
1004 " other coding style rules manually (see script arguments). "
1005 "All checks respect clang-format guards, except trailing whitespace and file encoding,"
1006 " which are always checked. "
1007 'When used in "check mode" (default), the script runs all checks in all files. '
1008 "If it detects non-formatted files, they will be printed and this process exits with a non-zero code. "
1009 'When used in "fix mode", this script automatically fixes the files and exits with 0 code.'
1011 parser.add_argument(
1016 help=
"List of paths to the files to check",
1018 parser.add_argument(
1019 "--no-include-prefixes",
1020 action=
"store_true",
1021 help=
'Do not check / fix #include headers from the same module with the "ns3/" prefix (respects clang-format guards)',
1023 parser.add_argument(
1024 "--no-include-quotes",
1025 action=
"store_true",
1026 help=
'Do not check / fix ns-3 #include headers using angle brackets <> rather than quotes "" (respects clang-format guards)',
1028 parser.add_argument(
1029 "--no-doxygen-tags",
1030 action=
"store_true",
1031 help=
"Do not check / fix Doxygen tags using @ rather than \\ (respects clang-format guards)",
1033 parser.add_argument(
1035 action=
"store_true",
1036 help=
"Do not check / fix SPDX licenses rather than GPL text (respects clang-format guards)",
1038 parser.add_argument(
1040 action=
"store_true",
1041 help=
"Do not check / fix emacs file style comments (respects clang-format guards)",
1043 parser.add_argument(
1045 action=
"store_true",
1046 help=
"Do not check / fix trailing whitespace",
1048 parser.add_argument(
1050 action=
"store_true",
1051 help=
"Do not check / fix tabs (respects clang-format guards)",
1053 parser.add_argument(
1055 action=
"store_true",
1056 help=
"Do not check / fix code formatting (respects clang-format guards)",
1058 parser.add_argument(
1060 action=
"store_true",
1061 help=f
"Do not check / fix file encoding ({FILE_ENCODING})",
1063 parser.add_argument(
1065 action=
"store_true",
1066 help=
"Fix coding style issues detected in the files",
1068 parser.add_argument(
1071 action=
"store_true",
1072 help=
"Show the lines that are not well-formatted",
1074 parser.add_argument(
1078 default=max(1, os.cpu_count() - 1),
1079 help=
"Number of parallel jobs",
1081 args = parser.parse_args()
1087 "include_prefixes":
not args.no_include_prefixes,
1088 "include_quotes":
not args.no_include_quotes,
1089 "doxygen_tags":
not args.no_doxygen_tags,
1090 "license":
not args.no_licenses,
1091 "emacs":
not args.no_emacs,
1092 "whitespace":
not args.no_whitespace,
1093 "tabs":
not args.no_tabs,
1094 "formatting":
not args.no_formatting,
1095 "encoding":
not args.no_encoding,
1098 verbose=args.verbose,
1102 except Exception
as ex:
1106 if not all_checks_successful:
1110 "Notes to fix the above formatting issues:",
1111 ' - To fix the formatting of specific files, run this script with the flag "--fix":',
1112 " $ ./utils/check-style-clang-format.py --fix path [path ...]",
1113 " - To fix the formatting of all files modified by this branch, run this script in the following way:",
1114 " $ git diff --name-only master | xargs ./utils/check-style-clang-format.py --fix",