run-tool.ts 9.93 KB
#!/usr/bin/env node
/**
 * 便携启动器:读取 config.json、解析路径、交互输入,然后调用 fill.runJob。
 * 配置中的相对路径以该 config.json 所在目录为基准。
 *
 * 排序(把仍有空白的记录排到末尾)由补齐流程在内存里一次做完,
 * 不再把刚写出的输出读回来重排、重写一遍 —— 几十万行的表格经不起两次整表读写。
 */
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import process from 'node:process';
import readline from 'node:readline';
import { fileURLToPath } from 'node:url';
import { interruptSignal, reportFailure, withSuffix } from './cli.ts';
import { UserError } from './errors.ts';
import { isExcel } from './excel-store.ts';
import { runJob, type Report } from './fill.ts';
import type { LookupClient } from './client.ts';

export const BASE = path.dirname(fileURLToPath(import.meta.url));

export type Config = {
  input: string;
  output: string;
  cache: string;
  workers: number;
  qps: number;
  limit: number | null;
  sort_incomplete_last: boolean;
  /** 用附近已知点的归属补空白;默认关闭,因为它是推断不是实测 */
  infer_nearby: boolean;
};

export const DEFAULTS: Config = {
  input: '',
  output: '',
  cache: '',
  workers: 20,
  qps: 100,
  limit: null,
  sort_incomplete_last: true,
  infer_nearby: false,
};

/** 严格校验配置值;不认识的字段与任何 Key 都会被拒绝。 */
export function validateConfig(supplied: unknown): Config {
  if (typeof supplied !== 'object' || supplied === null || Array.isArray(supplied)) {
    throw new UserError('config.json 必须是 JSON 对象');
  }
  const given = supplied as Record<string, unknown>;
  if (Object.keys(given).some((key) => !(key in DEFAULTS))) {
    throw new UserError('配置中存在不支持的字段,请参照 config.example.json;Key 不写入配置');
  }
  const config = { ...DEFAULTS, ...given } as Config;
  for (const name of ['input', 'output', 'cache'] as const) {
    if (typeof config[name] !== 'string') throw new UserError(`${name} 必须是路径字符串`);
  }
  if (!Number.isInteger(config.workers) || config.workers < 1) throw new UserError('workers 必须是正整数');
  if (typeof config.qps !== 'number' || !Number.isFinite(config.qps) || config.qps < 0) {
    throw new UserError('qps 必须是有限非负数');
  }
  if (config.limit !== null && (!Number.isInteger(config.limit) || config.limit < 1)) {
    throw new UserError('limit 必须是正整数或 null');
  }
  for (const name of ['sort_incomplete_last', 'infer_nearby'] as const) {
    if (typeof config[name] !== 'boolean') throw new UserError(`${name} 必须是 true 或 false`);
  }
  return config;
}

export function loadConfig(file: string): Config {
  if (!fs.existsSync(file)) return validateConfig({});
  const raw = fs.readFileSync(file, 'utf8');
  let supplied: unknown;
  try {
    supplied = JSON.parse(raw.replace(/^/, ''));
  } catch {
    throw new UserError('config.json 不是有效 JSON:不支持注释与结尾多余逗号,true、false、null 必须小写');
  }
  return validateConfig(supplied);
}

/** 展开 `~`;相对路径以 base 目录为基准。 */
export function resolvePath(value: string, base: string): string {
  const expanded = value === '~' || value.startsWith('~/') || value.startsWith('~\\')
    ? path.join(os.homedir(), value.slice(1).replace(/^[/\\]/, ''))
    : value;
  return path.resolve(base, expanded);
}

function ask(question: string): Promise<string> {
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
  return new Promise((resolve) => rl.question(question, (answer) => {
    rl.close();
    resolve(answer);
  }));
}

const LAUNCHER_USAGE = [
  '用法: node run-tool.ts [表格文件路径] [--config 配置文件] [--check]',
  '  表格文件(CSV 或 Excel)位置参数优先于 config.json;两者都没有时交互询问路径。',
  '  --config  使用另一份配置;其中的相对路径以该配置文件所在目录为基准。',
  '  --check   仅检查本机环境与配置,不访问高德、不验证 Key。',
  '',
  '取值顺序:表内原有 → 地址解析 → 接口缓存 →(可选)邻近地点 → 地图接口。',
  '地址读得出且读得准的行才不查接口;读出来可疑的值不采用,仍交给坐标查询。退出码 2 表示仍有缺失,具体看处理日志的来源列与备注列。',
  '',
  '退出码:0 全部补齐;2 仍有缺失或失败;130 已中断;1 配置或文件错误。',
].join('\n');

/** 只检查本机环境与依赖,不触碰网络、不验证 Key。 */
export function environmentCheck(): string {
  const [major, minor] = process.versions.node.split('.').map(Number);
  if (major < 22 || (major === 22 && minor < 18)) {
    throw new UserError(`需要 Node.js 22.18 或更新版本,当前为 ${process.versions.node}`);
  }
  return `环境检查通过:Node ${process.versions.node} / ${process.platform};`
    + '内置 sqlite 与 CSV、Excel 依赖已就绪。\n此检查未访问高德,未验证 Key 和网络。';
}

export type LauncherDeps = {
  /** 测试注入的客户端工厂:用于证明离线运行不会创建真实请求客户端。 */
  clientFactory?: (qps: number) => LookupClient | Promise<LookupClient>;
};

type ParsedArgs = { input: string; config: string; check: boolean; help: boolean; error: string };

export function parseLauncherArgs(argv: string[]): ParsedArgs {
  const result: ParsedArgs = { input: '', config: '', check: false, help: false, error: '' };
  for (let i = 0; i < argv.length; i += 1) {
    const token = argv[i];
    if (token === '--check') result.check = true;
    else if (token === '--help' || token === '-h') result.help = true;
    else if (token === '--config') {
      const value = argv[i + 1];
      if (value === undefined || value.startsWith('-')) {
        return { ...result, error: '选项 --config 需要一个值' };
      }
      result.config = value;
      i += 1;
    } else if (token.startsWith('-')) return { ...result, error: `无法识别的选项:${token}` };
    else if (result.input !== '') return { ...result, error: `多余的位置参数:${token}` };
    else result.input = token;
  }
  return result;
}

export async function main(argv: string[] = process.argv.slice(2),
  deps: LauncherDeps = {}): Promise<number> {
  const args = parseLauncherArgs(argv);
  if (args.help) {
    process.stdout.write(`${LAUNCHER_USAGE}\n`);
    return 0;
  }
  if (args.error !== '') {
    process.stderr.write(`${args.error}\n${LAUNCHER_USAGE}\n`);
    return 2;
  }
  const configPath = args.config === ''
    ? path.join(BASE, 'config.json')
    : path.resolve(process.cwd(), args.config);
  if (args.config !== '' && !fs.existsSync(configPath)) {
    process.stderr.write('指定的配置文件不存在\n');
    return 2;
  }
  try {
    const config = loadConfig(configPath);
    if (args.check) {
      process.stdout.write(`${environmentCheck()}\n`);
      return 0;
    }
    const root = path.dirname(configPath);
    let source: string;
    if (args.input !== '') source = resolvePath(args.input, process.cwd());
    else if (config.input !== '') source = resolvePath(config.input, root);
    else {
      if (process.stdin.isTTY !== true) {
        throw new UserError('请传入表格文件路径,或在 config.json 中设置 input');
      }
      const raw = (await ask('请输入或拖入 CSV/Excel 文件完整路径:')).trim().replace(/^"|"$/g, '');
      if (raw === '') throw new UserError('输入文件路径不能为空');
      source = resolvePath(raw, process.cwd());
    }
    if (!fs.existsSync(source) || !fs.statSync(source).isFile()) throw new UserError('输入文件不存在');
    const inputSuffix = path.extname(source).toLowerCase();
    if (inputSuffix !== '.csv' && !isExcel(source)) {
      throw new UserError('仅支持 CSV 与 Excel(.csv、.xlsx、.xlsm、.xlsb、.xls)');
    }
    // 正式表格与过程文件都跟着源文件走:工具目录不落运行产物
    const output = config.output === ''
      ? withSuffix(source, isExcel(source) ? '.已补全.xlsx' : '.已补全.csv',
        path.join(path.dirname(source), 'out'))
      : resolvePath(config.output, root);
    const outputSuffix = path.extname(output).toLowerCase();
    if (outputSuffix !== '.csv' && outputSuffix !== '.xlsx' && outputSuffix !== '.xlsm') {
      throw new UserError('输出文件扩展名必须为 .csv、.xlsx 或 .xlsm');
    }
    const cache = config.cache === ''
      ? path.join(path.dirname(source), 'cache', 'amap_regeo_cache.sqlite3')
      : resolvePath(config.cache, root);
    return await execute(config, source, output, cache, path.join(path.dirname(source), '.temp'), deps);
  } catch (exc) {
    return reportFailure(exc, '无法运行');
  }
}

async function execute(config: Config, source: string, output: string, cache: string,
  tempDir: string, deps: LauncherDeps): Promise<number> {
  const interrupt = interruptSignal();
  let report: Report;
  try {
    report = await runJob(source, output, cache, {
      limit: config.limit,
      workers: config.workers,
      qps: config.qps,
      inferNearby: config.infer_nearby,
      sortIncompleteLast: config.sort_incomplete_last,
      tempDir,
      clientFactory: deps.clientFactory,
      progress: (message) => process.stdout.write(`${message}\n`),
      signal: interrupt.signal,
    });
  } finally {
    interrupt.dispose();
  }
  if (interrupt.signal.aborted) {
    process.stderr.write('已中断;保留缓存后可使用原输入文件重新运行。\n');
    return 130;
  }
  process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
  if (report.exit_code === 2) {
    process.stdout.write('文件已生成,但仍有缺失、无效坐标或请求失败;请查看处理日志。\n');
  }
  return report.exit_code;
}

const invokedDirectly = process.argv[1] !== undefined
  && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url);
if (invokedDirectly) process.exitCode = await main();