A Discrete-Event Network Simulator
API
Loading...
Searching...
No Matches
check-style-clang-format.py
Go to the documentation of this file.
1#!/usr/bin/env python3
2
3# Copyright (c) 2022 Eduardo Nuno Almeida.
4#
5# SPDX-License-Identifier: GPL-2.0-only
6#
7# Author: Eduardo Nuno Almeida <enmsa@outlook.pt> [INESC TEC and FEUP, Portugal]
8
9"""Check and apply the ns-3 coding style recursively to all files in the PATH arguments.
10
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.
22
23This script can be applied to all text files in a given path or to individual files.
24
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.
28"""
29
30import argparse
31import concurrent.futures
32import itertools
33import os
34import re
35import shutil
36import subprocess
37import sys
38from typing import Callable, Dict, List, Tuple
39
40###########################################################
41# PARAMETERS
42###########################################################
43CLANG_FORMAT_MAX_VERSION = 22
44CLANG_FORMAT_MIN_VERSION = 20
45
46FORMAT_GUARD_ON = [
47 "// clang-format on",
48 "# cmake-format: on",
49 "# fmt: on",
50]
51FORMAT_GUARD_OFF = [
52 "// clang-format off",
53 "# cmake-format: off",
54 "# fmt: off",
55]
56
57DIRECTORIES_TO_SKIP = [
58 "__pycache__",
59 ".git",
60 ".venv",
61 "bindings",
62 "build",
63 "cmake-cache",
64 "testpy-output",
65 "third-party",
66 "venv",
67]
68
69# List of files entirely copied from elsewhere that should not be checked,
70# in order to optimize the performance of this script
71FILES_TO_SKIP = [
72 "valgrind.h",
73]
74
75# List of checks
76CHECKS = [
77 "include_prefixes",
78 "include_quotes",
79 "doxygen_tags",
80 "license",
81 "emacs",
82 "whitespace",
83 "tabs",
84 "formatting",
85 "encoding",
86]
87
88# Files to check
89FILES_TO_CHECK: Dict[str, List[str]] = {c: [] for c in CHECKS}
90FILES_TO_CHECK["tabs"] = [
91 ".clang-format",
92 ".clang-tidy",
93 ".codespellrc",
94 "CMakeLists.txt",
95 "codespell-ignored-lines",
96 "codespell-ignored-words",
97 "ns3",
98]
99FILES_TO_CHECK["whitespace"] = FILES_TO_CHECK["tabs"] + [
100 "Makefile",
101]
102
103# File extensions to check
104FILE_EXTENSIONS_TO_CHECK: Dict[str, List[str]] = {c: [] for c in CHECKS}
105FILE_EXTENSIONS_TO_CHECK["formatting"] = [
106 ".c",
107 ".cc",
108 ".h",
109]
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"] + [
114 ".rst",
115]
116FILE_EXTENSIONS_TO_CHECK["license"] = [
117 ".c",
118 ".cc",
119 ".cmake",
120 ".h",
121 ".py",
122]
123FILE_EXTENSIONS_TO_CHECK["emacs"] = [
124 ".c",
125 ".cc",
126 ".h",
127 ".py",
128 ".rst",
129]
130FILE_EXTENSIONS_TO_CHECK["tabs"] = [
131 ".c",
132 ".cc",
133 ".cmake",
134 ".css",
135 ".h",
136 ".html",
137 ".js",
138 ".json",
139 ".m",
140 ".md",
141 ".pl",
142 ".py",
143 ".rst",
144 ".sh",
145 ".toml",
146 ".yml",
147]
148FILE_EXTENSIONS_TO_CHECK["whitespace"] = FILE_EXTENSIONS_TO_CHECK["tabs"] + [
149 ".click",
150 ".cfg",
151 ".conf",
152 ".dot",
153 ".gnuplot",
154 ".gp",
155 ".mob",
156 ".ns_params",
157 ".ns_movements",
158 ".params",
159 ".plt",
160 ".seqdiag",
161 ".txt",
162]
163
164# Other check parameters
165TAB_SIZE = 4
166FILE_ENCODING = "UTF-8"
167
168
169###########################################################
170# AUXILIARY FUNCTIONS
171###########################################################
172def should_analyze_directory(dirpath: str) -> bool:
173 """Check whether a directory should be analyzed.
174
175 Args:
176 dirpath: Directory path.
177
178 Returns:
179 Whether the directory should be analyzed.
180 """
181
182 _, directory = os.path.split(dirpath)
183 return directory not in DIRECTORIES_TO_SKIP
184
185
187 path: str,
188 files_to_check: List[str],
189 file_extensions_to_check: List[str],
190) -> bool:
191 """Check whether a file should be analyzed.
192
193 Args:
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.
197
198 Returns:
199 Whether the file should be analyzed.
200 """
201
202 filename = os.path.split(path)[1]
203 extension = os.path.splitext(filename)[1]
204
205 if filename in FILES_TO_SKIP:
206 return False
207
208 return filename in files_to_check or extension in file_extensions_to_check
209
210
212 paths: List[str],
213) -> Dict[str, List[str]]:
214 """Find all files to be checked in a given list of paths.
215
216 Args:
217 paths: List of paths to the files to check.
218
219 Returns:
220 Dictionary of checks and corresponding list of files to check.
221 Example: {
222 "formatting": list_of_files_to_check_formatting,
223 ...,
224 }
225 """
226
227 # Get list of files found in the given path
228 files_found: List[str] = []
229
230 for path in paths:
231 abs_path = os.path.abspath(os.path.expanduser(path))
232
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):
237 if not should_analyze_directory(dirpath):
238 # Remove directory and its subdirectories
239 dirnames[:] = []
240 continue
241
242 files_found.extend([os.path.join(dirpath, f) for f in filenames])
243 else:
244 raise ValueError(f"{path} is not a valid file nor a directory")
245
246 files_found.sort()
247
248 # Check which files should be checked
249 files_to_check: Dict[str, List[str]] = {c: [] for c in CHECKS}
250
251 for f in files_found:
252 for check in CHECKS:
253 if should_analyze_file(f, FILES_TO_CHECK[check], FILE_EXTENSIONS_TO_CHECK[check]):
254 files_to_check[check].append(f)
255
256 return files_to_check
257
258
260 """Find the path to one of the supported versions of clang-format.
261
262 Returns:
263 Path to clang-format.
264
265 Raises:
266 RuntimeError: If no supported version of clang-format is found.
267 """
268
269 # Find exact version, starting from the most recent one
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
274
275 # Find default version and check if it is supported
276 clang_format_path = shutil.which("clang-format")
277 major_version = None
278
279 if clang_format_path:
280 process = subprocess.run(
281 [clang_format_path, "--version"],
282 capture_output=True,
283 text=True,
284 check=True,
285 )
286 clang_format_version = process.stdout.strip()
287 version_regex = re.findall(r"\b(\d+)(\.\d+){0,2}\b", clang_format_version)
288 if version_regex:
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
292
293 # No supported version of clang-format found
294 raise RuntimeError(
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 "")
298 )
299
300
301###########################################################
302# CHECK STYLE MAIN FUNCTIONS
303###########################################################
305 paths: List[str],
306 checks_enabled: Dict[str, bool],
307 fix: bool,
308 verbose: bool,
309 n_jobs: int = 1,
310) -> bool:
311 """Check / fix the coding style of a list of files.
312
313 Args:
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.
319
320 Returns:
321 Whether all files are compliant with all enabled style checks.
322 """
323
324 files_to_check = find_files_to_check_style(paths)
325 checks_successful = {c: True for c in CHECKS}
326
327 style_check_strs = {
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",
334 "tabs": "tabs",
335 "formatting": "bad code formatting",
336 "encoding": f"bad file encoding ({FILE_ENCODING})",
337 }
338
339 check_style_file_functions_kwargs = {
340 "include_prefixes": {
341 "function": check_manually_file,
342 "kwargs": {
343 "respect_clang_format_guards": True,
344 "check_style_line_function": check_include_prefixes_line,
345 },
346 },
347 "include_quotes": {
348 "function": check_manually_file,
349 "kwargs": {
350 "respect_clang_format_guards": True,
351 "check_style_line_function": check_include_quotes_line,
352 },
353 },
354 "doxygen_tags": {
355 "function": check_manually_file,
356 "kwargs": {
357 "respect_clang_format_guards": True,
358 "check_style_line_function": check_doxygen_tags_line,
359 },
360 },
361 "license": {
362 "function": check_manually_file,
363 "kwargs": {
364 "respect_clang_format_guards": True,
365 "check_style_line_function": check_licenses_line,
366 },
367 },
368 "emacs": {
369 "function": check_manually_file,
370 "kwargs": {
371 "respect_clang_format_guards": True,
372 "check_style_line_function": check_emacs_line,
373 },
374 },
375 "whitespace": {
376 "function": check_manually_file,
377 "kwargs": {
378 "respect_clang_format_guards": False,
379 "check_style_line_function": check_whitespace_line,
380 },
381 },
382 "tabs": {
383 "function": check_manually_file,
384 "kwargs": {
385 "respect_clang_format_guards": True,
386 "check_style_line_function": check_tabs_line,
387 },
388 },
389 "formatting": {
390 "function": check_formatting_file,
391 "kwargs": {}, # The formatting keywords are added below
392 },
393 "encoding": {
394 "function": check_encoding_file,
395 "kwargs": {},
396 },
397 }
398
399 if checks_enabled["formatting"]:
400 check_style_file_functions_kwargs["formatting"]["kwargs"] = {
401 "clang_format_path": find_clang_format_path(),
402 }
403
404 n_checks_enabled = sum(checks_enabled.values())
405 n_check = 0
406
407 for check in CHECKS:
408 if checks_enabled[check]:
409 checks_successful[check] = check_style_files(
410 style_check_strs[check],
411 check_style_file_functions_kwargs[check]["function"],
412 files_to_check[check],
413 fix,
414 verbose,
415 n_jobs,
416 **check_style_file_functions_kwargs[check]["kwargs"],
417 )
418
419 n_check += 1
420 if n_check < n_checks_enabled:
421 print("")
422
423 return all(checks_successful.values())
424
425
427 style_check_str: str,
428 check_style_file_function: Callable[..., Tuple[str, bool, List[str]]],
429 filenames: List[str],
430 fix: bool,
431 verbose: bool,
432 n_jobs: int,
433 **kwargs,
434) -> bool:
435 """Check / fix style of a list of files.
436
437 Args:
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.
445
446 Returns:
447 Whether all files are compliant with the style.
448 """
449
450 # Check files
451 non_compliant_files: List[str] = []
452 files_verbose_infos: Dict[str, List[str]] = {}
453
454 with concurrent.futures.ProcessPoolExecutor(n_jobs) as executor:
455 non_compliant_files_results = executor.map(
456 check_style_file_function,
457 filenames,
458 itertools.repeat(fix),
459 itertools.repeat(verbose),
460 *[arg if isinstance(arg, list) else itertools.repeat(arg) for arg in kwargs.values()],
461 )
462
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)
466
467 if verbose:
468 files_verbose_infos[filename] = verbose_infos
469
470 # Output results
471 if not non_compliant_files:
472 print(f"- No files detected with {style_check_str}")
473 return True
474 else:
475 n_non_compliant_files = len(non_compliant_files)
476
477 if fix:
478 print(f"- Fixed {style_check_str} in the files ({n_non_compliant_files}):")
479 else:
480 print(f"- Detected {style_check_str} in the files ({n_non_compliant_files}):")
481
482 for f in non_compliant_files:
483 if verbose:
484 print(*[f" {l}" for l in files_verbose_infos[f]], sep="\n")
485 else:
486 print(f" - {f}")
487
488 # If all files were fixed, there are no more non-compliant files
489 return fix
490
491
492###########################################################
493# CHECK STYLE FUNCTIONS
494###########################################################
496 filename: str,
497 fix: bool,
498 verbose: bool,
499 clang_format_path: str,
500) -> Tuple[str, bool, List[str]]:
501 """Check / fix the coding style of a file with clang-format.
502
503 Args:
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.
508
509 Returns:
510 Tuple (Filename,
511 Whether the file is compliant with the style (before the check),
512 Verbose information)
513 """
514
515 verbose_infos: List[str] = []
516
517 # Check if the file is well formatted
518 process = subprocess.run(
519 [
520 clang_format_path,
521 filename,
522 "-style=file",
523 "--dry-run",
524 "--Werror",
525 # Optimization: In non-verbose mode, only one error is needed to check that the file is not compliant
526 f"--ferror-limit={0 if verbose else 1}",
527 ],
528 check=False,
529 capture_output=True,
530 text=True,
531 )
532 is_file_compliant = process.returncode == 0
533 if verbose:
534 verbose_infos = process.stderr.splitlines()
535
536 # Fix file
537 if fix and not is_file_compliant:
538 process = subprocess.run(
539 [
540 clang_format_path,
541 filename,
542 "-style=file",
543 "-i",
544 ],
545 check=False,
546 stdout=subprocess.DEVNULL,
547 stderr=subprocess.DEVNULL,
548 )
549
550 return (filename, is_file_compliant, verbose_infos)
551
552
554 filename: str,
555 fix: bool,
556 verbose: bool,
557) -> Tuple[str, bool, List[str]]:
558 """Check / fix the encoding of a file.
559
560 Args:
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.
564
565 Returns:
566 Tuple (Filename,
567 Whether the file is compliant with the style (before the check),
568 Verbose information)
569 """
570
571 verbose_infos: List[str] = []
572 is_file_compliant = True
573
574 with open(filename, "rb") as f:
575 file_data = f.read()
576 file_lines = file_data.decode(FILE_ENCODING, errors="replace").splitlines(keepends=True)
577
578 # Check if file has correct encoding
579 try:
580 file_data.decode(FILE_ENCODING)
581 except UnicodeDecodeError as e:
582 is_file_compliant = False
583
584 if verbose:
585 # Find line and column with bad encoding
586 bad_char_start_index = e.start
587 n_chars_file_read = 0
588
589 for line_number, line in enumerate(file_lines):
590 n_chars_line = len(line)
591
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(
595 [
596 f"{filename}:{line_number + 1}:{bad_char_column + 1}: error: bad {FILE_ENCODING} encoding",
597 f" {line.rstrip()}",
598 f" {'':>{bad_char_column}}^",
599 ]
600 )
601 break
602
603 n_chars_file_read += n_chars_line
604
605 # Fix file encoding
606 if fix and not is_file_compliant:
607 with open(filename, "w", encoding=FILE_ENCODING) as f:
608 f.writelines(file_lines)
609
610 return (filename, is_file_compliant, verbose_infos)
611
612
614 filename: str,
615 fix: bool,
616 verbose: bool,
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.
621
622 Args:
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.
628
629 Returns:
630 Tuple (Filename,
631 Whether the file is compliant with the style (before the check),
632 Verbose information)
633 """
634
635 is_file_compliant = True
636 verbose_infos: List[str] = []
637 clang_format_enabled = True
638
639 with open(filename, "r", encoding=FILE_ENCODING) as f:
640 file_lines = f.readlines()
641
642 for i, line in enumerate(file_lines):
643 # Check clang-format guards
644 if respect_clang_format_guards:
645 line_stripped = line.strip()
646
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
651
652 if not clang_format_enabled and line_stripped not in (
653 FORMAT_GUARD_ON + FORMAT_GUARD_OFF
654 ):
655 continue
656
657 # Check if the line is compliant with the style and fix it
658 is_line_compliant, line_fixed, line_verbose_infos = check_style_line_function(
659 line, filename, i
660 )
661
662 if not is_line_compliant:
663 is_file_compliant = False
664 file_lines[i] = line_fixed
665 verbose_infos.extend(line_verbose_infos)
666
667 # Optimization: If running in non-verbose check mode, only one error is needed to check that the file is not compliant
668 if not fix and not verbose:
669 break
670
671 # Update file with the fixed lines
672 if fix and not is_file_compliant:
673 with open(filename, "w", encoding=FILE_ENCODING) as f:
674 f.writelines(file_lines)
675
676 return (filename, is_file_compliant, verbose_infos)
677
678
680 line: str,
681 filename: str,
682 line_number: int,
683) -> Tuple[bool, str, List[str]]:
684 """Check / fix #include headers from the same module with the "ns3/" prefix in a line.
685
686 Args:
687 line: The line to check.
688 filename: Name of the file to be checked.
689 line_number: The number of the line checked.
690
691 Returns:
692 Tuple (Filename,
693 Whether the line is compliant with the style (before the check),
694 Verbose information)
695 """
696
697 is_line_compliant = True
698 line_fixed = line
699 verbose_infos: List[str] = []
700
701 # Check if the line is an #include and extract its header file
702 line_stripped = line.strip()
703 header_file = re.findall(r'^#include ["<]ns3/(.*\.h)[">]', line_stripped)
704
705 if header_file:
706 # Check if the header file belongs to the same module and remove the "ns3/" prefix
707 header_file = header_file[0]
708 parent_path = os.path.split(filename)[0]
709
710 if os.path.exists(os.path.join(parent_path, header_file)):
711 is_line_compliant = False
712 line_fixed = (
713 line_stripped.replace(f"ns3/{header_file}", header_file)
714 .replace("<", '"')
715 .replace(">", '"')
716 + "\n"
717 )
718 header_index = len('#include "')
719 verbose_infos.extend(
720 [
721 f'{filename}:{line_number + 1}:{header_index + 1}: error: #include headers from the same module with the "ns3/" prefix detected',
722 f" {line_stripped}",
723 f" {'':>{header_index}}^",
724 ]
725 )
726
727 return (is_line_compliant, line_fixed, verbose_infos)
728
729
731 line: str,
732 filename: str,
733 line_number: int,
734) -> Tuple[bool, str, List[str]]:
735 """Check / fix ns-3 #include headers using angle brackets <> rather than quotes "" in a line.
736
737 Args:
738 line: The line to check.
739 filename: Name of the file to be checked.
740 line_number: The number of the line checked.
741
742 Returns:
743 Tuple (Whether the line is compliant with the style (before the check),
744 Fixed line,
745 Verbose information)
746 """
747
748 is_line_compliant = True
749 line_fixed = line
750 verbose_infos: List[str] = []
751
752 # Check if the line is an #include <ns3/...>
753 header_file = re.findall(r"^#include <ns3/.*\.h>", line)
754
755 if header_file:
756 is_line_compliant = False
757 line_fixed = line.replace("<", '"').replace(">", '"')
758 header_index = len("#include ")
759 verbose_infos = [
760 f"{filename}:{line_number + 1}:{header_index + 1}: error: ns-3 #include headers with angle brackets detected",
761 f" {line}",
762 f" {'':{header_index}}^",
763 ]
764
765 return (is_line_compliant, line_fixed, verbose_infos)
766
767
769 line: str,
770 filename: str,
771 line_number: int,
772) -> Tuple[bool, str, List[str]]:
773 """Check / fix Doxygen tags using \\ rather than @ in a line.
774
775 Args:
776 line: The line to check.
777 filename: Name of the file to be checked.
778 line_number: The number of the line checked.
779
780 Returns:
781 Tuple (Whether the line is compliant with the style (before the check),
782 Fixed line,
783 Verbose information)
784 """
785
786 IGNORED_WORDS = [
787 "\\dots",
788 "\\langle",
789 "\\quad",
790 ]
791
792 is_line_compliant = True
793 line_fixed = line
794 verbose_infos: List[str] = []
795
796 # Match Doxygen tags at the start of the line (e.g., "* \param arg Description")
797 line_stripped = line.rstrip()
798 regex_findings = re.findall(r"^\s*(?:\*|\/\*\*|\/\/\/)\s*(\\\w{3,})(?=(?:\s|$))", line_stripped)
799
800 if regex_findings:
801 doxygen_tag = regex_findings[0]
802
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(
808 [
809 f"{filename}:{line_number + 1}:{doxygen_tag_index + 1}: error: detected Doxygen tags using \\ rather than @",
810 f" {line_stripped}",
811 f" {'':{doxygen_tag_index}}^",
812 ]
813 )
814
815 return (is_line_compliant, line_fixed, verbose_infos)
816
817
819 line: str,
820 filename: str,
821 line_number: int,
822) -> Tuple[bool, str, List[str]]:
823 """Check / fix SPDX licenses rather than GPL text in a line.
824
825 Args:
826 line: The line to check.
827 filename: Name of the file to be checked.
828 line_number: The number of the line checked.
829
830 Returns:
831 Tuple (Whether the line is compliant with the style (before the check),
832 Fixed line,
833 Verbose information)
834 """
835
836 # fmt: off
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",
848 ]
849 # fmt: on
850
851 # REUSE-IgnoreStart
852 SPDX_LICENSE = "SPDX-License-Identifier: GPL-2.0-only"
853 # REUSE-IgnoreEnd
854
855 is_line_compliant = True
856 line_fixed = line
857 verbose_infos: List[str] = []
858
859 # Check if the line is a GPL license text
860 line_stripped = line.strip()
861 line_stripped_no_leading_comments = line_stripped.strip("*#/").strip()
862
863 if line_stripped_no_leading_comments in GPL_LICENSE_LINES:
864 is_line_compliant = False
865 col_index = 0
866
867 # Replace GPL text with SPDX license.
868 # Replace the first line of the GPL text with SPDX.
869 # Delete the remaining GPL text lines.
870 if line_stripped_no_leading_comments == GPL_LICENSE_LINES[0]:
871 line_fixed = line.replace(line_stripped_no_leading_comments, SPDX_LICENSE)
872 else:
873 line_fixed = ""
874
875 verbose_infos.extend(
876 [
877 f"{filename}:{line_number + 1}:{col_index}: error: GPL license text detected instead of SPDX license",
878 f" {line_stripped}",
879 f" {'':>{col_index}}^",
880 ]
881 )
882
883 return (is_line_compliant, line_fixed, verbose_infos)
884
885
887 line: str,
888 filename: str,
889 line_number: int,
890) -> Tuple[bool, str, List[str]]:
891 """Check / fix emacs file style comment in a line.
892
893 Args:
894 line: The line to check.
895 filename: Name of the file to be checked.
896 line_number: The number of the line checked.
897
898 Returns:
899 Tuple (Whether the line is compliant with the style (before the check),
900 Fixed line,
901 Verbose information)
902 """
903
904 is_line_compliant = True
905 line_fixed = line
906 verbose_infos: List[str] = []
907
908 # Check if line is an emacs file style comment
909 line_stripped = line.strip()
910 # fmt: off
911 emacs_line = re.search(r"c-file-style:|py-indent-offset:", line_stripped)
912 # fmt: on
913
914 if emacs_line:
915 is_line_compliant = False
916 line_fixed = ""
917 col_index = emacs_line.start()
918 verbose_infos = [
919 f"{filename}:{line_number + 1}:{col_index}: error: emacs file style comment detected",
920 f" {line_stripped}",
921 f" {'':{col_index}}^",
922 ]
923
924 return (is_line_compliant, line_fixed, verbose_infos)
925
926
928 line: str,
929 filename: str,
930 line_number: int,
931) -> Tuple[bool, str, List[str]]:
932 """Check / fix whitespace in a line.
933
934 Args:
935 line: The line to check.
936 filename: Name of the file to be checked.
937 line_number: The number of the line checked.
938
939 Returns:
940 Tuple (Whether the line is compliant with the style (before the check),
941 Fixed line,
942 Verbose information)
943 """
944
945 is_line_compliant = True
946 line_fixed = line.rstrip() + "\n"
947 verbose_infos: List[str] = []
948
949 if line_fixed != line:
950 is_line_compliant = False
951 line_fixed_stripped_expanded = line_fixed.rstrip().expandtabs(TAB_SIZE)
952 verbose_infos = [
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)}}^",
956 ]
957
958 return (is_line_compliant, line_fixed, verbose_infos)
959
960
962 line: str,
963 filename: str,
964 line_number: int,
965) -> Tuple[bool, str, List[str]]:
966 """Check / fix tabs in a line.
967
968 Args:
969 line: The line to check.
970 filename: Name of the file to be checked.
971 line_number: The number of the line checked.
972
973 Returns:
974 Tuple (Whether the line is compliant with the style (before the check),
975 Fixed line,
976 Verbose information)
977 """
978
979 is_line_compliant = True
980 line_fixed = line
981 verbose_infos: List[str] = []
982
983 tab_index = line.find("\t")
984
985 if tab_index != -1:
986 is_line_compliant = False
987 line_fixed = line.expandtabs(TAB_SIZE)
988 verbose_infos = [
989 f"{filename}:{line_number + 1}:{tab_index + 1}: error: Tab detected",
990 f" {line.rstrip()}",
991 f" {'':>{tab_index}}^",
992 ]
993
994 return (is_line_compliant, line_fixed, verbose_infos)
995
996
997###########################################################
998# MAIN
999###########################################################
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.'
1010 )
1011 parser.add_argument(
1012 "paths",
1013 action="store",
1014 type=str,
1015 nargs="+",
1016 help="List of paths to the files to check",
1017 )
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)',
1022 )
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)',
1027 )
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)",
1032 )
1033 parser.add_argument(
1034 "--no-licenses",
1035 action="store_true",
1036 help="Do not check / fix SPDX licenses rather than GPL text (respects clang-format guards)",
1037 )
1038 parser.add_argument(
1039 "--no-emacs",
1040 action="store_true",
1041 help="Do not check / fix emacs file style comments (respects clang-format guards)",
1042 )
1043 parser.add_argument(
1044 "--no-whitespace",
1045 action="store_true",
1046 help="Do not check / fix trailing whitespace",
1047 )
1048 parser.add_argument(
1049 "--no-tabs",
1050 action="store_true",
1051 help="Do not check / fix tabs (respects clang-format guards)",
1052 )
1053 parser.add_argument(
1054 "--no-formatting",
1055 action="store_true",
1056 help="Do not check / fix code formatting (respects clang-format guards)",
1057 )
1058 parser.add_argument(
1059 "--no-encoding",
1060 action="store_true",
1061 help=f"Do not check / fix file encoding ({FILE_ENCODING})",
1062 )
1063 parser.add_argument(
1064 "--fix",
1065 action="store_true",
1066 help="Fix coding style issues detected in the files",
1067 )
1068 parser.add_argument(
1069 "-v",
1070 "--verbose",
1071 action="store_true",
1072 help="Show the lines that are not well-formatted",
1073 )
1074 parser.add_argument(
1075 "-j",
1076 "--jobs",
1077 type=int,
1078 default=max(1, os.cpu_count() - 1),
1079 help="Number of parallel jobs",
1080 )
1081 args = parser.parse_args()
1082
1083 try:
1084 all_checks_successful = check_style_clang_format(
1085 paths=args.paths,
1086 checks_enabled={
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,
1096 },
1097 fix=args.fix,
1098 verbose=args.verbose,
1099 n_jobs=args.jobs,
1100 )
1101
1102 except Exception as ex:
1103 print("ERROR:", ex)
1104 sys.exit(1)
1105
1106 if not all_checks_successful:
1107 if args.verbose:
1108 print(
1109 "",
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",
1115 sep="\n",
1116 )
1117
1118 sys.exit(1)
Tuple[str, bool, List[str]] check_encoding_file(str filename, bool fix, bool verbose)
Tuple[bool, str, List[str]] check_doxygen_tags_line(str line, str filename, int line_number)
Tuple[bool, str, List[str]] check_whitespace_line(str line, str filename, int line_number)
Tuple[bool, str, List[str]] check_include_quotes_line(str line, str filename, int line_number)
Tuple[str, bool, List[str]] check_formatting_file(str filename, bool fix, bool verbose, str clang_format_path)
CHECK STYLE FUNCTIONS.
Dict[str, List[str]] find_files_to_check_style(List[str] paths)
bool check_style_clang_format(List[str] paths, Dict[str, bool] checks_enabled, bool fix, bool verbose, int n_jobs=1)
CHECK STYLE MAIN FUNCTIONS.
Tuple[str, bool, List[str]] check_manually_file(str filename, bool fix, bool verbose, bool respect_clang_format_guards, Callable[[str, str, int], Tuple[bool, str, List[str]]] check_style_line_function)
Tuple[bool, str, List[str]] check_emacs_line(str line, str filename, int line_number)
bool check_style_files(str style_check_str, Callable[..., Tuple[str, bool, List[str]]] check_style_file_function, List[str] filenames, bool fix, bool verbose, int n_jobs, **kwargs)
Tuple[bool, str, List[str]] check_include_prefixes_line(str line, str filename, int line_number)
bool should_analyze_file(str path, List[str] files_to_check, List[str] file_extensions_to_check)
Tuple[bool, str, List[str]] check_tabs_line(str line, str filename, int line_number)
bool should_analyze_directory(str dirpath)
AUXILIARY FUNCTIONS.
Tuple[bool, str, List[str]] check_licenses_line(str line, str filename, int line_number)