@latticexyz/cli 0.10.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/utils.ts ADDED
@@ -0,0 +1,69 @@
1
+ import { exec as nodeExec, spawn } from "child_process";
2
+ import { keccak256 as keccak256Bytes, toUtf8Bytes } from "ethers/lib/utils";
3
+ import { readFileSync } from "fs";
4
+
5
+ export const IDregex = new RegExp(/(?<=uint256 constant ID = uint256\(keccak256\(")(.*)(?="\))/);
6
+
7
+ /**
8
+ * A convenient way to create a promise with resolve and reject functions.
9
+ * @returns Tuple with resolve function, reject function and promise.
10
+ */
11
+ export function deferred<T>(): [(t: T) => void, (t: Error) => void, Promise<T>] {
12
+ let resolve: ((t: T) => void) | null = null;
13
+ let reject: ((t: Error) => void) | null = null;
14
+ const promise = new Promise<T>((r, rj) => {
15
+ resolve = (t: T) => r(t);
16
+ reject = (e: Error) => rj(e);
17
+ });
18
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
19
+ return [resolve as any, reject as any, promise];
20
+ }
21
+
22
+ /**
23
+ * Await execution of bash scripts
24
+ * @param command Bash script to execute
25
+ * @returns Promise that resolves with exit code when script finished executing
26
+ */
27
+ export async function exec(command: string): Promise<number> {
28
+ const [resolve, , promise] = deferred<number>();
29
+
30
+ const child = nodeExec(command, (error, stdout, stderr) => {
31
+ if (error || stderr) {
32
+ console.error(error);
33
+ console.error(stderr);
34
+ }
35
+ console.log(stdout);
36
+ });
37
+
38
+ child.on("exit", (code) => resolve(code ?? 0));
39
+
40
+ return promise;
41
+ }
42
+
43
+ /**
44
+ * Await execution of bash scripts
45
+ * @param command Bash script to execute
46
+ * @param options Args to pass to the script
47
+ * @returns Promise that resolves with exit code when script finished executing
48
+ */
49
+ export async function execLog(command: string, options: string[]): Promise<number> {
50
+ console.log("Cmd:");
51
+ console.log([command, ...options].join(" "));
52
+ const [resolve, , promise] = deferred<number>();
53
+
54
+ const child = spawn(command, options, { stdio: [process.stdin, process.stdout, process.stderr] });
55
+
56
+ child.on("exit", (code) => resolve(code ?? 0));
57
+
58
+ return promise;
59
+ }
60
+
61
+ export function extractIdFromFile(path: string): string | null {
62
+ const content = readFileSync(path).toString();
63
+ const regexResult = IDregex.exec(content);
64
+ return regexResult && regexResult[0];
65
+ }
66
+
67
+ export function keccak256(data: string) {
68
+ return keccak256Bytes(toUtf8Bytes(data));
69
+ }