| 65 | |
| 66 | |
| 67 | def main(): |
| 68 | parser = argparse.ArgumentParser( |
| 69 | description= |
| 70 | "Format source files using clang-format, eg: `./tools/format.py src -w`. \ |
| 71 | Require clang-format version == 12.0", |
| 72 | formatter_class=argparse.ArgumentDefaultsHelpFormatter, |
| 73 | ) |
| 74 | |
| 75 | parser.add_argument("path", |
| 76 | nargs="+", |
| 77 | help="file name or path based on MegCC root dir.") |
| 78 | parser.add_argument( |
| 79 | "-w", |
| 80 | "--write", |
| 81 | action="store_true", |
| 82 | help="use formatted file to replace original file.", |
| 83 | ) |
| 84 | parser.add_argument( |
| 85 | "--clang-format", |
| 86 | default=os.getenv("CLANG_FORMAT", "clang-format"), |
| 87 | help="clang-format executable name; it can also be " |
| 88 | "modified via the CLANG_FORMAT environment var", |
| 89 | ) |
| 90 | args = parser.parse_args() |
| 91 | |
| 92 | format_type = [".cpp", ".c", ".h", ".cu", ".cuh", ".inl"] |
| 93 | |
| 94 | def getfiles(path): |
| 95 | rst = [] |
| 96 | for p in os.listdir(path): |
| 97 | p = os.path.join(path, p) |
| 98 | if os.path.isdir(p): |
| 99 | if exclude_dir.count(p) == 1: |
| 100 | continue |
| 101 | rst += getfiles(p) |
| 102 | elif (os.path.isfile(p) and not os.path.islink(p) |
| 103 | and os.path.splitext(p)[1] in format_type): |
| 104 | rst.append(p) |
| 105 | return rst |
| 106 | |
| 107 | files = [] |
| 108 | for path in args.path: |
| 109 | if os.path.isdir(path): |
| 110 | files += getfiles(path) |
| 111 | elif os.path.isfile(path): |
| 112 | files.append(path) |
| 113 | else: |
| 114 | raise ValueError("Invalid path {}".format(path)) |
| 115 | |
| 116 | # check version, we only support 12.0.1 now |
| 117 | version = subprocess.check_output([ |
| 118 | args.clang_format, |
| 119 | "--version", |
| 120 | ], ) |
| 121 | version = version.decode("utf-8") |
| 122 | |
| 123 | need_version = "12.0.1" |
| 124 | if version.find(need_version) < 0: |