Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/man-page-option-groups.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@node-core/doc-kit': minor
---

`man-page` renders `###` option groups as subsections and fixes options dropped after nested lists.
49 changes: 34 additions & 15 deletions packages/node/src/man-page/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ It writes to `output`, a
## Writing the command-line page

The generator finds two sections by the slugs of their headings, and turns
every `###` heading in them into an entry of the man page:
the headings in them into entries of the man page:

```md displayName="docs/cli.md"
# Command-line reference
Expand All @@ -62,12 +62,35 @@ Where mytool keeps its cache. **Default:** `~/.mytool`.
`0` on success, `1` on any error.
```

- Options are the `###` headings between the options heading and the
environment variables heading, so the options section must come first.
- Options are the headings that start with a flag, between the options
heading and the environment variables heading, so the options section must
come first.
- Environment variables are the `###` headings after their heading, up to the
next `#` or `##` heading.
- Text right under a section heading, and `####` headings with their content,
are left out.
- Text right under a section heading, and headings below an entry with their
content, are left out.

### Grouping options

To group options by topic, put a `###` heading over each group and write its
options as `####` headings. Each group becomes a subsection of OPTIONS, titled
with the group's heading:

```md displayName="docs/cli.md"
## Options

### Output

#### `-o`, `--output=dir`

Writes the result to _dir_ instead of the working directory.

#### `--quiet`

Prints nothing but errors.
```

Options above the first group are listed before the subsections.

A slug is the anchor doc-kit gives a heading: GitHub-style, lowercase with hyphens for spaces, and with `-1`, `-2` and so on
when the same heading appears earlier on the page. Node.js's `cli.md` has a
Expand Down Expand Up @@ -116,10 +139,10 @@ and alerts too), images and HTML, so YAML metadata comments don't show up.
The default template describes Node.js: its name, synopsis, description and
links are all about `node`. For another command, write your own.

A template is an mdoc file with two placeholders, `__OPTIONS__` and
`__ENVIRONMENT__`. The generator replaces the first occurrence of each with the
entries it builds. Those entries are `.It` items, so put each placeholder
inside a `.Bl -tag` list:
A template is an mdoc file with two placeholders, `{options}` and
`{environment}`. The generator replaces them with the entries it builds, as
complete `.Bl -tag` lists (with `.Ss` subsections for grouped options), so put
each placeholder on a line of its own under its section heading:

```text displayName="man/template.1"
.Dd $Mdocdate$
Expand All @@ -133,13 +156,9 @@ inside a `.Bl -tag` list:
.Op Ar options
.Ar input
.Sh OPTIONS
.Bl -tag -width 6n
__OPTIONS__
.El
{options}
.Sh ENVIRONMENT
.Bl -tag -width 6n
__ENVIRONMENT__
.El
{environment}
```

Then set the template, the file name and the slugs your page needs:
Expand Down
20 changes: 20 additions & 0 deletions packages/node/src/man-page/__tests__/generate.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,26 @@ describe('man-page generate', () => {
assert.match(output, /\.It Ev NODE_THREE Ar value\nThird var\./);
});

it('extracts options nested in topic groups', async () => {
const input = [
entry(2, 'options', 'Options'),
entry(3, 'general', 'General'),
entry(4, '--foo', '`--foo`', 'Foo option.'),
entry(5, 'intentional-limitations', 'Intentional limitations'),
entry(3, 'modules', 'Modules'),
entry(4, '--bar', '`--bar`', 'Bar option.'),
entry(2, 'environment-variables-1', 'Environment variables'),
];

const output = await generate(input);

assert.match(
output,
/\.Ss General\n\.Bl -tag -width 6n\n\.It Fl -foo\nFoo option\.\n\.\n\.El\n\.Ss Modules\n\.Bl -tag -width 6n\n\.It Fl -bar\n/
);
assert.doesNotMatch(output, /limitations/);
});

it('stops the environment variables at the next section', async () => {
const input = [
entry(2, 'options', 'Options'),
Expand Down
63 changes: 40 additions & 23 deletions packages/node/src/man-page/generate.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { readFile } from 'node:fs/promises';
import { join } from 'node:path';

import getConfig from '@doc-kit/core/utils/configuration/index.mjs';
import { populate } from '@doc-kit/core/utils/configuration/templates.mjs';
import { writeFile } from '@doc-kit/core/utils/file.mjs';

import {
Expand All @@ -12,18 +13,44 @@ import {
} from './utils/converter.mjs';

/**
* @param {Array<import('@doc-kit/core/generators/metadata/types').MetadataEntry>} components
* @param {number} start
* @param {number} end
* @param {(element: import('@doc-kit/core/generators/metadata/types').MetadataEntry) => string} convert
* @returns {string}
* @param {string} items
*/
function extractMandoc(components, start, end, convert) {
return components
.slice(start, end)
const toList = items => `.Bl -tag -width 6n\n${items}.El`;

/**
* @param {Array<import('@doc-kit/core/generators/metadata/types').MetadataEntry>} entries
*/
function buildOptions(entries) {
const groups = [{ title: undefined, items: '' }];

for (const entry of entries) {
// Is it the start of a flag?
if (entry.heading.data.text.startsWith('`-')) {
Comment thread
ovflowd marked this conversation as resolved.
Resolved
groups.at(-1).items += convertOptionToMandoc(entry);
// Is it a group?
} else if (entry.heading.depth === 3) {
Comment thread
ovflowd marked this conversation as resolved.
Resolved
groups.push({ title: entry.heading.data.text, items: '' });
}
}

return groups
.filter(({ items }) => items)
.map(({ title, items }) =>
title ? `.Ss ${title}\n${toList(items)}` : toList(items)
Comment thread
ovflowd marked this conversation as resolved.
Resolved
)
.join('\n');
}

/**
* @param {Array<import('@doc-kit/core/generators/metadata/types').MetadataEntry>} entries
*/
function buildEnvironment(entries) {
const items = entries
.filter(({ heading }) => heading.depth === 3)
.map(convert)
.map(convertEnvVarToMandoc)
.join('');

return items && toList(items);
}

/**
Expand Down Expand Up @@ -54,26 +81,16 @@ export async function generate(input) {

const output = {
// Extract the CLI options.
options: extractMandoc(
input,
optionsStart + 1,
environmentStart,
convertOptionToMandoc
),
options: buildOptions(input.slice(optionsStart + 1, environmentStart)),
// Extract the environment variables.
env: extractMandoc(
input,
environmentStart + 1,
environmentEnd,
convertEnvVarToMandoc
environment: buildEnvironment(
input.slice(environmentStart + 1, environmentEnd)
),
};

const template = await readFile(config.templatePath, 'utf-8');

const filledTemplate = template
.replace('__OPTIONS__', () => output.options)
.replace('__ENVIRONMENT__', () => output.env);
const filledTemplate = populate(template, output);

if (config.output) {
await writeFile(join(config.output, config.fileName), filledTemplate);
Expand Down
33 changes: 15 additions & 18 deletions packages/node/src/man-page/template.1
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
.\"======================================================================
.Dd $Mdocdate$
.Dt NODE 1
.Os
.
.Sh NAME
.Nm node
Expand Down Expand Up @@ -37,14 +38,22 @@ Execute
without arguments to start a REPL.
.
.Sh OPTIONS
.Bl -tag -width 6n
__OPTIONS__
.El
{options}
.
.Sh ENVIRONMENT
.Bl -tag -width 6n
__ENVIRONMENT__
.El
{environment}
.
.Sh SEE ALSO
Website:
.Sy https://nodejs.org/
.
.Pp
Documentation:
.Sy https://nodejs.org/api/
.
.Pp
GitHub repository and issue tracker:
.Sy https://github.com/nodejs/node
.
.Sh BUGS
Bugs are tracked in GitHub Issues:
Expand All @@ -59,15 +68,3 @@ Node.js also includes external libraries that are available under a variety of l
See
.Sy https://github.com/nodejs/node/blob/HEAD/LICENSE
for the full license text.
.
.Sh SEE ALSO
Website:
.Sy https://nodejs.org/
.
.Pp
Documentation:
.Sy https://nodejs.org/api/
.
.Pp
GitHub repository and issue tracker:
.Sy https://github.com/nodejs/node
17 changes: 17 additions & 0 deletions packages/node/src/man-page/utils/__tests__/converter.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,16 @@ describe('Mandoc Conversion', () => {
expected: '',
},
{ input: u('paragraph', []), expected: '' },
{
input: u('list', [
u('listItem', [
u('paragraph', [textNode('Outer')]),
u('list', [u('listItem', [textNode('Inner')])]),
]),
]),
expected:
'.Bl -bullet\n.It\nOuter\n.Bl -bullet\n.It\nInner\n.El\n.El',
},
{ input: u('list', []), expected: '.Bl -bullet\n\n.El' },
{
input: u('strong', [textNode('strongly emphasized text')]),
Expand Down Expand Up @@ -149,6 +159,13 @@ describe('Mandoc Conversion', () => {
`.It Fl d , Fl -option Ns = Ns Ar value with spaces\nDescription of special options.\n.\n`
);
});

it('should leave the entry untouched', () => {
const mockElement = createMockElement('`-a`', 'Description.');
const { length } = mockElement.content.children;
convertOptionToMandoc(mockElement);
strictEqual(mockElement.content.children.length, length);
});
});

describe('Environment Variable Conversion', () => {
Expand Down
41 changes: 20 additions & 21 deletions packages/node/src/man-page/utils/converter.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,15 @@
* to its corresponding Mandoc markup representation. Unsupported node types will be ignored.
*
* @param {import('@types/mdast').Node} node - The AST node to be converted to Mandoc format.
* @param {boolean} [isListItem=false] - Indicates if the current node is a list item.
* This parameter is used to correctly format list elements in Mandoc.
* @returns {string} The Mandoc formatted string representing the given node and its children.
*/
export function convertNodeToMandoc(node, isListItem = false) {
export function convertNodeToMandoc(node) {
/**
* Converts the children of a node to Mandoc format.
* Converts the children of a node to Mandoc format, skipping ignored nodes.
* @param {string} separator
* @param {boolean} isListItem
*/
const convertChildren = (separator = '', isListItem = false) =>
node.children
.map(child => convertNodeToMandoc(child, isListItem))
.join(separator);
const convertChildren = (separator = '') =>
node.children.map(convertNodeToMandoc).filter(Boolean).join(separator);

/**
* Escapes special characters in plain text content.
Expand All @@ -36,10 +31,12 @@ export function convertNodeToMandoc(node, isListItem = false) {

case 'link':
case 'paragraph':
// Convert to Mandoc paragraph.
return convertChildren();

case 'listItem':
// Convert to Mandoc paragraph or list item.
// .It denotes a list item in Mandoc, added only if the node is a list item.
return `${isListItem && node.type === 'listItem' ? '.It\n' : ''}${convertChildren()}`;
// .It denotes a list item in Mandoc. Its children (e.g. nested lists) go on their own lines.
return `.It\n${convertChildren('\n')}`;

case 'text':
// Escape any special characters in plain text content.
Expand All @@ -63,7 +60,7 @@ export function convertNodeToMandoc(node, isListItem = false) {

case 'list':
// Convert to a bullet list in Mandoc, starting with .Bl -bullet and ending with .El.
return `.Bl -bullet\n${convertChildren('\n', true)}\n.El`;
return `.Bl -bullet\n${convertChildren('\n')}\n.El`;

case 'emphasis':
// Format emphasized text in Mandoc using italic markup (\\fI ... \\fR).
Expand Down Expand Up @@ -121,6 +118,14 @@ const formatFlag = flag =>
// 'Fl' denotes a flag, followed by an optional 'Ar' (argument).
`Fl ${flag.split(/\[?[= ]/)[0].slice(1)}${flagValueToMandoc(flag)}`;

/**
* Converts the content of an entry, without the header itself.
*
* @param {import('@doc-kit/core/generators/metadata/types').MetadataEntry} element
*/
const convertContent = ({ content }) =>
convertNodeToMandoc({ ...content, children: content.children.slice(1) });

/**
* Converts an API option metadata entry into the Mandoc format.
* This function formats command-line options, including flags and descriptions,
Expand All @@ -138,11 +143,8 @@ export function convertOptionToMandoc(element) {
.join(' , ')
.trim();

// Remove the header itself.
element.content.children.shift();

// Return the formatted flags and content, separated by Mandoc markers.
return `.It ${formattedFlags}\n${convertNodeToMandoc(element.content).trim()}\n.\n`;
return `.It ${formattedFlags}\n${convertContent(element).trim()}\n.\n`;
}

/**
Expand All @@ -162,9 +164,6 @@ export function convertEnvVarToMandoc(element) {
// Format the variable value if present.
const formattedValue = varValue ? ` Ar ${varValue}` : '';

// Remove the header itself.
element.content.children.shift();

// Return the formatted environment variable and content, using Mandoc's .It (List item) and .Ev (Env Var) macros.
return `.It Ev ${varName}${formattedValue}\n${convertNodeToMandoc(element.content)}\n.\n`;
return `.It Ev ${varName}${formattedValue}\n${convertContent(element)}\n.\n`;
}
Loading