-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathreadmetree.js
96 lines (77 loc) · 2.51 KB
/
readmetree.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
var fs = require('fs')
var path = require('path')
var marked = require('marked')
var highlight = require('highlight.js')
var special = require('special-html')
var glob = require('glob')
var style = fs.readFileSync(path.join(__dirname, 'assets', 'style.css'), 'utf8')
var nav = fs.readFileSync(path.join(__dirname, 'assets', 'nav.html'), 'utf8')
module.exports = ReadmeTree
function ReadmeTree(root) {
this.root = root || process.cwd()
this.root = path.resolve(process.cwd(), this.root)
this.content = {
'/': style
+ '<br><h1><a href="https://github.com/dtrejo/readmetree">readmetree</a><h1>'
}
marked.setOptions({
highlight: function (code) {
return highlight.highlightAuto(code).value
}
})
return this
}
ReadmeTree.prototype.setup = function setup(callback) {
var self = this
glob('**/readme.m*', { cwd: self.root, nocase: true }, renderFiles)
function renderFiles(err, files) {
if (err) {
console.error(err)
return process.exit(1)
}
var fileCount = files.length
files = files.sort(function(a, b) {
var aa = path.basename(path.dirname(a)).toLowerCase()
var bb = path.basename(path.dirname(b)).toLowerCase()
return aa.localeCompare(bb)
})
.forEach(function(readme) {
var shortpath = path.sep + readme.split(path.sep).slice(-2).join(path.sep)
var moduleName = shortpath.split(path.sep)[1]
if (shortpath.lastIndexOf(path.sep) === 0) {
moduleName = path.basename(self.root)
}
if (self.content[shortpath]) return --fileCount
self.content['/'] +=
'<br><a href="'+shortpath+'">'
+ moduleName + '</a>'
self.content[shortpath] = style + nav
loadReadme(path.resolve(self.root, readme), shortpath, moduleName)
})
function loadReadme(readme, shortpath, name) {
fs.readFile(readme, 'utf8', render)
function render(err, contents) {
if (err) {
return callback(err)
}
marked(contents, addReadme)
}
function addReadme(err, html) {
if (err) {
return callback(err)
}
self.content[shortpath] += special(html)
if (--fileCount === 0) {
callback(null, Object.keys(self.content).length)
}
}
}
}
}
ReadmeTree.prototype.serveRequest = function onRequest(req, res) {
if (!this.content.hasOwnProperty(req.url)) {
return res.end('<h1>404z dude.</h1>' + this.content['/'])
}
res.setHeader('content-type', 'text/html')
return res.end(this.content[req.url])
}