blob: ff6b1e092671b31465550548088f520cd77ef965 [file]
"""Build step class for validating JSON files."""
from __future__ import absolute_import
import collections
import json
import os
import re
from helpers import git_utils
from slave import base_step
_JSON_PARSE_ERROR_MSG = 'This JSON file failed to parse. {}'
_JSON_ERROR_POSITION_PATTERN = r'line (?P<linenum>\d+) column \d+'
class JsonCheckStep(base_step.BaseStep):
"""Build step class for validating JSON files."""
def __init__(self, **kwargs):
"""Creates a JsonCheckStep instance.
Args:
**kwargs: Any additional args to pass to BaseStep.
"""
base_step.BaseStep.__init__(self, name='json check', **kwargs)
def _value_error_to_comment(self, err):
comment = {'message': _JSON_PARSE_ERROR_MSG.format(str(err))}
match = re.search(_JSON_ERROR_POSITION_PATTERN, str(err))
if match:
comment['line'] = match.group('linenum')
return comment
def run(self):
"""Attempts to parse all .json files in the current commit.
Sets a build property "review" with the output if there are any errors.
Returns:
True iff there were no parsing errors.
"""
comments = collections.defaultdict(list)
for json_filename in self.changed_files(file_extensions=['.json']):
with open(os.path.join(self.directory, json_filename)) as json_file:
try:
json.load(json_file)
except ValueError as err:
comments[json_filename].append(self._value_error_to_comment(err))
if comments:
self.add_review({'comments': comments})
return False
# No Errors
return True