-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdantil.js
2148 lines (1974 loc) · 71.1 KB
/
dantil.js
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
/**
* @license
* dantil
* Copyright 2015-2016 Danny Nemer <http://dannynemer.com>
* Available under MIT license <http://opensource.org/licenses/MIT>
*/
var fs = require('fs')
var util = require('util')
var jsdiff = require('diff')
/**
* Checks if `options` does not adhere to `schema`, thereby simulating static function arguments (i.e., type checking and arity). If ill-formed, prints descriptive, helpful errors (including the file-path + line-number of the offending function call).
*
* @static
* @memberOf dantil
* @category Utility
* @param {Object} schema The definition of required and optional properties for `options`.
* @param {Object} [options] The options object to check for conformity to `schema`.
* @param {Object} [ignoreUndefined] Specify ignoring non-`required` `options` properties defined as `undefined`. Otherwise, reports them as errors, which is useful for catching broken references.
* @returns {boolean} Returns `true` if `options` is ill-formed, else `false`.
* @example
*
* var mySchema = {
* // Optionally accept an `boolean` for 'silent'.
* silent: Boolean,
* // Optionally accept an `Array` of `string`s for 'args'.
* args: { type: Array, arrayType: String },
* // Require `string` 'modulePath'.
* modulePath: { type: String, required: true },
* // Optionally accept one of predefined values for 'stdio'.
* stdio: { values: [ 'pipe', 'ignore', 0, 1, 2 ] },
* // Optionally accept an `Object` that adheres to the nested `schema` object.
* options: { type: Object, schema: {
* cwd: String,
* uid: Number,
* } },
* }
*
* function myFork(options) {
* if (dantil.illFormedOpts(mySchema, options)) {
* // => Prints descriptive, helpful error message
*
* throw new Error('Ill-formed options')
* }
*
* // ...stuff...
* }
* ```
* The contents of `foo.js`:
* ```js
* myFork({ modulePath: './myModule.js', stdio: 'out' })
* ```
* Output:
* <br><img src="https://raw.githubusercontent.com/DannyNemer/dantil/master/doc/img/dantil-illFormedOpts-example.jpg" alt="dantil.illFormedOpts() example output"/>
* ```
*/
exports.illFormedOpts = require('ill-formed-opts')
/**
* Invokes `func` within a `try` block, and catches and prints any thrown exceptions (including the stack trace if an `Error` is thrown).
*
* @static
* @memberOf dantil
* @category Utility
* @param {Function} func The function to invoke within a `try` block.
* @param {boolean} [exitProcessIfFailure] Specify exiting the process with failure code `1` after catching and printing an exception (thrown within `func`).
* @returns {*} Returns the return value of `func`.
* @example
*
* dantil.tryCatchWrapper(function () {
* // ...stuff...
* throw new Error('test failed')
* })
* // => Catches thrown exception and prints stack trace
*/
exports.tryCatchWrapper = function (func, exitProcessIfFailure) {
try {
return func()
} catch (e) {
// Print leading newline.
exports.log()
// Print exception.
if (e.stack) {
exports.log(e.stack)
} else {
exports.log(e)
}
if (exitProcessIfFailure) {
process.exit(1)
}
}
}
/**
* Removes the modules identified by the provided paths from cache, forcing them to be reloaded at next `require()` call.
*
* Without removing a module from cache, subsequent `require()` calls to the same module will not enable changes to its file(s). This is useful for enabling changes on a server without restarting the server.
*
* @static
* @memberOf dantil
* @category Utility
* @param {...string} [paths] The paths of modules to remove from cache.
* @example
*
* var myModule = require('./myModule.js')
* // => Loads module
*
* dantil.deleteModuleCache('./myModule.js')
* // => Removes module from cache
*
* myModule = require('./myModule.js')
* // => Loads module again, enabling changes to './myModule.js'
*/
exports.deleteModuleCache = function () {
for (var a = 0, argumentsLen = arguments.length; a < argumentsLen; ++a) {
delete require.cache[fs.realpathSync(arguments[a])]
}
}
/**
* Gets this method's invocation location in the format `filePath:lineNumber:columnNumber`.
*
* @static
* @memberOf dantil
* @category Utility
* @returns {string} Returns this method's invocation location.
* @example
*
* ```
* The contents of `foo.js`:
* ```js
* dantil.getLocation()
* // => '/Users/Danny/foo.js:1'
*/
exports.getLocation = function () {
// Get the frame for where this method was invoked.
var stack = getStackTraceArray()
return getFrameLocation(stack[0])
}
/**
* Gets the location of the function call that invoked the currently executing module in the format `filePath:lineNumber:columnNumber`.
*
* This is not necessarily the caller of the currently executing function, which can be another function within the same module. Nor is it necessarily this module's parent which instantiated the module. Rather, it is the most recent function call in the stack outside the currently executing module.
* • Skips stack frames for native Node functions (e.g., `require()`).
*
* When searching the call stack, skips those frames for modules in which `dantil.skipFileInLocationRetrieval()` was invoked.
* • This is useful for including a method's invocation location in an error message, though that location is deep within the call stack relative to the error's generation location. I.e., the error is caught several modules deep from the invocation to which the error applies, as opposed to being one module deep.
*
* Returns `undefined` if there is no other module in the stack below where this method was invoked that meets these criteria. This occurs when invoked from the root module.
*
* @static
* @memberOf dantil
* @category Utility
* @returns {string} Returns the location of the function call that invoked the currently executing module.
* @example
*
* ```
* The contents of `main.js`:
* ```js
* var child = require('./child.js')
* child.func()
*
* var grandchild = require('./grandchild.js')
* grandchild.foo()
*
* // Try to get the frame of the nonexistent function call that invoked this module.
* dantil.getModuleCallerLocation()
* // => undefined
* ```
* The contents of `child.js`:
* ```js
* var grandchild = require('./grandchild.js')
*
* exports.func = function () {
* // Get the frame of the invocation of the current execution of this module.
* dantil.getModuleCallerLocation()
* // => '/Users/Danny/main.js:2'
*
* // Call another function within the same module, though retrieves the same frame.
* subFunc()
*
* // Call a function in another module.
* grandchild.bar()
* }
*
* function subFunc() {
* // Get the frame of the invocation of the current execution of this module (which
* // is not the frame that invoked this function).
* dantil.getModuleCallerLocation()
* // => '/Users/Danny/main.js:2'
* }
* ```
* The contents of `grandchild.js`:
* ```js
* exports.foo = function () {
* dantil.getModuleCallerLocation()
* // => '/Users/Danny/main.js:5'
* }
*
* exports.bar = function () {
* dantil.getModuleCallerLocation()
* // => '/Users/Danny/child.js:13'
* }
*/
exports.getModuleCallerLocation = function () {
// Get the stack trace, excluding the stack frames for this module and native Node functions (e.g., `require()`).
var stack = getStackTraceArray()
var thisModuleName
for (var f = 0, stackLen = stack.length; f < stackLen; ++f) {
var frame = stack[f]
var frameFileName = frame.getFileName()
// Get the module name of where this method was invoked (in order to skip its associated frames).
if (!thisModuleName) {
thisModuleName = frameFileName
continue
}
// Find the frame of the most recent module after where this method was invoked, skipping frames for modules in which `dantil.skipFileInLocationRetrieval()` was invoked, if any.
if (thisModuleName !== frameFileName && _filesToSkipInLocationRetreival.indexOf(frameFileName) === -1) {
return getFrameLocation(frame)
}
}
// Returns `undefined` if there is no other module in the stack below where this method was invoked that meets these criteria.
}
/**
* The file names of stack frames for `dantil.getModuleCallerLocation()` to skip when searching the call stack for the function call that invoked the currently executing module.
*
* `dantil.skipFileInLocationRetrieval()` appends this array with the file name in which the method is invoked.
*
* @private
* @type {string[]}
*/
var _filesToSkipInLocationRetreival = []
/**
* Marks the module in which this method is invoked for `dantil.getModuleCallerLocation()` to skip when searching the call stack.
*
* This is useful for using `dantil.getModuleCallerLocation()` to include a method's invocation location in an error message, though that location is deep within the call stack relative to the error's generation location. I.e., the error is caught several modules deep from the invocation to which the error applies, as opposed to being one module deep.
*
* @static
* @memberOf dantil
* @category Utility
* @example
*
* ```
* The contents of `main.js`:
* ```js
* var child = require('./child.js')
*
* // Invoke `child.js`.
* child.func()
* ```
* The contents of `child.js`:
* ```js
* var grandchild = require('./grandchild.js')
*
* exports.func = function () {
* // Get the location of the function call that invoked the module `grandchild.js`.
* grandchild.getCallerLocation()
* // => '/Users/Danny/child.js:5:15'
*
* // Skip this module (`child.js`) when using `dantil.getModuleCallerLocation()`
* // in `grandchild.js` to get the location of the call that invoked the module's method.
* dantil.skipFileInLocationRetrieval()
*
* // Get the location of the function call that invoked this module, which
* // invoked the `grandchild.js` method.
* grandchild.getCallerLocation()
* // => '/Users/Danny/main.js:3:7'
* }
* ```
* The contents of `grandchild.js`:
* ```js
* exports.getCallerLocation = function () {
* // Get the location of the function call that invoked this module.
* return dantil.getModuleCallerLocation()
* }
*/
exports.skipFileInLocationRetrieval = function () {
var stack = getStackTraceArray()
var fileName = stack[0].getFileName()
// Alert if method invoked twice within same file.
if (_filesToSkipInLocationRetreival.indexOf(fileName) !== -1) {
exports.logError('`dantil.skipFileInLocationRetrieval()` invoked twice within same file:')
exports.log(' ' + exports.stylize(fileName) + '\n')
throw new Error('Duplicate file name to ignore')
}
_filesToSkipInLocationRetreival.push(fileName)
}
/**
* Creates a string representation of the location of `stackFrame` in the format `filePath:lineNumber:columnNumber`.
*
* @private
* @static
* @param {CallSite} stackFrame The stack frame.
* @returns {string} Returns the location of `stackFrame`.
*/
function getFrameLocation(stackFrame) {
var frameString = stackFrame.toString()
var lastParenIndex = frameString.lastIndexOf('(')
return lastParenIndex === -1 ? frameString : frameString.slice(lastParenIndex + 1, -1)
}
/**
* Gets the structured stack trace as an array of `CallSite` objects, excluding the stack frames for this module and native Node functions.
*
* @private
* @static
* @returns {CallSite[]} Returns the structured stack trace.
*/
function getStackTraceArray() {
var origStackTraceLimit = Error.stackTraceLimit
var origPrepareStackTrace = Error.prepareStackTrace
// Collect all stack frames.
Error.stackTraceLimit = Infinity
// Get a structured stack trace as an `Array` of `CallSite` objects, each of which represents a stack frame, with frames for native Node functions and this file removed.
Error.prepareStackTrace = function (error, structuredStackTrace) {
return structuredStackTrace.filter(function (frame) {
var filePath = frame.getFileName()
// Skip frames from within this module (i.e., `dantil`).
if (filePath === __filename) {
return false
}
// Skip frames for native Node functions (e.g., `require()`).
if (!/\//.test(filePath)) {
return false
}
return true
})
}
// Collect the stack trace.
var stack = Error().stack
// Restore stack trace configuration after collecting stack trace.
Error.stackTraceLimit = origStackTraceLimit
Error.prepareStackTrace = origPrepareStackTrace
return stack
}
/**
* Stylizes strings for printing to the console using the [`chalk`](https://github.com/chalk/chalk) module.
*
* @static
* @memberOf dantil
* @category Utility
* @type Object
* @example
*
* console.log(dantil.colors.red('Error'))
* // => Prints red-colored "Error"
*/
exports.colors = require('chalk')
/**
* Invokes `func` while synchronously writing the process's `stdout` to a file at `path` instead of the console. Creates the file if it does not exist or truncates the file to zero length if it does exist. Restores `stdout` to the console when `func` returns or if an exception is thrown.
*
* @static
* @memberOf dantil
* @category File System
* @param {string} path The path where to write `stdout`.
* @param {Function} func The function to invoke while writing output to `path`.
* @returns {*} Returns the value returned by `func`, if any.
* @example
*
* // Print to console.
* console.log('Begin output to file')
*
* // Redirect `stdout` from console to '~/Desktop/out.txt'.
* dantil.stdoutToFile('~/Desktop/out.txt', function () {
* console.log('Numbers:')
* for (var i = 0; i < 100; ++i) {
* console.log(i)
* }
* })
* // => Restores `stdout` to console and prints "Output saved: ~/Desktop/out.txt"
*
* // Print to console (after restoring `stdout`).
* console.log('Output to file complete')
*/
exports.stdoutToFile = function (path, func) {
// Expand '~' if present. Can not resolve `path` here because `path` may not exist.
path = exports.expandHomeDir(path)
// Disable ANSI escape codes for color and formatting in output.
var origSupportsColor = exports.colors.supportsColor
exports.colors.supportsColor = false
// Create file if does not exist, truncates file to zero length if it does exist, or throw an exception if `path` is a directory.
fs.writeFileSync(path)
// Redirect `process.stdout` to `path`.
var writable = fs.createWriteStream(path)
var origStdoutWrite = process.stdout.write
process.stdout.write = function () {
writable.write.apply(writable, arguments)
}
try {
// Write output to `path`.
var returnVal = func()
// Restore `process.stdout`.
process.stdout.write = origStdoutWrite
// Re-enable output stylization.
exports.colors.supportsColor = origSupportsColor
exports.log('Output saved:', fs.realpathSync(path))
return returnVal
} catch (e) {
// Restore `process.stdout`.
process.stdout.write = origStdoutWrite
// Re-enable output stylization.
exports.colors.supportsColor = origSupportsColor
throw e
}
}
/**
* Stringifies and writes `object` to a JSON file at `path`.
*
* @static
* @memberOf dantil
* @category File System
* @param {string} path The file path to which to write.
* @param {Object} object The object to save to `path`.
* @example
*
* var obj = {
* name: 'foo',
* value: 7,
* list: [ 'apple', 'orange' ]
* }
*
* dantil.writeJSONFile('./myObj.json', obj)
* // => Writes file and prints "File saved: /Users/Danny/myObj.json"
*/
exports.writeJSONFile = function (path, object) {
// Expand '~' if present. Can not resolve `path` here because `path` may not exist.
path = exports.expandHomeDir(path)
fs.writeFileSync(path, JSON.stringify(object, function (key, val) {
// Convert RegExp to strings for `JSON.stringify()`.
return val instanceof RegExp ? val.source : val
}, '\t'))
exports.log('File saved:', fs.realpathSync(path))
}
/**
* Gets the file path and line number in the format `filePath:lineNumber` of each occurrence of `value` in the source file at `filePath`. This is useful for error reporting.
*
* @static
* @memberOf dantil
* @category File System
* @param {string} filePath The path of the source file to search.
* @param {*} value The value for which to search.
* @returns {Array} Returns the set of matched file paths and line numbers.
* @example
*
* ```
* The contents of `foo.js`:
* ```js
* var list = [
* { name: 'lorem', num: 2 },
* { name: 'lorem ipsum', num: 5 },
* { name: 'ipsum', num: 3 }
* ]
* ```
* The contents of `bar.js`:
* ```js
* dantil.pathAndLineNumbersOf('./foo.js', 'ipsum')
* // => [ '/Users/Danny/foo.js:3', '/Users/Danny/foo.js:3' ]
*
* // Enclose sought value to distinguish `ipsum` from `'ipsum'`.
* dantil.pathAndLineNumbersOf('./foo.js', '\'ipsum\'')
* // => [ '/Users/Danny/foo.js:4' ]
*/
exports.pathAndLineNumbersOf = function (filePath, value) {
var matches = []
basePathAndLineNumbersOf(filePath, value, function (pathAndLineNumber) {
matches.push(pathAndLineNumber)
})
return matches
}
/**
* Gets the file path and line number in the format `filePath:lineNumber` of the first occurrence of `value` in the source file at `filePath`. This is useful for error reporting.
*
* If `subValue` is provided, gets the line number of the first occurrence of `subValue` after the first occurrence of `value`. This is useful for using `value` to distinguish multiple occurrences of `subValue` in the file.
*
* @static
* @memberOf dantil
* @category File System
* @param {string} filePath The path of the source file to search.
* @param {*} value The value for which to search.
* @param {*} [subValue] The second value for which to search, starting at the location of `value`.
* @returns {string|undefined} Returns the matched file path and line number, else `undefined`.
* @example
*
* ```
* The contents of `foo.js`:
* ```js
* var list = [
* {
* name: 'lorem',
* num: 2
* }, {
* name: 'lorem ipsum',
* num: 5
* }, {
* name: 'ipsum',
* num: 3
* }
* ]
* ```
* The contents of `bar.js`:
* ```js
* dantil.firstPathAndLineNumberOf('./foo.js', 'ipsum')
* // => '/Users/Danny/foo.js:6',
*
* // Get line number of first occurrence of `num` after `ipsum`.
* dantil.firstPathAndLineNumberOf('./foo.js', 'ipsum', 'num')
* // => '/Users/Danny/foo.js:7',
*
* // Enclose sought value to distinguish `ipsum` from `'ipsum'`.
* dantil.firstPathAndLineNumberOf('./foo.js', '\'ipsum\'')
* // => '/Users/Danny/foo.js:9'
*/
exports.firstPathAndLineNumberOf = function (filePath, value, subValue) {
var match
if (subValue) {
// Find first occurrence of `subValue` after `value`.
lineNumbersOf(filePath, value, function (lineNumber) {
return basePathAndLineNumbersOf(filePath, subValue, function (pathAndLineNumber) {
match = pathAndLineNumber
return true
}, lineNumber)
})
} else {
// Find first occurrence of `value`.
basePathAndLineNumbersOf(filePath, value, function (pathAndLineNumber) {
match = pathAndLineNumber
return true
})
}
return match
}
/**
* The base implementation of `dantil.pathAndLineNumbersOf()` and `dantil.firstPathAndLineNumberOf()` which finds occurrences of `value` in the source file at `filePath`. Stops iteration once `iteratee` returns truthy. Invokes `iteratee` with the path and line number in the format `filePath:lineNumber` as the only argument: (pathAndLineNumber).
*
* @private
* @static
* @param {string} filePath The path of the source file to search.
* @param {*} value The value for which to search.
* @param {Function} iteratee The function invoked per matched line until it returns truthy.
* @param {number} [fromLine=0] The line number at which to start the searching forward in the file at `filePath`.
* @returns {boolean} Returns `true` if `iteratee` is invoked and returns truthy, else `false`.
*/
function basePathAndLineNumbersOf(filePath, value, iteratee, fromLine) {
// Resolve `filePath` if relative.
filePath = exports.realpathSync(filePath)
return lineNumbersOf(filePath, value, function (lineNumber) {
// Exit if `iteratee` returns truthy.
return iteratee(filePath + ':' + lineNumber)
}, fromLine)
}
/**
* Gets the line numbers of occurrences of `value` in the source file at `filePath`. Stops iteration once `iteratee` returns truthy. Invokes `iteratee` with one argument: (lineNumber).
*
* @private
* @static
* @param {string} filePath The path of the source file to search.
* @param {*} value The value for which to search.
* @param {Function} iteratee The function invoked per matched line until it returns truthy.
* @param {number} [fromLine=0] The line number at which to start the searching forward in the file at `filePath`.
* @returns {boolean} Returns `true` if `iteratee` is invoked and returns truthy, else `false`.
*/
function lineNumbersOf(filePath, value, iteratee, fromLine) {
// Get `filePath` lines.
var fileLines = fs.readFileSync(filePath, 'utf8').split('\n')
// Find occurrences of `value` in `fileLines`.
for (var l = fromLine || 0, fileLinesLen = fileLines.length; l < fileLinesLen; ++l) {
if (fileLines[l].indexOf(value) !== -1) {
// Add 1 to line index because line numbers begin at 1.
if (iteratee(l + 1)) {
// Exit if `iteratee` returns truthy.
return true
}
}
}
return false
}
/**
* Replaces `'~'` in `path` (if present and at the path's start) with the home directory path.
*
* @static
* @memberOf dantil
* @category File System
* @param {string} path The file path.
* @returns {string} Returns `path` with `'~'`, if present, replaced with the home directory path.
* @example
*
* dantil.expandHomeDir('~/Desktop')
* // => '/Users/Danny/Desktop'
*/
exports.expandHomeDir = function (path) {
return path.replace(/^~/, process.env[process.platform === 'win32' ? 'USERPROFILE' : 'HOME'])
}
/**
* Synchronously resolves `path` to an absolute path.
*
* This method is similar to Node's `fs.realpathSync()`, but also expands `'~'` if found in `path`.
*
* @static
* @memberOf dantil
* @category File System
* @param {string} path The path to resolve.
* @returns {string} Returns the absolute path.
* @example
*
* dantil.realpathSync('~/Desktop/../../Danny')
* // => '/Users/Danny'
*/
exports.realpathSync = function (path) {
return fs.realpathSync(exports.expandHomeDir(path))
}
/**
* Synchronously checks if `path` exists by checking the file system.
*
* Replaces the deprecated `fs.existsSync()` by invoking `fs.accessSync(path)`, which throws an exception when `path` is not found, within a `try...catch` block.
*
* @static
* @memberOf dantil
* @category File System
* @param {string} path The path to check.
* @returns {boolean} Returns `true` if `path` exists, else `false`.
* @example
*
* dantil.pathExistsSync('/etc/passwd')
* // => true
*
* dantil.pathExistsSync('/wrong/path')
* // => false
*/
exports.pathExistsSync = function (path) {
try {
fs.accessSync(path)
return true
} catch (e) {
return false
}
}
/**
* Pretty-prints the provided values and objects to `stdout`, in color, recursing 2 times while formatting objects (which is the behavior of `console.log()`).
*
* Formats plain `Object`s and `Array`s with multi-line string representations on separate lines. Concatenates and formats all other consecutive values on the same line.
*
* If the first argument is of a complex type (e.g., `Object`, `Array`), left-aligns all remaining lines. Otherwise, equally indents each line after the first line, if any. If the first argument has leading whitespace (or is entirely whitespace), prepends all remaining arguments with the same whitespace (as indentation) excluding newline characters.
*
* @static
* @memberOf dantil
* @category Console
* @param {...*} [values] The values and objects to print.
* @returns {*} Returns the first argument.
* @example
*
* dantil.log({
* name: 'Danny',
* value: 3,
* terms: [ 'confident', 'farseeing', 'capable', 'prudent' ],
* exitFunc: process.exit,
* deepObject: {
* nestedArray: [ [ 1 ] ],
* nestedObject: { obj: { str: 'string', num: 2, bool: true, arr: [ 1, 2, 3, 4, 5, 6, 7 ] } }
* }
* })
* ```
* Output:
* <br><img src="https://raw.githubusercontent.com/DannyNemer/dantil/master/doc/img/dantil-log-example.jpg" alt="dantil.log() example output"/>
* ```
*/
exports.log = function () {
writeToProcessStream('stdout', prettify(arguments))
return arguments[0]
}
/**
* A version of `dantil.log()` that recurses indefinitely while formatting objects. This is useful for inspecting large, complicated objects.
*
* @static
* @memberOf dantil
* @category Console
* @param {...*} [values] The values and objects to print.
* @returns {*} Returns the first argument.
* @example
*
* dantil.dir({
* name: 'Danny',
* value: 3,
* terms: [ 'confident', 'farseeing', 'capable', 'prudent' ],
* exitFunc: process.exit,
* deepObject: {
* nestedArray: [ [ 1 ] ],
* nestedObject: { obj: { str: 'string', num: 2, bool: true, arr: [ 1, 2, 3, 4, 5, 6, 7 ] } }
* }
* })
* ```
* Output:
* <br><img src="https://raw.githubusercontent.com/DannyNemer/dantil/master/doc/img/dantil-dir-example.jpg" alt="dantil.dir() example output"/>
* ```
*/
exports.dir = function () {
// Recurse indefinitely while formatting objects.
writeToProcessStream('stdout', prettify(arguments, { depth: null }))
return arguments[0]
}
/**
* Prints `object` like `dantil.log()` but recurses `depth` times while formatting. This is useful for inspecting large, complicated objects.
*
* @static
* @memberOf dantil
* @category Console
* @param {Object} object The object to print.
* @param {number} depth The number of times to recurse while formatting `object`.
* @returns {Object} Returns `object`.
* @example
*
* var obj = {
* name: 'Danny',
* nestedObj: { array: [ { isGood: false } ] }
* }
*
* dantil.logObjectAtDepth(obj, 1)
* dantil.logObjectAtDepth(obj, 2)
* dantil.logObjectAtDepth(obj, 3)
* ```
* Output:
* <br><img src="https://raw.githubusercontent.com/DannyNemer/dantil/master/doc/img/dantil-logObjectAtDepth-example.jpg" alt="dantil.logObjectAtDepth() example output"/>
* ```
*/
exports.logObjectAtDepth = function (object, depth) {
writeToProcessStream('stdout', prettify([ object ], { depth: depth }))
return object
}
/**
* Prints the provided values like `dantil.log()`, preceded by this method's invocation location.
*
* @static
* @memberOf dantil
* @category Console
* @param {...*} [values] The values and objects to print.
* @returns {*} Returns the first argument.
* @example
*
* dantil.logWithLine({
* name: 'Danny',
* value: 3,
* terms: [ 'confident', 'farseeing', 'capable', 'prudent' ],
* exitFunc: process.exit,
* deepObject: {
* nestedArray: [ [ 1 ] ],
* nestedObject: { obj: { str: 'string', num: 2, bool: true, arr: [ 1, 2, 3, 4, 5, 6, 7 ] } }
* }
* })
* ```
* Output:
* <br><img src="https://raw.githubusercontent.com/DannyNemer/dantil/master/doc/img/dantil-logWithLine-example.jpg" alt="dantil.logWithLine() example output"/>
* ```
*/
exports.logWithLine = function () {
exports.log(exports.colors.grey(exports.getLocation()))
return exports.log.apply(null, arguments)
}
/**
* Prints the provided values like `dantil.dir()`, preceded by this method's invocation location.
*
* @static
* @memberOf dantil
* @category Console
* @param {...*} [values] The values and objects to print.
* @returns {*} Returns the first argument.
* @example
*
* dantil.dirWithLine({
* name: 'Danny',
* value: 3,
* terms: [ 'confident', 'farseeing', 'capable', 'prudent' ],
* exitFunc: process.exit,
* deepObject: {
* nestedArray: [ [ 1 ] ],
* nestedObject: { obj: { str: 'string', num: 2, bool: true, arr: [ 1, 2, 3, 4, 5, 6, 7 ] } }
* }
* })
* ```
* Output:
* <br><img src="https://raw.githubusercontent.com/DannyNemer/dantil/master/doc/img/dantil-dirWithLine-example.jpg" alt="dantil.dirWithLine() example output"/>
* ```
*/
exports.dirWithLine = function () {
exports.log(exports.colors.grey(exports.getLocation()))
return exports.dir.apply(null, arguments)
}
/**
* A version of `dantil.log()` that prints to `stderr`.
*
* @static
* @memberOf dantil
* @category Console
* @param {...*} [values] The values and objects to print.
* @returns {*} Returns the first argument.
*/
exports.logStderr = function () {
writeToProcessStream('stderr', prettify(arguments))
return arguments[0]
}
/**
* Writes `string` with a trailing newline to `processStreamName`.
*
* @private
* @static
* @param {string} processStreamName The name of the writable process stream (e.g., `stout`, `stderr`).
* @param {string} string The string to print.
*/
function writeToProcessStream(processStreamName, string) {
var writableStream = process[processStreamName]
if (writableStream) {
writableStream.write(string + '\n')
} else {
throw new Error('Unrecognized process stream: ' + exports.stylize(processStreamName))
}
}
/**
* Formats the provided values and objects in color for pretty-printing, recursing `options.depth` times while formatting objects.
*
* Formats plain `Object` and `Array` instances with multi-line string representations on separate lines. Concatenates and formats all other consecutive values on the same line.
*
* If the first argument is of a complex type (e.g., `Object`, `Array`), left-aligns all remaining lines. Otherwise, equally indents each line after the first line, if any. If the first argument has leading whitespace (or is entirely whitespace), prepends all remaining arguments with the same whitespace (as indentation) excluding newline characters.
*
* @private
* @static
* @param {Array} args The values and objects to format.
* @param {Object} [options] The options object.
* @param {number} [options.depth=2] The number of times to recurse while formating `args`. Pass `null` to recurse indefinitely.
* @param {number} [options.stylizeStings=false] Specify stylizing strings in `args`. This does not apply to `Object` properties.
* @returns {string} Returns the formatted string.
*/
function prettify(args, options) {
if (!options) {
options = {}
}
var stylizeOptions = {
// Number of times to recurse while formatting; defaults to 2.
depth: options.depth,
// Format in color if the terminal supports color.
colors: exports.colors.supportsColor,
}
// Use `RegExp()` to get correct `reMultiLined.source`.
var reMultiLined = RegExp('\n', 'g')
var reWhitespaceOnly = /^\s+$/
var indent = ' '
var prevArgIsSeperateLine = false
var argsArray = Array.prototype.slice.call(args)
// Remove any leading newline characters in the first argument, and prepend them to the remainder of the formatted arguments instead of including the characters in the indentation of each argument (as occurs with other whitespace characters in the first argument).
var firstArg = argsArray[0]
var leadingNewlines = ''
if (/^\n+/.test(firstArg)) {
var lastNewlineIdx = firstArg.lastIndexOf('\n')
if (lastNewlineIdx === firstArg.length - 1) {
argsArray.shift()
} else {
argsArray[0] = firstArg.slice(lastNewlineIdx + 1)
firstArg = firstArg.slice(0, lastNewlineIdx + 1)
}
leadingNewlines = firstArg
}
return leadingNewlines + argsArray.reduce(function (formattedArgs, arg, i, args) {
var argIsString = typeof arg === 'string'
// Parse numbers passed as string for styling.
if (argIsString && /^\S+$/.test(arg) && !isNaN(arg)) {
arg = parseFloat(arg)
argIsString = false
}
// Do not stylize strings passed as arguments (i.e., not `Object` properties). This also preserves any already-stylized arguments.
var formattedArg = !options.stylizeStings && argIsString ? arg : exports.stylize(arg, stylizeOptions)
if (i === 0) {
// Extend indent for remaining arguments with the first argument's leading whitespace, if any.
if (argIsString) {
// Get the substring of leading whitespace characters from the start of the string, up to the first non-whitespace character, if any.
var firstNonWhitespaceIndex = arg.search(/[^\s]/)
arg = arg.slice(0, firstNonWhitespaceIndex === -1 ? arg.length : firstNonWhitespaceIndex)
// JavaScript will not properly indent if '\t' is appended to spaces (i.e., reverse order as here).
// If the first argument is entirely whitespace, indent all remaining arguments with that whitespace.
indent = reWhitespaceOnly.test(formattedArg) ? arg : arg + indent
// If first argument is entirely whitespace, exclude from output because it serves only to set indentation of all remaining arguments.
if (reWhitespaceOnly.test(formattedArg)) {
// Force the next argument to be pushed to `formattedArgs` to avoid concatenating with `undefined` (because `formattedArgs` remains empty).
prevArgIsSeperateLine = true
} else {
formattedArgs.push(formattedArg)
}
} else {
formattedArgs.push(formattedArg)
if (arg instanceof Object) {
// Do not indent remaining arguments if the first argument is of a complex type.
indent = ''
// Format the complex type on a separate line.
prevArgIsSeperateLine = true
}
}
} else if (arg instanceof Object && (!Array.isArray(arg) || reMultiLined.test(formattedArg) || args[0] instanceof Object)) {
// Format plain `Object`s, `Array`s with multi-line string representations, and `Array`s when the first argument is of a complex type on separate lines.
formattedArgs.push(indent + formattedArg.replace(reMultiLined, reMultiLined.source + indent))
prevArgIsSeperateLine = true
} else if (prevArgIsSeperateLine) {
// Format anything that follows a multi-line string representations on a new line.
formattedArgs.push(indent + formattedArg)
prevArgIsSeperateLine = false
} else {
// Concatenate all consecutive primitive data types.
formattedArgs[formattedArgs.length - 1] += ' ' + formattedArg
}
return formattedArgs
}, []).join('\n')
}
/**
* Formats `value` in color for pretty-printing, recursing `options.depth` times while formatting.
*
* This method is similar to Node's `util.inspect()`, but formats in color by default if the terminal supports color.
*
* @static
* @memberOf dantil
* @category Console
* @param {*} value The object or value to stylize.
* @param {Object} [options] The options object.
* @param {boolean} [options.colors=true] Specify coloring the string for pretty-printing.
* @param {number} [options.depth=2] The number of times to recurse while formating `value` if of a complex type. Pass `null` to recurse indefinitely.
* @returns {string} Returns a stylized string representation of `value`.
*/
exports.stylize = function (value, options) {
if (!options) {
options = {}
}
// Print in color if the terminal supports color.