2021-09-30 20:25:38 +00:00
|
|
|
import * as glob from 'glob';
|
|
|
|
import markdownToc = require('markdown-toc');
|
2021-08-24 22:56:47 +00:00
|
|
|
|
|
|
|
/** Files that may contain tables of contents. */
|
2023-09-22 23:09:36 +00:00
|
|
|
export const files = glob.sync('**/*.md?(.d.ts)', {
|
2021-08-24 22:56:47 +00:00
|
|
|
ignore: ['node_modules/**/*.md', '**/*.changes.md'],
|
|
|
|
});
|
|
|
|
|
|
|
|
// Returns the index of the first `*` in `markdown`'s table of contents, or
|
|
|
|
// `null` if `markdown` doesn't include a table of contents.
|
2021-09-30 20:25:38 +00:00
|
|
|
function findStartIndex(markdown: string): number | null {
|
2021-08-24 22:56:47 +00:00
|
|
|
const match = markdown.match(/\n## Table of Contents\n/);
|
|
|
|
if (match === null || match.index === undefined) return null;
|
|
|
|
return match.index + match[0].length - 1;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Returns the table of contents in `markdown` if it contains one, or `null`
|
|
|
|
* otherwise.
|
|
|
|
*/
|
2021-09-30 20:25:38 +00:00
|
|
|
export function getCurrent(markdown: string): string | null {
|
2021-08-24 22:56:47 +00:00
|
|
|
const startIndex = findStartIndex(markdown);
|
|
|
|
if (startIndex === null) return null;
|
|
|
|
|
|
|
|
const endIndex = markdown.indexOf('## ', startIndex) - 1;
|
|
|
|
if (endIndex < 0) return null;
|
|
|
|
|
2022-01-14 23:01:51 +00:00
|
|
|
return markdown.substring(startIndex, endIndex).trim() || null;
|
2021-08-24 22:56:47 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/** Returns the expected table of contents for `markdown`. */
|
2021-09-30 20:25:38 +00:00
|
|
|
export function generate(markdown: string): string {
|
2021-08-24 22:56:47 +00:00
|
|
|
return markdownToc(markdown, {
|
|
|
|
filter: contents => contents.indexOf('Table of Contents') === -1,
|
|
|
|
firsth1: false,
|
|
|
|
bullets: '*',
|
|
|
|
}).content;
|
|
|
|
}
|