All files / src/helpers markdown.helper.ts

82.86% Statements 145/175
92.77% Branches 77/83
80% Functions 12/15
82.86% Lines 145/175

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 1761x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 1x 17x 17x 17x 1x 15x 15x 15x 15x 15x 15x 1x 15x 15x 9x 9x 6x 15x 2x 1x 1x 1x 1x 2x 4x 4x 4x 1x 1x 1x     1x 1x 1x 1x 1x 1x 1x 1x 8x 8x 8x 8x 8x 1x 1x 7x 7x 7x 1x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 1x 48x 48x 48x 48x 7x 4x 7x 48x 48x 1x 23x 23x 2x 2x 21x 23x 23x 23x 23x 23x 23x 23x 1x 44x 44x 44x 44x 44x 44x 44x 1x 44x 44x 13x 13x 31x 31x 31x 44x 44x 44x 44x 44x 1x                       1x                             1x        
import {
    UsageGuideConfig,
    JsImport,
    IWriteMarkDown,
    ArgumentConfig,
    CommandLineOption,
    ParseOptions,
    Content,
    HeaderLevel,
    OptionContent,
    SectionHeader,
} from '../contracts';
import { join } from 'path';
import { normaliseConfig, createCommandLineConfig } from './command-line.helper';
import { generateTableFooter, getOptionSections, mapDefinitionDetails } from './options.helper';
import { convertChalkStringToMarkdown } from './string.helper';
 
export function createUsageGuide<T = any>(config: UsageGuideConfig<T>): string {
    const options = config.parseOptions || {};
    const headerSections = options.headerContentSections || [];
    const footerSections = options.footerContentSections || [];
 
    return [
        ...headerSections.filter(filterMarkdownSections).map((section) => createSection(section, config)),
        ...createOptionsSections(config.arguments, options),
        ...footerSections.filter(filterMarkdownSections).map((section) => createSection(section, config)),
    ].join('\n');
}
 
function filterMarkdownSections(section: Content): boolean {
    return section.includeIn == null || section.includeIn === 'both' || section.includeIn === 'markdown';
}
 
export function createSection<T>(section: Content, config: UsageGuideConfig<T>): string {
    return `
${createHeading(section, config.parseOptions?.defaultSectionHeaderLevel || 1)}
${createSectionContent(section)}
`;
}
 
export function createSectionContent(section: Content): string {
    if (typeof section.content === 'string') {
        return convertChalkStringToMarkdown(section.content);
    }
 
    if (Array.isArray(section.content)) {
        if (section.content.every((content) => typeof content === 'string')) {
            return (section.content as string[]).map(convertChalkStringToMarkdown).join('\n');
        } else if (section.content.every((content) => typeof content === 'object')) {
            return createSectionTable(section.content);
        }
    }
 
    return '';
}
 
export function createSectionTable(rows: any[]): string {
    if (rows.length === 0) {
        return ``;
    }
    const cellKeys = Object.keys(rows[0]);
 
    return `
|${cellKeys.map((key) => ` ${key} `).join('|')}|
|${cellKeys.map(() => '-').join('|')}|
${rows.map((row) => `| ${cellKeys.map((key) => convertChalkStringToMarkdown(row[key])).join(' | ')} |`).join('\n')}`;
}
 
export function createOptionsSections<T>(cliArguments: ArgumentConfig<T>, options: ParseOptions<any>): string[] {
    const normalisedConfig = normaliseConfig(cliArguments);
    const optionList = createCommandLineConfig(normalisedConfig);
 
    if (optionList.length === 0) {
        return [];
    }
 
    return getOptionSections(options).map((section) => createOptionsSection(optionList, section, options));
}
 
export function createOptionsSection<T>(
    optionList: CommandLineOption<any>[],
    content: OptionContent,
    options: ParseOptions<any>,
): string {
    optionList = optionList.filter((option) => filterOptions(option, content.group));
    const anyAlias = optionList.some((option) => option.alias != null);
    const anyDescription = optionList.some((option) => option.description != null);
 
    const footer = generateTableFooter(optionList, options);
 
    return `
${createHeading(content, 2)}
| Argument |${anyAlias ? ' Alias |' : ''} Type |${anyDescription ? ' Description |' : ''}
|-|${anyAlias ? '-|' : ''}-|${anyDescription ? '-|' : ''}
${optionList
    .map((option) => mapDefinitionDetails(option, options))
    .map((option) => createOptionRow(option, anyAlias, anyDescription))
    .join('\n')}
${footer != null ? footer + '\n' : ''}`;
}
 
function filterOptions(option: CommandLineOption, groups?: string | string[]): boolean {
    return (
        groups == null ||
        (typeof groups === 'string' && (groups === option.group || (groups === '_none' && option.group == null))) ||
        (Array.isArray(groups) &&
            (groups.some((group) => group === option.group) ||
                (groups.some((group) => group === '_none') && option.group == null)))
    );
}
 
export function createHeading(section: SectionHeader, defaultLevel: HeaderLevel): string {
    if (section.header == null) {
        return '';
    }
 
    const headingLevel = Array.from({ length: section.headerLevel || defaultLevel })
        .map(() => `#`)
        .join('');
 
    return `${headingLevel} ${section.header}
`;
}
 
export function createOptionRow(option: CommandLineOption, includeAlias = true, includeDescription = true): string {
    const alias = includeAlias ? ` ${option.alias == null ? '' : '**' + option.alias + '** '}|` : ``;
    const description = includeDescription
        ? ` ${option.description == null ? '' : convertChalkStringToMarkdown(option.description) + ' '}|`
        : ``;
    return `| **${option.name}** |${alias} ${getType(option)}|${description}`;
}
 
export function getType(option: CommandLineOption): string {
    if (option.typeLabel) {
        return `${convertChalkStringToMarkdown(option.typeLabel)} `;
    }
 
    //TODO: add modifiers
 
    const type = option.type ? option.type.name.toLowerCase() : 'string';
    const multiple = option.multiple || option.lazyMultiple ? '[]' : '';
 
    return `${type}${multiple} `;
}
 
export function generateUsageGuides(args: IWriteMarkDown): string[] {
    function mapJsImports(imports: JsImport[], jsFile: string) {
        return [...imports, ...args.configImportName.map((importName) => ({ jsFile, importName }))];
    }

    return args.jsFile
        .reduce(mapJsImports, new Array<JsImport>())
        .map(({ jsFile, importName }) => loadArgConfig(jsFile, importName))
        .filter(isDefined)
        .map(createUsageGuide);
}
 
export function loadArgConfig(jsFile: string, importName: string): UsageGuideConfig | undefined {
    const jsPath = join(process.cwd(), jsFile);
    // eslint-disable-next-line @typescript-eslint/no-var-requires
    const jsExports = require(jsPath);

    const argConfig: UsageGuideConfig = jsExports[importName];

    if (argConfig == null) {
        console.warn(`Could not import ArgumentConfig named '${importName}' from jsFile '${jsFile}'`);
        return undefined;
    }

    return argConfig;
}
 
function isDefined<T>(value: T | undefined | null): value is T {
    return value != null;
}