-
Notifications
You must be signed in to change notification settings - Fork 0
/
cli.js
executable file
·124 lines (96 loc) · 2.47 KB
/
cli.js
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
#!/usr/bin/env node
'use strict';
var help = require('help-version')(usage()).help,
readmeToManPage = require('readme-to-man-page'),
readmeFilenames = require('readme-filenames'),
manPager = require('man-pager'),
npmExpansion = require('npm-expansion'),
findRoot = require('find-root'),
resolveFrom = require('resolve-from'),
minimist = require('minimist'),
npmPrefix = require('npm-prefix');
var fs = require('fs'),
path = require('path');
function usage () {
return 'Usage: readman [--global | -g] [<module>]';
}
function error (err) {
if (err) console.error(err.toString());
}
var opts = minimist(process.argv.slice(2), {
boolean: ['global'],
alias: {
global: 'g'
},
unknown: function (arg) {
if (arg[0] == '-') {
return help(1);
}
}
});
(function main (opts, argv) {
if (argv.length > 1) {
return help(1);
}
var name = argv[0];
var root;
if (name) {
try {
root = rootForPackageName(name, opts.global);
}
catch (err) {
return error(err);
}
}
else {
if (opts.global) {
return error(Error('--global expects an explicit module name.'));
}
try {
root = findRoot(process.cwd());
}
catch (err) {
root = process.cwd();
}
}
readReadme(root, error);
}(opts, opts._));
function rootForPackageName (name, global) {
var basedir = global ? path.join(npmPrefix(), 'lib') : process.cwd();
var resolve = resolveFrom.bind(null, basedir);
// Clarify error message if package is missing.
resolve(name);
return path.dirname(resolve(path.join(name, 'package.json')));
}
function readReadme (root, cb) {
var pkg;
try {
pkg = require(path.join(root, 'package.json'));
}
catch (err) {}
fs.readdir(root, function (err, files) {
if (err) return cb(err);
var readmes = files.filter(function (filename) {
return readmeFilenames.indexOf(filename) >= 0;
});
if (readmes.length != 1) {
return error(Error('Readme not found.'));
}
displayReadme(pkg, path.join(root, readmes[0]), cb);
});
}
function displayReadme (pkg, readmePath, cb) {
fs.readFile(readmePath, 'utf8', function (err, readme) {
if (err) return cb(err);
var manPage = readmeToManPage(readme, pkg ? {
name: pkg.name,
version: pkg.version,
description: pkg.description,
section: 'npm',
manual: npmExpansion()
} : {
name: path.basename(process.cwd())
});
manPager().end(manPage);
});
}