OverviewFilesCommitsIssuesDocsReleasesPeers

pear-git-v3 / lib / services / migrate / version-file.js

41 lines · javascript ref:
/**
 * File-backed schema-version store for the daemon — a tiny JSON file in the
 * storage dir, matching the daemon's other state files (issue-registry-index.json,
 * pending-pairings.json, repo-puller-cursor.json). Provides the getVersion /
 * setVersion pair migrateStore() needs.
 *
 * Version is bumped AFTER each migration's `up` resolves (the runner's
 * contract), so a crash mid-chain leaves the file at the last completed
 * version → the next boot resumes from there.
 */

import fs from '#node:fs'
import { join } from '#node:path'

const FILE = 'schema-version.json'

/**
 * @param {string} storageDir - the daemon's opts.storage
 * @returns {{ path:string, getVersion:()=>Promise<number>, setVersion:(v:number)=>Promise<void> }}
 */
export function fileVersionStore (storageDir) {
  const path = join(storageDir, FILE)
  return {
    path,
    async getVersion () {
      try {
        const raw = fs.readFileSync(path, 'utf8')
        const v = JSON.parse(raw).version
        return typeof v === 'number' ? v : 0
      } catch {
        return 0 // absent / unreadable → v0 (pre-migration)
      }
    },
    async setVersion (v) {
      const tmp = path + '.tmp'
      fs.writeFileSync(tmp, JSON.stringify({ version: v, updatedAt: Date.now() }))
      fs.renameSync(tmp, path) // atomic replace
    }
  }
}