e97820c9af37c85a4a0ac163ae223db0c98e0faf
[platform/upstream/nodejs.git] / lib / util.js
1 // Copyright Joyent, Inc. and other Node contributors.
2 //
3 // Permission is hereby granted, free of charge, to any person obtaining a
4 // copy of this software and associated documentation files (the
5 // "Software"), to deal in the Software without restriction, including
6 // without limitation the rights to use, copy, modify, merge, publish,
7 // distribute, sublicense, and/or sell copies of the Software, and to permit
8 // persons to whom the Software is furnished to do so, subject to the
9 // following conditions:
10 //
11 // The above copyright notice and this permission notice shall be included
12 // in all copies or substantial portions of the Software.
13 //
14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20 // USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22 var formatRegExp = /%[sdj%]/g;
23 exports.format = function(f) {
24   if (!isString(f)) {
25     var objects = [];
26     for (var i = 0; i < arguments.length; i++) {
27       objects.push(inspect(arguments[i]));
28     }
29     return objects.join(' ');
30   }
31
32   var i = 1;
33   var args = arguments;
34   var len = args.length;
35   var str = String(f).replace(formatRegExp, function(x) {
36     if (x === '%%') return '%';
37     if (i >= len) return x;
38     switch (x) {
39       case '%s': return String(args[i++]);
40       case '%d': return Number(args[i++]);
41       case '%j':
42         try {
43           return JSON.stringify(args[i++]);
44         } catch (_) {
45           return '[Circular]';
46         }
47       default:
48         return x;
49     }
50   });
51   for (var x = args[i]; i < len; x = args[++i]) {
52     if (isNull(x) || !isObject(x)) {
53       str += ' ' + x;
54     } else {
55       str += ' ' + inspect(x);
56     }
57   }
58   return str;
59 };
60
61
62 // Mark that a method should not be used.
63 // Returns a modified function which warns once by default.
64 // If --no-deprecation is set, then it is a no-op.
65 exports.deprecate = function(fn, msg) {
66   // Allow for deprecating things in the process of starting up.
67   if (isUndefined(global.process)) {
68     return function() {
69       return exports.deprecate(fn, msg).apply(this, arguments);
70     };
71   }
72
73   if (process.noDeprecation === true) {
74     return fn;
75   }
76
77   var warned = false;
78   function deprecated() {
79     if (!warned) {
80       if (process.throwDeprecation) {
81         throw new Error(msg);
82       } else if (process.traceDeprecation) {
83         console.trace(msg);
84       } else {
85         console.error(msg);
86       }
87       warned = true;
88     }
89     return fn.apply(this, arguments);
90   }
91
92   return deprecated;
93 };
94
95
96 var debugs = {};
97 var debugEnviron;
98 exports.debuglog = function(set) {
99   if (isUndefined(debugEnviron))
100     debugEnviron = process.env.NODE_DEBUG || '';
101   set = set.toUpperCase();
102   if (!debugs[set]) {
103     if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
104       var pid = process.pid;
105       debugs[set] = function() {
106         var msg = exports.format.apply(exports, arguments);
107         console.error('%s %d: %s', set, pid, msg);
108       };
109     } else {
110       debugs[set] = function() {};
111     }
112   }
113   return debugs[set];
114 };
115
116
117 /**
118  * Echos the value of a value. Trys to print the value out
119  * in the best way possible given the different types.
120  *
121  * @param {Object} obj The object to print out.
122  * @param {Object} opts Optional options object that alters the output.
123  */
124 /* legacy: obj, showHidden, depth, colors*/
125 function inspect(obj, opts) {
126   // default options
127   var ctx = {
128     seen: [],
129     stylize: stylizeNoColor
130   };
131   // legacy...
132   if (arguments.length >= 3) ctx.depth = arguments[2];
133   if (arguments.length >= 4) ctx.colors = arguments[3];
134   if (isBoolean(opts)) {
135     // legacy...
136     ctx.showHidden = opts;
137   } else if (opts) {
138     // got an "options" object
139     exports._extend(ctx, opts);
140   }
141   // set default options
142   if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
143   if (isUndefined(ctx.depth)) ctx.depth = 2;
144   if (isUndefined(ctx.colors)) ctx.colors = false;
145   if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
146   if (ctx.colors) ctx.stylize = stylizeWithColor;
147   return formatValue(ctx, obj, ctx.depth);
148 }
149 exports.inspect = inspect;
150
151
152 // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
153 inspect.colors = {
154   'bold' : [1, 22],
155   'italic' : [3, 23],
156   'underline' : [4, 24],
157   'inverse' : [7, 27],
158   'white' : [37, 39],
159   'grey' : [90, 39],
160   'black' : [30, 39],
161   'blue' : [34, 39],
162   'cyan' : [36, 39],
163   'green' : [32, 39],
164   'magenta' : [35, 39],
165   'red' : [31, 39],
166   'yellow' : [33, 39]
167 };
168
169 // Don't use 'blue' not visible on cmd.exe
170 inspect.styles = {
171   'special': 'cyan',
172   'number': 'yellow',
173   'boolean': 'yellow',
174   'undefined': 'grey',
175   'null': 'bold',
176   'string': 'green',
177   'symbol': 'green',
178   'date': 'magenta',
179   // "name": intentionally not styling
180   'regexp': 'red'
181 };
182
183
184 function stylizeWithColor(str, styleType) {
185   var style = inspect.styles[styleType];
186
187   if (style) {
188     return '\u001b[' + inspect.colors[style][0] + 'm' + str +
189            '\u001b[' + inspect.colors[style][1] + 'm';
190   } else {
191     return str;
192   }
193 }
194
195
196 function stylizeNoColor(str, styleType) {
197   return str;
198 }
199
200
201 function arrayToHash(array) {
202   var hash = {};
203
204   array.forEach(function(val, idx) {
205     hash[val] = true;
206   });
207
208   return hash;
209 }
210
211
212 function formatValue(ctx, value, recurseTimes) {
213   // Provide a hook for user-specified inspect functions.
214   // Check that value is an object with an inspect function on it
215   if (ctx.customInspect &&
216       value &&
217       isFunction(value.inspect) &&
218       // Filter out the util module, it's inspect function is special
219       value.inspect !== exports.inspect &&
220       // Also filter out any prototype objects using the circular check.
221       !(value.constructor && value.constructor.prototype === value)) {
222     var ret = value.inspect(recurseTimes, ctx);
223     if (!isString(ret)) {
224       ret = formatValue(ctx, ret, recurseTimes);
225     }
226     return ret;
227   }
228
229   // Primitive types cannot have properties
230   var primitive = formatPrimitive(ctx, value);
231   if (primitive) {
232     return primitive;
233   }
234
235   // Look up the keys of the object.
236   var keys = Object.keys(value);
237   var visibleKeys = arrayToHash(keys);
238
239   if (ctx.showHidden) {
240     keys = Object.getOwnPropertyNames(value);
241   }
242
243   // This could be a boxed primitive (new String(), etc.), check valueOf()
244   // NOTE: Avoid calling `valueOf` on `Date` instance because it will return
245   // a number which, when object has some additional user-stored `keys`,
246   // will be printed out.
247   var formatted;
248   var raw = value;
249   try {
250     // the .valueOf() call can fail for a multitude of reasons
251     if (!isDate(value))
252       raw = value.valueOf();
253   } catch (e) {
254     // ignore...
255   }
256
257   if (isString(raw)) {
258     // for boxed Strings, we have to remove the 0-n indexed entries,
259     // since they just noisey up the output and are redundant
260     keys = keys.filter(function(key) {
261       return !(key >= 0 && key < raw.length);
262     });
263   }
264
265   // Some type of object without properties can be shortcutted.
266   if (keys.length === 0) {
267     if (isFunction(value)) {
268       var name = value.name ? ': ' + value.name : '';
269       return ctx.stylize('[Function' + name + ']', 'special');
270     }
271     if (isRegExp(value)) {
272       return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
273     }
274     if (isDate(value)) {
275       return ctx.stylize(Date.prototype.toString.call(value), 'date');
276     }
277     if (isError(value)) {
278       return formatError(value);
279     }
280     // now check the `raw` value to handle boxed primitives
281     if (isString(raw)) {
282       formatted = formatPrimitiveNoColor(ctx, raw);
283       return ctx.stylize('[String: ' + formatted + ']', 'string');
284     }
285     if (isNumber(raw)) {
286       formatted = formatPrimitiveNoColor(ctx, raw);
287       return ctx.stylize('[Number: ' + formatted + ']', 'number');
288     }
289     if (isBoolean(raw)) {
290       formatted = formatPrimitiveNoColor(ctx, raw);
291       return ctx.stylize('[Boolean: ' + formatted + ']', 'boolean');
292     }
293   }
294
295   var base = '', array = false, braces = ['{', '}'];
296
297   // Make Array say that they are Array
298   if (isArray(value)) {
299     array = true;
300     braces = ['[', ']'];
301   }
302
303   // Make functions say that they are functions
304   if (isFunction(value)) {
305     var n = value.name ? ': ' + value.name : '';
306     base = ' [Function' + n + ']';
307   }
308
309   // Make RegExps say that they are RegExps
310   if (isRegExp(value)) {
311     base = ' ' + RegExp.prototype.toString.call(value);
312   }
313
314   // Make dates with properties first say the date
315   if (isDate(value)) {
316     base = ' ' + Date.prototype.toUTCString.call(value);
317   }
318
319   // Make error with message first say the error
320   if (isError(value)) {
321     base = ' ' + formatError(value);
322   }
323
324   // Make boxed primitive Strings look like such
325   if (isString(raw)) {
326     formatted = formatPrimitiveNoColor(ctx, raw);
327     base = ' ' + '[String: ' + formatted + ']';
328   }
329
330   // Make boxed primitive Numbers look like such
331   if (isNumber(raw)) {
332     formatted = formatPrimitiveNoColor(ctx, raw);
333     base = ' ' + '[Number: ' + formatted + ']';
334   }
335
336   // Make boxed primitive Booleans look like such
337   if (isBoolean(raw)) {
338     formatted = formatPrimitiveNoColor(ctx, raw);
339     base = ' ' + '[Boolean: ' + formatted + ']';
340   }
341
342   if (keys.length === 0 && (!array || value.length === 0)) {
343     return braces[0] + base + braces[1];
344   }
345
346   if (recurseTimes < 0) {
347     if (isRegExp(value)) {
348       return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
349     } else {
350       return ctx.stylize('[Object]', 'special');
351     }
352   }
353
354   ctx.seen.push(value);
355
356   var output;
357   if (array) {
358     output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
359   } else {
360     output = keys.map(function(key) {
361       return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
362     });
363   }
364
365   ctx.seen.pop();
366
367   return reduceToSingleString(output, base, braces);
368 }
369
370
371 function formatPrimitive(ctx, value) {
372   if (isUndefined(value))
373     return ctx.stylize('undefined', 'undefined');
374   if (isString(value)) {
375     var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
376                                              .replace(/'/g, "\\'")
377                                              .replace(/\\"/g, '"') + '\'';
378     return ctx.stylize(simple, 'string');
379   }
380   if (isNumber(value)) {
381     // Format -0 as '-0'. Strict equality won't distinguish 0 from -0,
382     // so instead we use the fact that 1 / -0 < 0 whereas 1 / 0 > 0 .
383     if (value === 0 && 1 / value < 0)
384       return ctx.stylize('-0', 'number');
385     return ctx.stylize('' + value, 'number');
386   }
387   if (isBoolean(value))
388     return ctx.stylize('' + value, 'boolean');
389   // For some reason typeof null is "object", so special case here.
390   if (isNull(value))
391     return ctx.stylize('null', 'null');
392   // es6 symbol primitive
393   if (isSymbol(value))
394     return ctx.stylize(value.toString(), 'symbol');
395 }
396
397
398 function formatPrimitiveNoColor(ctx, value) {
399   var stylize = ctx.stylize;
400   ctx.stylize = stylizeNoColor;
401   var str = formatPrimitive(ctx, value);
402   ctx.stylize = stylize;
403   return str;
404 }
405
406
407 function formatError(value) {
408   return '[' + Error.prototype.toString.call(value) + ']';
409 }
410
411
412 function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
413   var output = [];
414   for (var i = 0, l = value.length; i < l; ++i) {
415     if (hasOwnProperty(value, String(i))) {
416       output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
417           String(i), true));
418     } else {
419       output.push('');
420     }
421   }
422   keys.forEach(function(key) {
423     if (!key.match(/^\d+$/)) {
424       output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
425           key, true));
426     }
427   });
428   return output;
429 }
430
431
432 function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
433   var name, str, desc;
434   desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
435   if (desc.get) {
436     if (desc.set) {
437       str = ctx.stylize('[Getter/Setter]', 'special');
438     } else {
439       str = ctx.stylize('[Getter]', 'special');
440     }
441   } else {
442     if (desc.set) {
443       str = ctx.stylize('[Setter]', 'special');
444     }
445   }
446   if (!hasOwnProperty(visibleKeys, key)) {
447     name = '[' + key + ']';
448   }
449   if (!str) {
450     if (ctx.seen.indexOf(desc.value) < 0) {
451       if (isNull(recurseTimes)) {
452         str = formatValue(ctx, desc.value, null);
453       } else {
454         str = formatValue(ctx, desc.value, recurseTimes - 1);
455       }
456       if (str.indexOf('\n') > -1) {
457         if (array) {
458           str = str.split('\n').map(function(line) {
459             return '  ' + line;
460           }).join('\n').substr(2);
461         } else {
462           str = '\n' + str.split('\n').map(function(line) {
463             return '   ' + line;
464           }).join('\n');
465         }
466       }
467     } else {
468       str = ctx.stylize('[Circular]', 'special');
469     }
470   }
471   if (isUndefined(name)) {
472     if (array && key.match(/^\d+$/)) {
473       return str;
474     }
475     name = JSON.stringify('' + key);
476     if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
477       name = name.substr(1, name.length - 2);
478       name = ctx.stylize(name, 'name');
479     } else {
480       name = name.replace(/'/g, "\\'")
481                  .replace(/\\"/g, '"')
482                  .replace(/(^"|"$)/g, "'")
483                  .replace(/\\\\/g, '\\');
484       name = ctx.stylize(name, 'string');
485     }
486   }
487
488   return name + ': ' + str;
489 }
490
491
492 function reduceToSingleString(output, base, braces) {
493   var length = output.reduce(function(prev, cur) {
494     return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
495   }, 0);
496
497   if (length > 60) {
498     return braces[0] +
499            (base === '' ? '' : base + '\n ') +
500            ' ' +
501            output.join(',\n  ') +
502            ' ' +
503            braces[1];
504   }
505
506   return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
507 }
508
509
510 // NOTE: These type checking functions intentionally don't use `instanceof`
511 // because it is fragile and can be easily faked with `Object.create()`.
512 var isArray = exports.isArray = Array.isArray;
513
514 function isBoolean(arg) {
515   return typeof arg === 'boolean';
516 }
517 exports.isBoolean = isBoolean;
518
519 function isNull(arg) {
520   return arg === null;
521 }
522 exports.isNull = isNull;
523
524 function isNullOrUndefined(arg) {
525   return arg == null;
526 }
527 exports.isNullOrUndefined = isNullOrUndefined;
528
529 function isNumber(arg) {
530   return typeof arg === 'number';
531 }
532 exports.isNumber = isNumber;
533
534 function isString(arg) {
535   return typeof arg === 'string';
536 }
537 exports.isString = isString;
538
539 function isSymbol(arg) {
540   return typeof arg === 'symbol';
541 }
542 exports.isSymbol = isSymbol;
543
544 function isUndefined(arg) {
545   return arg === void 0;
546 }
547 exports.isUndefined = isUndefined;
548
549 function isRegExp(re) {
550   return isObject(re) && objectToString(re) === '[object RegExp]';
551 }
552 exports.isRegExp = isRegExp;
553
554 function isObject(arg) {
555   return typeof arg === 'object' && arg !== null;
556 }
557 exports.isObject = isObject;
558
559 function isDate(d) {
560   return isObject(d) && objectToString(d) === '[object Date]';
561 }
562 exports.isDate = isDate;
563
564 function isError(e) {
565   return isObject(e) &&
566       (objectToString(e) === '[object Error]' || e instanceof Error);
567 }
568 exports.isError = isError;
569
570 function isFunction(arg) {
571   return typeof arg === 'function';
572 }
573 exports.isFunction = isFunction;
574
575 function isPrimitive(arg) {
576   return arg === null ||
577          typeof arg === 'boolean' ||
578          typeof arg === 'number' ||
579          typeof arg === 'string' ||
580          typeof arg === 'symbol' ||  // ES6 symbol
581          typeof arg === 'undefined';
582 }
583 exports.isPrimitive = isPrimitive;
584
585 function isBuffer(arg) {
586   return arg instanceof Buffer;
587 }
588 exports.isBuffer = isBuffer;
589
590 function objectToString(o) {
591   return Object.prototype.toString.call(o);
592 }
593
594
595 function pad(n) {
596   return n < 10 ? '0' + n.toString(10) : n.toString(10);
597 }
598
599
600 var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
601               'Oct', 'Nov', 'Dec'];
602
603 // 26 Feb 16:19:34
604 function timestamp() {
605   var d = new Date();
606   var time = [pad(d.getHours()),
607               pad(d.getMinutes()),
608               pad(d.getSeconds())].join(':');
609   return [d.getDate(), months[d.getMonth()], time].join(' ');
610 }
611
612
613 // log is just a thin wrapper to console.log that prepends a timestamp
614 exports.log = function() {
615   console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
616 };
617
618
619 /**
620  * Inherit the prototype methods from one constructor into another.
621  *
622  * The Function.prototype.inherits from lang.js rewritten as a standalone
623  * function (not on Function.prototype). NOTE: If this file is to be loaded
624  * during bootstrapping this function needs to be rewritten using some native
625  * functions as prototype setup using normal JavaScript does not work as
626  * expected during bootstrapping (see mirror.js in r114903).
627  *
628  * @param {function} ctor Constructor function which needs to inherit the
629  *     prototype.
630  * @param {function} superCtor Constructor function to inherit prototype from.
631  */
632 exports.inherits = function(ctor, superCtor) {
633   ctor.super_ = superCtor;
634   ctor.prototype = Object.create(superCtor.prototype, {
635     constructor: {
636       value: ctor,
637       enumerable: false,
638       writable: true,
639       configurable: true
640     }
641   });
642 };
643
644 exports._extend = function(origin, add) {
645   // Don't do anything if add isn't an object
646   if (!add || !isObject(add)) return origin;
647
648   var keys = Object.keys(add);
649   var i = keys.length;
650   while (i--) {
651     origin[keys[i]] = add[keys[i]];
652   }
653   return origin;
654 };
655
656 function hasOwnProperty(obj, prop) {
657   return Object.prototype.hasOwnProperty.call(obj, prop);
658 }
659
660
661 // Deprecated old stuff.
662
663 exports.p = exports.deprecate(function() {
664   for (var i = 0, len = arguments.length; i < len; ++i) {
665     console.error(exports.inspect(arguments[i]));
666   }
667 }, 'util.p: Use console.error() instead');
668
669
670 exports.exec = exports.deprecate(function() {
671   return require('child_process').exec.apply(this, arguments);
672 }, 'util.exec is now called `child_process.exec`.');
673
674
675 exports.print = exports.deprecate(function() {
676   for (var i = 0, len = arguments.length; i < len; ++i) {
677     process.stdout.write(String(arguments[i]));
678   }
679 }, 'util.print: Use console.log instead');
680
681
682 exports.puts = exports.deprecate(function() {
683   for (var i = 0, len = arguments.length; i < len; ++i) {
684     process.stdout.write(arguments[i] + '\n');
685   }
686 }, 'util.puts: Use console.log instead');
687
688
689 exports.debug = exports.deprecate(function(x) {
690   process.stderr.write('DEBUG: ' + x + '\n');
691 }, 'util.debug: Use console.error instead');
692
693
694 exports.error = exports.deprecate(function(x) {
695   for (var i = 0, len = arguments.length; i < len; ++i) {
696     process.stderr.write(arguments[i] + '\n');
697   }
698 }, 'util.error: Use console.error instead');
699
700
701 exports.pump = exports.deprecate(function(readStream, writeStream, callback) {
702   var callbackCalled = false;
703
704   function call(a, b, c) {
705     if (callback && !callbackCalled) {
706       callback(a, b, c);
707       callbackCalled = true;
708     }
709   }
710
711   readStream.addListener('data', function(chunk) {
712     if (writeStream.write(chunk) === false) readStream.pause();
713   });
714
715   writeStream.addListener('drain', function() {
716     readStream.resume();
717   });
718
719   readStream.addListener('end', function() {
720     writeStream.end();
721   });
722
723   readStream.addListener('close', function() {
724     call();
725   });
726
727   readStream.addListener('error', function(err) {
728     writeStream.end();
729     call(err);
730   });
731
732   writeStream.addListener('error', function(err) {
733     readStream.destroy();
734     call(err);
735   });
736 }, 'util.pump(): Use readableStream.pipe() instead');
737
738
739 var uv;
740 exports._errnoException = function(err, syscall, original) {
741   if (isUndefined(uv)) uv = process.binding('uv');
742   var errname = uv.errname(err);
743   var message = syscall + ' ' + errname;
744   if (original)
745     message += ' ' + original;
746   var e = new Error(message);
747   e.code = errname;
748   e.errno = errname;
749   e.syscall = syscall;
750   return e;
751 };