-
Notifications
You must be signed in to change notification settings - Fork 74
Expand file tree
/
Copy pathgenerateNodeConfigType.ts
More file actions
207 lines (172 loc) Β· 5.9 KB
/
generateNodeConfigType.ts
File metadata and controls
207 lines (172 loc) Β· 5.9 KB
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
205
206
207
import { execSync } from 'child_process';
import { readFileSync, rmSync } from 'fs';
import { Project, WriterFunction, Writers } from 'ts-morph';
const { objectType } = Writers;
function getNitroNodeImageTag(): string {
const defaultNitroNodeTag = 'v3.6.0-fc07dd2';
const argv = process.argv.slice(2);
if (argv.length < 2 || argv[0] !== '--nitro-node-tag') {
console.log(
`Using default nitro-node tag since none was provided. If you want to specify a tag, you can do "--nitro-node-tag v2.2.2-8f33fea".`,
);
return defaultNitroNodeTag;
}
return argv[1];
}
const nitroNodeTag = getNitroNodeImageTag();
const nitroNodeImage = `offchainlabs/nitro-node:${nitroNodeTag}`;
const nitroNodeHelpOutputFile = `${nitroNodeImage.replace('/', '-')}-help.txt`;
console.log(`Using image "${nitroNodeImage}".`);
function generateHeader() {
return [
`// ---`,
`//`,
`// THIS FILE IS AUTOMATICALLY GENERATED AND SHOULD NOT BE EDITED MANUALLY`,
`//`,
`// IMAGE: ${nitroNodeImage}`,
`// TIMESTAMP: ${new Date().toISOString()}`,
`// `,
`// ---`,
].join('\n');
}
type CliOption = {
name: string;
type: string;
docs: string[];
};
function parseCliOptions(fileContents: string): CliOption[] {
const types: Record<string, string | undefined> = {
string: 'string',
strings: 'string[]',
stringArray: 'string[]',
int: 'number',
int16: 'number',
int32: 'number',
uint: 'number',
uint16: 'number',
uint32: 'number',
float: 'number',
AllowedSeeks: 'number',
backendConfigList: 'string',
boolean: 'boolean',
duration: 'string',
durationSlice: 'string[]',
};
// split into lines
let lines = fileContents.split('\n');
// trim whitespaces
lines = lines.map((line) => line.trim());
// special case for flags with comments that span multiple lines
// todo: generalize this so it automatically detects and merges multi-line comments??
lines = lines.map((line, lineIndex) => {
// this comment spans 3 lines
if (line.includes('max-fee-cap-formula')) {
return `${line} ${lines[lineIndex + 1]} ${lines[lineIndex + 2]}`;
}
return line;
});
// only leave lines that start with "--", e.g. "--auth.addr string" but exclude "--help" and "--dev"
lines = lines.filter(
(line) => line.startsWith('--') && !line.includes('--help') && !line.includes('--dev'),
);
// sanitize the boolean types
lines = lines.map((line) => {
let split = line.split(' ');
// if the flag is just a boolean, then the type is omitted from the --help output, e.g. "--init.force"
// to make things simpler and consistent, we replace the empty string with boolean
if (split[1] === '') {
split[1] = 'boolean';
}
return split.join(' ');
});
return lines.map((line) => {
const [name, type] = line.split(' ');
// get the mapped type from go to typescript
const sanitizedType = types[type];
// docs is everything after the param name and type (and one space in between)
const docsStart = name.length + 1 + type.length;
const docs = line.slice(docsStart).trim();
if (typeof sanitizedType === 'undefined') {
throw new Error(`Unknown type: ${type}`);
}
return {
// remove "--" from the name
name: name.replace('--', ''),
// map the go type to the typescript type
type: sanitizedType,
// copy the rest of the line as docs
docs: [docs],
};
});
}
type CliOptionNestedObject = {
[key: string]: CliOption | CliOptionNestedObject;
};
function createCliOptionsNestedObject(options: CliOption[]): CliOptionNestedObject {
const result: CliOptionNestedObject = {};
options.forEach((option) => {
let paths = option.name.split('.');
let current: CliOptionNestedObject = result;
for (let i = 0; i < paths.length; i++) {
const path = paths[i];
const pathIsFinal = i === paths.length - 1;
if (typeof current[path] === 'undefined') {
current[path] = pathIsFinal ? option : {};
}
current = current[path] as CliOptionNestedObject;
}
});
return result;
}
function isCliOption(value: CliOption | CliOptionNestedObject): value is CliOption {
return 'type' in value;
}
function getDocs(value: CliOption | CliOptionNestedObject): string[] {
if (isCliOption(value)) {
return value.docs;
}
// docs only available for "primitive" properties, not objects
return [];
}
function getTypeRecursively(value: CliOption | CliOptionNestedObject): string | WriterFunction {
// if we reached the "primitive" property, we can just return its type
if (isCliOption(value)) {
return value.type;
}
// if not, recursively figure out the type for each of the object's properties
return objectType({
properties: Object.entries(value).map(([currentKey, currentValue]) => ({
name: `'${currentKey}'`,
type: getTypeRecursively(currentValue),
docs: getDocs(currentValue),
// make it optional
hasQuestionToken: true,
})),
});
}
function main() {
// run --help on the nitro binary and save the output to a file
execSync(`docker run --rm ${nitroNodeImage} --help > ${nitroNodeHelpOutputFile} 2>&1`);
// read and parse the file
const content = readFileSync(nitroNodeHelpOutputFile, 'utf8');
const cliOptions = parseCliOptions(content);
const cliOptionsNestedObject = createCliOptionsNestedObject(cliOptions);
// create the new source file
const sourceFile = new Project().createSourceFile('./src/types/NodeConfig.generated.ts', '', {
overwrite: true,
});
// append header
sourceFile.insertText(0, generateHeader());
// append NodeConfig type declaration
sourceFile.addTypeAlias({
name: 'NodeConfig',
type: getTypeRecursively(cliOptionsNestedObject),
docs: ['Nitro node configuration options'],
isExported: true,
});
// save file to disk
sourceFile.saveSync();
// remove output file that we used for parsing
rmSync(nitroNodeHelpOutputFile);
}
main();