forked from microsoft/vscode-arduino
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.ts
435 lines (398 loc) · 13.5 KB
/
util.ts
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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
import * as child_process from "child_process";
import * as fs from "fs";
import * as iconv from "iconv-lite";
import * as os from "os";
import * as path from "path";
import * as properties from "properties";
import * as vscode from "vscode";
import * as WinReg from "winreg";
import { arduinoChannel } from "./outputChannel";
const encodingMapping: object = JSON.parse(fs.readFileSync(path.join(__dirname, "../../../misc", "codepageMapping.json"), "utf8"));
/**
* This function will detect the file existing in the sync mode.
* @function fileExistsSync
* @argument {string} filePath
*/
export function fileExistsSync(filePath: string): boolean {
try {
return fs.statSync(filePath).isFile();
} catch (e) {
return false;
}
}
/**
* This function will detect the directoy existing in the sync mode.
* @function directoryExistsSync
* @argument {string} dirPath
*/
export function directoryExistsSync(dirPath: string): boolean {
try {
return fs.statSync(dirPath).isDirectory();
} catch (e) {
return false;
}
}
/**
* This function will implement the same function as the fs.readdirSync,
* besides it could filter out folders only when the second argument is true.
* @function readdirSync
* @argument {string} dirPath
* @argument {boolean} folderOnly
*/
export function readdirSync(dirPath: string, folderOnly: boolean = false): string[] {
const dirs = fs.readdirSync(dirPath);
if (folderOnly) {
return dirs.filter((subdir) => {
return directoryExistsSync(path.join(dirPath, subdir));
});
} else {
return dirs;
}
}
/**
* Recursively create directories. Equals to "mkdir -p"
* @function mkdirRecursivelySync
* @argument {string} dirPath
*/
export function mkdirRecursivelySync(dirPath: string): void {
if (directoryExistsSync(dirPath)) {
return;
}
const dirname = path.dirname(dirPath);
if (path.normalize(dirname) === path.normalize(dirPath)) {
fs.mkdirSync(dirPath);
} else if (directoryExistsSync(dirname)) {
fs.mkdirSync(dirPath);
} else {
mkdirRecursivelySync(dirname);
fs.mkdirSync(dirPath);
}
}
/**
* Recursively delete files. Equals to "rm -rf"
* @function rmdirRecursivelySync
* @argument {string} rootPath
*/
export function rmdirRecursivelySync(rootPath: string): void {
if (fs.existsSync(rootPath)) {
fs.readdirSync(rootPath).forEach((file) => {
const curPath = path.join(rootPath, file);
if (fs.lstatSync(curPath).isDirectory()) { // recurse
rmdirRecursivelySync(curPath);
} else { // delete file
fs.unlinkSync(curPath);
}
});
fs.rmdirSync(rootPath);
}
}
function copyFileSync(src, dest, overwrite: boolean = true) {
if (!fileExistsSync(src) || (!overwrite && fileExistsSync(dest))) {
return;
}
const BUF_LENGTH = 64 * 1024;
const buf = new Buffer(BUF_LENGTH);
let lastBytes = BUF_LENGTH;
let pos = 0;
let srcFd = null;
let destFd = null;
try {
srcFd = fs.openSync(src, "r");
} catch (error) {
}
try {
destFd = fs.openSync(dest, "w");
} catch (error) {
}
try {
while (lastBytes === BUF_LENGTH) {
lastBytes = fs.readSync(srcFd, buf, 0, BUF_LENGTH, pos);
fs.writeSync(destFd, buf, 0, lastBytes);
pos += lastBytes;
}
} catch (error) {
}
if (srcFd) {
fs.closeSync(srcFd);
}
if (destFd) {
fs.closeSync(destFd);
}
}
function copyFolderRecursivelySync(src, dest) {
if (!directoryExistsSync(src)) {
return;
}
if (!directoryExistsSync(dest)) {
mkdirRecursivelySync(dest);
}
const items = fs.readdirSync(src);
for (const item of items) {
const fullPath = path.join(src, item);
const targetPath = path.join(dest, item);
if (directoryExistsSync(fullPath)) {
copyFolderRecursivelySync(fullPath, targetPath);
} else if (fileExistsSync(fullPath)) {
copyFileSync(fullPath, targetPath);
}
}
}
/**
* Copy files & directories recursively. Equals to "cp -r"
* @argument {string} src
* @argument {string} dest
*/
export function cp(src, dest) {
if (fileExistsSync(src)) {
let targetFile = dest;
if (directoryExistsSync(dest)) {
targetFile = path.join(dest, path.basename(src));
}
if (path.relative(src, targetFile)) {
// if the source and target file is the same, skip copying.
return;
}
copyFileSync(src, targetFile);
} else if (directoryExistsSync(src)) {
copyFolderRecursivelySync(src, dest);
} else {
throw new Error(`No such file or directory: ${src}`);
}
}
/**
* Check if the specified file is an arduino file (*.ino, *.pde).
* @argument {string} filePath
*/
export function isArduinoFile(filePath): boolean {
return fileExistsSync(filePath) && (path.extname(filePath) === ".ino" || path.extname(filePath) === ".pde");
}
/**
* Send a command to arduino
* @param {string} command - base command path (either Arduino IDE or CLI)
* @param {vscode.OutputChannel} outputChannel - output display channel
* @param {string[]} [args=[]] - arguments to pass to the command
* @param {any} [options={}] - options and flags for the arguments
* @param {(string) => {}} - callback for stdout text
*/
export function spawn(
command: string,
args: string[] = [],
options: child_process.SpawnOptions = {},
output?: {channel?: vscode.OutputChannel,
stdout?: (s: string) => void,
stderr?: (s: string) => void},
): Thenable<object> {
return new Promise((resolve, reject) => {
options.cwd = options.cwd || path.resolve(path.join(__dirname, ".."));
const child = child_process.spawn(command, args, options);
let codepage = "65001";
if (os.platform() === "win32") {
try {
const chcp = child_process.execSync(`chcp.com ${codepage}`);
codepage = chcp.toString().split(":").pop().trim();
} catch (error) {
arduinoChannel.warning(`Defaulting to code page 850 because chcp.com failed.\
\rEnsure your path includes %SystemRoot%\\system32\r${error.message}`);
codepage = "850";
}
}
if (output) {
if (output.channel || output.stdout) {
child.stdout.on("data", (data: Buffer) => {
const decoded = decodeData(data, codepage);
if (output.stdout) {
output.stdout(decoded);
}
if (output.channel) {
output.channel.append(decoded);
}
});
}
if (output.channel || output.stderr) {
child.stderr.on("data", (data: Buffer) => {
const decoded = decodeData(data, codepage);
if (output.stderr) {
output.stderr(decoded);
}
if (output.channel) {
output.channel.append(decoded);
}
});
}
}
child.on("error", (error) => reject({ error }));
child.on("exit", (code) => {
if (code === 0) {
resolve({ code });
} else {
reject({ code });
}
});
});
}
export function decodeData(data: Buffer, codepage: string): string {
if (encodingMapping.hasOwnProperty(codepage)) {
return iconv.decode(data, encodingMapping[codepage]);
}
return data.toString();
}
export function tryParseJSON(jsonString: string) {
try {
const jsonObj = JSON.parse(jsonString);
if (jsonObj && typeof jsonObj === "object") {
return jsonObj;
}
} catch (ex) { }
return undefined;
}
export function isJunk(filename: string): boolean {
// tslint:disable-next-line
const re = /^npm-debug\.log$|^\..*\.swp$|^\.DS_Store$|^\.AppleDouble$|^\.LSOverride$|^Icon\r$|^\._.*|^\.Spotlight-V100(?:$|\/)|\.Trashes|^__MACOSX$|~$|^Thumbs\.db$|^ehthumbs\.db$|^Desktop\.ini$/;
return re.test(filename);
}
export function filterJunk(files: any[]): any[] {
return files.filter((file) => !isJunk(file));
}
export function parseProperties(propertiesFile: string): Thenable<object> {
return new Promise((resolve, reject) => {
properties.parse(propertiesFile, { path: true }, (error, obj) => {
if (error) {
reject(error);
} else {
resolve(obj);
}
});
});
}
export function formatVersion(version: string): string {
if (!version) {
return version;
}
const versions = String(version).split(".");
if (versions.length < 2) {
versions.push("0");
}
if (versions.length < 3) {
versions.push("0");
}
return versions.join(".");
}
export function trim(value: any) {
if (Array.isArray(value)) {
for (let i = 0; i < value.length; i++) {
value[i] = trim(value[i]);
}
} else if (typeof value === "string") {
value = value.trim();
}
return value;
}
export function union(a: any[], b: any[], compare?: (item1, item2) => boolean) {
const result = [].concat(a);
b.forEach((item) => {
const exist = result.find((element) => {
return (compare ? compare(item, element) : Object.is(item, element));
});
if (!exist) {
result.push(item);
}
});
return result;
}
/**
* This method pads the current string with another string (repeated, if needed)
* so that the resulting string reaches the given length.
* The padding is applied from the start (left) of the current string.
* @argument {string} sourceString
* @argument {string} targetLength
* @argument {string} padString
*/
export function padStart(sourceString: string, targetLength: number, padString?: string): string {
if (!sourceString) {
return sourceString;
}
if (!(String.prototype as any).padStart) {
// https://github.com/uxitten/polyfill/blob/master/string.polyfill.js
padString = String(padString || " ");
if (sourceString.length > targetLength) {
return sourceString;
} else {
targetLength = targetLength - sourceString.length;
if (targetLength > padString.length) {
padString += padString.repeat(targetLength / padString.length); // append to original to ensure we are longer than needed
}
return padString.slice(0, targetLength) + sourceString;
}
} else {
return (sourceString as any).padStart(targetLength, padString);
}
}
export function parseConfigFile(fullFileName, filterComment: boolean = true): Map<string, string> {
const result = new Map<string, string>();
if (fileExistsSync(fullFileName)) {
const rawText = fs.readFileSync(fullFileName, "utf8");
const lines = rawText.split("\n");
lines.forEach((line) => {
if (line) {
line = line.trim();
if (filterComment) {
if (line.trim() && line.startsWith("#")) {
return;
}
}
const separator = line.indexOf("=");
if (separator > 0) {
const key = line.substring(0, separator).trim();
const value = line.substring(separator + 1, line.length).trim();
result.set(key, value);
}
}
});
}
return result;
}
export function getRegistryValues(hive: string, key: string, name: string): Promise<string> {
return new Promise((resolve, reject) => {
try {
const regKey = new WinReg({
hive,
key,
});
regKey.valueExists(name, (e, exists) => {
if (e) {
return reject(e);
}
if (exists) {
regKey.get(name, (err, result) => {
if (!err) {
resolve(result ? result.value : "");
} else {
reject(err);
}
});
} else {
resolve("");
}
});
} catch (ex) {
reject(ex);
}
});
}
export function convertToHex(number, width = 0) {
return padStart(number.toString(16), width, "0");
}
/**
* This will accept any Arduino*.app on Mac OS,
* in case you named Arduino with a version number
* @argument {string} arduinoPath
*/
export function resolveMacArduinoAppPath(arduinoPath: string): string {
if (/Arduino.*\.app/.test(arduinoPath)) {
return arduinoPath;
} else {
return path.join(arduinoPath, "Arduino.app");
}
}