1#!/usr/bin/env python3 2 3# 4# Copyright 2024, 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"""This is a general Json Config checker that checks string values 20against a predefined vocabulary list. 21""" 22 23import json 24import os 25import subprocess 26import sys 27 28class PixelConfigLexiconChecker(object): 29 """A object for common JSON configuration checking. 30 31 Takes a json_files = dict(file_path, JSON Object) and 32 lexicon_path (list of words) and checks every field name and 33 string value against the list of words. 34 35 Typical usage example: 36 37 foo = PixelConfigLexiconChecker(files, vocabulary_path) 38 success, error = foo.check_json_spelling() 39 """ 40 valid_words = None 41 json_files = None 42 commit_sha = None 43 44 def __init__(self, json_files, lexicon_path): 45 self.valid_words = self.load_words_from_txt(lexicon_path) 46 self.json_files = json_files 47 48 def load_words_from_txt(self, file_path): 49 """ Function to load list of words from file 50 51 input: 52 file_path: path to lexicon 53 54 output: Set of words. 55 """ 56 words = set() 57 with open(file_path, 'r') as f: 58 for line in f: 59 word = line.strip() 60 if word: 61 words.add(word) 62 return words 63 64 def _check_json_spelling(self, data): 65 """ Recursive function that traverses the json object 66 checking every field and string value. 67 68 input: 69 data: JSON object 70 71 output: 72 Tuple of Success and word if unknown. 73 """ 74 if isinstance(data, dict): 75 for key, value in data.items(): 76 if key not in self.valid_words: 77 return False, key 78 ok, word = self._check_json_spelling(value) 79 if not ok: 80 return False, word 81 82 if isinstance(data, list): 83 for item in data: 84 ok, word = self._check_json_spelling(item) 85 if not ok: 86 return False, word 87 88 return True, None 89 90 def check_json_spelling(self): 91 """ Entry function to check strings and field names if known. 92 93 output: 94 Tuple of Success and error message. 95 """ 96 for file_path, json_object in self.json_files.items(): 97 success, message = self._check_json_spelling(json_object) 98 if not success: 99 return False, "File " + file_path +": Unknown string: " + message 100 101 return True, "" 102