Created
April 5, 2018 03:59
-
-
Save foreverbell/9c1cfa6892da9ee0cfc86f6802063daa to your computer and use it in GitHub Desktop.
fmt-all.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python | |
| import distutils.spawn | |
| import os, os.path | |
| import subprocess | |
| class Formatter(object): | |
| def __init__(self, suffixes, exes, args): | |
| self.suffixes = suffixes | |
| self.name = exes[0] | |
| self.cmd = None | |
| for exe in exes: | |
| self.cmd = distutils.spawn.find_executable(exe) | |
| if not self.cmd is None: | |
| self.cmd = [self.cmd] + args | |
| break | |
| def accept(self, path): | |
| for s in self.suffixes: | |
| if path.endswith(s): | |
| return True | |
| return False | |
| def format(self, path): | |
| if self.cmd: | |
| cmd = self.cmd + [path] | |
| print(' '.join(cmd)) | |
| subprocess.call(cmd) | |
| cc_formatter = Formatter([".h", ".hpp", ".c", ".cc", ".cpp", ".cxx"], [ | |
| "clang-format", "clang-format-3.6", "clang-format-3.7", "clang-format-3.8", | |
| "clang-format-3.9" | |
| ], ["-style=google", "-i"]) | |
| py_formatter = Formatter([".py"], ["yapf"], ["-i"]) | |
| rs_formatter = Formatter([".rs"], ["rustfmt"], ["--write-mode=overwrite"]) | |
| go_formatter = Formatter([".go"], ["gofmt"], ["-s", "w"]) | |
| formatters = [cc_formatter, py_formatter, rs_formatter, go_formatter] | |
| def check_toolchains(): | |
| for formatter in formatters: | |
| if formatter.cmd is None: | |
| print("%s seems not installed", formatter.name) | |
| def main(): | |
| for subdir, _, files in os.walk('.'): # _ is for directories. | |
| for file in files: | |
| path = os.path.join(subdir, file) | |
| for formatter in formatters: | |
| if formatter.accept(path): | |
| formatter.format(path) | |
| if __name__ == "__main__": | |
| check_toolchains() | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment