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 fs = require("fs"); 17var peg = require("pegjs"); 18 19function usageAndExit() { 20 console.error(` 21State Management Library 22================ 23 24Comments out console.[log, info, debug] calls. 25Other calls such as console.[error, warn] are allowed. 26 27Usage: 28Disable all console.[log, info, debug] from a file. 29node disableLogs.js <filePath> 30 31WARNING: 32Original file is overwritten. 33`); 34 process.exit(-1); 35} 36 37// load parser sources and compile them 38// returns the parser object 39function makeParser() { 40 let pegjsSources = ""; 41 try { 42 pegjsSources = fs.readFileSync("parser.pegjs") + "\n"; 43 } catch (err) { 44 console.error("While trying to read: 'parser.pegjs': " + err); 45 process.exit(-1); 46 } 47 console.log(` Read parser sources 'parser.pegjs': ${pegjsSources.length} Bytes.`) 48 49 // generate the parser from parser.pegjs source file: 50 var parser; 51 try { 52 parser = peg.generate(pegjsSources, 53 { 54 "allowedStartRules": [ 55 "program" 56 ] 57 }); 58 } catch (err) { 59 console.error("Failed to compile parser. Error: " + err); 60 process.exit(-1); 61 } 62 return parser; 63} 64 65// load the specified source file and return the buffer 66function loadFile(fileName) { 67 let content = ""; 68 try { 69 content = fs.readFileSync(fileName) + "\n"; 70 } catch (err) { 71 console.error(`While trying to read source file ${fileName}: ${err}`); 72 process.exit(-1); 73 } 74 console.log(` Read source file ${fileName}: ${content.length} Bytes.`) 75 return content; 76} 77 78function saveFile(fileName, content) { 79 fs.writeFileSync(fileName, content); 80 console.log(` Logs disabled. '${fileName}': ${content.length} Bytes. OK.`); 81} 82 83 84function main() { 85 86 if (process.argv.length < 3) { 87 usageAndExit(); 88 } 89 90 let fileName = process.argv[2]; 91 92 console.log(`Loading file to disable console.logs. File: ${fileName}`); 93 94 let parser = makeParser(); 95 let content = loadFile(fileName); 96 97 let newContent; 98 try { 99 newContent = parser.parse(content); 100 } catch (err) { 101 console.error(`Failed disabling logs. Error: ${err}`); 102 process.exit(-1); 103 } 104 105 saveFile(fileName, newContent); 106} 107 108main();