random 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #!/usr/bin/env node
  2. "use strict";
  3. /*
  4. https://github.com/visionmedia/commander.js
  5. http://visionmedia.github.io/commander.js/
  6. https://github.com/visionmedia/commander.js/tree/master/examples
  7. sudo npm install ./ -g
  8. */
  9. var path = require('path')
  10. var program = require('commander')
  11. var pkg = require(path.resolve(__dirname, '../package.json'))
  12. var Random = require('../dist/mock.js').Random
  13. program
  14. .version(pkg.version)
  15. .on('--help', function() {
  16. console.log(' Examples:')
  17. console.log('')
  18. console.log(' $ random date yyyy-MM-dd')
  19. console.log(' $ random time HH:mm:ss')
  20. console.log('')
  21. })
  22. ;
  23. (function() {
  24. var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m
  25. var FN_ARG_SPLIT = /,/
  26. var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/
  27. var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg
  28. var EXCLUDE = [
  29. 'extend',
  30. 'dataImage', // mock/random/image
  31. 'capitalize', 'upper', 'lower', 'pick', 'shuffle', 'order', // mock/random/helper.js
  32. 'increment', 'inc' // mock/random/misc.js
  33. ]
  34. function parseArgs(fn) {
  35. var fnText = fn.toString().replace(STRIP_COMMENTS, '')
  36. var argDecl = fnText.match(FN_ARGS)
  37. return argDecl[1].split(FN_ARG_SPLIT).join(', ')
  38. }
  39. Object.keys(Random).forEach(function(key) {
  40. if (key[0] === '_') return
  41. if (EXCLUDE.indexOf(key) !== -1) return
  42. var fn = Random[key]
  43. if (typeof fn === 'function') {
  44. var argDecl = parseArgs(fn)
  45. if (argDecl) argDecl = '( ' + argDecl + ' )'
  46. else argDecl = '()';
  47. program
  48. .command(key)
  49. .description('Random.' + key + argDecl)
  50. .action(function() {
  51. var args = [].slice.call(arguments, 0, -1)
  52. var result = fn.apply(Random, args)
  53. console.log(result)
  54. })
  55. }
  56. })
  57. })()
  58. program.parse(process.argv)
  59. ;
  60. (function() {
  61. var cmd = program.args[0]
  62. if (!cmd) {
  63. process.stdout.write(program.helpInformation())
  64. program.emit('--help')
  65. process.exit()
  66. }
  67. })()