amap-fill.ts 7.08 KB
#!/usr/bin/env node
/**
 * 命令行入口:解析参数、取用 Key、发出中断信号,然后把活交给 fill.runJob。
 * Node 22.18+ 直接运行本文件,无需构建。
 *
 * 这一层只做「人怎么用它」的事,取值口径全在 fill.ts / address.ts / client.ts 里;
 * 交付时只带 --input/--output/--cache 三个路径也能跑起来。
 */
import path from 'node:path';
import process from 'node:process';
import { fileURLToPath } from 'node:url';
import { interruptSignal, reportFailure, withSuffix } from './cli.ts';
import { isExcel } from './excel-store.ts';
import { runJob } from './fill.ts';

const USAGE = [
  '用法: node amap-fill.ts --input <csv|xlsx> [选项]',
  '按「地址解析 → 接口缓存 → 地图接口」的顺序补齐空白的行政区、街道、道路;表头缺这三列时自动追加。',
  '能靠地址文本补齐的行不会调用接口,读出来可疑的同样不采用;一次运行的花费只等于地址补不齐或不可信的那些坐标。',
  '',
  '  --input PATH     输入 UTF-8 CSV 或 Excel(必需)',
  '  --output PATH    输出新表格,默认写到源文件旁的 out/ 下,沿用源格式并加 .已补全;Excel 输出仅支持 .xlsx/.xlsm',
  '  --cache PATH     SQLite 缓存路径,默认源文件旁的 cache/;重跑使用相同路径可续跑',
  '  --limit N        仅处理并输出前 N 行数据,用于样例验证',
  '  --workers N      最大并发请求数,默认 20',
  '  --qps N          全局每秒请求上限,默认 100;0 为不限',
  '  --infer-nearby   允许用附近已知点的归属补空白(默认关闭;半径见 targets.ts)',
  '  --sort-last      把仍有空白的记录排到末尾,完整记录在前(默认开启);--sort-last=false 关闭',
  '  --only-list PATH 只跑这份清单里的行:清单外的行本次不许问接口,输出仍是完整表格',
  '  --help           显示本帮助',
  '',
  '处理日志与三份清单(限流待重试、补不出、待复核)写在源文件旁的 .temp/ 下,out/ 只放正式表格;空白的类别不写文件。',
  '把清单里的行单独再跑一次:--only-list "上一次的清单.csv",配合同一个 --input 与 --cache。',
  '',
  'Key 只从环境变量 AMAP_KEY 或终端隐藏输入取得,不写入配置、日志与缓存。',
  '退出码:0 全部补齐;2 仍有缺失或失败;130 已中断;1 参数或文件错误。',
].join('\n');

type Flags = {
  options: Map<string, string>;
  inferNearby: boolean;
  sortIncompleteLast: boolean;
  help: boolean;
  error: string;
};

const VALUE_NAMES = ['input', 'output', 'cache', 'limit', 'workers', 'qps', 'only-list'];
const BOOL_NAMES = ['infer-nearby', 'sort-last'];

/** 值选项必须带值,开关选项可写 --sort-last=false;未知选项一律拒绝而不是忽略。 */
export function parseCoreArgs(argv: string[]): Flags {
  const options = new Map<string, string>();
  let inferNearby = false;
  let sortIncompleteLast = true;
  let help = false;
  for (let i = 0; i < argv.length; i += 1) {
    const token = argv[i];
    if (token === '--help' || token === '-h') {
      help = true;
      continue;
    }
    if (!token.startsWith('--')) return { options, inferNearby, sortIncompleteLast, help, error: `无法识别的参数:${token}` };
    const [rawName, inline] = token.slice(2).split(/=(.*)/s);
    if (VALUE_NAMES.includes(rawName)) {
      const value = inline ?? argv[i + 1];
      if (value === undefined || (inline === undefined && value.startsWith('--'))) {
        return { options, inferNearby, sortIncompleteLast, help, error: `选项 ${token} 需要一个值` };
      }
      if (inline === undefined) i += 1;
      options.set(rawName, value);
      continue;
    }
    if (BOOL_NAMES.includes(rawName)) {
      const value = inline === undefined ? 'true' : inline;
      if (value !== 'true' && value !== 'false') {
        return { options, inferNearby, sortIncompleteLast, help, error: `选项 --${rawName} 只能写 true 或 false` };
      }
      if (rawName === 'infer-nearby') inferNearby = value === 'true';
      else sortIncompleteLast = value === 'true';
      continue;
    }
    return { options, inferNearby, sortIncompleteLast, help, error: `无法识别的选项:${token}` };
  }
  return { options, inferNearby, sortIncompleteLast, help, error: '' };
}

function readNumber(options: Map<string, string>, name: string, fallback: number,
  integer: boolean): { value: number; error: string } {
  const raw = options.get(name);
  if (raw === undefined) return { value: fallback, error: '' };
  const value = Number(raw);
  const valid = integer ? /^\d+$/.test(raw) && Number.isSafeInteger(value) : /^\d+(\.\d+)?$/.test(raw);
  if (!valid) return { value: 0, error: `选项 --${name} 需要${integer ? '整数' : '数字'},得到 ${raw}` };
  return { value, error: '' };
}

export async function main(argv: string[] = process.argv.slice(2)): Promise<number> {
  const flags = parseCoreArgs(argv);
  if (flags.help) {
    process.stdout.write(`${USAGE}\n`);
    return 0;
  }
  if (flags.error !== '') {
    process.stderr.write(`${flags.error}\n${USAGE}\n`);
    return 2;
  }
  const input = flags.options.get('input');
  if (input === undefined) {
    process.stderr.write(`以下参数必需: --input\n${USAGE}\n`);
    return 2;
  }
  const limit = readNumber(flags.options, 'limit', 0, true);
  const workers = readNumber(flags.options, 'workers', 20, true);
  const qps = readNumber(flags.options, 'qps', 100, false);
  const bad = [limit, workers, qps].find((item) => item.error !== '');
  if (bad !== undefined) {
    process.stderr.write(`${bad.error}\n`);
    return 2;
  }
  const sourceFile = path.resolve(input);
  const output = flags.options.get('output')
    ?? withSuffix(input, isExcel(input) ? '.已补全.xlsx' : '.已补全.csv',
      path.join(path.dirname(sourceFile), 'out'));
  // 三样产物都跟着源文件走:out/ 放表格,.temp/ 放过程文件,cache/ 放已查坐标
  const cache = flags.options.get('cache')
    ?? path.join(path.dirname(sourceFile), 'cache', 'amap_regeo_cache.sqlite3');
  const tempDir = path.join(path.dirname(sourceFile), '.temp');
  const interrupt = interruptSignal();
  try {
    const report = await runJob(input, output, cache, {
      limit: limit.value > 0 ? limit.value : null,
      workers: workers.value,
      qps: qps.value,
      inferNearby: flags.inferNearby,
      sortIncompleteLast: flags.sortIncompleteLast,
      onlyList: flags.options.get('only-list') ?? '',
      tempDir,
      progress: (message) => process.stdout.write(`${message}\n`),
      signal: interrupt.signal,
    });
    process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
    return report.exit_code;
  } catch (exc) {
    if (interrupt.signal.aborted) {
      process.stderr.write('已中断;再次使用相同输入和缓存路径即可继续。\n');
      return 130;
    }
    return reportFailure(exc);
  } finally {
    interrupt.dispose();
  }
}

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