extsprintf.js 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. /*
  2. * extsprintf.js: extended POSIX-style sprintf
  3. */
  4. var mod_assert = require('assert');
  5. var mod_util = require('util');
  6. /*
  7. * Public interface
  8. */
  9. exports.sprintf = jsSprintf;
  10. exports.printf = jsPrintf;
  11. exports.fprintf = jsFprintf;
  12. /*
  13. * Stripped down version of s[n]printf(3c). We make a best effort to throw an
  14. * exception when given a format string we don't understand, rather than
  15. * ignoring it, so that we won't break existing programs if/when we go implement
  16. * the rest of this.
  17. *
  18. * This implementation currently supports specifying
  19. * - field alignment ('-' flag),
  20. * - zero-pad ('0' flag)
  21. * - always show numeric sign ('+' flag),
  22. * - field width
  23. * - conversions for strings, decimal integers, and floats (numbers).
  24. * - argument size specifiers. These are all accepted but ignored, since
  25. * Javascript has no notion of the physical size of an argument.
  26. *
  27. * Everything else is currently unsupported, most notably precision, unsigned
  28. * numbers, non-decimal numbers, and characters.
  29. */
  30. function jsSprintf(fmt)
  31. {
  32. var regex = [
  33. '([^%]*)', /* normal text */
  34. '%', /* start of format */
  35. '([\'\\-+ #0]*?)', /* flags (optional) */
  36. '([1-9]\\d*)?', /* width (optional) */
  37. '(\\.([1-9]\\d*))?', /* precision (optional) */
  38. '[lhjztL]*?', /* length mods (ignored) */
  39. '([diouxXfFeEgGaAcCsSp%jr])' /* conversion */
  40. ].join('');
  41. var re = new RegExp(regex);
  42. var args = Array.prototype.slice.call(arguments, 1);
  43. var flags, width, precision, conversion;
  44. var left, pad, sign, arg, match;
  45. var ret = '';
  46. var argn = 1;
  47. mod_assert.equal('string', typeof (fmt));
  48. while ((match = re.exec(fmt)) !== null) {
  49. ret += match[1];
  50. fmt = fmt.substring(match[0].length);
  51. flags = match[2] || '';
  52. width = match[3] || 0;
  53. precision = match[4] || '';
  54. conversion = match[6];
  55. left = false;
  56. sign = false;
  57. pad = ' ';
  58. if (conversion == '%') {
  59. ret += '%';
  60. continue;
  61. }
  62. if (args.length === 0)
  63. throw (new Error('too few args to sprintf'));
  64. arg = args.shift();
  65. argn++;
  66. if (flags.match(/[\' #]/))
  67. throw (new Error(
  68. 'unsupported flags: ' + flags));
  69. if (precision.length > 0)
  70. throw (new Error(
  71. 'non-zero precision not supported'));
  72. if (flags.match(/-/))
  73. left = true;
  74. if (flags.match(/0/))
  75. pad = '0';
  76. if (flags.match(/\+/))
  77. sign = true;
  78. switch (conversion) {
  79. case 's':
  80. if (arg === undefined || arg === null)
  81. throw (new Error('argument ' + argn +
  82. ': attempted to print undefined or null ' +
  83. 'as a string'));
  84. ret += doPad(pad, width, left, arg.toString());
  85. break;
  86. case 'd':
  87. arg = Math.floor(arg);
  88. /*jsl:fallthru*/
  89. case 'f':
  90. sign = sign && arg > 0 ? '+' : '';
  91. ret += sign + doPad(pad, width, left,
  92. arg.toString());
  93. break;
  94. case 'x':
  95. ret += doPad(pad, width, left, arg.toString(16));
  96. break;
  97. case 'j': /* non-standard */
  98. if (width === 0)
  99. width = 10;
  100. ret += mod_util.inspect(arg, false, width);
  101. break;
  102. case 'r': /* non-standard */
  103. ret += dumpException(arg);
  104. break;
  105. default:
  106. throw (new Error('unsupported conversion: ' +
  107. conversion));
  108. }
  109. }
  110. ret += fmt;
  111. return (ret);
  112. }
  113. function jsPrintf() {
  114. var args = Array.prototype.slice.call(arguments);
  115. args.unshift(process.stdout);
  116. jsFprintf.apply(null, args);
  117. }
  118. function jsFprintf(stream) {
  119. var args = Array.prototype.slice.call(arguments, 1);
  120. return (stream.write(jsSprintf.apply(this, args)));
  121. }
  122. function doPad(chr, width, left, str)
  123. {
  124. var ret = str;
  125. while (ret.length < width) {
  126. if (left)
  127. ret += chr;
  128. else
  129. ret = chr + ret;
  130. }
  131. return (ret);
  132. }
  133. /*
  134. * This function dumps long stack traces for exceptions having a cause() method.
  135. * See node-verror for an example.
  136. */
  137. function dumpException(ex)
  138. {
  139. var ret;
  140. if (!(ex instanceof Error))
  141. throw (new Error(jsSprintf('invalid type for %%r: %j', ex)));
  142. /* Note that V8 prepends "ex.stack" with ex.toString(). */
  143. ret = 'EXCEPTION: ' + ex.constructor.name + ': ' + ex.stack;
  144. if (ex.cause && typeof (ex.cause) === 'function') {
  145. var cex = ex.cause();
  146. if (cex) {
  147. ret += '\nCaused by: ' + dumpException(cex);
  148. }
  149. }
  150. return (ret);
  151. }