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 out, i, len, c; 67 var char2, char3; 68 69 out = ""; 70 len = array.length; 71 i = 0; 72 while (i < len) { 73 c = array[i++]; 74 switch (c >> 4) { 75 case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: 76 // 0xxxxxxx 77 out += String.fromCharCode(c); 78 break; 79 case 12: case 13: 80 // 110x xxxx 10xx xxxx 81 char2 = array[i++]; 82 out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F)); 83 break; 84 case 14: 85 // 1110 xxxx 10xx xxxx 10xx xxxx 86 char2 = array[i++]; 87 char3 = array[i++]; 88 out += String.fromCharCode(((c & 0x0F) << 12) | 89 ((char2 & 0x3F) << 6) | 90 ((char3 & 0x3F) << 0)); 91 break; 92 } 93 } 94 95 return out; 96 } 97 98 function readFile(fn) { 99 if (!fs.existsSync(fn)) { 100 return ""; 101 } 102 let data = fs.readFileSync(fn); 103 data = utf8ArrayToStr(data); 104 return data; 105 } 106 107module.exports = { 108 replaceAll, 109 detectPlatform, 110 checkFileError, 111 readFile 112}