Blame view

node_modules/mockjs/bin/random 2.13 KB
aaac7fed   liuqimichale   add
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
  #!/usr/bin/env node
  
  "use strict";
  
  /*
      https://github.com/visionmedia/commander.js
      http://visionmedia.github.io/commander.js/
      https://github.com/visionmedia/commander.js/tree/master/examples
  
      sudo npm install ./ -g
  */
  
  var path = require('path')
  var program = require('commander')
  var pkg = require(path.resolve(__dirname, '../package.json'))
  var Random = require('../dist/mock.js').Random
  
  program
      .version(pkg.version)
      .on('--help', function() {
          console.log('  Examples:')
          console.log('')
          console.log('    $ random date yyyy-MM-dd')
          console.log('    $ random time HH:mm:ss')
          console.log('')
      })
  
  ;
  (function() {
  
      var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m
      var FN_ARG_SPLIT = /,/
      var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/
      var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg
      var EXCLUDE = [
          'extend',
          'dataImage', // mock/random/image
          'capitalize', 'upper', 'lower', 'pick', 'shuffle', 'order', // mock/random/helper.js
          'increment', 'inc' // mock/random/misc.js
      ]
  
      function parseArgs(fn) {
          var fnText = fn.toString().replace(STRIP_COMMENTS, '')
          var argDecl = fnText.match(FN_ARGS)
          return argDecl[1].split(FN_ARG_SPLIT).join(', ')
      }
  
      Object.keys(Random).forEach(function(key) {
          if (key[0] === '_') return
          if (EXCLUDE.indexOf(key) !== -1) return
  
          var fn = Random[key]
          if (typeof fn === 'function') {
              var argDecl = parseArgs(fn)
              if (argDecl) argDecl = '( ' + argDecl + ' )'
              else argDecl = '()';
  
              program
                  .command(key)
                  .description('Random.' + key + argDecl)
                  .action(function() {
                      var args = [].slice.call(arguments, 0, -1)
                      var result = fn.apply(Random, args)
                      console.log(result)
                  })
          }
      })
  
  })()
  
  program.parse(process.argv)
  
  ;
  (function() {
      var cmd = program.args[0]
      if (!cmd) {
          process.stdout.write(program.helpInformation())
          program.emit('--help')
          process.exit()
      }
  })()