Home | History | Annotate | Download | only in ktlint
      1 #!/usr/bin/python
      2 
      3 #
      4 # Copyright 2017, The Android Open Source Project
      5 #
      6 # Licensed under the Apache License, Version 2.0 (the "License");
      7 # you may not use this file except in compliance with the License.
      8 # You may obtain a copy of the License at
      9 #
     10 #     http://www.apache.org/licenses/LICENSE-2.0
     11 #
     12 # Unless required by applicable law or agreed to in writing, software
     13 # distributed under the License is distributed on an "AS IS" BASIS,
     14 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     15 # See the License for the specific language governing permissions and
     16 # limitations under the License.
     17 #
     18 
     19 """Script that is used by developers to run style checks on Kotlin files."""
     20 
     21 import argparse
     22 import errno
     23 import os
     24 import subprocess
     25 import sys
     26 
     27 MAIN_DIRECTORY = os.path.normpath(os.path.dirname(__file__))
     28 KTLINT_JAR = os.path.join(MAIN_DIRECTORY, 'ktlint-android-all.jar')
     29 
     30 
     31 def main(args=None):
     32   parser = argparse.ArgumentParser()
     33   parser.add_argument('--file', '-f', nargs='*')
     34   parser.add_argument('--format', '-F', dest='format', action='store_true')
     35   parser.add_argument('--noformat', dest='format', action='store_false')
     36   parser.set_defaults(format=False)
     37   args = parser.parse_args()
     38   ktlint_args = [f for f in args.file if f.endswith('.kt')]
     39   if args.format:
     40     ktlint_args += ['-F']
     41   if not ktlint_args:
     42     sys.exit(0)
     43 
     44   ktlint_env = os.environ.copy()
     45   ktlint_env['JAVA_CMD'] = 'java'
     46   try:
     47     check = subprocess.Popen(['java', '-jar', KTLINT_JAR] + ktlint_args,
     48                              stdout=subprocess.PIPE, env=ktlint_env)
     49     stdout, _ = check.communicate()
     50     if stdout:
     51       print 'prebuilts/ktlint found errors in files you changed:'
     52       print stdout
     53       sys.exit(1)
     54     else:
     55       sys.exit(0)
     56   except OSError as e:
     57     if e.errno == errno.ENOENT:
     58       print 'Error running ktlint!'
     59       sys.exit(1)
     60 
     61 if __name__ == '__main__':
     62   main()
     63