-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathcli.js
362 lines (331 loc) · 11.7 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
352
353
354
355
356
357
358
359
360
361
362
'use strict';
var async = require('async');
var cleancss = require('clean-css');
var spawn = require('child_process').spawn;
var findit = require('findit');
var fs = require('fs');
var jade = require('jade');
var marked = require('marked');
var mkdirp = require('mkdirp');
var path = require('path');
var uglifyjs = require('uglify-js');
var util = require('util');
var styledocco = require('./styledocco');
var version = require('./package').version;
marked.setOptions({ sanitize: false, gfm: true });
// Helper functions
var mincss = function(css) { return cleancss.process(css); };
var minjs = uglifyjs;
var pluck = function(arr, prop) {
return arr.map(function(item) { return item[prop]; });
};
var isType = function(o, type) {
return Object.prototype.toString.call(o) === '[object ' + type + ']';
};
var flatten = function(arr) {
return arr.reduce(function(tot, cur) {
return tot.concat(isArray(cur) ? flatten(cur) : cur);
}, []);
};
var inArray = function(arr, str) { return arr.indexOf(str) !== -1; };
var isArray = function(obj) { return isType(obj, 'Array'); };
var isString = function(obj) { return isType(obj, 'String'); };
var urlsRelative = function(css, path) {
if (isString(css) && isString(path)) {
path = path.indexOf('/', path.length -1) > -1? path : path + '/';
var regex = /(url\(["']?)(?!https?:|data:)([^/'"][\w/.]*)/gm;
return css.replace(regex, "$1" + path + "$2");
} else {
throw new Error('1st and 2nd args must be strings.');
}
};
var dirUp = function(steps) {
if ( ! steps) return '';
var str = '';
for (var i = 0; i < steps; ++i) {
str += '../';
}
return str;
};
// Get a filename without the extension
var baseFilename = function(str) {
return path.basename(str, path.extname(str)).replace(/^_/, '');
};
var basePathname = function(file, basePath) {
return path.join(
path.dirname(path.relative(basePath, file) || path.basename(basePath)),
baseFilename(file)
);
};
// Build an HTML file name, named by it's path relative to basePath
var htmlFilename = function(file, basePath) {
return path.join(
path.dirname(path.relative(basePath, file) || path.basename(basePath)),
baseFilename(file) + '.html'
).replace(/[\\/]/g, '-');
};
// Find first file matching `re` in `dir`.
var findFile = function(dir, re, cb) {
fs.stat(dir, function(err, stat) {
var files = fs.readdir(dir, function(err, files) {
files = files.sort().filter(function(file) { return file.match(re); });
if (!files.length) cb(new Error('No file found.'));
else cb(null, path.join(dir, files[0]));
});
});
};
var getFiles = function(inPath, cb) {
fs.stat(inPath, function(err, stat) {
if (err != null) return cb(err);
if (stat.isFile()) {
cb(null, [ inPath ]);
} else {
var finder = findit(inPath);
var files = [];
finder.on('file', function(file) { files.push(file); });
finder.on('end', function() { cb(null, files); });
}
});
};
// Make `link` objects for the menu.
var menuLinks = function(files, basePath) {
return files.map(function(file) {
var parts = path.dirname(file).split(path.sep);
parts.shift(); // Remove base directory name
return {
name: baseFilename(file),
href: htmlFilename(file, basePath),
directory: parts[parts.length-1] || './'
};
})
.reduce(function(links, link) {
if (links[link.directory] != null) {
links[link.directory].push(link);
} else {
links[link.directory] = [ link ];
}
return links;
}, {});
};
var preprocess = function(file, pp, options, cb) {
// stdin would have been nice here, but not all preprocessors (less)
// accepts that, so we need to read the file both here and for the parser.
// Don't process SASS partials.
if (file.match(/(^|\/)_.*\.s(c|a)ss$/) != null) {
process.nextTick(function() { cb(null, ''); });
} else if (pp != null) {
pp += ' ';
pp += file;
pp = pp.split(' ');
pp = spawn(pp.shift(), pp);
pp.stderr.setEncoding('utf8');
pp.stdout.setEncoding('utf8');
var stdout = '';
pp.on('error', function(err) {
if (err != null && options.verbose) console.error(err.message);
});
pp.on('close', function() {
cb(null, stdout);
});
pp.stderr.on('data', function(data) {
if (data.length && options.verbose) console.error(data);
});
pp.stdout.on('data', function(data) {
stdout += data;
});
} else {
fs.readFile(file, 'utf8', cb);
}
};
var cli = function(options) {
var errorMessages = { noFiles: 'No css files found' };
var resourcesDir = __dirname + '/share/';
// Filetypes and matching preprocessor binaries.
var fileTypes = {
'.css': null,
'.sass': 'sass',
'.scss': 'scss',
'.less': 'lessc',
'.styl': 'stylus'
};
var log = options.verbose ? function(str) { console.log(str); }
: function() {};
// Custom error also outputing StyleDocco and Node versions.
var SDError = function(msg, err) {
this.message = msg + '\n' + err.message + '\n' +
'StyleDocco v' + version +
' running on Node ' + process.version + ' ' + process.platform;
if (options.verbose) {
this.message += '\nOptions: ' + JSON.stringify(options);
}
};
util.inherits(SDError, Error);
mkdirp(options.out);
// Fetch all static resources.
async.parallel({
template: function(cb) {
fs.readFile(resourcesDir + 'docs.jade', 'utf8', function(err, contents) {
if (err != null) return cb(err);
cb(null, jade.compile(contents));
});
},
docs: function(cb) {
async.parallel({
css: async.apply(fs.readFile, resourcesDir + 'docs.css', 'utf8'),
js: function(cb) {
async.parallel([
async.apply(fs.readFile, resourcesDir + 'docs.ui.js', 'utf8'),
async.apply(fs.readFile, resourcesDir + 'docs.previews.js', 'utf8')
], function(err, res) {
if (err != null) return cb(err);
cb(null, res.join(''));
});
}
}, cb);
},
// Extra JavaScript and CSS files to include in previews.
previews: function(cb) {
fs.readFile(resourcesDir + 'previews.js', 'utf8', function(err, js) {
if (err != null) return cb(err);
var code = { js: js, css: '' };
var files = options.include.filter(function(file) {
return inArray(['.css', '.js'], path.extname(file));
});
async.filter(files, fs.exists, function(files) {
async.reduce(files, code, function(tot, cur, cb) {
fs.readFile(cur, 'utf8', function(err, contents) {
if (err != null) return cb(err);
tot[path.extname(cur).slice(1)] += contents;
cb(null, tot);
});
}, cb);
});
});
},
// Find input files.
files: function(cb) {
async.reduce(options['in'], [], function(all, cur, cb) {
getFiles(cur, function(err, files) {
if (err != null) return cb(err);
cb(null, all.concat(files));
});
}, function(err, files) {
if (err != null) return cb(err);
files = files.filter(function(file) {
// No hidden files
if (file.match(/(\/|^)\.[^\.\/]/)) return false;
// Only supported file types
if (!(path.extname(file) in fileTypes)) return false;
return true;
}).sort();
if (!files.length) cb(new Error(errorMessages.noFiles + ' in path "' + options['in'] + '"'));
cb(null, files);
});
},
// Look for a README file.
readme: function(cb) {
findFile(options.basePath, /^readme\.m(ark)?d(own)?/i, function(err, file) {
if (file != null && err == null) return read(file);
findFile(process.cwd(), /^readme\.m(ark)?d(own)?/i, function(err, file) {
if (err != null) file = resourcesDir + 'README.md';
read(file);
});
});
var read = function(file) {
fs.readFile(file, 'utf8', function(err, content) {
if (err != null) cb(err);
cb(null, content);
});
};
}
}, function(err, resources) {
if (err != null) {
if (err.message.indexOf(errorMessages.noFiles) > -1) {
console.error(err);
return;
} else {
throw new SDError('Could not process files.', err);
}
}
var menu = menuLinks(resources.files, options.basePath);
// Run files through preprocessor and StyleDocco parser.
async.map(resources.files, function(file, cb) {
async.parallel({
css: async.apply(preprocess, file,
options.preprocessor || fileTypes[path.extname(file)], options),
docs: function(cb) {
fs.readFile(file, 'utf8', function(err, code) {
if (err != null) return cb(err);
cb(null, styledocco(code));
});
}
}, function(err, data) {
if (err != null) return cb(err);
data.path = file;
cb(null, data);
});
}, function(err, files) {
if (err != null) throw err;
// Get the combined CSS from all files.
var previewStyles = pluck(files, 'css').join('');
previewStyles += resources.previews.css;
// Build a JSON string of all files and their headings, for client side search.
var searchIndex = flatten(files.map(function(file) {
var arr = [ { title: baseFilename(file.path),
filename: basePathname(file.path, options.basePath),
url: htmlFilename(file.path, options.basePath) } ];
return arr.concat(file.docs.map(function(section) {
return { title: section.title,
filename: basePathname(file.path, options.basePath),
url: htmlFilename(file.path, options.basePath) + '#' + section.slug };
}));
}));
searchIndex = 'var searchIndex=' + JSON.stringify(searchIndex) + ';';
var processJS = function(src) { return options.minify ? minjs(src) : src; };
var processCSS = function(src) { return options.minify ? mincss(src) : src; };
var docsScript = '(function(){' + searchIndex + resources.docs.js + '})();';
// Render files
var htmlFiles = files.map(function(file) {
var relativePath = file.path.split('/');
relativePath.pop();
relativePath = dirUp(options.out.split('/').length) + relativePath.join('/');
return {
path: file.path,
html: resources.template({
title: baseFilename(file.path),
sections: file.docs,
project: { name: options.name, menu: menu },
resources: {
docs: { js: processJS(docsScript), css: processCSS(resources.docs.css) },
previews: { js: processJS(resources.previews.js), css: processCSS(urlsRelative(previewStyles, relativePath)) }
}
})
};
});
// Add readme with "fake" index path.
htmlFiles.push({
path: path.join(options.basePath, 'index'),
html: resources.template({
title: '',
sections: styledocco.makeSections([{ docs: resources.readme, code: '' }]),
project: { name: options.name, menu: menu },
resources: {
docs: { js: processJS(docsScript), css: processCSS(resources.docs.css) }
}
})
});
// Write files to the output dir.
htmlFiles.forEach(function(file) {
var dest = path.join(options.out, htmlFilename(file.path, options.basePath));
log('styledocco: writing ' + file.path + ' -> ' + dest);
fs.writeFileSync(dest, file.html);
});
});
});
};
module.exports = cli;
module.exports.htmlFilename = htmlFilename;
module.exports.menuLinks = menuLinks;
module.exports.urlsRelative = urlsRelative;
module.exports.preprocess = preprocess;
module.exports.getFiles = getFiles;