1# Copyright 2013 The Chromium Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5"""Script that is used by PRESUBMIT.py to run style checks on Java files."""
6
7import os
8import subprocess
9
10
11CHROMIUM_SRC = os.path.normpath(
12    os.path.join(os.path.dirname(__file__),
13                 os.pardir, os.pardir, os.pardir))
14CHECKSTYLE_ROOT = os.path.join(CHROMIUM_SRC, 'third_party', 'checkstyle',
15                               'checkstyle-5.7-all.jar')
16
17
18def RunCheckstyle(input_api, output_api, style_file):
19  if not os.path.exists(style_file):
20    file_error = ('  Java checkstyle configuration file is missing: '
21                  + style_file)
22    return [output_api.PresubmitError(file_error)]
23
24  # Filter out non-Java files and files that were deleted.
25  java_files = [x.LocalPath() for x in input_api.AffectedFiles(False, False)
26                if os.path.splitext(x.LocalPath())[1] == '.java']
27  if not java_files:
28    return []
29
30  # Run checkstyle
31  checkstyle_env = os.environ.copy()
32  checkstyle_env['JAVA_CMD'] = 'java'
33  try:
34    check = subprocess.Popen(['java', '-cp',
35                              CHECKSTYLE_ROOT,
36                              'com.puppycrawl.tools.checkstyle.Main', '-c',
37                              style_file] + java_files,
38                             stdout=subprocess.PIPE, env=checkstyle_env)
39    stdout, _ = check.communicate()
40    if check.returncode == 0:
41      return []
42  except OSError as e:
43    import errno
44    if e.errno == errno.ENOENT:
45      install_error = ('  checkstyle is not installed. Please run '
46                       'build/install-build-deps-android.sh')
47      return [output_api.PresubmitPromptWarning(install_error)]
48
49  # Remove non-error values from stdout
50  errors = stdout.splitlines()
51
52  if errors and errors[0] == 'Starting audit...':
53    del errors[0]
54  if errors and errors[-1] == 'Audit done.':
55    del errors[-1]
56
57  # Filter out warnings
58  errors = [x for x in errors if 'warning: ' not in x]
59  if not errors:
60    return []
61
62  local_path = input_api.PresubmitLocalPath()
63  output = []
64  for error in errors:
65    # Change the full file path to relative path in the output lines
66    full_path, end = error.split(':', 1)
67    rel_path = os.path.relpath(full_path, local_path)
68    output.append('  %s:%s' % (rel_path, end))
69  return [output_api.PresubmitPromptWarning('\n'.join(output))]
70