-
Notifications
You must be signed in to change notification settings - Fork 82
/
Copy pathgenerate-types.ts
executable file
·204 lines (159 loc) · 5.58 KB
/
generate-types.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
#!/usr/bin/env ts-node-transpile-only
import { strict as assert } from "assert";
import * as fs from "fs";
import { JSONSchema7, JSONSchema7Definition } from "json-schema";
import { format } from "prettier";
type JSONSchemaWithRef = JSONSchema7 & Required<Pick<JSONSchema7, "$ref">>;
interface Schema extends JSONSchema7 {
definitions: Record<string, JSONSchema7>;
oneOf: JSONSchemaWithRef[];
}
const schema = require("@octokit/webhooks-definitions/schema.json") as Schema;
const titleCase = (str: string) => `${str[0].toUpperCase()}${str.substring(1)}`;
const guessAtInterfaceName = (str: string) =>
str.split(/[$_-]/u).map(titleCase).join("");
const guessAtEventName = (name: string) => {
const [, eventName] = /^(.+)[$_-]event/u.exec(name) ?? [];
assert.ok(eventName, `unable to guess event name for "${name}"`);
return eventName;
};
const guessAtActionName = (name: string) => name.replace("$", ".");
const getDefinitionName = (ref: string): string => {
assert.ok(
ref.startsWith("#/definitions/"),
`${ref} does not reference a valid definition`
);
const [, name] = /^#\/definitions\/(.+)$/u.exec(ref) ?? [];
assert.ok(name, `unable to find definition name ${ref}`);
return name;
};
type NameAndActions = [name: string, actions: string[]];
type Property = [key: string, value: string];
type ImportsAndProperties = [imports: string[], properties: Property[]];
const buildEventProperties = ([
eventName,
actions,
]: NameAndActions): ImportsAndProperties => {
const interfaceName = guessAtInterfaceName(eventName);
const importsAndProperties: ImportsAndProperties = [
[interfaceName],
[[guessAtEventName(eventName), interfaceName]],
];
if (actions.length) {
actions.forEach((actionName) => {
const actionInterfaceName = guessAtInterfaceName(`${actionName}_event`);
importsAndProperties[0].push(actionInterfaceName);
importsAndProperties[1].push([
guessAtActionName(actionName),
actionInterfaceName,
]);
});
}
return importsAndProperties;
};
const isJSONSchemaWithRef = (
object: JSONSchema7Definition
): object is JSONSchemaWithRef =>
typeof object === "object" && object.$ref !== undefined;
const listEvents = () => {
return schema.oneOf.map<NameAndActions>(({ $ref }) => {
const name = getDefinitionName($ref);
const definition = schema.definitions[name];
assert.ok(definition, `unable to find definition named ${name}`);
if (definition.oneOf?.every(isJSONSchemaWithRef)) {
return [name, definition.oneOf.map((def) => getDefinitionName(def.$ref))];
}
return [name, []];
});
};
const getImportsAndProperties = (): ImportsAndProperties => {
const importsAndProperties = listEvents().map(buildEventProperties);
return importsAndProperties.reduce<ImportsAndProperties>(
(allImportsAndProperties, [imports, properties]) => {
return [
allImportsAndProperties[0].concat(imports),
allImportsAndProperties[1].concat(properties),
];
},
[[], []]
);
};
const outDir = "src/generated/";
const generateTypeScriptFile = (name: string, contents: string[]) => {
fs.writeFileSync(
`${outDir}/${name}.ts`,
format(contents.join("\n"), { parser: "typescript" })
);
};
const asCode = (str: string): string => `\`${str}\``;
const asLink = (event: string): string => {
const link = `https://developer.github.com/v3/activity/events/types/#${event.replace(
/[^a-z]/g,
""
)}event`;
return `[${asCode(event)}](${link})`;
};
const updateReadme = (properties: string[]) => {
const headers = "| Event | Actions |";
const events = properties.reduce<Record<string, string[]>>(
(events, property) => {
console.log(property);
const [event, action] = property.split(".");
events[event] ||= [];
if (action) {
events[event].push(action);
}
return events;
},
{}
);
const rows = Object.entries(events).map(
([event, actions]) =>
`| ${asLink(event)} | ${actions.map(asCode).join("<br>")} |`
);
const table = format([headers, "| --- | --- |", ...rows].join("\n"), {
parser: "markdown",
});
const readme = fs.readFileSync("README.md", "utf-8");
const TableStartString =
"<!-- autogenerated via scripts/generate-types.ts -->";
const TableEndString =
"<!-- /autogenerated via scripts/generate-types.ts -->";
const tableStartIndex = readme.indexOf(TableStartString);
const tableEndIndex = readme.indexOf(TableEndString);
assert.ok(tableStartIndex !== -1, "cannot find start of table");
assert.ok(tableEndIndex !== -1, "cannot find end of table");
fs.writeFileSync(
"README.md",
`${readme.slice(
0,
tableStartIndex + TableStartString.length
)}\n\n${table}\n${readme.slice(tableEndIndex)}`
);
};
const run = () => {
const [imports, properties] = getImportsAndProperties();
const lines: string[] = [
"// THIS FILE IS GENERATED - DO NOT EDIT DIRECTLY",
"// make edits in scripts/generate-types.ts",
"",
"import {",
...imports.map((str) => ` ${str},`),
'} from "@octokit/webhooks-definitions/schema";',
"",
"export interface EmitterEventWebhookPayloadMap {",
...properties.map(([key, value]) => `"${key}": ${value}`),
"}",
];
generateTypeScriptFile("get-webhook-payload-type-from-event", lines);
generateTypeScriptFile("webhook-names", [
"// THIS FILE IS GENERATED - DO NOT EDIT DIRECTLY",
"// make edits in scripts/generate-types.ts",
"",
"export const emitterEventNames = [",
...properties.map(([key]) => `"${key}",`),
"];",
]);
updateReadme(properties.map(([key]) => key));
};
run();