export-community-schema.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. #!/usr/bin/env node
  2. import { existsSync, mkdirSync, readdirSync, copyFileSync, rmSync, writeFileSync } from 'node:fs'
  3. import { dirname, join, resolve } from 'node:path'
  4. import { fileURLToPath } from 'node:url'
  5. const scriptDir = dirname(fileURLToPath(import.meta.url))
  6. const config = await readConfig()
  7. const migrationDir = resolve(scriptDir, config.migrationDir)
  8. const exportDir = resolve(scriptDir, config.exportDir, 'migration')
  9. const dryRun = process.argv.includes('--dry-run')
  10. const migrationPattern = /^V\d+\.\d+\.\d+__[a-z0-9_]+\.sql$/
  11. if (!existsSync(migrationDir)) {
  12. fail(`migration directory not found: ${migrationDir}`)
  13. }
  14. const files = readdirSync(migrationDir)
  15. .filter(file => file.endsWith('.sql'))
  16. .sort()
  17. const invalidFiles = files.filter(file => !migrationPattern.test(file))
  18. if (invalidFiles.length > 0) {
  19. fail(`invalid migration file names:\n${invalidFiles.map(file => `- ${file}`).join('\n')}`)
  20. }
  21. if (!dryRun) {
  22. rmSync(exportDir, { recursive: true, force: true })
  23. mkdirSync(exportDir, { recursive: true })
  24. for (const file of files) {
  25. copyFileSync(join(migrationDir, file), join(exportDir, file))
  26. }
  27. }
  28. const summary = {
  29. type: 'schema',
  30. dryRun,
  31. source: migrationDir,
  32. target: exportDir,
  33. files
  34. }
  35. writeFileSync(resolve(scriptDir, config.exportDir, 'schema-summary.json'), `${JSON.stringify(summary, null, 2)}\n`)
  36. console.log(JSON.stringify(summary, null, 2))
  37. async function readConfig() {
  38. const configPath = resolve(scriptDir, 'community-db.config.json')
  39. return JSON.parse(await import('node:fs/promises').then(fs => fs.readFile(configPath, 'utf8')))
  40. }
  41. function fail(message) {
  42. console.error(message)
  43. process.exit(1)
  44. }