gen-package-invariants.ts 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. /** Generate or verify package-owned invariant companion baselines. */
  2. import { readFileSync, writeFileSync } from 'node:fs'
  3. import { resolve } from 'node:path'
  4. import {
  5. GENERATED_INVARIANT_MARKER,
  6. collectPackageInvariantViolations,
  7. formatPackageInvariantViolation,
  8. packageInvariantOwners,
  9. renderBaselineInvariant,
  10. } from './package-invariants.ts'
  11. const root = resolve(import.meta.dirname, '..')
  12. const check = process.argv.includes('--check')
  13. if (!check) {
  14. let generated = 0
  15. for (const owner of packageInvariantOwners(root)) {
  16. const path = resolve(root, owner.sourcePath)
  17. let current: string | undefined
  18. try {
  19. current = readFileSync(path, 'utf8')
  20. } catch (error) {
  21. if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
  22. }
  23. if (current !== undefined && !current.includes(GENERATED_INVARIANT_MARKER)) continue
  24. const expected = renderBaselineInvariant(owner)
  25. if (current === expected) continue
  26. writeFileSync(path, expected)
  27. generated += 1
  28. }
  29. console.log(`gen-package-invariants: wrote ${generated} generated baseline companion(s).`)
  30. }
  31. const violations = collectPackageInvariantViolations(root)
  32. if (violations.length > 0) {
  33. console.error('verify-package-invariants: violations found:')
  34. for (const violation of violations) {
  35. console.error(` ${formatPackageInvariantViolation(root, violation)}`)
  36. }
  37. process.exit(1)
  38. }
  39. console.log(`verify-package-invariants: ${packageInvariantOwners(root).length} package companion(s) conform.`)