csv-store.ts 4.06 KB
/** CSV 读写与防覆盖路径校验;输出为 UTF-8 BOM、CRLF 行尾。 */
import crypto from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
import process from 'node:process';
import { parse as parseCsv } from 'csv-parse/sync';
import { stringify as stringifyCsv } from 'csv-stringify/sync';
import { UserError } from './errors.ts';
import { COORDINATE_COLUMNS } from './targets.ts';

const BOM = '';

/** UTF-8 / UTF-8 BOM CSV:表头无重名,每条记录列数与表头一致。清单这类辅助文件用这个。 */
export function readTable(file: string, limit: number | null): { header: string[]; rows: string[][] } {
  const content = fs.readFileSync(file, 'utf8');
  const records = parseCsv(content, {
    bom: true,
    skip_empty_lines: false,
    relax_quotes: false,
    relax_column_count: true,
    trim: false,
  }) as string[][];
  const header = records.shift() ?? [];
  if (header.length === 0 || new Set(header).size !== header.length) {
    throw new UserError('CSV 表头为空或含重名列');
  }
  const rows = limit === null ? records : records.slice(0, limit);
  rows.forEach((row, position) => {
    if (row.length !== header.length) {
      throw new UserError(`第 ${position + 2} 条 CSV 记录列数与表头不一致`);
    }
  });
  return { header, rows };
}

/** 数据源用的 CSV:在通用校验之上再要求经纬度列。 */
export function readCsv(file: string, limit: number | null): { header: string[]; rows: string[][] } {
  const table = readTable(file, limit);
  if (COORDINATE_COLUMNS.some((name) => !table.header.includes(name))) {
    throw new UserError('CSV 必须包含经度、纬度列');
  }
  return table;
}

function pathKeys(file: string): string[] {
  const resolved = path.resolve(file);
  const keys = [process.platform === 'win32' ? resolved.toLowerCase() : resolved];
  try {
    const stat = fs.statSync(resolved);
    keys.push(`${stat.dev}:${stat.ino}`);
  } catch {
    // 文件尚不存在(SQLite sidecar 常见):只比较规范化路径。
  }
  return keys;
}

/** 输入、输出、缓存与日志必须互不相同,禁止覆盖源文件。 */
export function validatePaths(source: string, output: string, cache: string,
  tempDir: string): string {
  const log = logPathFor(output, tempDir);
  const names = [source, output, cache, log,
    ...['-journal', '-wal', '-shm'].map((suffix) => `${cache}${suffix}`)];
  const keys = names.map(pathKeys);
  for (let i = 0; i < keys.length; i += 1) {
    for (let j = i + 1; j < keys.length; j += 1) {
      if (keys[i].some((key) => keys[j].includes(key))) {
        throw new UserError('输入、输出、缓存及日志路径必须不同,禁止覆盖源文件');
      }
    }
  }
  return log;
}

/**
 * 处理日志落在临时目录:文件名跟着输出走,便于对上是哪一次运行。
 * 输出目录只放正式交付的表格;日志、清单这类过程文件一律进 .temp。
 */
export function logPathFor(output: string, tempDir: string): string {
  return path.join(tempDir, `${path.basename(output, path.extname(output))}.处理日志.csv`);
}

/** 先写同目录临时文件并 fsync,再原子替换,避免中断留下半份文件。 */
export function atomicWrite(file: string, body: string | Uint8Array): void {
  const target = path.resolve(file);
  const directory = path.dirname(target);
  fs.mkdirSync(directory, { recursive: true });
  const temporary = path.join(directory,
    `${path.basename(target)}.${crypto.randomBytes(6).toString('hex')}.tmp`);
  try {
    const handle = fs.openSync(temporary, 'w');
    try {
      fs.writeFileSync(handle, body, 'utf8');
      fs.fsyncSync(handle);
    } finally {
      fs.closeSync(handle);
    }
    fs.renameSync(temporary, target);
  } finally {
    if (fs.existsSync(temporary)) fs.unlinkSync(temporary);
  }
}

/** UTF-8 BOM + CRLF 行尾的 CSV 输出。 */
export function atomicCsv(file: string, header: readonly string[], rows: readonly string[][]): void {
  atomicWrite(file, BOM + stringifyCsv([header as string[], ...rows.map((row) => row as string[])],
    { record_delimiter: '\r\n' }));
}