/
index.ts
1271 lines (1105 loc) · 31.8 KB
/
index.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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* This file is part of the vscode-helpers distribution.
* Copyright (c) Marcel Joachim Kloubert.
*
* vscode-helpers is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, version 3.
*
* vscode-helpers is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import * as _ from 'lodash';
import * as ChildProcess from 'child_process';
import * as Crypto from 'crypto';
import * as Enumerable from 'node-enumerable';
import * as FSExtra from 'fs-extra';
const IsBinaryFile = require("isbinaryfile");
import * as IsStream from 'is-stream';
const MergeDeep = require('merge-deep');
import * as Minimatch from 'minimatch';
import * as Moment from 'moment';
import * as OS from 'os';
import * as Path from 'path';
import * as PQueue from 'p-queue';
import * as Stream from 'stream';
import * as vscode from 'vscode';
import * as vscode_helpers_devtools from './devtools';
import * as vscode_helpers_events from './events';
import * as vscode_helpers_scm_git from './scm/git';
// !!!THESE MUST BE INCLUDED AFTER UPPER INCLUDED MODULES!!!
import * as MomentTimeZone from 'moment-timezone';
// sub modules
export * from './cache';
export * from './devtools';
export * from './disposable';
export * from './events';
export * from './fs';
export * from './html';
export * from './http';
export * from './logging';
export { from, range, repeat } from 'node-enumerable';
export * from './notifications';
export * from './progress';
export * from './timers';
export * from './workflows';
export * from './workspaces';
/**
* Result of a file execution.
*/
export interface ExecFileResult {
/**
* The output from 'standard error' stream.
*/
stdErr: Buffer;
/**
* The output from 'standard output' stream.
*/
stdOut: Buffer;
/**
* The underlying process.
*/
process: ChildProcess.ChildProcess;
}
/**
* Action for 'forEachAsync()' function.
*
* @param {T} item The current item.
* @param {number} index The zero based index.
* @param {T[]} array The array of all elements.
*
* @return {TResult|PromiseLike<TResult>} The result.
*/
export type ForEachAsyncAction<T, TResult> = (item: T, index: number, array: T[]) => TResult | PromiseLike<TResult>;
/**
* Describes the structure of the package file (package.json).
*/
export interface PackageFile {
/**
* The display name.
*/
displayName?: string;
/**
* The (internal) name.
*/
name?: string;
/**
* The version string.
*/
version?: string;
}
/**
* Options for 'openAndShowTextDocument()' function.
*/
export type OpenAndShowTextDocumentOptions = string | {
/**
* The initial content.
*/
content?: string;
/**
* The language.
*/
language?: string;
};
/**
* Describes a simple 'completed' action.
*
* @param {any} err The occurred error.
* @param {TResult} [result] The result.
*/
export type SimpleCompletedAction<TResult> = (err: any, result?: TResult) => void;
/**
* Normalizes a string.
*
* @param {TStr} str The value to normalize.
*
* @return {string} The normalized string.
*/
export type StringNormalizer<TStr = string> = (str: TStr) => string;
let extensionRoot: string;
/**
* Is AIX or not.
*/
export const IS_AIX = process.platform === 'aix';
/**
* Is Free BSD or not.
*/
export const IS_FREE_BSD = process.platform === 'freebsd';
/**
* Is Linux or not.
*/
export const IS_LINUX = process.platform === 'linux';
/**
* Is Sun OS or not.
*/
export const IS_MAC = process.platform === 'darwin';
/**
* Is Open BSD or not.
*/
export const IS_OPEN_BSD = process.platform === 'openbsd';
/**
* Is Sun OS or not.
*/
export const IS_SUNOS = process.platform === 'sunos';
/**
* Is Windows or not.
*/
export const IS_WINDOWS = process.platform === 'win32';
/**
* Global execution queue, which only allows one execution at the same time.
*/
export const QUEUE = new PQueue({
autoStart: true,
concurrency: 1,
});
/**
* Stores global data for the current extension session.
*/
export const SESSION: { [key: string]: any } = {};
/**
* Disposes 'SESSION', by removing its data.
*/
export const SESSION_DISPOSER: vscode.Disposable = {
/** @inheritdoc */
dispose: () => {
for (const P of Object.keys(SESSION)) {
delete SESSION[ P ];
}
}
};
/**
* Applies a function for a specific object / value.
*
* @param {TFunc} func The function.
* @param {any} [thisArgs] The object to apply to the function.
*
* @return {TFunc} The wrapped function.
*/
export function applyFuncFor<TFunc extends Function = Function>(
func: TFunc, thisArgs: any
): TFunc {
return <any>function() {
return func.apply(thisArgs, arguments);
};
}
/**
* Returns a value as array.
*
* @param {T|T[]} val The value.
* @param {boolean} [removeEmpty] Remove items that are (null) / (undefined) or not.
*
* @return {T[]} The value as (new) array.
*/
export function asArray<T>(val: T | T[], removeEmpty = true): T[] {
removeEmpty = toBooleanSafe(removeEmpty, true);
return (_.isArray(val) ? val : [ val ]).filter(i => {
if (removeEmpty) {
return !_.isNil(i);
}
return true;
});
}
/**
* Returns a value as buffer.
*
* @param {any} val The value to convert / cast.
* @param {string} enc The custom encoding for the string parsers.
* @param {number} [maxDepth] The custom value for the max depth of wrapped functions. Default: 63
*
* @return {Promise<Buffer>} The promise with the buffer.
*/
export async function asBuffer(val: any, enc?: string, maxDepth?: number): Promise<Buffer> {
return await asBufferInner(val, enc, null, maxDepth);
}
async function asBufferInner(val: any, enc?: string,
funcDepth?: number, maxDepth?: number): Promise<Buffer> {
enc = normalizeString(enc);
if ('' === enc) {
enc = undefined;
}
if (isNaN(funcDepth)) {
funcDepth = 0;
}
if (isNaN(maxDepth)) {
maxDepth = 63;
}
if (funcDepth > maxDepth) {
throw new Error(`Maximum depth of ${maxDepth} reached!`);
}
if (Buffer.isBuffer(val) || _.isNil(val)) {
return val;
}
if (_.isFunction(val)) {
// wrapped
return asBufferInner(
await Promise.resolve(
val(enc, funcDepth, maxDepth),
),
enc,
funcDepth + 1, maxDepth,
);
}
if (IsStream.readable(val)) {
// stream
return await readAll(val);
}
if (_.isObject(val)) {
// JSON object
return new Buffer(JSON.stringify(val),
enc);
}
// handle as string
return new Buffer(toStringSafe(val),
enc);
}
/**
* Returns a value as local Moment instance.
*
* @param {any} val The input value.
*
* @return {Moment.Moment} The output value.
*/
export function asLocalTime(val: any): Moment.Moment {
let localTime: Moment.Moment;
if (!_.isNil(val)) {
if (Moment.isMoment(val)) {
localTime = val;
} else if (Moment.isDate(val)) {
localTime = Moment( val );
} else {
localTime = Moment( toStringSafe(val) );
}
}
if (localTime) {
if (!localTime.isLocal()) {
localTime = localTime.local();
}
}
return localTime;
}
/**
* Returns a value as UTC Moment instance.
*
* @param {any} val The input value.
*
* @return {Moment.Moment} The output value.
*/
export function asUTC(val: any): Moment.Moment {
let utcTime: Moment.Moment;
if (!_.isNil(val)) {
if (Moment.isMoment(val)) {
utcTime = val;
} else if (Moment.isDate(val)) {
utcTime = Moment( val );
} else {
utcTime = Moment( toStringSafe(val) );
}
}
if (utcTime) {
if (!utcTime.isUTC()) {
utcTime = utcTime.utc();
}
}
return utcTime;
}
/**
* Clones an object / value deep.
*
* @param {T} val The value / object to clone.
*
* @return {T} The cloned value / object.
*/
export function cloneObject<T>(val: T): T {
if (!val) {
return val;
}
return JSON.parse(
JSON.stringify(val)
);
}
/**
* Clones an value flat.
*
* @param {T} val The object to clone.
* @param {boolean} [useNewObjectForFunctions] Use new object as 'thisArg' for functions (true) or
* the original 'val' (false).
*
* @return {T} The cloned object.
*/
export function cloneObjectFlat<T>(val: T,
useNewObjectForFunctions = true): T {
useNewObjectForFunctions = toBooleanSafe(useNewObjectForFunctions, true);
if (_.isNil(val)) {
return val;
}
const CLONED_OBJ: T = <any>{};
const THIS_ARG: any = useNewObjectForFunctions ? CLONED_OBJ : val;
const ADD_PROPERTY = (prop: string, value: any) => {
Object.defineProperty(CLONED_OBJ, prop, {
configurable: true,
enumerable: true,
get: () => {
return value;
},
set: (newValue) => {
value = newValue;
},
});
};
_.forIn(val, (value, prop) => {
let valueToSet: any = value;
if (_.isFunction(valueToSet)) {
const FUNC = valueToSet;
valueToSet = function() {
return FUNC.apply(THIS_ARG, arguments);
};
}
ADD_PROPERTY(prop, valueToSet);
});
return CLONED_OBJ;
}
/**
* Compares two values for a sort operation.
*
* @param {T} x The left value.
* @param {T} y The right value.
*
* @return {number} The "sort value".
*/
export function compareValues<T>(x: T, y: T): number {
if (x !== y) {
if (x > y) {
return 1;
} else if (x < y) {
return -1;
}
}
return 0;
}
/**
* Compares values by using a selector.
*
* @param {T} x The left value.
* @param {T} y The right value.
* @param {Function} selector The selector.
*
* @return {number} The "sort value".
*/
export function compareValuesBy<T, U>(x: T, y: T,
selector: (t: T) => U): number {
return compareValues(selector(x),
selector(y));
}
/**
* Alias for 'createDevToolsClient'.
*/
export function createChromeClient(opts?: vscode_helpers_devtools.DevToolsClientOptions): vscode_helpers_devtools.DevToolsClient {
return createDevToolsClient.apply(null, arguments);
}
/**
* Creates a simple 'completed' callback for a promise.
*
* @param {Function} resolve The 'succeeded' callback.
* @param {Function} reject The 'error' callback.
*
* @return {SimpleCompletedAction<TResult>} The created action.
*/
export function createCompletedAction<TResult = any>(resolve: (value?: TResult | PromiseLike<TResult>) => void,
reject?: (reason: any) => void): SimpleCompletedAction<TResult> {
let completedInvoked = false;
return (err, result?) => {
if (completedInvoked) {
return;
}
completedInvoked = true;
if (err) {
if (reject) {
reject(err);
}
} else {
if (resolve) {
resolve(result);
}
}
};
}
/**
* Creates a new instance of a client, which can connect to a DevTools compatible
* browser like Google Chrome.
*
* @param {vscode_helpers_devtools.DevToolsClientOptions} [opts] Custom options.
*
* @return {vscode_helpers_devtools.DevToolsClient} The new client instance.
*/
export function createDevToolsClient(opts?: vscode_helpers_devtools.DevToolsClientOptions) {
return new vscode_helpers_devtools.DevToolsClient( opts );
}
/**
* Creates a Git client.
*
* @param {string} [cwd] The custom working directory.
* @param {string} [path] The optional specific path where to search first.
*
* @return {Promise<vscode_helpers_scm_git.GitClient|false>} The promise with the client or (false) if no client found.
*/
export function createGitClient(cwd?: string, path?: string) {
return Promise.resolve(
createGitClientSync(cwd, path)
);
}
/**
* Creates a Git client (sync).
*
* @param {string} [cwd] The custom working directory.
* @param {string} [path] The optional specific path where to search first.
*
* @return {vscode_helpers_scm_git.GitClient|false} The client or (false) if no client found.
*/
export function createGitClientSync(cwd?: string, path?: string): vscode_helpers_scm_git.GitClient {
const CLIENT = tryCreateGitClientSync(cwd, path);
if (false === CLIENT) {
throw new Error('No git client found!');
}
return CLIENT;
}
/**
* Creates a new queue.
*
* @param {TOpts} [opts] The custom options.
*
* @return {PQueue<PQueue.DefaultAddOptions>} The new queue.
*/
export function createQueue<TOpts extends PQueue.QueueAddOptions = PQueue.DefaultAddOptions>(
opts?: TOpts
) {
const DEFAULT_OPTS: PQueue.QueueAddOptions = {
autoStart: true,
concurrency: 1,
};
return new PQueue(
MergeDeep(DEFAULT_OPTS, opts)
);
}
/**
* Handles a value as string and checks if it does match at least one (minimatch) pattern.
*
* @param {any} val The value to check.
* @param {string|string[]} patterns One or more patterns.
* @param {Minimatch.IOptions} [options] Additional options.
*
* @return {boolean} Does match or not.
*/
export function doesMatch(val: any, patterns: string | string[], options?: Minimatch.IOptions): boolean {
val = toStringSafe(val);
patterns = asArray(patterns).map(p => {
return toStringSafe(p);
});
for (const P of patterns) {
if (Minimatch(val, P, options)) {
return true;
}
}
return false;
}
/**
* Executes a file.
*
* @param {string} command The thing / command to execute.
* @param {any[]} [args] One or more argument for the execution.
* @param {ChildProcess.ExecFileOptions} [opts] Custom options.
*
* @return {Promise<ExecFileResult>} The promise with the result.
*/
export async function execFile(command: string, args?: any[], opts?: ChildProcess.ExecFileOptions) {
command = toStringSafe(command);
args = asArray(args, false).map(a => {
return toStringSafe(a);
});
if (!opts) {
opts = {};
}
if (_.isNil(opts.env)) {
opts.env = process.env;
}
return new Promise<ExecFileResult>((resolve, reject) => {
const RESULT: ExecFileResult = {
stdErr: undefined,
stdOut: undefined,
process: undefined,
};
let completedInvoked = false;
const COMPLETED = (err: any) => {
if (completedInvoked) {
return;
}
completedInvoked = true;
if (err) {
reject(err);
} else {
resolve(RESULT);
}
};
try {
const P = ChildProcess.execFile(command, args, opts, (err, stdout, stderr) => {
if (err) {
COMPLETED(err);
} else {
try {
RESULT.process = P;
(async () => {
RESULT.stdErr = await asBuffer(stderr, 'utf8');
RESULT.stdOut = await asBuffer(stdout, 'utf8');
})().then(() => {
COMPLETED(null);
}, (err) => {
COMPLETED(err);
});
} catch (e) {
COMPLETED(e);
}
}
});
} catch (e) {
COMPLETED(e);
}
});
}
/**
* Async 'forEach'.
*
* @param {Enumerable.Sequence<T>} items The items to iterate.
* @param {Function} action The item action.
* @param {any} [thisArg] The underlying object / value for the item action.
*
* @return {TResult} The result of the last action call.
*/
export async function forEachAsync<T, TResult>(items: Enumerable.Sequence<T>,
action: ForEachAsyncAction<T, TResult>,
thisArg?: any) {
if (!_.isArrayLike(items)) {
items = Enumerable.from(items)
.toArray();
}
let lastResult: TResult;
for (let i = 0; i < (<ArrayLike<T>>items).length; i++) {
lastResult = await Promise.resolve(
action.apply(thisArg,
[ items[i], i, items ]),
);
}
return lastResult;
}
/**
* Formats a string.
*
* @param {any} formatStr The value that represents the format string.
* @param {any[]} [args] The arguments for 'formatStr'.
*
* @return {string} The formated string.
*/
export function format(formatStr: any, ...args: any[]): string {
return formatArray(formatStr, args);
}
/**
* Formats a string.
*
* @param {any} formatStr The value that represents the format string.
* @param {Enumerable.Sequence<any>} [args] The arguments for 'formatStr'.
*
* @return {string} The formated string.
*/
export function formatArray(formatStr: any, args: Enumerable.Sequence<any>): string {
formatStr = toStringSafe(formatStr);
if (!_.isArrayLike(args)) {
args = Enumerable.from(args)
.toArray();
}
// apply arguments in
// placeholders
return formatStr.replace(/{(\d+)(\:)?([^}]*)}/g, (match, index, formatSeparator, formatExpr) => {
index = parseInt(
toStringSafe(index)
);
let resultValue = (<ArrayLike<any>>args)[index];
if (':' === formatSeparator) {
// collect "format providers"
const FORMAT_PROVIDERS = toStringSafe(formatExpr).split(',')
.map(x => x.toLowerCase().trim())
.filter(x => x);
// transform argument by
// format providers
FORMAT_PROVIDERS.forEach(fp => {
switch (fp) {
case 'ending_space':
resultValue = toStringSafe(resultValue);
if ('' !== resultValue) {
resultValue = resultValue + ' ';
}
break;
case 'leading_space':
resultValue = toStringSafe(resultValue);
if ('' !== resultValue) {
resultValue = ' ' + resultValue;
}
break;
case 'lower':
resultValue = toStringSafe(resultValue).toLowerCase();
break;
case 'trim':
resultValue = toStringSafe(resultValue).trim();
break;
case 'upper':
resultValue = toStringSafe(resultValue).toUpperCase();
break;
case 'surround':
resultValue = toStringSafe(resultValue);
if ('' !== resultValue) {
resultValue = "'" + toStringSafe(resultValue) + "'";
}
break;
}
});
}
if (_.isUndefined(resultValue)) {
return match;
}
return toStringSafe(resultValue);
});
}
/**
* Gets the root directory of the extension.
*
* @return {string} The root directory of the extension.
*/
export function getExtensionRoot() {
return extensionRoot;
}
/**
* Loads the package file (package.json) of the extension.
*
* @param {string} [packageJson] The custom path to the file.
*
* @return {Promise<PackageFile>} The promise with the meta data of the file.
*/
export async function getPackageFile(
packageJson = '../package.json'
): Promise<PackageFile> {
return JSON.parse(
(await FSExtra.readFile(
getPackageFilePath(packageJson)
)).toString('utf8')
);
}
function getPackageFilePath(
packageJson?: string
) {
packageJson = toStringSafe(packageJson);
if ('' === packageJson.trim()) {
packageJson = '../package.json';
}
if (!Path.isAbsolute(packageJson)) {
packageJson = Path.join(
getExtensionRoot(), packageJson
);
}
return Path.resolve( packageJson );
}
/**
* Loads the package file (package.json) of the extension sync.
*
* @param {string} [packageJson] The custom path to the file.
*
* @return {PackageFile} The meta data of the file.
*/
export function getPackageFileSync(
packageJson = '../package.json'
): PackageFile {
return JSON.parse(
(FSExtra.readFileSync(
getPackageFilePath(packageJson)
)).toString('utf8')
);
}
/**
* Alias for 'uuid'.
*/
export function guid(ver?: string, ...args: any[]): string {
return uuid.apply(this,
arguments);
}
/**
* Checks if data is binary or text content.
*
* @param {Buffer} data The data to check.
*
* @returns {Promise<boolean>} The promise that indicates if content is binary or not.
*/
export function isBinaryContent(data: Buffer): Promise<boolean> {
return new Promise<boolean>((resolve, reject) => {
const COMPLETED = createCompletedAction<boolean>(resolve, reject);
try {
IsBinaryFile(data, data.length, (err, result) => {
COMPLETED(err, result);
});
} catch (e) {
COMPLETED(e);
}
});
}
/**
* Checks if data is binary or text content (sync).
*
* @param {Buffer} data The data to check.
*
* @returns {boolean} Content is binary or not.
*/
export function isBinaryContentSync(data: Buffer): boolean {
return IsBinaryFile.sync(data, data.length);
}
/**
* Checks if the string representation of a value is empty
* or contains whitespaces only.
*
* @param {any} val The value to check.
*
* @return {boolean} Is empty or not.
*/
export function isEmptyString(val: any): boolean {
return '' === toStringSafe(val).trim();
}
/**
* Loads a module from a script.
*
* @param {string} file The path to the script.
* @param {boolean} [fromCache] Cache module or not.
*
* @return {TModule} The loaded module.
*/
export function loadModule<TModule = any>(file: string, fromCache = false): TModule {
file = toStringSafe(file);
if (isEmptyString(file)) {
file = './module.js';
}
if (!Path.isAbsolute(file)) {
file = Path.join(process.cwd(), file);
}
file = Path.resolve(file);
fromCache = toBooleanSafe(fromCache);
if (!fromCache) {
delete require.cache[file];
}
return require(file);
}
/**
* Normalizes a value as string so that is comparable.
*
* @param {any} val The value to convert.
* @param {StringNormalizer} [normalizer] The custom normalizer.
*
* @return {string} The normalized value.
*/
export function normalizeString(val: any, normalizer?: StringNormalizer): string {
if (!normalizer) {
normalizer = (str) => str.toLowerCase().trim();
}
return normalizer( toStringSafe(val) );
}
/**
* Returns the current time.
*
* @param {string} [timezone] The custom timezone to use.
*
* @return {Moment.Moment} The current time.
*/
export function now(timezone?: string): Moment.Moment {
timezone = toStringSafe(timezone).trim();
const NOW = Moment();
return '' === timezone ? NOW
: NOW.tz(timezone);
}
/**
* Opens and shows a new text document / editor.
*
* @param {OpenAndShowTextDocumentOptions} [filenameOrOpts] The custom options or the path to the file to open.
*
* @return {vscode.TextEditor} The promise with the new, opened text editor.
*/
export async function openAndShowTextDocument(filenameOrOpts?: OpenAndShowTextDocumentOptions) {
if (_.isNil(filenameOrOpts)) {
filenameOrOpts = {
content: '',
language: 'plaintext',
};
}
return await vscode.window.showTextDocument(
await vscode.workspace.openTextDocument( <any>filenameOrOpts )
);
}
/**
* Promise version of 'crypto.randomBytes()' function.
*
* @param {number} size The size of the result.
*
* @return {Promise<Buffer>} The buffer with the random bytes.
*/
export function randomBytes(size: number) {
size = parseInt(
toStringSafe(size).trim()
);
return new Promise<Buffer>((resolve, reject) => {
const COMPLETED = createCompletedAction(resolve, reject);
Crypto.randomBytes(size, (err, buf) => {
COMPLETED(err, buf);
});
});
}
/**
* Reads the content of a stream.
*
* @param {Stream.Readable} stream The stream.
* @param {string} [enc] The custom (string) encoding to use.
*
* @returns {Promise<Buffer>} The promise with the content.
*/
export function readAll(stream: Stream.Readable, enc?: string): Promise<Buffer> {
enc = normalizeString(enc);
if ('' === enc) {
enc = undefined;
}
return new Promise<Buffer>((resolve, reject) => {
let buff: Buffer;
let dataListener: (chunk: Buffer | string) => void;
let endListener: () => void;
let errorListener: (err: any) => void;
let completedInvoked = false;
const COMPLETED = (err: any) => {