1 #!/usr/bin/python -u 2 # Copyright 2016 The Chromium OS Authors. All rights reserved. 3 # Use of this source code is governed by a BSD-style license that can be 4 # found in the LICENSE file. 5 6 """ 7 Check if a json file is valid. 8 9 This wrapper is invoked through autotest's PRESUBMIT.cfg for every commit 10 that edits a json file. 11 """ 12 13 import json 14 import os 15 16 17 class InvalidJsonFile(Exception): 18 """Exception to raise when a json file can't be parsed.""" 19 20 21 def main(): 22 """Check if all json files that are a part of this commit are valid.""" 23 file_list = os.environ.get('PRESUBMIT_FILES') 24 if file_list is None: 25 raise InvalidJsonFile('Expected a list of presubmit files in ' 26 'the PRESUBMIT_FILES environment variable.') 27 28 for f in file_list.split(): 29 if f.lower().endswith('.json'): 30 try: 31 with open(f) as json_file: 32 json.load(json_file) 33 except ValueError: 34 # Re-raise the error to include the file path. 35 print ('Presubmit check `check_json_file` failed. If the file ' 36 'is meant to be malformated, please do not name it as a ' 37 'json file, or you will have to upload the CL using ' 38 '--no-verify') 39 raise InvalidJsonFile('Invalid json file: %s' % f) 40 41 42 if __name__ == '__main__': 43 main() 44