-
-
Notifications
You must be signed in to change notification settings - Fork 107
Expand file tree
/
Copy pathPlatform.ts
More file actions
363 lines (305 loc) · 11.2 KB
/
Copy pathPlatform.ts
File metadata and controls
363 lines (305 loc) · 11.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
/*
MIT License
Copyright (c) 2019 github0null
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import * as vscode from 'vscode';
import * as child_process from 'child_process';
import * as NodePath from 'path';
import * as os from 'os';
import * as fs from 'fs';
import { File } from '../lib/node-utility/File';
import { FileWatcher } from '../lib/node-utility/FileWatcher';
import { ERROR } from './StringTable';
export const UUID_NULL = 'FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF';
let uuid: string | undefined;
let osPlatform: NodeJS.Platform = os.platform();
let linuxOsId: string | undefined;
const devNull: string = os.platform() == 'win32' ? 'nul' : '/dev/null';
// arch class
const ARCH_ID_MAP: { [id: string]: string[] } = {
'x86': ['x86', 'i32', 'ia32', 'x32', 'i686'],
'x86_64': ['x86_64', 'amd64', 'x64', 'ia64', 'i64'],
'arm64': ['arm64', 'aarch64'],
};
// platform info, default value is for 'Windows-x64'
let runtimeId: string = 'win32';
let archId: string = 'x86_64';
// platform requirements
const SUPPORTED_OS_TYPE: NodeJS.Platform[] = ['win32', 'linux', 'darwin'];
const SUPPORTED_ARCH_TYPE: string[] = ARCH_ID_MAP['x86_64'].concat(ARCH_ID_MAP['arm64']);
let globalState: vscode.Memento & {
setKeysForSync(keys: readonly string[]): void;
};
export function getGlobalState(): vscode.Memento & {
setKeysForSync(keys: readonly string[]): void;
} {
return globalState;
}
function fmtArchId(n: string): string {
n = n.toLowerCase();
for (const key in ARCH_ID_MAP) {
if (ARCH_ID_MAP[key].includes(n)) {
return key;
}
}
return n;
}
export function init(context: vscode.ExtensionContext) {
globalState = context.globalState;
if (!SUPPORTED_OS_TYPE.includes(os.platform())) {
const msg = `${ERROR} : This plug-in is only for '${SUPPORTED_OS_TYPE.join('/')}' platform, but your OS is '${os.platform()}' !`;
throw new Error(msg);
}
// win32
if (osPlatform == 'win32') {
if (process.env['PROCESSOR_ARCHITECTURE']) {
const archStr = process.env['PROCESSOR_ARCHITECTURE'].toLowerCase();
archId = fmtArchId(archStr);
if (!SUPPORTED_ARCH_TYPE.includes(archStr)) {
const msg = `${ERROR} : This plug-in is only support '${SUPPORTED_ARCH_TYPE.join('/')}' arch, but your CPU ARCH is '${archStr}' !`;
throw new Error(msg);
}
}
}
// linux
else if (osPlatform == 'linux') {
const archStr = child_process.execSync(`uname -m`).toString().trim();
archId = fmtArchId(archStr);
runtimeId = `linux-${archId}`;
if (!SUPPORTED_ARCH_TYPE.includes(archStr)) {
const msg = `${ERROR} : This plug-in is only support '${SUPPORTED_ARCH_TYPE.join('/')}' arch, but your CPU ARCH is '${archStr}' !`;
throw new Error(msg);
}
}
// MacOS
else if (osPlatform == 'darwin') {
const archStr = child_process.execSync(`uname -m`).toString().trim();
archId = fmtArchId(archStr);
runtimeId = `osx-${archId}`;
if (!SUPPORTED_ARCH_TYPE.includes(archStr)) {
const msg = `${ERROR} : This plug-in is only support '${SUPPORTED_ARCH_TYPE.join('/')}' arch, but your CPU ARCH is '${archStr}' !`;
throw new Error(msg);
}
}
}
export function getRuntimeId(): string {
return runtimeId;
}
export function getArchId(): string {
return archId;
}
export function getLinuxOsId(): string | undefined {
if (linuxOsId) return linuxOsId;
if (osPlatform == 'linux') {
try {
const infList = child_process.execSync(`cat /etc/os-release`).toString().trim().split(/\r\n|\n/);
for (const str of infList) {
if (str.startsWith('ID=')) {
linuxOsId = str.replace('ID=', '').trim();
return linuxOsId;
}
}
} catch (error) {
// nothing todo
}
}
}
export function osType(): NodeJS.Platform {
return osPlatform;
}
export function osGetNullDev(): string {
return devNull;
}
export function createSafetyFileWatcher(_file: File, _recursive: boolean = false, watchSelfDir?: boolean) {
if (osPlatform != 'win32' &&
osPlatform != 'darwin') {
_recursive = false;
}
return new FileWatcher(_file, _recursive, watchSelfDir);
}
export function exeSuffix(): string {
if (osPlatform == 'win32') {
return '.exe';
} else {
return '';
}
}
export function GetUUID(): string {
if (uuid) {
return uuid;
}
try {
if (osPlatform == 'win32') {
const buf: string = child_process.execSync('wmic csproduct get UUID', { windowsHide: true, encoding: 'utf8' }).toString();
const list = buf.match(/[a-zA-Z0-9]{8}-[a-zA-Z0-9]{4}-[a-zA-Z0-9]{4}-[a-zA-Z0-9]{4}-[a-zA-Z0-9]{12}/);
uuid = list ? list[0] : UUID_NULL;
} else {
uuid = 'machine-id-' + child_process.execSync(`cat /etc/machine-id`).toString().trim();
}
} catch (error) {
uuid = UUID_NULL;
}
return uuid;
}
export function GetLocalCodePage(): string | undefined {
try {
if (osPlatform == 'win32') {
const buf: string = child_process.execSync('chcp', { windowsHide: true, encoding: 'utf8' }).toString();
const list = buf.match(/[0-9]+/);
return list ? list[0].trim() : undefined;
} else {
// for linux, use default: en_US.UTF-8
return undefined;
}
} catch (error) {
return undefined;
}
}
function checkFolderBeforeDelete(dir: File): boolean {
if (osPlatform == 'win32') {
return !['c:\\', 'c:'].includes(dir.path.toLowerCase());
} else {
return !['/', '/home'].includes(dir.path);
}
}
export function DeleteDir(dir: File): string {
try {
if (!checkFolderBeforeDelete(dir))
return 'can not delete system root folder !';
if (osPlatform == 'win32') {
return child_process.execSync(`rmdir /S /Q "${dir.path}"`, { encoding: 'ascii' });
} else {
return child_process.execSync(`rm -rf "${dir.path}"`, { encoding: 'utf8' });
}
} catch (error) {
return JSON.stringify(error);
}
}
export function DeleteAllChildren(dir: File): string {
try {
if (!checkFolderBeforeDelete(dir))
return 'can not delete system root folder !';
if (osPlatform == 'win32') {
return child_process.execSync('powershell Remove-Item \'' + dir.path + '\\*\' -Recurse -Force -ErrorAction:Continue', { encoding: 'utf8' });
} else {
return child_process.execSync(`rm -rf "${dir.path}/*"`, { encoding: 'utf8' });
}
} catch (error) {
return JSON.stringify(error);
}
}
const __find_cache: Map<string, string> = new Map();
/**
* @brief Find a exe path in System Path,
* - if found, return a path with string type.
* - if not found, return 'undefined'
*/
export function find(fileName: string, refreshCache?: boolean): string | undefined {
if (refreshCache)
__find_cache.delete(fileName);
if (__find_cache.has(fileName))
return __find_cache.get(fileName);
try {
if (osPlatform == 'win32') {
const nameList = child_process.execSync(`where "${fileName}"`,
{ windowsHide: true, encoding: 'ascii', shell: 'cmd' }).toString().trim().split(/\r\n|\n/);
if (nameList.length > 0) {
const path = nameList[0].replace(/"/g, '');
if (File.isAbsolute(path)) {
__find_cache.set(fileName, path);
return path;
}
}
} else {
const res = child_process.execSync(`which ${fileName}`).toString().trim();
const path = res.replace(/"'/g, '');
__find_cache.set(fileName, path);
return path;
}
} catch (error) {
return undefined;
}
}
export function appendToSysEnv(env: NodeJS.ProcessEnv, paths: string[]) {
const pName = os.platform() == 'win32' ? 'Path' : 'PATH';
const sep = os.platform() == 'win32' ? ';' : ':';
if (env[pName]) {
const pList = [<string>env[pName]].concat(paths);
env[pName] = pList.join(sep);
}
}
export function prependToSysEnv(env: NodeJS.ProcessEnv, paths: string[]) {
const pList = paths.concat();
const pName = os.platform() == 'win32' ? 'Path' : 'PATH';
const sep = os.platform() == 'win32' ? ';' : ':';
if (env[pName]) {
pList.push(<string>env[pName]);
}
env[pName] = pList.join(sep);
}
export function concatSystemEnvPath(paths: string[], defEnv?: NodeJS.ProcessEnv): { [key: string]: string } {
const env = JSON.parse(JSON.stringify(defEnv || process.env || {}));
if (os.platform() == 'win32') {
env['Path'] = env['Path'] ? `${paths.join(';')};${env['Path']}` : paths.join(';');
} else {
env['PATH'] = env['PATH'] ? `${paths.join(':')}:${env['PATH']}` : paths.join(':');
}
return env;
}
export function kill(pid: number): boolean {
try {
if (os.platform() == 'win32') {
child_process.execSync(`taskkill /PID ${pid} /T /F`);
} else {
child_process.execSync(`kill -9 ${pid}`);
}
} catch (error) {
return false;
}
return true;
}
export function realpathSync(path: string): string {
try {
return fs.realpathSync(path);
} catch (error) {
return path;
}
}
/*
export function getWindowsMainVersion(): number | undefined {
try {
const lines = child_process.execSync(`ver`,
{ windowsHide: true, encoding: 'ascii', shell: 'cmd' }).split(/\r\n|\n/);
for (let line of lines) {
const mRes = /(\d+)[\d\.]+\]\s*$/.exec(line);
if (mRes && mRes.length > 1) {
const version = parseInt(mRes[1]);
return version || undefined;
}
}
} catch (error) {
return undefined;
}
}
*/
export function userhome(): string {
if (process.env['VSCODE_PORTABLE'])
return NodePath.join(process.env['VSCODE_PORTABLE'], 'user-data');
else
return os.homedir();
}