1/* 2 * Copyright (c) 2021 Huawei Device Co., Ltd. 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 */ 15 16const path = require('path'); 17const fs = require('fs'); 18const os = require('os'); 19const isType = require('./lite-utils'); 20/** 21 * Check if the custom file exists.If it does not exist, follow the normal process. 22 * If it exists, get the file content. 23 */ 24function checkFilePath() { 25 const rulePath = path.resolve(os.userInfo().homedir, '.literc.js'); 26 if (fs.existsSync(rulePath)) { 27 process.env.RULE_PATH = rulePath; 28 const customTag = require(rulePath); 29 checkContent(customTag); 30 } 31} 32/** 33 * Check if the object thrown by the file is correct. 34 * @param {Object} customTag User defined custom file content. 35 */ 36function checkContent(customTag) { 37 throwError( 38 !isType.isObject(customTag), 39 `The configuration in the '.literc.js' file is incorrect.(it should be an object.)`, 40 ); 41 throwError( 42 isType.isUndefined(customTag.rules), 43 `You must write the 'rules' attribute in '.literc.js' file`, 44 ); 45 throwError( 46 !isType.isObject(customTag.rules), 47 `The value of 'rules' in '.literc.js' file is incorrect.(it should be an object)`, 48 ); 49 if (customTag.extends == 'recommended') { 50 validatorCustomTag(customTag.rules); 51 } 52} 53 54/** 55 * Check whether the user-defined rules are correct. 56 * @param {Object} rules User defined custom file content. 57 */ 58function validatorCustomTag(rules) { 59 const keys = Object.keys(rules); 60 for (let i = 0; i < keys.length; i++) { 61 const key = keys[i]; 62 const value = rules[key]; 63 throwError( 64 !isType.isObject(value), 65 `The value of '${key}' is incorrect, it should be an object.`, 66 ); 67 const children = Object.keys(value); 68 for (let j = 0; j < children.length; j++) { 69 const child = children[j]; 70 throwError( 71 child != 'attrs', 72 `'${key}' object can only contain 'attrs' attributes`, 73 ); 74 } 75 } 76} 77/** 78 * Tool method, if the condition is true, throw an exception. 79 * @param {Boolean} condition Analyzing conditions. 80 * @param {String} reason Output wrong information. 81 */ 82function throwError(condition, reason) { 83 if (condition) { 84 throw Error(`\u001b[31mError: ${reason} \u001b[39m`).message; 85 } 86} 87exports.checkFilePath = checkFilePath; 88