Initial commit
[yaffs-website] / node_modules / meow / index.js
1 'use strict';
2 var path = require('path');
3 var minimist = require('minimist');
4 var objectAssign = require('object-assign');
5 var camelcaseKeys = require('camelcase-keys');
6 var decamelize = require('decamelize');
7 var mapObj = require('map-obj');
8 var trimNewlines = require('trim-newlines');
9 var redent = require('redent');
10 var readPkgUp = require('read-pkg-up');
11 var loudRejection = require('loud-rejection');
12 var normalizePackageData = require('normalize-package-data');
13
14 // get the uncached parent
15 delete require.cache[__filename];
16 var parentDir = path.dirname(module.parent.filename);
17
18 module.exports = function (opts, minimistOpts) {
19         loudRejection();
20
21         if (Array.isArray(opts) || typeof opts === 'string') {
22                 opts = {help: opts};
23         }
24
25         opts = objectAssign({
26                 pkg: readPkgUp.sync({
27                         cwd: parentDir,
28                         normalize: false
29                 }).pkg,
30                 argv: process.argv.slice(2)
31         }, opts);
32
33         minimistOpts = objectAssign({}, minimistOpts);
34
35         minimistOpts.default = mapObj(minimistOpts.default || {}, function (key, value) {
36                 return [decamelize(key, '-'), value];
37         });
38
39         if (Array.isArray(opts.help)) {
40                 opts.help = opts.help.join('\n');
41         }
42
43         var pkg = typeof opts.pkg === 'string' ? require(path.join(parentDir, opts.pkg)) : opts.pkg;
44         var argv = minimist(opts.argv, minimistOpts);
45         var help = redent(trimNewlines(opts.help || ''), 2);
46
47         normalizePackageData(pkg);
48
49         process.title = pkg.bin ? Object.keys(pkg.bin)[0] : pkg.name;
50
51         var description = opts.description;
52         if (!description && description !== false) {
53                 description = pkg.description;
54         }
55
56         help = (description ? '\n  ' + description + '\n' : '') + (help ? '\n' + help : '\n');
57
58         var showHelp = function (code) {
59                 console.log(help);
60                 process.exit(code || 0);
61         };
62
63         if (argv.version && opts.version !== false) {
64                 console.log(typeof opts.version === 'string' ? opts.version : pkg.version);
65                 process.exit();
66         }
67
68         if (argv.help && opts.help !== false) {
69                 showHelp();
70         }
71
72         var _ = argv._;
73         delete argv._;
74
75         return {
76                 input: _,
77                 flags: camelcaseKeys(argv),
78                 pkg: pkg,
79                 help: help,
80                 showHelp: showHelp
81         };
82 };