-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
432 lines (379 loc) · 16 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
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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
const glob = require('glob')
const fs = require('fs')
const { map, filter, isNil, isString, trim, trimChars, zip, fromPairs, set, get, find, reduce, has, toPairs, every, forEach, isObject, forOwn } = require('lodash/fp')
const HMP = require('hm-parser')
const { inspect } = require('util')
const babylon = require('babylon')
const handlebars = require('handlebars')
const debug = require('debug')('hm-doc')
const getDescription =
get('description')
const legitDescription = o =>
isString(getDescription(o))
&& getDescription(o).length > 0
const parsedCommentToMarkdown = comment => {
const base = `## .${get('hmParsed.name', comment)}
\`${get('signature', comment)}\``
if(legitDescription(comment)) {
return `${base}
${getDescription(comment)}`
}
return base
}
const combineComments = filename => comments =>
reduce(
(commentsString, comment) =>
`${commentsString}\n${parsedCommentToMarkdown(comment)}`,
`## ${filename}\n\n`,
comments
)
const registerResult = handlebars.registerHelper('hmdoc', (items, options) =>
reduce(
(acc, [filename, comments] ) =>
combineComments(filename)(comments),
'',
toPairs(get('data.root', items))
)
)
const loadFilenames = stringGlob => options =>
debug("loadFilenames, stringGlob:", stringGlob, ", options:", options) ||
new Promise((success, failure) =>
glob(stringGlob, options, (err, files) =>
debug("loadFilenames result, err: %o, files: %O", err, files) ||
err
? failure(err)
: success(files)
)
)
const truncateChars = o =>
o.substring(0, 20)
const addElipsesIfBig = o =>
o.length >= 20
? `${o} ...`
: o
const truncateText = o =>
isString(o)
? addElipsesIfBig(truncateChars(o))
: o
const readFile = filename =>
debug("readFile, filename: %o", filename) ||
new Promise((success, failure) =>
fs.readFile(filename, (err, data) =>
err
? failure(err)
: success(data.toString())
)
)
const log = o => console.log(inspect(o, {depth: 8, colors: true}))
const parseCode = code => { // eslint-disable-line fp-jxl/no-nil
try {
debug("parseCode, code:", truncateText(code)) // eslint-disable-line fp-jxl/no-unused-expression
const data = babylon.parse(code)
debug("parseCode, successfully parsed via babylon.") // eslint-disable-line fp-jxl/no-unused-expression
return Promise.resolve(data)
} catch(error) {
debug("parseCode failed, error: %O", error) // eslint-disable-line fp-jxl/no-unused-expression
return Promise.reject(error)
}
}
const getProgramBody = get('program.body')
const getComments =
map(
get('leadingComments')
)
const getCleanedComments =
filter(
item => isNil(item) === false
)
const findCommentBlock =
find(
item => get('type', item) === 'CommentBlock'
)
const findCommentLine =
find(
item => get('type', item) === 'CommentLine'
)
const toTypeAndDocumentationPair =
map(
item => ({ hm: findCommentLine(item), description: findCommentBlock(item) })
)
const stripAST =
map(
item => ({ hm: get('hm.value', item), description: get('description.value', item) })
)
const trimmedStars =
map(
item => set('hm', trimChars('*', get('hm', item)), item)
)
const trimmedWhitespace =
map(
item => set('hm', trim(get('hm', item)), item)
)
const safeHMPParse = string => { // eslint-disable-line fp-jxl/no-nil
try {
const data = HMP.parse(string)
return { ok: true, data }
} catch(error) {
return { ok: false, error }
}
}
// [jwarden 10.3.2018] TODO/FIXME: Should look at proceeding line as random 1 line comments will break lol.
// For now, will attempt to if see it's parseable. If not, return state that it should be disposed of.
const parsedComments =
map(
item => {
const { ok, data, error } = safeHMPParse(get('hm', item))
if(ok) {
return set('hmParsed', data, item)
}
return set('hmParseFailure', error, item)
}
)
const removeFailedCommentParsing =
filter(
item => has('hmParseFailure', item) === false
)
const typeSignaturesAttached =
map(
item => set('signature', trim(get('hm', item).split('::')[1]), item)
)
const filterFailedParsing =
filter(
item => isNil(item) === false
)
// [jwarden 11.12.2018] TODO: Figure out how to support specific number tapConsoles, like tapConsole2, tapConsole3, etc.
const tapConsole = label => (...args) => { // eslint-disable-line fp-jxl/no-rest-parameters
console.log.apply(console, [`${label}:`, ...args]) // eslint-disable-line fp-jxl/no-unused-expression
return Promise.resolve.apply(Promise, args)
}
// [jwarden 11.12.2018] TODO: Figure out how to support specific number tapDebug, like tapDebug2, tapDebug3, etc.
const tapDebug = label => (...args) => { // eslint-disable-line fp-jxl/no-rest-parameters
// debug.apply(debug, [label, ...args])
debug(label) // eslint-disable-line fp-jxl/no-unused-expression
return Promise.resolve.apply(Promise, args)
}
// [jwarden 11.12.2018] TODO: Figure out how to support specific number tapDebug, like tapDebugAndShowArgs2, tapDebugAndShowArgs3, etc.
const tapDebugAndShowArgs = label => (...args) => { // eslint-disable-line fp-jxl/no-rest-parameters
debug.apply(debug, [label, ...args]) // eslint-disable-line fp-jxl/no-unused-expression
return Promise.resolve.apply(Promise, args)
}
// [jwarden 10.3.2018] NOTE: We're basically finding all comments in the file, and assuming they might possibly be what we're looking for.
// That is probably not the case, heh, so sometimes HMP will fail, or won't fail but it isn't a Hindley-Milner comment for example.
// I believe JSDocs uses the "slash star star" to recognize the start of a JSDoc block comment. I didn't want to introduce another
// commenting format, and rather, keep what developers know. SO... until we get better at parsing the AST Bablylon gives us,
// we'll just have to add verification steps like this.
const okLookingHM = o =>
isString(get('hm', o))
&& get('hm', o).length > 0
const hmParsedSuccessfully = o =>
isObject(get('hmParsed', o))
const okLookingSignature = o =>
isString(get('signature', o))
&& get('signature', o).length > 0
const legitParsedComment = parsedComment =>
every(
predicate => predicate(parsedComment),
[
okLookingHM,
hmParsedSuccessfully,
okLookingSignature
]
)
const filterLegitParsedComments = filter(legitParsedComment)
const codeToMarkdown = code =>
tapDebug("codeToMarkdown start...")()
.then(() => Promise.resolve(code))
.then(tapDebug("codeToMarkdown, parsing code..."))
.then(parseCode)
.then(tapDebug("codeToMarkdown, getProgramBody..."))
.then(getProgramBody)
.then(tapDebug("codeToMarkdown, getComments..."))
.then(getComments)
.then(tapDebug("codeToMarkdown, getCleanedComments..."))
.then(getCleanedComments)
.then(tapDebug("codeToMarkdown, toTypeAndDocumentationPair..."))
.then(toTypeAndDocumentationPair)
.then(tapDebug("codeToMarkdown, stripAST..."))
.then(stripAST)
.then(tapDebug("codeToMarkdown, trimmedStars..."))
.then(trimmedStars)
.then(tapDebug("codeToMarkdown, trimmedWhitespace..."))
.then(trimmedWhitespace)
.then(tapDebug("codeToMarkdown, parsedComments..."))
.then(parsedComments)
.then(tapDebug("codeToMarkdown, removeFailedCommentParsing..."))
.then(removeFailedCommentParsing)
.then(tapDebug("codeToMarkdown, typeSignaturesAttached..."))
.then(typeSignaturesAttached)
.then(tapDebug("codeToMarkdown, filterFailedParsing..."))
.then(filterFailedParsing)
.then(tapDebug("codeToMarkdown, filterFailedParsing..."))
.then(filterLegitParsedComments)
.then(tapDebugAndShowArgs("codeToMarkdown, filterLegitParsedComments done"))
.then(tapDebug("codeToMarkdown, done."))
const cleanEmptyResults = filesObject => {
debug("cleanEmptyResults, start:", filesObject) // eslint-disable-line fp-jxl/no-unused-expression
const filenames = Object.keys(filesObject)
const cleanedObject = reduce(
(acc, filename) => {
const parsedComments = get([filename], filesObject)
if(parsedComments.length > 0) {
return {...acc, [filename]: parsedComments}
}
return acc
}
, {}
, filenames
)
debug("cleanEmptyResults, end:", cleanedObject) // eslint-disable-line fp-jxl/no-unused-expression
return cleanedObject
}
/*
### Description
Reads a file glob and parses all comments out and all Hindley-Milner type signatures it finds in the file(s). You'll get an Array of Objects that have the filename as the key, and the value is an Array of comment lines and comment blocks it found.
| Param | Type | Description |
| --------------------------- | ------------------- | ----------------------------- |
| glob | <code>String</code> | A glob String, like "example.js" or "./folder/file.js" or for all files in `src`, "./src/** /*.js (remove the space after the 2 stars, heh). See glob for more information: https://www.npmjs.com/package/glob |
| globOptions | <code>Object</code> | Glob options Object. Feel free to use {} as default, else refer to the glob documentation on what options you can use. https://github.com/isaacs/node-glob#options
### Returns
<code>Promise</code> - Promise contains a list of parsed comments, or an Error as to why it failed.
### Example
```javascript
parse
('./src/** /*.js') // ignore space after 2 stars
({ ignore: 'example' })
.then(console.log)
.catch(console.log)
```
*/
// parse :: glob -> globOptions -> Promise
const parse = fileGlob => fileGlobOptions =>
debug("parse, fileGlob: %s", fileGlob) ||
loadFilenames(fileGlob)(fileGlobOptions)
.then(files =>
debug("parse, files loaded, about to read them: %o", files) ||
Promise.all(
map(
readFile,
files
)
)
)
.then(fileContents =>
debug("parse, fileContents loaded, attempting to parse out comments from AST...") ||
Promise.all(
map(
codeToMarkdown,
fileContents
)
))
.then(markdowns =>
debug("parse, markdowns parsed, combining with file names: %O", markdowns) ||
Promise.all([
loadFilenames(fileGlob)(fileGlobOptions),
markdowns
])
)
.then( ([filenames, markdowns]) =>
debug("parse, combining filenames and markdown...") ||
zip(filenames, markdowns))
.then(fromPairs)
.then( result =>
debug("parse, cleaning empty results...") ||
cleanEmptyResults(result)
)
.then(tapDebugAndShowArgs("parse done, showing result"))
.then(tapDebug("parse, done."))
const renderMarkdown = sourceFileContents => data =>
handlebars.compile
(sourceFileContents)
(data)
const readFileToString = filename =>
new Promise((success, failure) =>
fs.readFile(filename, (error, data) =>
err
? failure(error)
: success(data.toString())
)
)
const writeFile = filename => data =>
new Promise((success, failure) =>
fs.writeFile(filename, data, err =>
err
? failure(err)
: success(`Successfully wrote filename: ${filename}`)
)
)
/*
### Description
Reads a file glob, parses all comments out and all Hindley-Milner type signatures, reads your Handlebars template, compiles it with the parsed comments, and prints out the compiled text.
| Param | Type | Description |
| --------------------------- | ------------------- | ----------------------------- |
| glob | <code>String</code> | A glob String, like "example.js" or "./folder/file.js" or for all files in `src`, "./src/** /*.js (remove the space after the 2 stars, heh). See glob for more information: https://www.npmjs.com/package/glob |
| globOptions | <code>Object</code> | Glob options Object. Feel free to use {} as default, else refer to the glob documentation on what options you can use. https://github.com/isaacs/node-glob#options
| handlebarsTemplateFile | <code>String</code> | Filepath to the Handlebars template file you want to inject your code comments into. It should have a string {{#hmdoc}}{{/hmdoc}} somewhere in there; this is where hm-doc will render the API documentation. See http://handlebarsjs.com/ for more information. |
### Returns
<code>Promise</code> - Promise contains either the text content of the of the rendered Markdown or an error as to why it failed.
### Example
```javascript
getMarkdown
('./src/** /*.js') // ignore space after 2 stars
({ ignore: './examples' })
('README_template.hbs')
.then(console.log)
.catch(console.log)
```
*/
// getMarkdown :: glob -> globOptions -> handlebarsTemplateFile -> Promise
const getMarkdown = glob => globOptions => handlebarsTemplateFile =>
tapDebug("getMarkdown, looking for glob: %s, handlebarsTemplateFile: %s", glob, globOptions, handlebarsTemplateFile)()
.then(() => Promise.all([
parse(glob)(globOptions),
readFile(handlebarsTemplateFile)
]))
.then(tapDebug("getMarkdown, parsed glob and read template file, rendering markdown..."))
.then( ([ data, templateString ]) =>
renderMarkdown
(templateString)
(data)
)
.then(tapDebug("getMarkdown, rendered markdown."))
/*
### Description
Reads a file glob, parses all comments out and all Hindley-Milner type signatures, reads your Handlebars template, compiles it with the parsed comments, and finally writes that compiled text to a file.
| Param | Type | Description |
| --------------------------- | ------------------- | ----------------------------- |
| glob | <code>String</code> | A glob String, like "example.js" or "./folder/file.js" or for all files in `src`, "./src/** /*.js (remove the space after the 2 stars, heh). See glob for more information: https://www.npmjs.com/package/glob |
| globOptions | <code>Object</code> | Glob options Object. Feel free to use {} as default, else refer to the glob documentation on what options you can use. https://github.com/isaacs/node-glob#options
| handlebarsTemplateFile | <code>String</code> | Filepath to the Handlebars template file you want to inject your code comments into. It should have a string {{#hmdoc}}{{/hmdoc}} somewhere in there; this is where hm-doc will render the API documentation. See http://handlebarsjs.com/ for more information. |
| outputFilename | <code>String</code> | File you want to write your rendered Markdown to, probably `README.md`.
### Returns
<code>Promise</code> - Promise contains a success message of the file it wrote, an error as to why it failed.
### Example
```javascript
writeMarkdownFile
('./src/** /*.js') // ignore space after 2 stars
({ ignore: '' })
('README_template.hbs')
('README.md')
.then(console.log)
.catch(console.log)
```
*/
// writeMarkdownFile :: glob -> handlebarsTemplateFile -> outputFilename -> Promise
const writeMarkdownFile = glob => globOptions => handlebarsTemplateFile => outputFilename =>
tapDebug("writeMarkdownFile, looking for glob: %s, handlebarsTemplateFile: %s, outputFilename: %s", glob, handlebarsTemplateFile, outputFilename)()
.then(() => getMarkdown(glob)(globOptions)(handlebarsTemplateFile))
.then(tapDebug("writeMarkdownFile, markdown rendered, writing file..."))
.then( markdown =>
writeFile
(outputFilename)
(markdown)
)
module.exports = {
codeToMarkdown,
parse,
renderMarkdown,
getMarkdown,
writeMarkdownFile
}