StoragePathMerge.js 5.28 KB
import { TEMP_DB_FILE, DB_FILE } from './constants.js'
import { normalizePath } from './pathCache.js'
import {
  loadPathCache,
  savePathCache,
  createDefaultCache,
  ensureDefaultRootsInCache,
  getNonCurrentPaths
} from './pathCache.js'
import {
  getCurrentPackageRoot,
  findDbInPackageRoot,
  getRuntimePackageName,
  getPackageNamesForMerge,
  getAppId
} from './pathResolver.js'
import { copyFileToDoc, removeFile, removeDocRelative, fileExists } from './fileIo.js'
import {
  openTempDb,
  closeTempDb,
  openMainDbIfNeeded,
  selectTempRecords,
  mergeRecordsToMain,
  purgeMergeSeedRecordsFromMain
} from './dbMerge.js'
import { isRestrictedInternalPath } from './pathAccess.js'
import { logInfo, logError, waitForPlus } from './log.js'

function isAndroidApp(plusRef) {
  const osName = plusRef?.os?.name
  return !!plusRef && (osName === 'Android' || osName === 'android')
}

async function mergeFromDbFile(dbPath, label) {
  if (!dbPath || isRestrictedInternalPath(dbPath)) return

  logInfo(`发现待合并数据库:${dbPath}`)

  await removeDocRelative(TEMP_DB_FILE)

  try {
    await copyFileToDoc(dbPath, TEMP_DB_FILE)
  } catch (e) {
    logError(`复制数据库失败(来源 ${dbPath}):${e?.message || e}`)
    return
  }

  try {
    await openTempDb()
    const rows = await selectTempRecords()
    if (!rows || rows.length === 0) {
      logInfo(`临时库无 records 数据,跳过:${label || dbPath}`)
      await closeTempDb()
      await removeDocRelative(TEMP_DB_FILE)
      return
    }

    await openMainDbIfNeeded()
    const ok = await mergeRecordsToMain(rows)
    await closeTempDb()

    await removeDocRelative(TEMP_DB_FILE)

    if (ok) {
      try {
        await removeFile(dbPath)
        logInfo(`合并成功,已删除源库:${dbPath}`)
      } catch (e) {
        logError(`合并成功但删除源库失败:${e?.message || e}`)
      }
    } else {
      logError(`合并失败:${label || dbPath}`)
    }
  } catch (e) {
    logError(`处理路径异常 ${label || dbPath}:${e?.message || e}`)
    try {
      await closeTempDb()
    } catch (_) {
      /* ignore */
    }
    try {
      await removeDocRelative(TEMP_DB_FILE)
    } catch (_) {
      /* ignore */
    }
  }
}

async function processPath(packageRoot) {
  if (isRestrictedInternalPath(packageRoot)) {
    logInfo(`跳过内部私有路径(API29+ 不可直接复制):${packageRoot}`)
    return
  }

  const dbPath = await findDbInPackageRoot(packageRoot)
  if (!dbPath) {
    logInfo(`该路径下未找到数据库:${packageRoot}`)
    return
  }

  if (isRestrictedInternalPath(dbPath)) {
    logInfo(`跳过内部路径下的数据库:${dbPath}`)
    return
  }

  await mergeFromDbFile(dbPath, packageRoot)
}

/** 主库在 apps/xxx/doc 时,包根下扁平 zyzs.db 视为遗留库(同包名场景可测) */
async function processLegacyFlatDbAtCurrentRoot(currentRoot) {
  if (!currentRoot || isRestrictedInternalPath(currentRoot)) return

  const root = normalizePath(currentRoot)
  const flatDb = `${root}/${DB_FILE}`
  const mainDocDb = normalizePath(`${root}/apps/${getAppId()}/doc/${DB_FILE}`)

  if (!(await fileExists(flatDb))) {
    logInfo(`当前包根无遗留扁平库:${flatDb}`)
    return
  }

  if (normalizePath(flatDb) === mainDocDb) {
    logInfo(`包根库与 _doc 主库路径相同,跳过:${flatDb}`)
    return
  }

  logInfo(`扫描当前包根遗留库(${DB_FILE} 在包根,非 apps/.../doc)`)
  await mergeFromDbFile(flatDb, `${currentRoot}#legacy-flat`)
}

class StoragePathMerge {
  static async run() {
    logInfo('开始执行路径合并')

    const plusRef = await waitForPlus()
    if (!isAndroidApp(plusRef)) {
      logInfo('跳过:非 Android APP-PLUS 环境', {
        有Plus: !!plusRef,
        系统: plusRef?.os?.name
      })
      return
    }

    try {
      const currentRoot = await getCurrentPackageRoot()
      const runtimePkg = getRuntimePackageName()
      const mergePkgs = getPackageNamesForMerge()
      logInfo(`当前运行包名:${runtimePkg};参与扫描的包名:${mergePkgs.join('、')}`)
      logInfo(
        `当前包根目录:${currentRoot}(其它包名目录整包扫描;本包仅合并包根下遗留 ${DB_FILE})`
      )

      let cache = loadPathCache()
      if (!cache || !cache.length) {
        cache = createDefaultCache(currentRoot)
      } else {
        cache = ensureDefaultRootsInCache(cache, currentRoot)
      }
      savePathCache(cache)

      const paths = getNonCurrentPaths(cache)
      const scanList = paths.map(p => p.path)
      logInfo(`待扫描非当前路径 ${paths.length} 个`, { 路径列表: scanList })

      for (const item of paths) {
        try {
          await processPath(item.path)
        } catch (e) {
          logError(`扫描路径出错 ${item.path}:${e?.message || e}`)
        }
      }

      try {
        await processLegacyFlatDbAtCurrentRoot(currentRoot)
      } catch (e) {
        logError(`扫描包根遗留库出错:${e?.message || e}`)
      }

      const purged = await purgeMergeSeedRecordsFromMain()
      if (purged > 0) {
        logInfo(`已清理主库中 ${purged} 条路径合并测试记录`)
      }
      logInfo('路径合并执行完毕')
    } catch (e) {
      logError(`路径合并失败:${e?.message || e}`)
      throw e
    }
  }
}

export default StoragePathMerge