@lark-project/cli
Version:
飞书项目插件开发工具
74 lines (73 loc) • 2.92 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.peekText = void 0;
const fs_extra_1 = require("fs-extra");
/**
* Positional / regex / head-tail slicing. Works on any file — used as the
* fallback when file extension has no structural parser, and also delegated
* to by structured peekers when the user passes --line / --match / --head / --tail.
*/
function peekText(file, opts) {
var _a, _b, _c;
const content = (0, fs_extra_1.readFileSync)(file, 'utf8');
const lines = content.split('\n');
let start = 1; // 1-based inclusive
let end = lines.length; // 1-based inclusive
if (typeof opts.head === 'number' && opts.head > 0) {
start = 1;
end = Math.min(lines.length, opts.head);
}
else if (typeof opts.tail === 'number' && opts.tail > 0) {
start = Math.max(1, lines.length - opts.tail + 1);
end = lines.length;
}
else if (opts.match) {
const re = toRegex(opts.match);
const matchIdx = lines.findIndex(l => re.test(l));
if (matchIdx < 0) {
process.stderr.write(`No match found for pattern: ${opts.match}\n`);
process.exit(1);
}
const before = (_a = opts.before) !== null && _a !== void 0 ? _a : 0;
const after = (_b = opts.after) !== null && _b !== void 0 ? _b : (opts.limit ? Math.max(opts.limit - 1, 0) : 0);
start = Math.max(1, matchIdx + 1 - before);
end = Math.min(lines.length, matchIdx + 1 + after);
}
else if (typeof opts.line === 'number') {
start = Math.max(1, opts.line);
const limit = (_c = opts.limit) !== null && _c !== void 0 ? _c : 50;
end = Math.min(lines.length, start + limit - 1);
}
else {
// 完全没有切片指令:给前 50 行 + 提示 --head/--tail/--line/--match
end = Math.min(lines.length, 50);
process.stderr.write('No slice option given; showing first 50 lines. Use --head/--tail/--line/--match to narrow.\n');
}
const slice = lines.slice(start - 1, end);
if (opts.format === 'json') {
process.stdout.write(JSON.stringify({
file,
range: [start, end],
total: lines.length,
lines: slice,
}) + '\n');
return;
}
// text:带行号前缀,方便 AI 引用回跳
const width = String(end).length;
for (let i = 0; i < slice.length; i++) {
const lineNo = String(start + i).padStart(width, ' ');
process.stdout.write(`${lineNo}\t${slice[i]}\n`);
}
}
exports.peekText = peekText;
function toRegex(pattern) {
// 如果 pattern 包含明显的正则特殊字符就当正则用,否则当字面量
// 对 AI 来说:"ERROR" 当字面量用更符合直觉
try {
return new RegExp(pattern);
}
catch (_a) {
return new RegExp(pattern.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
}
}