-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.js
132 lines (112 loc) · 2.79 KB
/
index.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
"use strict";
/* globals require, module */
const fs = require("fs");
const path = require("path");
const mkdirp = require("mkdirp");
const through2 = require("through2");
const assign = require("object-assign");
const fileRegister = require("text-file-register");
const parser = require("./lib/parser.js");
/**
* Pug Documentation generator
* returns a JSON stream
* optionally writes a JSON array containing
* all docs to an output file.
*/
function pugDoc(options) {
if (typeof options === "undefined") {
throw new Error("Pug doc requires a settings object.");
}
if (typeof options.input === "undefined") {
throw new Error("Pug doc requires settings.input to be set.");
}
// options
options = assign(
{
input: null,
output: null,
locals: {},
complete: function () {},
},
options
);
let counter = 0;
// register files
const register = fileRegister();
register.addFiles(options.input, init);
// create readable stream
const stream = through2(
{ objectMode: true },
function (chunk, enc, next) {
this.push(chunk);
next();
},
function (cb) {
cb();
}
);
let output;
/**
* Init
*/
function init() {
// write stream to output file
if (options.output) {
// create directory if it doesn't exist
mkdirp.sync(path.dirname(options.output));
// create writable stream
output = fs.createWriteStream(options.output);
output.write("[");
output.on("close", function () {
stream.emit("complete");
});
output.on("finish", function () {
if (options.complete && typeof options.complete === "function") {
options.complete();
}
});
}
// get all pug files
const files = register.getAll();
let file;
// collect docs for all files
for (file in files) {
let pugDocDocuments = parser.getPugdocDocuments(
files[file],
file,
options.locals
);
pugDocDocuments
.filter(function (docItem) {
return Boolean(docItem);
})
.forEach(function (docItem) {
// omit first comma
if (counter !== 0 && options.output) {
output.write(",");
}
// add object to stream
stream.push(docItem);
if (options.output) {
// send to output
output.write(JSON.stringify(docItem));
}
// up counter
++counter;
});
}
// end json array stream
if (options.output) {
output.write("]");
output.end();
} else {
if (options.complete && typeof options.complete === "function") {
options.complete();
}
}
// end stream
stream.push(null);
}
return stream;
}
module.exports = pugDoc;