• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env python3
2# Copyright 2016 The Android Open Source Project
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8#      http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16"""Wrapper to run git-clang-format and parse its output."""
17
18import argparse
19import os
20import sys
21
22_path = os.path.realpath(__file__ + '/../..')
23if sys.path[0] != _path:
24    sys.path.insert(0, _path)
25del _path
26
27# We have to import our local modules after the sys.path tweak.  We can't use
28# relative imports because this is an executable program, not a module.
29# pylint: disable=wrong-import-position
30import rh.shell
31import rh.utils
32
33
34# Since we're asking git-clang-format to print a diff, all modified filenames
35# that have formatting errors are printed with this prefix.
36DIFF_MARKER_PREFIX = '+++ b/'
37
38
39def get_parser():
40    """Return a command line parser."""
41    parser = argparse.ArgumentParser(description=__doc__)
42    parser.add_argument('--clang-format', default='clang-format',
43                        help='The path of the clang-format executable.')
44    parser.add_argument('--git-clang-format', default='git-clang-format',
45                        help='The path of the git-clang-format executable.')
46    parser.add_argument('--style', metavar='STYLE', type=str,
47                        help='The style that clang-format will use.')
48    parser.add_argument('--extensions', metavar='EXTENSIONS', type=str,
49                        help='Comma-separated list of file extensions to '
50                             'format.')
51    parser.add_argument('--fix', action='store_true',
52                        help='Fix any formatting errors automatically.')
53
54    scope = parser.add_mutually_exclusive_group(required=True)
55    scope.add_argument('--commit', type=str, default='HEAD',
56                       help='Specify the commit to validate.')
57    scope.add_argument('--working-tree', action='store_true',
58                       help='Validates the files that have changed from '
59                            'HEAD in the working directory.')
60
61    parser.add_argument('files', type=str, nargs='*',
62                        help='If specified, only consider differences in '
63                             'these files.')
64    return parser
65
66
67def main(argv):
68    """The main entry."""
69    parser = get_parser()
70    opts = parser.parse_args(argv)
71
72    cmd = [opts.git_clang_format, '--binary', opts.clang_format, '--diff']
73    if opts.style:
74        cmd.extend(['--style', opts.style])
75    if opts.extensions:
76        cmd.extend(['--extensions', opts.extensions])
77    if not opts.working_tree:
78        cmd.extend(['%s^' % opts.commit, opts.commit])
79    cmd.extend(['--'] + opts.files)
80
81    # Fail gracefully if clang-format itself aborts/fails.
82    try:
83        result = rh.utils.run(cmd, capture_output=True)
84    except rh.utils.CalledProcessError as e:
85        print('clang-format failed:\n%s' % (e,), file=sys.stderr)
86        print('\nPlease report this to the clang team.', file=sys.stderr)
87        return 1
88
89    stdout = result.stdout
90    if stdout.rstrip('\n') == 'no modified files to format':
91        # This is always printed when only files that clang-format does not
92        # understand were modified.
93        return 0
94
95    diff_filenames = []
96    for line in stdout.splitlines():
97        if line.startswith(DIFF_MARKER_PREFIX):
98            diff_filenames.append(line[len(DIFF_MARKER_PREFIX):].rstrip())
99
100    if diff_filenames:
101        if opts.fix:
102            result = rh.utils.run(['git', 'apply'], input=stdout, check=False)
103            if result.returncode:
104                print('Error: Unable to automatically fix things.\n'
105                      '  Make sure your checkout is clean first.\n'
106                      '  If you have multiple commits, you might have to '
107                      'manually rebase your tree first.',
108                      file=sys.stderr)
109                return result.returncode
110        else:
111            print('The following files have formatting errors:')
112            for filename in diff_filenames:
113                print('\t%s' % filename)
114            print('You can try to fix this by running:\n%s --fix %s' %
115                  (sys.argv[0], rh.shell.cmd_to_str(argv)))
116            return 1
117
118    return 0
119
120
121if __name__ == '__main__':
122    sys.exit(main(sys.argv[1:]))
123