@lark-project/cli
Version:
飞书项目插件开发工具
84 lines (83 loc) • 3.07 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.peekMarkdown = void 0;
const fs_extra_1 = require("fs-extra");
const text_1 = require("./text");
function parseHeadings(lines) {
const headings = [];
let inFence = false;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
// 跳过代码块里的 # 标题
if (/^\s*```/.test(line)) {
inFence = !inFence;
continue;
}
if (inFence)
continue;
const m = /^(#{1,6})\s+(.+?)\s*#*\s*$/.exec(line);
if (m) {
headings.push({ level: m[1].length, title: m[2].trim(), line: i + 1 });
}
}
return headings;
}
function peekMarkdown(file, name, opts) {
// 纯位置/grep 类切片直接走 text
if (opts.line || opts.match || opts.head || opts.tail) {
return (0, text_1.peekText)(file, opts);
}
const content = (0, fs_extra_1.readFileSync)(file, 'utf8');
const lines = content.split('\n');
const headings = parseHeadings(lines);
if (opts.list || opts.index) {
if (opts.format === 'json') {
process.stdout.write(JSON.stringify(headings.map(h => ({ level: h.level, title: h.title, line: h.line }))) + '\n');
return;
}
for (const h of headings) {
process.stdout.write(`${' '.repeat(h.level - 1)}L${h.line}\t${'#'.repeat(h.level)} ${h.title}\n`);
}
return;
}
if (!name) {
// 无 name、无 slice 参数:给 --list 提示
process.stderr.write('Markdown peek requires a section title (e.g. `lpm ai peek doc.md "订阅属性"`), or --list / --index to see all headings.\n');
process.exit(1);
}
const target = findHeading(headings, name);
if (!target) {
process.stderr.write(`Heading not found: ${name}\n`);
process.stderr.write('Use --list to see all headings.\n');
process.exit(1);
}
// section 结束于「下一个同级或更高级的 heading」或文件末尾
const startIdx = target.line - 1; // 0-based
let endIdx = lines.length; // exclusive
for (const h of headings) {
if (h.line > target.line && h.level <= target.level) {
endIdx = h.line - 1;
break;
}
}
const section = lines.slice(startIdx, endIdx);
if (opts.format === 'json') {
process.stdout.write(JSON.stringify({
file,
title: target.title,
level: target.level,
range: [target.line, endIdx],
lines: section,
}) + '\n');
return;
}
process.stdout.write(section.join('\n') + '\n');
}
exports.peekMarkdown = peekMarkdown;
function findHeading(headings, name) {
const lower = name.toLowerCase();
// 精确匹配优先,其次大小写不敏感,最后子串
return (headings.find(h => h.title === name) ||
headings.find(h => h.title.toLowerCase() === lower) ||
headings.find(h => h.title.toLowerCase().includes(lower)));
}