1/* 2* Copyright (c) 2022 Shenzhen Kaihong Digital Industry Development 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*/ 15const os = require('os'); 16const tsc = require("../../node_modules/typescript"); 17const fs = require('fs'); 18let vscode = null; 19try { 20 vscode = require('vscode'); 21} 22catch (err) { 23 vscode = null; 24} 25 26function replaceAll(s, sfrom, sto) { 27 while (s.indexOf(sfrom) >= 0) { 28 s = s.replace(sfrom, sto) 29 } 30 return s; 31} 32 33function detectPlatform() { 34 if (os.type() == 'Windows_NT') { 35 return 'win'; 36 } else if (os.type() == 'Darwin') { 37 return 'mac'; 38 } else if (os.type() == 'Linux') { 39 return 'Linux'; 40 } 41} 42 43function checkFileError(ifname) { 44 let program = tsc.createProgram([ifname], {}) 45 let emitResult = program.emit(); 46 let allDiagnostics = tsc.getPreEmitDiagnostics(program).concat(emitResult.diagnostics); 47 48 let errorMsg = '' 49 allDiagnostics.forEach(diagnostic => { 50 if (diagnostic.file) { 51 let { line, character } = tsc.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start); 52 let message = tsc.flattenDiagnosticMessageText(diagnostic.messageText, "\n"); 53 errorMsg += `${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}\n`; 54 } else { 55 errorMsg += tsc.flattenDiagnosticMessageText(diagnostic.messageText, "\n") + "\n"; 56 } 57 }); 58 59 if (allDiagnostics.length > 0) { 60 return [false, errorMsg]; 61 } 62 return [true, ""]; 63} 64 65function utf8ArrayToStr(array) { 66 var res, i, arrLen; 67 var ch1, ch2, ch3; 68 69 res = ""; 70 arrLen = array.length; 71 i = 0; 72 while (i < arrLen) { 73 ch1 = array[i++]; 74 switch (ch1 >> 4) { 75 // 0xxxxxxx 76 case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: 77 res += String.fromCharCode(ch1); 78 break; 79 // 110x xxxx 10xx xxxx 80 case 12: case 13: 81 ch2 = array[i++]; 82 res += String.fromCharCode(((ch1 & 0x1F) << 6) | (ch2 & 0x3F)); 83 break; 84 // 1110 xxxx 10xx xxxx 10xx xxxx 85 case 14: 86 ch2 = array[i++]; 87 ch3 = array[i++]; 88 res += String.fromCharCode(((ch1 & 0x0F) << 12) | 89 ((ch2 & 0x3F) << 6) | 90 ((ch3 & 0x3F) << 0)); 91 break; 92 } 93 } 94 return res; 95 } 96 97 function readFile(fn) { 98 if (!fs.existsSync(fn)) { 99 return ""; 100 } 101 let data = fs.readFileSync(fn); 102 data = utf8ArrayToStr(data); 103 return data; 104 } 105 106module.exports = { 107 replaceAll, 108 detectPlatform, 109 checkFileError, 110 readFile 111}