|
| 1 | +/* eslint-disable no-console */ |
| 2 | +import { program } from '@commander-js/extra-typings'; |
| 3 | +import { lib } from '@mirascript/mirascript/subtle'; |
| 4 | +import { KEYWORDS, OPERATORS } from '@mirascript/help'; |
| 5 | +import styles from 'ansi-styles'; |
| 6 | +import { noColor } from '../utils/color.js'; |
| 7 | +import { print } from '../utils/print.js'; |
| 8 | + |
| 9 | +/** 打印表格 */ |
| 10 | +function printTable<T>( |
| 11 | + map: Record<string, T>, |
| 12 | + title: string, |
| 13 | + formatter: (value: T, key: string) => string = String, |
| 14 | +): void { |
| 15 | + console.log(title); |
| 16 | + const keys = Object.keys(map).sort(); |
| 17 | + const maxKeyLength = Math.max(...keys.map((k) => k.length)); |
| 18 | + for (const key of keys) { |
| 19 | + const value = map[key]; |
| 20 | + if (value === undefined) continue; |
| 21 | + const firstLine = formatter(value, key).split('\n')[0]; |
| 22 | + let subject = key.padEnd(maxKeyLength); |
| 23 | + if (!noColor) { |
| 24 | + subject = styles.bold.open + subject + styles.bold.close; |
| 25 | + } |
| 26 | + console.log(` ${subject} ${firstLine}`); |
| 27 | + } |
| 28 | +} |
| 29 | + |
| 30 | +/** 打印库 */ |
| 31 | +function printLib(key: string): void { |
| 32 | + const value = lib[key as keyof typeof lib]; |
| 33 | + if (value === undefined) return; |
| 34 | + if ('summary' in value) { |
| 35 | + if (typeof value == 'function') { |
| 36 | + console.log(`fn ${key}()`); |
| 37 | + console.log(value.summary ?? ''); |
| 38 | + } else { |
| 39 | + console.log(`${key} = ${print(value.value)}`); |
| 40 | + console.log(value.summary ?? ''); |
| 41 | + } |
| 42 | + } else { |
| 43 | + console.log(`模块 ${key}`); |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +const command = program.command('man'); |
| 48 | +command |
| 49 | + .description('显示 MiraScript 的手册') |
| 50 | + .argument('<topic>', '要显示的主题') |
| 51 | + .action((topic) => { |
| 52 | + if (topic in KEYWORDS) { |
| 53 | + const desc = KEYWORDS[topic as keyof typeof KEYWORDS]; |
| 54 | + console.log(desc); |
| 55 | + } else if (topic in OPERATORS) { |
| 56 | + const desc = OPERATORS[topic as keyof typeof OPERATORS]; |
| 57 | + console.log(desc); |
| 58 | + } else if (topic in lib) { |
| 59 | + printLib(topic); |
| 60 | + } else if (topic === 'keywords') { |
| 61 | + printTable(KEYWORDS, 'MiraScript 关键字:'); |
| 62 | + } else if (topic === 'operators') { |
| 63 | + printTable(OPERATORS, 'MiraScript 操作符:'); |
| 64 | + } else if (topic === 'libraries') { |
| 65 | + printTable(lib, 'MiraScript 标准库:', (v, k) => { |
| 66 | + if ('summary' in v) { |
| 67 | + return v.summary ?? k; |
| 68 | + } |
| 69 | + return `模块 ${k}`; |
| 70 | + }); |
| 71 | + } else { |
| 72 | + command.help({ error: true }); |
| 73 | + } |
| 74 | + }); |
0 commit comments