cli.ts 1.86 KB
/** CLI 共用的外壳:错误措辞、输出路径派生、Ctrl+C 转中断信号。命令行入口与启动器都用它。 */
import path from 'node:path';
import process from 'node:process';
import { QueryError } from './client.ts';
import { UserError } from './errors.ts';

/**
 * 只原样打印经过审核的消息;其余错误仅报告类型,避免泄露凭证。
 *
 * 审核过的消息本身就写着下一步该做什么(缺 Key、路径不存在、限流等),
 * 再补一句「文件是否被 Excel 占用」只会把人往错的方向引 —— 那句排查提示
 * 只给没审核过的错误(多半是读写文件的系统错误)。
 */
export function reportFailure(exc: unknown, prefix = '无法完成'): number {
  const reviewed = exc instanceof UserError || exc instanceof QueryError;
  const detail = reviewed ? exc.message
    : exc instanceof Error ? exc.name : '未知错误';
  const hint = reviewed ? '' : '(请检查配置、路径权限,以及表格文件是否正被 Excel 占用)';
  process.stderr.write(`${prefix}:${detail}${hint}\n`);
  return 1;
}

/**
 * 默认输出名:沿用源文件名与扩展名,只在尾部加标记。
 * `directory` 不给时与源文件同目录;给了就落到那个目录(工具默认落在 out/)。
 */
export function withSuffix(file: string, suffix: string,
  directory: string = path.dirname(file)): string {
  const stem = path.basename(file, path.extname(file));
  return path.join(directory, `${stem}${suffix}`);
}

/** Ctrl+C 时转为中断信号:保留已完成结果并写出文件,退出码 130。 */
export function interruptSignal(): { signal: AbortSignal; dispose(): void } {
  const controller = new AbortController();
  const onSigint = () => controller.abort();
  process.on('SIGINT', onSigint);
  return { signal: controller.signal, dispose: () => process.off('SIGINT', onSigint) };
}