format.py
Go to the documentation of this file.
1 import argparse
2 import difflib
3 import os
4 import subprocess
5 import sys
6 from typing import List
7 
8 IGNORE_DIRS = ["build"]
9 EXTENSIONS = [".cpp", ".hpp"]
10 
11 
12 def main(dirs: List[str], fix: bool):
13  changed_paths: List[str] = []
14  for root in dirs:
15  for dirpath, dirnames, filenames in os.walk(root):
16  # Filter out directories to skip
17  dirnames[:] = filter(lambda d: d not in IGNORE_DIRS, dirnames)
18 
19  for name in filenames:
20  path = os.path.join(dirpath, name)
21  if any(name.endswith(ext) for ext in EXTENSIONS):
22  if fix:
23  subprocess.check_call(["clang-format", "-i", path])
24  continue
25 
26  stdout = (
27  subprocess.check_output(["clang-format", path])
28  .decode("utf-8")
29  .splitlines()
30  )
31 
32  with open(path, "r") as f:
33  orig = [line.rstrip("\n") for line in f]
34  diff = difflib.unified_diff(
35  orig,
36  stdout,
37  fromfile=path,
38  tofile=f"clang-format {path}", # cspell:disable-line
39  lineterm="",
40  )
41  had_diff = False
42  for line in diff:
43  had_diff = True
44  print(line)
45  if had_diff:
46  changed_paths.append(path)
47  print("\n")
48 
49  if changed_paths:
50  print(f"{len(changed_paths)} files need to be formatted:")
51  for path in changed_paths:
52  print(f" {path}")
53  return 1
54  return 0
55 
56 
57 if __name__ == "__main__":
58  parser = argparse.ArgumentParser(
59  description="Run clang-format and display changed files."
60  )
61  parser.add_argument(
62  "dirs", help="List of directories to search", nargs="+")
63  parser.add_argument("--fix", action="store_true")
64  args = parser.parse_args()
65  sys.exit(main(**vars(args)))
def main
Definition: format.py:12


foxglove_bridge
Author(s): Foxglove
autogenerated on Mon Jul 3 2023 02:12:22