1# Copyright (C) 2018 The Android Open Source Project 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# http://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14 15from __future__ import print_function 16import time 17import subprocess 18from os.path import relpath, dirname, join 19 20USE_PYTHON3 = True 21 22 23def RunAndReportIfLong(func, *args, **kargs): 24 start = time.time() 25 results = func(*args, **kargs) 26 end = time.time() 27 limit = 3.0 # seconds 28 name = func.__name__ 29 runtime = end - start 30 if runtime > limit: 31 print("{} took >{:.2}s ({:.2}s)".format(name, limit, runtime)) 32 return results 33 34 35def CheckChange(input, output): 36 results = [] 37 results += RunAndReportIfLong(CheckPrettierAndEslint, input, output) 38 results += RunAndReportIfLong(CheckImports, input, output) 39 results += RunAndReportIfLong(CheckAnyRachet, input, output) 40 return results 41 42 43def CheckChangeOnUpload(input_api, output_api): 44 return CheckChange(input_api, output_api) 45 46 47def CheckChangeOnCommit(input_api, output_api): 48 return CheckChange(input_api, output_api) 49 50 51def CheckPrettierAndEslint(input_api, output_api): 52 ui_path = input_api.PresubmitLocalPath() 53 format_sources_path = join(ui_path, 'format-sources') 54 cmd = [format_sources_path, '--check-only'] 55 if subprocess.call(cmd): 56 s = ' '.join(cmd) 57 return [ 58 output_api.PresubmitError(f"""Prettier/Eslint errors. To fix, run: 59{format_sources_path}""") 60 ] 61 return [] 62 63 64def CheckImports(input_api, output_api): 65 path = input_api.os_path 66 ui_path = input_api.PresubmitLocalPath() 67 check_imports_path = join(dirname(ui_path), 'tools', 'check_imports') 68 69 def file_filter(x): 70 return input_api.FilterSourceFile( 71 x, files_to_check=[r'.*\.ts$', r'.*\.js$']) 72 73 files = input_api.AffectedSourceFiles(file_filter) 74 75 if not files: 76 return [] 77 78 if subprocess.call([check_imports_path]): 79 return [output_api.PresubmitError(f"")] 80 return [] 81 82 83def CheckAnyRachet(input_api, output_api): 84 path = input_api.os_path 85 ui_path = input_api.PresubmitLocalPath() 86 check_ratchet_path = join(dirname(ui_path), 'tools', 'check_ratchet') 87 88 def file_filter(x): 89 return input_api.FilterSourceFile(x, files_to_check=[r'.*\.ts$']) 90 91 files = input_api.AffectedSourceFiles(file_filter) 92 93 if not files: 94 return [] 95 96 if subprocess.call([check_ratchet_path]): 97 return [output_api.PresubmitError(f"")] 98 return [] 99