-
Notifications
You must be signed in to change notification settings - Fork 45
Expand file tree
/
Copy pathindex.mjs
More file actions
101 lines (86 loc) · 2.5 KB
/
index.mjs
File metadata and controls
101 lines (86 loc) · 2.5 KB
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
'use strict';
import { writeFile, readFile } from 'node:fs/promises';
import { join } from 'node:path';
import {
convertOptionToMandoc,
convertEnvVarToMandoc,
} from './utils/converter.mjs';
import { DOC_SLUG_ENVIRONMENT, DOC_SLUG_OPTIONS } from '../../constants.mjs';
/**
* This generator generates a man page version of the CLI.md file.
* See https://man.openbsd.org/mdoc.7 for the formatting.
*
* @typedef {Array<ApiDocMetadataEntry>} Input
*
* @type {GeneratorMetadata<Input, string>}
*/
export default {
name: 'man-page',
version: '1.0.0',
description: 'Generates the Node.js man-page.',
dependsOn: 'ast',
/**
* Generates the Node.js man-page
* @param {Input} input
* @param {Partial<GeneratorOptions>} options
*/
async generate(input, options) {
// Filter to only 'cli'.
const components = input.filter(({ api }) => api === 'cli');
if (!components.length) {
throw new Error('Could not find any `cli` documentation.');
}
// Find the appropriate headers
const optionsStart = components.findIndex(
({ slug }) => slug === DOC_SLUG_OPTIONS
);
const environmentStart = components.findIndex(
({ slug }) => slug === DOC_SLUG_ENVIRONMENT
);
// The first header that is <3 in depth after environmentStart
const environmentEnd = components.findIndex(
({ heading }, index) => heading.depth < 3 && index > environmentStart
);
const output = {
// Extract the CLI options.
options: extractMandoc(
components,
optionsStart + 1,
environmentStart,
convertOptionToMandoc
),
// Extract the environment variables.
env: extractMandoc(
components,
environmentStart + 1,
environmentEnd,
convertEnvVarToMandoc
),
};
const template = await readFile(
join(import.meta.dirname, 'template.1'),
'utf-8'
);
const filledTemplate = template
.replace('__OPTIONS__', output.options)
.replace('__ENVIRONMENT__', output.env);
if (options.output) {
await writeFile(options.output, filledTemplate);
}
return filledTemplate;
},
};
/**
* @param {Array<ApiDocMetadataEntry>} components
* @param {number} start
* @param {number} end
* @param {(element: ApiDocMetadataEntry) => string} convert
* @returns {string}
*/
function extractMandoc(components, start, end, convert) {
return components
.slice(start, end)
.filter(({ heading }) => heading.depth === 3)
.map(convert)
.join('');
}