Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

Annotations.ts

72 lines2.8 KB

1import * as Effect from "effect/Effect"
2import * as FileSystem from "effect/FileSystem"
3import * as Path from "effect/Path"
4import * as Yaml from "yaml"
5import { ApiDiffError, isApiDiffError } from "./Error.ts"
6​
7export interface MigrationAnnotation {
8 readonly replacement: string
9 readonly note: string
10 readonly example?: string | undefined
12​
13const compareStrings = (left: string, right: string): number => left < right ? -1 : left > right ? 1 : 0
14​
15const parseAnnotation = (id: string, value: unknown, file: string): MigrationAnnotation => {
16 if (
17 typeof value !== "object" || value === null ||
18 typeof Reflect.get(value, "replacement") !== "string" ||
19 typeof Reflect.get(value, "note") !== "string" ||
20 (Reflect.get(value, "example") !== undefined && typeof Reflect.get(value, "example") !== "string")
21 ) {
22 throw new Error(`Invalid annotation for ${id} in ${file}`)
23 }
24 return {
25 replacement: Reflect.get(value, "replacement"),
26 note: Reflect.get(value, "note"),
27 ...(Reflect.get(value, "example") === undefined ? {} : { example: Reflect.get(value, "example") })
28 }
30​
31const loadAnnotationsInternal = Effect.fnUntraced(function*(directory: string) {
32 const fs = yield* FileSystem.FileSystem
33 const path = yield* Path.Path
34 if (!(yield* fs.exists(directory))) {
35 return new Map<string, MigrationAnnotation>()
36 }
37​
38 const annotations = new Map<string, MigrationAnnotation>()
39 const files = (yield* fs.readDirectory(directory))
40 .filter((file) => file.endsWith(".yaml") || file.endsWith(".yml"))
41 .sort(compareStrings)
42 for (const file of files) {
43 const source = yield* fs.readFileString(path.join(directory, file))
44 const document = yield* Effect.try({
45 try: () => Yaml.parse(source) as unknown,
46 catch: (cause) => new ApiDiffError({ message: `Could not parse annotation file ${file}`, cause })
47 })
48 if (typeof document !== "object" || document === null || Array.isArray(document)) {
49 return yield* new ApiDiffError({ message: `Annotation file ${file} must contain an object` })
50 }
51 for (const [id, value] of Object.entries(document).sort(([left], [right]) => compareStrings(left, right))) {
52 if (annotations.has(id)) {
53 return yield* new ApiDiffError({ message: `Duplicate annotation id ${id}` })
54 }
55 const annotation = yield* Effect.try({
56 try: () => parseAnnotation(id, value, file),
57 catch: (cause) => new ApiDiffError({ message: String(cause), cause })
58 })
59 annotations.set(id, annotation)
60 }
61 }
62 return annotations
63})
64​
65export const loadAnnotations = (directory: string) =>
66 loadAnnotationsInternal(directory).pipe(
67 Effect.mapError((cause) =>
68 isApiDiffError(cause)
69 ? cause
70 : new ApiDiffError({ message: `Could not load annotations from ${directory}`, cause })
71 )
72 )