-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathgen-protobufs.mjs
218 lines (205 loc) · 5.7 KB
/
gen-protobufs.mjs
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
208
209
210
211
212
213
214
215
216
217
218
// @ts-check
/**
* This script generates the src/protobufs directory from the proto files in the
* repos specified in `REPOS`. It uses `buf` to generate TS files from the proto
* files, and then generates an `index.ts` file to re-export the generated code.
*/
import { spawnSync } from "child_process";
import degit from "degit";
import {
mkdirSync,
readFileSync,
readdirSync,
renameSync,
rmSync,
statSync,
writeFileSync,
} from "fs";
import { globSync } from "glob";
import { capitalize } from "lodash-es";
import { dirname, join } from "path";
import { fileURLToPath } from "url";
/**
* @typedef Repo
* @type {object}
* @property {string} repo - Git repo and branch to clone
* @property {string[]} paths - Paths to proto files relative to the repo root
*/
/**
* TODO: Add more repos here when necessary.
* @type {Repo[]}
*/
const REPOS = [
{
repo: "cosmos/cosmos-sdk#v0.47.9",
paths: ["proto"],
},
{
repo: "cosmos/ics23#master",
paths: ["proto"],
},
{
repo: "cosmos/ibc-go#main",
paths: ["proto"],
},
{
repo: "CosmWasm/wasmd#main",
paths: ["proto"],
},
{
repo: "osmosis-labs/osmosis#main",
paths: ["proto"],
},
{
repo: "InjectiveLabs/sdk-go#master",
paths: ["proto"],
},
{
repo: "evmos/ethermint#main",
paths: ["proto"],
},
{
repo: "dymensionxyz/osmosis#main-dym",
paths: ["proto"],
},
];
const __dirname = dirname(fileURLToPath(import.meta.url));
const PROTOBUFS_DIR = join(__dirname, "..", "src", "protobufs");
const TMP_DIR = join(PROTOBUFS_DIR, ".tmp");
/** Generates a unique dirname from `repo` to use in `TMP_DIR`. */
const id = (/** @type {string} */ repo) => repo.replace(/[#/]/g, "-");
console.log("Initialising directories...");
{
rmSync(PROTOBUFS_DIR, { recursive: true, force: true });
rmSync(TMP_DIR, { recursive: true, force: true });
mkdirSync(PROTOBUFS_DIR);
mkdirSync(TMP_DIR);
}
console.log("Cloning required repos...");
{
await Promise.all(
REPOS.map(({ repo }) => degit(repo).clone(join(TMP_DIR, id(repo))))
);
}
console.log("Generating TS files from proto files...");
{
for (const { repo, paths } of REPOS) {
for (const path of paths) {
spawnSync(
"pnpm",
[
"buf",
"generate",
join(TMP_DIR, id(repo), path),
"--output",
join(
PROTOBUFS_DIR,
repo.startsWith("dymensionxyz") ? "dymension" : ""
),
],
{
cwd: process.cwd(),
stdio: "inherit",
}
);
}
console.log(`✔️ [${repo}]`);
}
}
console.log("Flattening dymension protobufs...");
{
// Move all dirs in protobufs/dymension/osmosis out into protobufs/dymension
const dymensionDir = join(PROTOBUFS_DIR, "dymension");
const dymensionOsmosisDir = join(dymensionDir, "osmosis");
// Move all subdirs up one level
readdirSync(dymensionOsmosisDir).forEach((file) => {
const currentFile = join(dymensionOsmosisDir, file);
const stats = statSync(currentFile);
if (stats.isDirectory()) {
renameSync(currentFile, join(dymensionDir, file));
}
});
// Remove all empty dirs
readdirSync(dymensionDir).forEach((file) => {
const currentFile = join(dymensionDir, file);
const stats = statSync(currentFile);
if (stats.isDirectory() && stats.size === 0) {
rmSync(currentFile, { recursive: true, force: true });
}
});
}
console.log("Generating src/index.ts file and renaming exports...");
{
const LAST_SEGMENT_REGEX = /[^/]+$/;
const EXPORTED_NAME_REGEX = /^export \w+ (\w+) /gm;
let contents =
"/** This file is generated by gen-protobufs.mjs. Do not edit. */\n\n";
/**
* Builds the `src/proto/index.ts` file to re-export generated code.
* A prefix is added to the exported names to avoid name collisions.
* The prefix is the names of the directories in `proto` leading up
* to the directory of the exported code, concatenated in PascalCase.
* For example, if the exported code is in `proto/foo/bar/goo.ts`, the
* prefix will be `FooBar`.
* @param {string} dir
*/
function generateIndexExports(dir) {
const files = globSync(join(dir, "*"));
if (files.length === 0) {
return;
}
const prefixName = dir
.replace(PROTOBUFS_DIR + "/", "")
.split("/")
.map((name) =>
// convert all names to PascalCase
name.split(/[-_]/).map(capitalize).join("")
)
.join("");
for (const file of files) {
const fileName = file.match(LAST_SEGMENT_REGEX)?.[0];
if (!fileName) {
console.error("Could not find name for", file);
continue;
}
if (!fileName.endsWith(".ts")) {
continue;
}
const code = readFileSync(file, "utf8");
contents += `export {\n`;
for (const match of code.matchAll(EXPORTED_NAME_REGEX)) {
const exportedName = match[1];
contents += ` ${exportedName} as ${prefixName + exportedName},\n`;
}
const exportedFile = file
.replace(PROTOBUFS_DIR + "/", "")
.replace(".ts", ".js");
contents += `} from "./${exportedFile}";\n`;
}
for (const file of files) {
generateIndexExports(file);
}
}
generateIndexExports(PROTOBUFS_DIR);
writeFileSync(join(PROTOBUFS_DIR, "index.ts"), contents);
}
console.log("Rewriting Injective's legacy CosmWasm dependencies...");
{
const path = join(
PROTOBUFS_DIR,
"injective",
"wasmx",
"v1",
"proposal_pb.ts"
);
const contents = readFileSync(path, "utf8").replace(
"proposal_pb.js",
"proposal_legacy_pb.js"
);
writeFileSync(path, contents);
}
console.log("Cleaning up...");
{
rmSync(TMP_DIR, { recursive: true, force: true });
}
console.log("Proto generation completed successfully!");