|
| 1 | +#!/usr/bin/env python |
| 2 | +''' |
| 3 | +Wrapper script for clang-format |
| 4 | +
|
| 5 | +Copyright (c) 2015 MarcoFalke |
| 6 | +Copyright (c) 2015 The Bitcoin Core developers |
| 7 | +Distributed under the MIT software license, see the accompanying |
| 8 | +file COPYING or http://www.opensource.org/licenses/mit-license.php. |
| 9 | +''' |
| 10 | + |
| 11 | +import os |
| 12 | +import sys |
| 13 | +import subprocess |
| 14 | + |
| 15 | +tested_versions = ['3.6.0', '3.6.1', '3.6.2'] # A set of versions known to produce the same output |
| 16 | +accepted_file_extensions = ('.h', '.cpp') # Files to format |
| 17 | + |
| 18 | +def check_clang_format_version(clang_format_exe): |
| 19 | + try: |
| 20 | + output = subprocess.check_output([clang_format_exe, '-version']) |
| 21 | + for ver in tested_versions: |
| 22 | + if ver in output: |
| 23 | + print "Detected clang-format version " + ver |
| 24 | + return |
| 25 | + raise RuntimeError("Untested version: " + output) |
| 26 | + except Exception as e: |
| 27 | + print 'Could not verify version of ' + clang_format_exe + '.' |
| 28 | + raise e |
| 29 | + |
| 30 | +def check_command_line_args(argv): |
| 31 | + required_args = ['{clang-format-exe}', '{files}'] |
| 32 | + example_args = ['clang-format-3.x', 'src/main.cpp', 'src/wallet/*'] |
| 33 | + |
| 34 | + if(len(argv) < len(required_args) + 1): |
| 35 | + for word in (['Usage:', argv[0]] + required_args): |
| 36 | + print word, |
| 37 | + print '' |
| 38 | + for word in (['E.g:', argv[0]] + example_args): |
| 39 | + print word, |
| 40 | + print '' |
| 41 | + sys.exit(1) |
| 42 | + |
| 43 | +def run_clang_format(clang_format_exe, files): |
| 44 | + for target in files: |
| 45 | + if os.path.isdir(target): |
| 46 | + for path, dirs, files in os.walk(target): |
| 47 | + run_clang_format(clang_format_exe, (os.path.join(path, f) for f in files)) |
| 48 | + elif target.endswith(accepted_file_extensions): |
| 49 | + print "Format " + target |
| 50 | + subprocess.check_call([clang_format_exe, '-i', '-style=file', target], stdout=open(os.devnull, 'wb'), stderr=subprocess.STDOUT) |
| 51 | + else: |
| 52 | + print "Skip " + target |
| 53 | + |
| 54 | +def main(argv): |
| 55 | + check_command_line_args(argv) |
| 56 | + clang_format_exe = argv[1] |
| 57 | + files = argv[2:] |
| 58 | + check_clang_format_version(clang_format_exe) |
| 59 | + run_clang_format(clang_format_exe, files) |
| 60 | + |
| 61 | +if __name__ == "__main__": |
| 62 | + main(sys.argv) |
0 commit comments