OverviewFilesCommitsIssuesDocsReleasesPeers

pgh / scripts / migrate-index.js

71 lines · javascript ref:
#!/usr/bin/env node
/**
 * migrate-index — one-shot cleanup of ~/.config/pgh/published-index.json.
 *
 * Applies the retention-policy invariants:
 *   - Trim each app's versions to PublishedIndex.maxVersions (default 3),
 *     preserving any pinned: true entry.
 *   - Strip publisher-local _sourcePath strings from every surviving
 *     version's lockfile.deps.
 *
 * Safe to run multiple times. Idempotent.
 *
 * Usage:
 *   node scripts/migrate-index.js [--dry-run] [--max-versions N] [--path PATH]
 */

import fs from 'fs'
import { PublishedIndex, DEFAULT_PATH, DEFAULT_MAX_VERSIONS } from '../lib/published-index.js'

function flag (name) {
  const idx = process.argv.indexOf(name)
  if (idx === -1) return undefined
  return process.argv[idx + 1]
}

const dryRun = process.argv.includes('--dry-run')
const indexPath = flag('--path') || DEFAULT_PATH
const maxVersionsRaw = flag('--max-versions')
const maxVersions = maxVersionsRaw ? parseInt(maxVersionsRaw, 10) : DEFAULT_MAX_VERSIONS

if (!fs.existsSync(indexPath)) {
  console.log('no index at ' + indexPath + ' — nothing to migrate')
  process.exit(0)
}

const before = fs.statSync(indexPath).size
console.log('migrating ' + indexPath)
console.log('  before: ' + (before / 1024 / 1024).toFixed(1) + ' MB')
console.log('  maxVersions: ' + maxVersions)
console.log('  dryRun: ' + dryRun)

if (dryRun) {
  // Compute the effect without writing. Load the file, run rewrite into
  // a throwaway tmp path, compare sizes.
  const tmp = indexPath + '.dry-run.' + Date.now()
  fs.copyFileSync(indexPath, tmp)
  try {
    const idx = new PublishedIndex({ path: tmp, maxVersions })
    idx.rewriteWithRetention()
    const after = fs.statSync(tmp).size
    console.log('  after:  ' + (after / 1024 / 1024).toFixed(1) + ' MB')
    console.log('  saved:  ' + ((before - after) / 1024 / 1024).toFixed(1) + ' MB')
    console.log('(dry run — original file untouched)')
  } finally {
    fs.rmSync(tmp, { force: true })
  }
  process.exit(0)
}

// Real migration — back up the original first.
const backup = indexPath + '.backup-' + new Date().toISOString().replace(/[:.]/g, '-')
fs.copyFileSync(indexPath, backup)
console.log('  backup: ' + backup)

const idx = new PublishedIndex({ path: indexPath, maxVersions })
idx.rewriteWithRetention()

const after = fs.statSync(indexPath).size
console.log('  after:  ' + (after / 1024 / 1024).toFixed(1) + ' MB')
console.log('  saved:  ' + ((before - after) / 1024 / 1024).toFixed(1) + ' MB')