1# Copyright 2015 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"""Presubmit script for devil.
6
7See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for
8details on the presubmit API built into depot_tools.
9"""
10
11
12def _RunPylint(input_api, output_api):
13  return input_api.RunTests(input_api.canned_checks.RunPylint(
14      input_api, output_api, pylintrc='pylintrc'))
15
16
17def _RunUnitTests(input_api, output_api):
18  def J(*dirs):
19    """Returns a path relative to presubmit directory."""
20    return input_api.os_path.join(
21        input_api.PresubmitLocalPath(), 'devil', *dirs)
22
23  test_env = dict(input_api.environ)
24  test_env.update({
25    'PYTHONDONTWRITEBYTECODE': '1',
26    'PYTHONPATH': ':'.join([J(), J('..')]),
27  })
28
29  message_type = (output_api.PresubmitError if input_api.is_committing
30                  else output_api.PresubmitPromptWarning)
31
32  return input_api.RunTests([
33      input_api.Command(
34          name='devil/bin/run_py_tests',
35          cmd=[
36            input_api.os_path.join(
37                input_api.PresubmitLocalPath(), 'bin', 'run_py_tests')],
38          kwargs={'env': test_env},
39          message=message_type)])
40
41
42def _EnsureNoPylibUse(input_api, output_api):
43  def other_python_files(f):
44    this_presubmit_file = input_api.os_path.join(
45        input_api.PresubmitLocalPath(), 'PRESUBMIT.py')
46    return (f.LocalPath().endswith('.py')
47            and not f.AbsoluteLocalPath() == this_presubmit_file)
48
49  changed_files = input_api.AffectedSourceFiles(other_python_files)
50  import_error_re = input_api.re.compile(
51      r'(from pylib.* import)|(import pylib)')
52
53  errors = []
54  for f in changed_files:
55    errors.extend(
56        '%s:%d' % (f.LocalPath(), line_number)
57        for line_number, line_text in f.ChangedContents()
58        if import_error_re.search(line_text))
59
60  if errors:
61    return [output_api.PresubmitError(
62        'pylib modules should not be imported from devil modules.',
63        items=errors)]
64  return []
65
66
67def CommonChecks(input_api, output_api):
68  output = []
69  output += _RunPylint(input_api, output_api)
70  output += _RunUnitTests(input_api, output_api)
71  output += _EnsureNoPylibUse(input_api, output_api)
72  return output
73
74
75def CheckChangeOnUpload(input_api, output_api):
76  return CommonChecks(input_api, output_api)
77
78
79def CheckChangeOnCommit(input_api, output_api):
80  return CommonChecks(input_api, output_api)
81
82