releases.ts 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import { readFileSync } from 'node:fs'
  2. export interface ReleaseManifest {
  3. schemaVersion: 1
  4. releaseVersion: string
  5. webVersion: string
  6. pluginVersion: string
  7. gitTag: string
  8. }
  9. const VERSION_PATTERN = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/
  10. function version(value: unknown, field: string): string {
  11. if (typeof value !== 'string' || !VERSION_PATTERN.test(value)) {
  12. throw new Error(`${field} 必须是有效的语义版本`)
  13. }
  14. return value
  15. }
  16. export function parseReleaseManifest(value: unknown): ReleaseManifest {
  17. if (!value || typeof value !== 'object' || Array.isArray(value)) {
  18. throw new Error('release.json 必须是对象')
  19. }
  20. const input = value as Record<string, unknown>
  21. if (input.schemaVersion !== 1) throw new Error('release.json schemaVersion 必须为 1')
  22. const releaseVersion = version(input.releaseVersion, 'releaseVersion')
  23. const webVersion = version(input.webVersion, 'webVersion')
  24. const pluginVersion = version(input.pluginVersion, 'pluginVersion')
  25. const gitTag = typeof input.gitTag === 'string' ? input.gitTag : ''
  26. if (releaseVersion !== webVersion) throw new Error('releaseVersion 与 webVersion 必须一致')
  27. if (gitTag !== `v${releaseVersion}`) throw new Error('gitTag 必须与 releaseVersion 一致')
  28. return { schemaVersion: 1, releaseVersion, webVersion, pluginVersion, gitTag }
  29. }
  30. export function readReleaseManifest(path: string): ReleaseManifest {
  31. return parseReleaseManifest(JSON.parse(readFileSync(path, 'utf8')))
  32. }
  33. function numericCore(value: string): [number, number, number] {
  34. const [major = 0, minor = 0, patch = 0] = value.split('-', 1)[0]!.split('.').map(Number)
  35. return [major, minor, patch]
  36. }
  37. export function compareReleaseVersions(left: string, right: string): number {
  38. const a = numericCore(left)
  39. const b = numericCore(right)
  40. for (let index = 0; index < 3; index += 1) {
  41. if (a[index] !== b[index]) return a[index]! - b[index]!
  42. }
  43. const leftSuffix = left.includes('-') ? left.slice(left.indexOf('-') + 1) : ''
  44. const rightSuffix = right.includes('-') ? right.slice(right.indexOf('-') + 1) : ''
  45. if (!leftSuffix && rightSuffix) return 1
  46. if (leftSuffix && !rightSuffix) return -1
  47. return leftSuffix.localeCompare(rightSuffix)
  48. }