diff --git a/.changeset/man-page-option-groups.md b/.changeset/man-page-option-groups.md new file mode 100644 index 000000000..4b9b5b7c7 --- /dev/null +++ b/.changeset/man-page-option-groups.md @@ -0,0 +1,5 @@ +--- +'@node-core/doc-kit': minor +--- + +`man-page` renders `###` option groups as subsections and fixes options dropped after nested lists. diff --git a/packages/node/src/man-page/README.md b/packages/node/src/man-page/README.md index 341f50ba2..c14985168 100644 --- a/packages/node/src/man-page/README.md +++ b/packages/node/src/man-page/README.md @@ -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 @@ -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 @@ -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$ @@ -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: diff --git a/packages/node/src/man-page/__tests__/generate.test.mjs b/packages/node/src/man-page/__tests__/generate.test.mjs index 2435325eb..85d95fc55 100644 --- a/packages/node/src/man-page/__tests__/generate.test.mjs +++ b/packages/node/src/man-page/__tests__/generate.test.mjs @@ -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'), diff --git a/packages/node/src/man-page/generate.mjs b/packages/node/src/man-page/generate.mjs index 56fb9cf87..cad1902c6 100644 --- a/packages/node/src/man-page/generate.mjs +++ b/packages/node/src/man-page/generate.mjs @@ -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 { @@ -12,18 +13,44 @@ import { } from './utils/converter.mjs'; /** - * @param {Array} 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} 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('`-')) { + groups.at(-1).items += convertOptionToMandoc(entry); + // Is it a group? + } else if (entry.heading.depth === 3) { + groups.push({ title: entry.heading.data.text, items: '' }); + } + } + + return groups + .filter(({ items }) => items) + .map(({ title, items }) => + title ? `.Ss ${title}\n${toList(items)}` : toList(items) + ) + .join('\n'); +} + +/** + * @param {Array} entries + */ +function buildEnvironment(entries) { + const items = entries .filter(({ heading }) => heading.depth === 3) - .map(convert) + .map(convertEnvVarToMandoc) .join(''); + + return items && toList(items); } /** @@ -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); diff --git a/packages/node/src/man-page/template.1 b/packages/node/src/man-page/template.1 index d2e2ffd5f..102f1b44e 100644 --- a/packages/node/src/man-page/template.1 +++ b/packages/node/src/man-page/template.1 @@ -8,6 +8,7 @@ .\"====================================================================== .Dd $Mdocdate$ .Dt NODE 1 +.Os . .Sh NAME .Nm node @@ -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: @@ -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 diff --git a/packages/node/src/man-page/utils/__tests__/converter.test.mjs b/packages/node/src/man-page/utils/__tests__/converter.test.mjs index 505a9b706..56b1e932f 100644 --- a/packages/node/src/man-page/utils/__tests__/converter.test.mjs +++ b/packages/node/src/man-page/utils/__tests__/converter.test.mjs @@ -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')]), @@ -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', () => { diff --git a/packages/node/src/man-page/utils/converter.mjs b/packages/node/src/man-page/utils/converter.mjs index e23b886c8..2f2f6ffb9 100644 --- a/packages/node/src/man-page/utils/converter.mjs +++ b/packages/node/src/man-page/utils/converter.mjs @@ -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. @@ -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. @@ -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). @@ -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, @@ -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`; } /** @@ -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`; }