File indexing completed on 2025-01-18 09:10:44
0001
0002
0003 from pathlib import Path
0004 import os
0005 import argparse
0006 from fnmatch import fnmatch
0007 import re
0008 import sys
0009
0010
0011 type_list = [
0012 "size_t",
0013 "ptrdiff_t",
0014 "nullptr_t",
0015 "int8_t",
0016 "int16_t",
0017 "int32_t",
0018 "int64_t",
0019 "uint8_t",
0020 "uint16_t",
0021 "uint32_t",
0022 "uint64_t",
0023 "max_align_t",
0024 ]
0025
0026 github = "GITHUB_ACTIONS" in os.environ
0027
0028
0029 def handle_file(file: Path, fix: bool, c_type: str) -> list[tuple[int, str]]:
0030 ex = re.compile(rf"\b(?<!std::){c_type}\b")
0031
0032 content = file.read_text()
0033 lines = content.splitlines()
0034
0035 changed_lines = []
0036
0037 for i, oline in enumerate(lines):
0038 line, n_subs = ex.subn(rf"std::{c_type}", oline)
0039 lines[i] = line
0040 if n_subs > 0:
0041 changed_lines.append((i, oline))
0042
0043 if fix and len(changed_lines) > 0:
0044 file.write_text("\n".join(lines) + "\n")
0045
0046 return changed_lines
0047
0048
0049 def main():
0050 p = argparse.ArgumentParser()
0051 p.add_argument("input", nargs="+")
0052 p.add_argument("--fix", action="store_true", help="Attempt to fix C-style types.")
0053 p.add_argument("--exclude", "-e", action="append", default=[])
0054
0055 args = p.parse_args()
0056
0057 exit_code = 0
0058
0059 inputs = []
0060
0061 if len(args.input) == 1 and os.path.isdir(args.input[0]):
0062
0063 for root, _, files in os.walk(args.input[0]):
0064 root = Path(root)
0065 for filename in files:
0066
0067 filepath = root / filename
0068 if filepath.suffix not in (
0069 ".hpp",
0070 ".cpp",
0071 ".ipp",
0072 ".h",
0073 ".C",
0074 ".c",
0075 ".cu",
0076 ".cuh",
0077 ):
0078 continue
0079
0080 if any([fnmatch(str(filepath), e) for e in args.exclude]):
0081 continue
0082
0083 inputs.append(filepath)
0084 else:
0085 for file in args.input:
0086 inputs.append(Path(file))
0087
0088 for filepath in inputs:
0089 for c_type in type_list:
0090 changed_lines = handle_file(file=filepath, fix=args.fix, c_type=c_type)
0091 if len(changed_lines) > 0:
0092 exit_code = 1
0093 print()
0094 print(filepath)
0095 for i, oline in changed_lines:
0096 print(f"{i}: {oline}")
0097
0098 if github:
0099 print(
0100 f"::error file={filepath},line={i+1},title=Do not use C-style {c_type}::Replace {c_type} with std::{c_type}"
0101 )
0102
0103 return exit_code
0104
0105
0106 if "__main__" == __name__:
0107 sys.exit(main())