forked from get-alex/alex
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cli.js
executable file
·351 lines (295 loc) · 7.99 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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
#!/usr/bin/env node
/**
* @author Titus Wormer
* @copyright 2015 Titus Wormer
* @license MIT
* @module alex
* @fileoverview CLI for alex.
*/
'use strict';
/* eslint-env node */
/* eslint-disable no-console */
/* jscs:disable requireVarDeclFirst */ /* Buggy with shebang */
/*
* Dependencies.
*/
var fs = require('fs');
var bail = require('bail');
var notifier = require('update-notifier');
var meow = require('meow');
var globby = require('globby');
var hasMagic = require('glob').hasMagic;
var minimatch = require('minimatch');
var getStdin = require('get-stdin');
var findDown = require('vfile-find-down');
var findUp = require('vfile-find-up');
var format = require('vfile-reporter');
var toFile = require('to-vfile');
var alex = require('./');
var pack = require('./package');
/*
* Methods.
*/
var readFile = fs.readFileSync;
var stat = fs.statSync;
/*
* Constants.
*/
var expextPipeIn = !process.stdin.isTTY;
var IGNORE = '.alexignore';
var RC = '.alexrc';
var PACKAGE = 'package.json';
var PACKAGE_FIELD = 'alex';
var ENCODING = 'utf-8';
var BACKSLASH = '\\';
var SLASH = '/';
var CD = './';
var HASH = '#';
var EMPTY = '';
var defaultIgnore = [
'node_modules/',
'bower_components/'
];
var extensions = [
'txt',
'text',
'md',
'markdown',
'mkd',
'mkdn',
'mkdown',
'ron'
];
/*
* Update messages.
*/
notifier({
'pkg': pack
}).notify();
/*
* Set-up meow.
*/
var cli = meow({
'help': [
'Usage: alex [<file> | <dir> ...] [-w, --why] [-t, --text]',
'',
'Options:',
'',
' -w, --why output more info regarding why things might be ' +
'offensive',
' -t, --text treat input as plain-text (not markdown)',
'',
'When no input files are given, searches for markdown and text',
'files in the current directory, `doc`, and `docs`.',
'',
'Examples',
' $ echo "His network looks good" | alex',
' $ alex *.md !example.md',
' $ alex'
]
});
/*
* Set-up.
*/
var exit = 0;
var result = [];
var why = Boolean(cli.flags.w || cli.flags.why);
var fn = (cli.flags.t || cli.flags.text) ? 'text' : 'markdown';
var globs = cli.input.length ? cli.input : [
'{docs/**/,doc/**/,}*.{' + extensions.join(',') + '}'
];
/*
* Exit.
*/
process.on('exit', function () {
console.log(format(result, {
'verbose': why
}));
process.exit(exit);
});
/**
* Log a virtual file processed by alex.
*
* @param {VFile} file - Virtual file.
*/
function log(file) {
result.push(file);
if (!exit && file.messages.length) {
exit = 1;
}
}
/**
* Check if `file` matches `pattern`.
*
* @example
* match('baz.md', '*.md'); // true
*
* @param {string} filePath - File location.
* @param {string} pattern - Glob pattern.
* @return {boolean} - Whether `file` matches.
*/
function match(filePath, pattern) {
return minimatch(filePath, pattern) ||
minimatch(filePath, pattern + '/**');
}
/**
* Check if `filePath` is matched included in `patterns`.
*
* @example
* shouldIgnore(['node_modules/'], 'node_modules/foo'); // true
*
* @param {Array.<string>} patterns - Glob patterns.
* @param {string} filePath - File location.
* @return {boolean} - Whether `filePath` should be ignored.
*/
function shouldIgnore(patterns, filePath) {
var normalized = filePath.replace(BACKSLASH, SLASH).replace(CD, EMPTY);
return patterns.reduce(function (isIgnored, pattern) {
var isNegated = pattern.charAt(0) === '!';
if (isNegated) {
pattern = pattern.slice(1);
}
if (pattern.indexOf(CD) === 0) {
pattern = pattern.slice(CD.length);
}
return match(normalized, pattern) ? !isNegated : isIgnored;
}, false);
}
/**
* Load an ignore file.
*
* @param {string} ignore - File location.
* @return {Array.<string>} - Patterns.
*/
function loadIgnore(ignore) {
return readFile(ignore, ENCODING).split(/\r?\n/).filter(function (value) {
var line = value.trim();
return line.length && line.charAt(0) !== HASH;
});
}
/**
* Factory to create a file filter based on bound ignore
* patterns.
*
* @param {Array.<string>} ignore - Ignore patterns.
* @param {Array.<string>} given - List of given file paths.
* @return {Function} - Filter.
*/
function filterFactory(ignore, given) {
/**
* Check whether a virtual file is applicable.
*
* @param {VFile} file - Virtual file.
*/
return function (file) {
var filePath = file.filePath();
var extension = file.extension;
if (given.indexOf(filePath) !== -1 || shouldIgnore(ignore, filePath)) {
return findDown.SKIP;
}
return extension && extensions.indexOf(extension) !== -1;
};
}
/**
* Factory to create a file filter based on bound ignore
* patterns.
*
* @param {Array.<VFile>} given - List of given files.
* @param {Array.<string>} allow - List of allowed phrases.
* @return {Function} - Process callback.
*/
function processFactory(given, allow) {
/**
* Process all found files (and failed ones too).
*
* @param {Error} [err] - Finding error (not used by
* vfile-find-down).
* @param {Array.<VFile>} [files] - Virtual files.
*/
return function (err, files) {
given.concat(files || []).forEach(function (file) {
file.quiet = true;
try {
file.contents = readFile(file.filePath(), ENCODING);
} catch (err) {
file.fail(err);
}
alex[fn](file, allow);
log(file);
});
};
}
/*
* Either handle stdin(4) or patterns.
*/
if (!cli.input.length && expextPipeIn) {
getStdin().then(function (value) {
var file = toFile('<stdin>');
file.contents = value;
alex(file);
log(file);
}, bail);
} else {
globby(globs).then(function (filePaths) {
var files = [];
var given = [];
/*
* Check whether files are given directly that either
* do not exist or which might not match the default
* search patterns (based on extensions).
*/
globs.forEach(function (glob) {
if (hasMagic(glob)) {
return;
}
files.push(toFile(glob));
given.push(glob);
try {
if (!stat(glob).isFile()) {
files.pop();
given.pop();
}
} catch (err) { /* Empty. */ }
});
/*
* Search for an ignore file.
*/
findUp.one(IGNORE, function (err, file) {
var ignore = [];
try {
ignore = file && loadIgnore(file.filePath());
} catch (err) { /* Empty. */ }
ignore = defaultIgnore.concat(ignore || []);
/*
* Search for rc files.
*/
findUp.all([PACKAGE, RC], function (err, configs) {
var allow = [];
var length = configs && configs.length;
var index = -1;
var file;
var contents;
while (++index < length) {
file = configs[index];
file.contents = readFile(file.filePath(), ENCODING);
file.quiet = true;
try {
contents = JSON.parse(file.contents);
if (file.basename() === PACKAGE) {
contents = contents[PACKAGE_FIELD] || {};
}
allow = [].concat.apply(allow, contents.allow);
} catch (err) {
file.warn(err);
files.push(file);
}
}
findDown.all(
filterFactory(ignore, given),
filePaths,
processFactory(files, allow)
);
});
});
}, bail);
}